diff --git a/apps/web/src/app/api/newsletter/subscribe/route.ts b/apps/web/src/app/api/newsletter/subscribe/route.ts index d401bae8b0..bb1a2d1b22 100644 --- a/apps/web/src/app/api/newsletter/subscribe/route.ts +++ b/apps/web/src/app/api/newsletter/subscribe/route.ts @@ -18,7 +18,7 @@ const CADENCES = new Set(["weekly", "monthly"]); */ const TURNSTILE_ACTION = "newsletter-subscribe"; -const SOURCES = new Set(["community-page", "creator-page", "settings", "landing-page", "publish-prompt", "post-page", "self-hosted-blog"]); +const SOURCES = new Set(["community-page", "creator-page", "settings", "landing-page", "publish-prompt", "post-page", "self-hosted-blog", "mobile-app"]); /** * Subscribe to a community or creator digest. diff --git a/apps/web/src/features/newsletter/types.ts b/apps/web/src/features/newsletter/types.ts index 81a05c1421..219ea4aabd 100644 --- a/apps/web/src/features/newsletter/types.ts +++ b/apps/web/src/features/newsletter/types.ts @@ -38,7 +38,8 @@ export interface SubscribeInput { | "landing-page" | "publish-prompt" | "post-page" - | "self-hosted-blog"; + | "self-hosted-blog" + | "mobile-app"; /** * Cloudflare Turnstile token. Required by the route whenever the caller has no * account; ignored for signed-in callers, whose account is the proof. diff --git a/apps/web/src/specs/api/newsletter-subscribe-route.spec.ts b/apps/web/src/specs/api/newsletter-subscribe-route.spec.ts index 4b2ee6ae96..d8b3a87433 100644 --- a/apps/web/src/specs/api/newsletter-subscribe-route.spec.ts +++ b/apps/web/src/specs/api/newsletter-subscribe-route.spec.ts @@ -132,6 +132,19 @@ describe("POST /api/newsletter/subscribe", () => { expect(JSON.parse(mocks.fetch.mock.calls[0][1].body)).toMatchObject({ type: "site", target: "ecency", source: "landing-page" }); }); + it("accepts a signed-in mobile-app subscribe and relays the source intact", async () => { + mocks.verify.mockResolvedValue({ ok: true, username: "alice" }); + mocks.fetch.mockResolvedValue(upstream(200, { status: "active" })); + const r = await post({ ...VALID, type: "creator", target: "someone", source: "mobile-app", code: "hs-token", captchaToken: undefined }); + expect(r.status).toBe(200); + expect(JSON.parse(mocks.fetch.mock.calls[0][1].body)).toMatchObject({ + type: "creator", + target: "someone", + source: "mobile-app", + account: "alice" + }); + }); + it("the own digest needs a verified account and its target must be that account", async () => { // Anonymous: no account to be the target of. expect((await post({ ...VALID, type: "own", target: "alice" })).status).toBe(401); diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md index 4cb21203c1..61b761ee84 100644 --- a/packages/sdk/CHANGELOG.md +++ b/packages/sdk/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 2.3.92 + +### Patch Changes + +- feat(sdk): shared newsletter client module for digest subscriptions and sender API (#1677) + ## 2.3.91 ### Patch Changes diff --git a/packages/sdk/dist/browser/index.d.ts b/packages/sdk/dist/browser/index.d.ts index 214039b70e..3ebd3547b9 100644 --- a/packages/sdk/dist/browser/index.d.ts +++ b/packages/sdk/dist/browser/index.d.ts @@ -1629,6 +1629,13 @@ declare const QueryKeys: { readonly quests: { readonly status: (username: string | undefined) => (string | undefined)[]; }; + readonly newsletter: { + readonly subscriptions: (username: string | undefined) => (string | undefined)[]; + readonly sender: (type: string, target: string, username: string | undefined) => (string | undefined)[]; + readonly issues: (type: string, target: string, username: string | undefined) => (string | undefined)[]; + readonly posts: (type: string, target: string, username: string | undefined, limit: number) => (string | number | undefined)[]; + readonly _prefix: readonly ["newsletter"]; + }; readonly support: { readonly settings: (username: string | undefined) => (string | undefined)[]; readonly _prefix: readonly ["support"]; @@ -4384,7 +4391,11 @@ interface WavesFeedParams { following?: string; /** Only this author's waves (across all containers); the per-author feed. */ author?: string; - /** The viewing user; exclude authors they currently mute. */ + /** + * The viewing user; exclude authors they currently mute. Ecency's own + * moderation mutes are applied by esync regardless of this value, so leaving + * it unset drops the viewer's personal mutes, not the platform ones. + */ observer?: string; /** Page size (default 20). */ limit?: number; @@ -4441,7 +4452,10 @@ interface ShortsFeedParams { tag?: string; /** Only this author's shorts (across all containers). */ author?: string; - /** The viewing user; exclude authors they currently mute. */ + /** + * The viewing user; exclude authors they currently mute. Ecency's own + * moderation mutes are applied by esync regardless of this value. + */ observer?: string; /** Page size (default 20). */ limit?: number; @@ -9726,4 +9740,280 @@ declare function getContentModerationReason(content: ModerationCandidate | undef /** True if the post body contains an outbound (non-Hive, non-image) link. */ declare function hasExternalLink(body: string | undefined | null): boolean; -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, ContentModerationReason, 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, HIDDEN_POST_MIN_VOTES, HIDDEN_POST_RSHARES_THRESHOLD, 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, LOW_TRUST_REPUTATION_THRESHOLD, 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 ModerationCandidate, 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 RcPrecheckPayload, type RcPrecheckResult, type RcPriceCurveParams, type RcPricedUsage, type RcResourceDynamicsParams, type RcResourceName, type RcResourceParamEntry, type RcResourceParams, type RcResourceUsage, 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, SIGNATURE_BYTES, 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, TRANSACTION_HEADER_BYTES, 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 VoteLike, 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, countVoteResourceUsage, decodeObj, dedupeAndSortKeyAuths, deleteDraft, deleteImage, deleteSchedule, downVotingPower, earnsQuestContentCredit, encodeObj, enforceThreeSpeakBeneficiary, estimateCommentRcCost, estimateCommentTransactionBytes, estimateRcPrecheck, estimateVoteTransactionBytes, extractAccountProfile, formatError, formattedNumber, gameClaimRequest, 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, getContentModerationReason, 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, hasExternalLink, hasThreeSpeakEmbed, hsTokenRenew, invalidateAfterBroadcast, isAuthorMuted, isCommunity, isEmptyDate, isHiddenPost, isInfoError, isLowTrustSeoPost, 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, priceRcUsage, proMembersSet, rcPower, removeOptimisticDiscussionEntry, resolveAccountHistoryLimit, resolveContentActivityType, resolveHiveOperationFilters, resolvePost, restoreDiscussionSnapshots, restoreEntryInCache, roleMap, saveNotificationSetting, search, searchPath, searchQueryOptions, sha256, shouldTriggerAuthFallback, signUp, similar, sortDiscussions, stringFieldBytes, 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 }; +type DigestType = "own" | "community" | "creator" | "site"; +type DigestCadence = "weekly" | "monthly"; +type DigestStatus = "active" | "pending_confirmation" | "suppressed" | "ended"; +/** The two list types that have a sender side (own/site digests are system-sent). */ +type NewsletterListType = "creator" | "community"; +interface DigestSubscription { + id: string; + email: string; + account: string | null; + type: DigestType; + target: string; + cadence: DigestCadence; + status: DigestStatus; + created_at: string; +} +/** + * Where the subscribe request originated. The relay keeps a closed allowlist + * (apps/web/src/app/api/newsletter/subscribe/route.ts SOURCES) — a value the + * route does not accept is a silent 400, so additions land there first. + */ +type DigestSubscribeSource = "community-page" | "creator-page" | "settings" | "landing-page" | "publish-prompt" | "post-page" | "self-hosted-blog" | "mobile-app"; +interface DigestSubscribeInput { + email: string; + type: DigestType; + target: string; + cadence: DigestCadence; + source: DigestSubscribeSource; + /** + * Cloudflare Turnstile token. Required by the relay whenever the caller has + * no verified account; ignored for authenticated callers, whose account is + * the proof. + */ + captchaToken?: string; +} +interface DigestSubscribeResult { + status: "active" | "pending_confirmation" | "refused"; + /** Proven (authenticated or already-confirmed) callers only. */ + subscription?: DigestSubscription; + created?: boolean; + confirmationSent?: boolean; + reason?: "suppressed"; +} +interface NewsletterPostRef { + author: string; + permlink: string; +} +/** One post, the post being the issue. */ +interface NewsletterSendRef extends NewsletterPostRef { + type: NewsletterListType; + target: string; +} +/** Several posts with a subject and an intro. */ +interface NewsletterComposeRequest { + type: NewsletterListType; + target: string; + posts: NewsletterPostRef[]; + subject?: string; + intro?: string; +} +type NewsletterSendRequest = NewsletterSendRef | NewsletterComposeRequest; +interface NewsletterCandidatePost extends NewsletterPostRef { + title: string; + created: string; + featured: boolean; +} +interface NewsletterSendPreview { + subject: string; + html: string; + text: string; + post: { + author: string; + permlink: string; + title: string; + }; + posts: Array<{ + author: string; + permlink: string; + title: string; + }>; + subscribers: { + weekly: number; + monthly: number; + }; + alreadySent: DigestCadence[]; +} +interface NewsletterSendResult { + issues: Array<{ + issueId: string; + cadence: DigestCadence; + period: string; + send: { + recipients: number; + sent: number; + pending: number; + }; + }>; +} +interface NewsletterSentIssue { + id: string; + cadence: DigestCadence; + kind: "digest" | "post"; + period_start: string; + subject: string; + status: string; + post_author: string | null; + post_permlink: string | null; + requested_by: string | null; + created_at: string; + delivered: number; + bounced: number; + rejected: number; +} +interface NewsletterSenderStanding { + type: DigestType; + target: string; + status: "active" | "suspended"; + reason: string | null; + since: string | null; + stats: { + delivered: number; + bounced: number; + rejected: number; + complaints: number; + unsubscribed: number; + complaintRate: number; + bounceRate: number; + }; + /** Live, mailable subscribers per cadence. */ + subscribers?: { + weekly: number; + monthly: number; + }; +} + +/** + * Client for the newsletter relay at {privateApiHost}/api/newsletter/* + * (Next.js route handlers on ecency.com, which alone hold the news-service + * credentials — clients never talk to the service directly). + * + * Identity is the HiveSigner access token, passed here as the explicit `code` + * argument. Transport mirrors the deployed web client per route: subscribe and + * unsubscribe-all carry it in the POST body as `code` (the subscribe route + * authenticates ONLY from the body — a header alone is treated as anonymous); + * every other call, the send/preview POSTs included, uses the `X-HS-Token` + * header. The relay verifies it upstream and derives the account from it, so + * a stale token 401s — callers are responsible for supplying a fresh one + * (web: ensureValidToken; mobile: the token-refresh wrapper). + * + * The email-token confirm/unsubscribe flows are deliberately absent: those + * links land on web pages. + */ +declare class NewsletterApiError extends Error { + readonly status: number; + readonly data?: unknown | undefined; + constructor(message: string, status: number, data?: unknown | undefined); +} +/** A refused send, carrying the relay's routing `code` (already_sent, suspended, ...). */ +declare class NewsletterSendRefusedError extends NewsletterApiError { + readonly code?: string | undefined; + readonly taken?: Array<{ + cadence: string; + period: string; + kind: string; + }> | undefined; + constructor(message: string, status: number, code?: string | undefined, taken?: Array<{ + cadence: string; + period: string; + kind: string; + }> | undefined, data?: unknown); +} +/** + * Subscribe an address to a digest. Authenticated callers (code given) skip + * the captcha; anonymous callers must supply `captchaToken` in the input and + * get double opt-in. The `own` digest type is always authenticated. + */ +declare function subscribeDigestRequest(input: DigestSubscribeInput, code?: string): Promise; +/** Every live digest subscription attributed to the token's account. */ +declare function getDigestSubscriptionsRequest(code: string): Promise; +/** Leave one digest by subscription id. */ +declare function leaveDigestRequest(id: string, code: string): Promise; +/** + * Suppress ONE address entirely (no Ecency bulk mail to it again). Only that + * address stops: an account can hold subscriptions under several addresses. + */ +declare function unsubscribeAllDigestsRequest(email: string, code: string): Promise; +/** Sender standing (status, complaint/bounce stats, subscriber counts) for a list. */ +declare function getNewsletterSenderRequest(type: NewsletterListType, target: string, code: string): Promise; +/** Already-sent issues for a list, newest first. */ +declare function getNewsletterIssuesRequest(type: NewsletterListType, target: string, code: string): Promise; +/** Candidate posts for composing a digest issue. */ +declare function getNewsletterPostsRequest(type: NewsletterListType, target: string, code: string, limit?: number): Promise; +/** Render the would-be issue (subject/html/text, counts, taken periods) without sending. */ +declare function previewNewsletterSendRequest(request: NewsletterSendRequest, code: string): Promise; +/** Send a post or composed digest to the list's subscribers. Pro/team gated by the relay. */ +declare function sendNewsletterIssueRequest(request: NewsletterSendRequest, code: string): Promise; + +/** + * The signed-in account's live digest subscriptions. Disabled without a + * username + token: callers render nothing then, and a request that + * predictably 401s is noise. `retry: false` because the common failure is a + * stale token, which a retry with the same token cannot fix. + */ +declare function getDigestSubscriptionsQueryOptions(username: string | undefined, code: string | undefined): _tanstack_react_query.OmitKeyof<_tanstack_react_query.UseQueryOptions, "queryFn"> & { + queryFn?: _tanstack_react_query.QueryFunction | undefined; +} & { + queryKey: (string | undefined)[] & { + [dataTagSymbol]: DigestSubscription[]; + [dataTagErrorSymbol]: Error; + }; +}; + +/** + * Sender standing for a creator/community list. View access is the list's + * owner (creator) or the community team, decided by the relay — enable this + * only for callers already known to be the sender. + */ +declare function getNewsletterSenderQueryOptions(type: NewsletterListType, target: string, username: string | undefined, code: string | undefined): _tanstack_react_query.OmitKeyof<_tanstack_react_query.UseQueryOptions, "queryFn"> & { + queryFn?: _tanstack_react_query.QueryFunction | undefined; +} & { + queryKey: (string | undefined)[] & { + [dataTagSymbol]: NewsletterSenderStanding; + [dataTagErrorSymbol]: Error; + }; +}; + +/** Already-sent issues for a creator/community list (sender-only view). */ +declare function getNewsletterIssuesQueryOptions(type: NewsletterListType, target: string, username: string | undefined, code: string | undefined): _tanstack_react_query.OmitKeyof<_tanstack_react_query.UseQueryOptions, "queryFn"> & { + queryFn?: _tanstack_react_query.QueryFunction | undefined; +} & { + queryKey: (string | undefined)[] & { + [dataTagSymbol]: NewsletterSentIssue[]; + [dataTagErrorSymbol]: Error; + }; +}; + +/** Candidate posts for composing a digest issue (send-gated by the relay). */ +declare function getNewsletterPostsQueryOptions(type: NewsletterListType, target: string, username: string | undefined, code: string | undefined, limit?: number): _tanstack_react_query.OmitKeyof<_tanstack_react_query.UseQueryOptions, "queryFn"> & { + queryFn?: _tanstack_react_query.QueryFunction | undefined; +} & { + queryKey: (string | number | undefined)[] & { + [dataTagSymbol]: NewsletterCandidatePost[]; + [dataTagErrorSymbol]: Error; + }; +}; + +/** + * Subscribe to a digest (also re-used to change cadence: same list + address + * with a new cadence updates the row). Works signed-in (code) and anonymous + * (input.captchaToken); the signed-in path refreshes the account's + * subscriptions list on success. + */ +declare function useSubscribeDigest(username: string | undefined, code: string | undefined): _tanstack_react_query.UseMutationResult; + +/** Leave one digest by subscription id; drops the row from the cached list. */ +declare function useLeaveDigest(username: string | undefined, code: string | undefined): _tanstack_react_query.UseMutationResult; + +/** + * Stop all Ecency mail to ONE address. Only that address's rows leave the + * cached list: an account can hold subscriptions under more than one address, + * and those stay visible. + */ +declare function useUnsubscribeAllDigests(username: string | undefined, code: string | undefined): _tanstack_react_query.UseMutationResult; + +/** + * Preview the would-be issue. No cache side effects: a preview changes + * nothing server-side. + */ +declare function usePreviewNewsletterIssue(username: string | undefined, code: string | undefined): _tanstack_react_query.UseMutationResult; +/** + * Send a post or composed digest to a list. Errors are + * NewsletterSendRefusedError with the relay's routing `code` + * (already_sent + taken periods, suspended, post_refused, ...). On success the + * list's issues + sender standing refresh. + */ +declare function useSendNewsletterIssue(username: string | undefined, code: string | undefined): _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 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, ContentModerationReason, 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 DigestCadence, type DigestStatus, type DigestSubscribeInput, type DigestSubscribeResult, type DigestSubscribeSource, type DigestSubscription, type DigestType, 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, HIDDEN_POST_MIN_VOTES, HIDDEN_POST_RSHARES_THRESHOLD, 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, LOW_TRUST_REPUTATION_THRESHOLD, 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 ModerationCandidate, type MutePostPayload, NaiMap, NewsletterApiError, type NewsletterCandidatePost, type NewsletterComposeRequest, type NewsletterListType, type NewsletterPostRef, type NewsletterSendPreview, type NewsletterSendRef, NewsletterSendRefusedError, type NewsletterSendRequest, type NewsletterSendResult, type NewsletterSenderStanding, type NewsletterSentIssue, 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 RcPrecheckPayload, type RcPrecheckResult, type RcPriceCurveParams, type RcPricedUsage, type RcResourceDynamicsParams, type RcResourceName, type RcResourceParamEntry, type RcResourceParams, type RcResourceUsage, 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, SIGNATURE_BYTES, 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, TRANSACTION_HEADER_BYTES, 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 VoteLike, 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, countVoteResourceUsage, decodeObj, dedupeAndSortKeyAuths, deleteDraft, deleteImage, deleteSchedule, downVotingPower, earnsQuestContentCredit, encodeObj, enforceThreeSpeakBeneficiary, estimateCommentRcCost, estimateCommentTransactionBytes, estimateRcPrecheck, estimateVoteTransactionBytes, extractAccountProfile, formatError, formattedNumber, gameClaimRequest, 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, getContentModerationReason, getContentQueryOptions, getContentRepliesQueryOptions, getControversialRisingInfiniteQueryOptions, getConversionRequestsQueryOptions, getCurrencyRate, getCurrencyRates, getCurrencyTokenRate, getCurrentMedianHistoryPriceQueryOptions, getCustomJsonAuthority, getDeletedEntryQueryOptions, getDigestSubscriptionsQueryOptions, getDigestSubscriptionsRequest, 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, getNewsletterIssuesQueryOptions, getNewsletterIssuesRequest, getNewsletterPostsQueryOptions, getNewsletterPostsRequest, getNewsletterSenderQueryOptions, getNewsletterSenderRequest, 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, hasExternalLink, hasThreeSpeakEmbed, hsTokenRenew, invalidateAfterBroadcast, isAuthorMuted, isCommunity, isEmptyDate, isHiddenPost, isInfoError, isLowTrustSeoPost, isNetworkError, isQueryableAccountName, isResourceCreditsError, isThreeSpeakBeneficiary, isVoteAlreadyReflected, isWif, isWrappedResponse, leaveDigestRequest, lookupAccountsQueryOptions, makeQueryClient, mapMetaChoicesToPollChoices, mapThreadItemsToWaveEntries, markNotifications, measureQuestContentLength, moveSchedule, normalizePost, normalizeSearchAuthor, normalizeSearchCategory, normalizeSearchTags, normalizeToWrappedResponse, normalizeWaveEntryFromApi, onboardEmail, parseAccounts, parseAsset, parseChainError, parsePostingMetadataRoot, parseProfileMetadata, pickRicherMetadataSnapshot, powerRechargeTime, previewNewsletterSendRequest, priceRcUsage, proMembersSet, rcPower, removeOptimisticDiscussionEntry, resolveAccountHistoryLimit, resolveContentActivityType, resolveHiveOperationFilters, resolvePost, restoreDiscussionSnapshots, restoreEntryInCache, roleMap, saveNotificationSetting, search, searchPath, searchQueryOptions, sendNewsletterIssueRequest, sha256, shouldTriggerAuthFallback, signUp, similar, sortDiscussions, stringFieldBytes, subscribeDigestRequest, subscribeEmail, toEntryArray, unsubscribeAllDigestsRequest, 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, useLeaveDigest, useLimitOrderCancel, useLimitOrderCreate, useMarkNotificationsRead, useMoveSchedule, useMutePost, usePinPost, usePollVote, usePreviewNewsletterIssue, usePromote, useProposalCreate, useProposalVote, useRcDelegation, useReblog, useRecordActivity, useRegisterCommunityRewards, useRemoveFragment, useSendNewsletterIssue, useSetCommunityRole, useSetLastRead, useSetWithdrawVestingRoute, useSignOperationByHivesigner, useSignOperationByKey, useSignOperationByKeychain, useStakeEngineToken, useSubscribeCommunity, useSubscribeDigest, useTransfer, useTransferEngineToken, useTransferFromSavings, useTransferPoint, useTransferToSavings, useTransferToVesting, useUndelegateEngineToken, useUnfollow, useUnstakeEngineToken, useUnsubscribeAllDigests, 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 ab084d517d..18520a166e 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 On 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 fo from'hivesigner';var yn=Object.defineProperty;var Ji=(e,t,r)=>t in e?yn(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var At=(e,t)=>{for(var r in t)yn(e,r,{get:t[r],enumerable:true});};var P=(e,t,r)=>Ji(e,typeof t!="symbol"?t+"":t,r);var Ot=new ArrayBuffer(0),xt=null,Et=null;function Yi(){return xt||(typeof TextEncoder<"u"?xt=new TextEncoder:xt={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)}}),xt}function hn(){return Et||(typeof TextDecoder<"u"?Et=new TextDecoder:Et={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+(i&1023)));}return r}}),Et}var j=class j{constructor(t=j.DEFAULT_CAPACITY,r=j.DEFAULT_ENDIAN){P(this,"buffer");P(this,"view");P(this,"offset");P(this,"markedOffset");P(this,"limit");P(this,"littleEndian");P(this,"readUInt32",this.readUint32);this.buffer=t===0?Ot:new ArrayBuffer(t),this.view=t===0?new DataView(Ot):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(Ot));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 o;return t instanceof j?(o=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=o.length):t instanceof Uint8Array?o=t:t instanceof ArrayBuffer?o=new Uint8Array(t):o=new Uint8Array(t),o.length<=0?this:(r+o.length>this.buffer.byteLength&&this.resize(r+o.length),new Uint8Array(this.buffer).set(o,r),n&&(this.offset+=o.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,o=new j(n,this.littleEndian);return o.offset=0,o.limit=n,new Uint8Array(o.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),o}copyTo(t,r,n,o){let i=typeof r>"u",s=typeof n>"u";r=i?t.offset:r,n=s?this.offset:n,o=o===void 0?this.limit:o;let a=o-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,o),r),s&&(this.offset+=a),i&&(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?Ot: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 o=this.calculateVarint32(t);for(r+o>this.buffer.byteLength&&this.resize(r+o),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):o}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,o=0,i;do i=this.view.getUint8(t++),n<5&&(o|=(i&127)<<7*n),++n;while((i&128)!==0);return o|=0,r?(this.offset=t,o):{value:o,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",o=n?this.offset:r,i=Yi().encode(t),s=i.length,a=this.calculateVarint32(s);return o+a+s>this.buffer.byteLength&&this.resize(o+a+s),this.writeVarint32(s,o),o+=a,new Uint8Array(this.buffer).set(i,o),o+=s,n?(this.offset=o,this):o-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,o=this.readVarint32(t),i=o.value,s=o.length;t+=s;let a=hn().decode(new Uint8Array(this.buffer,t,i));return t+=i,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 o=hn().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,o):{string:o,length:t}}};P(j,"LITTLE_ENDIAN",true),P(j,"BIG_ENDIAN",false),P(j,"DEFAULT_CAPACITY",16),P(j,"DEFAULT_ENDIAN",j.BIG_ENDIAN);var K=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}},_n=["bridge.get_ranked_posts","bridge.get_account_posts","bridge.get_post","bridge.get_discussion","bridge.get_profile","bridge.get_profiles","bridge.get_community","bridge.list_communities","condenser_api.get_accounts","condenser_api.get_content","condenser_api.get_dynamic_global_properties","condenser_api.get_trending_tags"],St=null,or=e=>{if(e===null){St=null;return}if(!e||typeof e!="object")return;let t=typeof e.url=="string"?e.url.trim():"";if(!/^https?:\/\//i.test(t))return;let r={};if(e.headers&&typeof e.headers=="object")for(let[s,a]of Object.entries(e.headers))typeof a=="string"&&a&&!/[\u0000-\u001f\u007f]/.test(a)&&!/[\u0000-\u001f\u007f]/.test(s)&&(r[s]=a);let n=typeof e.timeoutMs=="number"&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:2e3,o=e.methods===void 0?[..._n]:Array.isArray(e.methods)?e.methods.filter(s=>typeof s=="string"&&s.includes(".")):[];if(o.length===0)return;let i=(s,a)=>typeof s=="number"&&Number.isFinite(s)&&s>0?s:a;St={url:t,headers:r,timeoutMs:n,methods:o,failureThreshold:Math.floor(i(e.failureThreshold,3)),cooldownMs:i(e.cooldownMs,1e4),methodSet:new Set(o)};},ir=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)))]:[],sr=e=>{let t=ir(e);t.length&&(E.nodes=t);},ar=e=>{let t=ir(e);t.length&&(E.restNodes=t);},cr=e=>{if(!e||typeof e!="object")return;let t={...E.restNodesByApi};for(let[r,n]of Object.entries(e)){let o=ir(n);o.length?t[r]=o:delete t[r];}E.restNodesByApi=t;},ur=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(E.userAgent=t);},pr=e=>{if(!e||typeof e!="object")return;let t=E.resilience,r=o=>typeof o=="boolean",n=o=>typeof o=="number"&&Number.isFinite(o)&&o>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 ke=class e{constructor(t,r,n){P(this,"data");P(this,"recovery");P(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,o=true;n<0&&(o=false,n=n+4);let i=r.subarray(1);return new e(i,n,o)}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 Z(n.recoverPublicKey(t).toBytes())}};var Z=class e{constructor(t,r){P(this,"key");P(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 o;try{o=On.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(o.length!==37)throw new Error("Invalid public key length");let i=o.subarray(0,33),s=o.subarray(33,37),a=ripemd160(i).subarray(0,4);if(!Zi(s,a))throw new Error("Public key checksum mismatch");try{secp256k1.Point.fromBytes(i);}catch{throw new Error("Invalid public key")}return new e(i,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=ke.from(r)),secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return Xi(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},Xi=(e,t)=>{let r=ripemd160(e);return t+On.encode(new Uint8Array([...e,...r.subarray(0,4)]))},Zi=(e,t)=>{if(e.byteLength!==t.byteLength)return false;for(let r=0;r{throw new Error("Void can not be serialized")},b=(e,t)=>{e.writeVString(t);},rs=(e,t)=>{e.writeInt16(t);},En=(e,t)=>{e.writeInt64(t);},xn=(e,t)=>{e.writeUint8(t);},de=(e,t)=>{e.writeUint16(t);},ee=(e,t)=>{e.writeUint32(t);},Sn=(e,t)=>{e.writeUint64(t);},ve=(e,t)=>{e.writeByte(t?1:0);},kn=e=>(t,r)=>{let[n,o]=r;t.writeVarint32(n),e[n](t,o);},D=(e,t)=>{let r=kt.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let o=0;o<7;o++)e.writeUint8(r.symbol.charCodeAt(o)||0);},Ce=(e,t)=>{e.writeUint32(Math.floor(new Date(t+"Z").getTime()/1e3));},he=(e,t)=>{t===null||typeof t=="string"&&t.slice(-39)==="1111111111111111111111111111111114T1Anm"?e.append(new Uint8Array(33).fill(0)):e.append(Z.from(t).key);},Cn=(e=null)=>(t,r)=>{r=Ct.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);},Rn=Cn(),lr=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[o,i]of n)e(r,o),t(r,i);},L=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},fe=e=>(t,r)=>{for(let[n,o]of e)try{o(t,r[n]);}catch(i){throw i.message=`${n}: ${i.message}`,i}},Ke=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},z=fe([["weight_threshold",ee],["account_auths",lr(b,de)],["key_auths",lr(he,de)]]),ns=fe([["account",b],["weight",de]]),dr=fe([["base",D],["quote",D]]),os=fe([["account_creation_fee",D],["maximum_block_size",ee],["hbd_interest_rate",de]]),T=(e,t)=>{let r=fe(t);return (n,o)=>{n.writeVarint32(e),r(n,o);}},k={};k.account_create=T(R.account_create,[["fee",D],["creator",b],["new_account_name",b],["owner",z],["active",z],["posting",z],["memo_key",he],["json_metadata",b]]);k.account_create_with_delegation=T(R.account_create_with_delegation,[["fee",D],["delegation",D],["creator",b],["new_account_name",b],["owner",z],["active",z],["posting",z],["memo_key",he],["json_metadata",b],["extensions",L(ae)]]);k.account_update=T(R.account_update,[["account",b],["owner",Ke(z)],["active",Ke(z)],["posting",Ke(z)],["memo_key",he],["json_metadata",b]]);k.account_witness_proxy=T(R.account_witness_proxy,[["account",b],["proxy",b]]);k.account_witness_vote=T(R.account_witness_vote,[["account",b],["witness",b],["approve",ve]]);k.cancel_transfer_from_savings=T(R.cancel_transfer_from_savings,[["from",b],["request_id",ee]]);k.change_recovery_account=T(R.change_recovery_account,[["account_to_recover",b],["new_recovery_account",b],["extensions",L(ae)]]);k.claim_account=T(R.claim_account,[["creator",b],["fee",D],["extensions",L(ae)]]);k.claim_reward_balance=T(R.claim_reward_balance,[["account",b],["reward_hive",D],["reward_hbd",D],["reward_vests",D]]);k.comment=T(R.comment,[["parent_author",b],["parent_permlink",b],["author",b],["permlink",b],["title",b],["body",b],["json_metadata",b]]);k.comment_options=T(R.comment_options,[["author",b],["permlink",b],["max_accepted_payout",D],["percent_hbd",de],["allow_votes",ve],["allow_curation_rewards",ve],["extensions",L(kn([fe([["beneficiaries",L(ns)]])]))]]);k.convert=T(R.convert,[["owner",b],["requestid",ee],["amount",D]]);k.create_claimed_account=T(R.create_claimed_account,[["creator",b],["new_account_name",b],["owner",z],["active",z],["posting",z],["memo_key",he],["json_metadata",b],["extensions",L(ae)]]);k.custom=T(R.custom,[["required_auths",L(b)],["id",de],["data",Rn]]);k.custom_json=T(R.custom_json,[["required_auths",L(b)],["required_posting_auths",L(b)],["id",b],["json",b]]);k.decline_voting_rights=T(R.decline_voting_rights,[["account",b],["decline",ve]]);k.delegate_vesting_shares=T(R.delegate_vesting_shares,[["delegator",b],["delegatee",b],["vesting_shares",D]]);k.delete_comment=T(R.delete_comment,[["author",b],["permlink",b]]);k.escrow_approve=T(R.escrow_approve,[["from",b],["to",b],["agent",b],["who",b],["escrow_id",ee],["approve",ve]]);k.escrow_dispute=T(R.escrow_dispute,[["from",b],["to",b],["agent",b],["who",b],["escrow_id",ee]]);k.escrow_release=T(R.escrow_release,[["from",b],["to",b],["agent",b],["who",b],["receiver",b],["escrow_id",ee],["hbd_amount",D],["hive_amount",D]]);k.escrow_transfer=T(R.escrow_transfer,[["from",b],["to",b],["hbd_amount",D],["hive_amount",D],["escrow_id",ee],["agent",b],["fee",D],["json_meta",b],["ratification_deadline",Ce],["escrow_expiration",Ce]]);k.feed_publish=T(R.feed_publish,[["publisher",b],["exchange_rate",dr]]);k.limit_order_cancel=T(R.limit_order_cancel,[["owner",b],["orderid",ee]]);k.limit_order_create=T(R.limit_order_create,[["owner",b],["orderid",ee],["amount_to_sell",D],["min_to_receive",D],["fill_or_kill",ve],["expiration",Ce]]);k.limit_order_create2=T(R.limit_order_create2,[["owner",b],["orderid",ee],["amount_to_sell",D],["exchange_rate",dr],["fill_or_kill",ve],["expiration",Ce]]);k.recover_account=T(R.recover_account,[["account_to_recover",b],["new_owner_authority",z],["recent_owner_authority",z],["extensions",L(ae)]]);k.request_account_recovery=T(R.request_account_recovery,[["recovery_account",b],["account_to_recover",b],["new_owner_authority",z],["extensions",L(ae)]]);k.reset_account=T(R.reset_account,[["reset_account",b],["account_to_reset",b],["new_owner_authority",z]]);k.set_reset_account=T(R.set_reset_account,[["account",b],["current_reset_account",b],["reset_account",b]]);k.set_withdraw_vesting_route=T(R.set_withdraw_vesting_route,[["from_account",b],["to_account",b],["percent",de],["auto_vest",ve]]);k.transfer=T(R.transfer,[["from",b],["to",b],["amount",D],["memo",b]]);k.transfer_from_savings=T(R.transfer_from_savings,[["from",b],["request_id",ee],["to",b],["amount",D],["memo",b]]);k.transfer_to_savings=T(R.transfer_to_savings,[["from",b],["to",b],["amount",D],["memo",b]]);k.transfer_to_vesting=T(R.transfer_to_vesting,[["from",b],["to",b],["amount",D]]);k.vote=T(R.vote,[["voter",b],["author",b],["permlink",b],["weight",rs]]);k.withdraw_vesting=T(R.withdraw_vesting,[["account",b],["vesting_shares",D]]);k.witness_update=T(R.witness_update,[["owner",b],["url",b],["block_signing_key",he],["props",os],["fee",D]]);k.witness_set_properties=T(R.witness_set_properties,[["owner",b],["props",lr(b,Rn)],["extensions",L(ae)]]);k.account_update2=T(R.account_update2,[["account",b],["owner",Ke(z)],["active",Ke(z)],["posting",Ke(z)],["memo_key",Ke(he)],["json_metadata",b],["posting_json_metadata",b],["extensions",L(ae)]]);k.create_proposal=T(R.create_proposal,[["creator",b],["receiver",b],["start_date",Ce],["end_date",Ce],["daily_pay",D],["subject",b],["permlink",b],["extensions",L(ae)]]);k.update_proposal_votes=T(R.update_proposal_votes,[["voter",b],["proposal_ids",L(En)],["approve",ve],["extensions",L(ae)]]);k.remove_proposal=T(R.remove_proposal,[["proposal_owner",b],["proposal_ids",L(En)],["extensions",L(ae)]]);var is=fe([["end_date",Ce]]);k.update_proposal=T(R.update_proposal,[["proposal_id",Sn],["creator",b],["daily_pay",D],["subject",b],["permlink",b],["extensions",L(kn([ae,is]))]]);k.collateralized_convert=T(R.collateralized_convert,[["owner",b],["requestid",ee],["amount",D]]);k.recurrent_transfer=T(R.recurrent_transfer,[["from",b],["to",b],["amount",D],["memo",b],["recurrence",de],["executions",de],["extensions",L(fe([["type",xn],["value",fe([["pair_id",xn]])]]))]]);var ss=(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}},as=fe([["ref_block_num",de],["ref_block_prefix",ee],["expiration",Ce],["operations",L(ss)],["extensions",L(b)]]),cs=fe([["from",he],["to",he],["nonce",Sn],["check",ee],["encrypted",Cn()]]),me={Asset:D,Memo:cs,Price:dr,PublicKey:he,String:b,Transaction:as,UInt16:de,UInt32:ee};var st=e=>new Promise(t=>setTimeout(t,e));var Kn=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function hr(){return Kn?{"User-Agent":E.userAgent}:{}}var Te={served:0,fallback:0,skipped:0,fallbackByReason:{status:0,rpcerror:0,timeout:0,transport:0,validate:0,parse:0}},Fe=class extends Error{constructor(r,n){super(n);P(this,"reason",r);}},Tn=e=>e instanceof Error?e.message:typeof e=="string"?e:String(e),Rt=0,Fn=0;async function us(e,t,r,n,o,i){let s=t.indexOf(".");if(s<=0||s===t.length-1)throw new Fe("transport",`method without an api prefix: ${t}`);let{signal:a,cleanup:c}=br(Math.min(e.timeoutMs,n)),{signal:p,cleanup:l}=qt(a,o);try{let d;try{d=await fetch(e.url,{method:"POST",body:JSON.stringify({api:t.slice(0,s),method:t.slice(s+1),params:r}),headers:{"Content-Type":"application/json",...hr(),...e.headers},signal:p});}catch(g){throw o?.aborted?g:new Fe(a.aborted?"timeout":"transport",Tn(g))}if(d.status!==200){try{await d.body?.cancel();}catch{}let g=d.status===502&&(d.headers.get("x-ssr-cache")??"").toUpperCase()==="RPCERROR";throw new Fe(g?"rpcerror":"status",g?"proxy relayed a node error":`proxy answered ${d.status}`)}let m;try{m=await d.json();}catch(g){throw o?.aborted?g:new Fe(a.aborted?"timeout":"parse",Tn(g))}if(i&&!i(m))throw new Fe("validate","proxy result rejected by validator");return m}finally{c(),l();}}var te=class extends Error{constructor(r){super(r.message);P(this,"name","RPCError");P(this,"data");P(this,"code");P(this,"stack");this.code=r.code,"data"in r&&(this.data=r.data);}},Be=class extends Error{constructor(r,n,o={}){super(n);P(this,"node");P(this,"rateLimitMs");P(this,"isRateLimit");this.node=r,this.rateLimitMs=o.rateLimitMs??0,this.isRateLimit=o.isRateLimit??false;}};function Bn(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 ps=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],ls=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function ds(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 fs(e){if(!e)return false;if(e instanceof Be)return true;if(e instanceof te)return false;let t=ds(e);return !!(ps.some(r=>t.includes(r))||ls.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function fr(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function Mn(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var ms=1e4,gs=6e4,ys=12e4,In=2,qn=6e4,Dn=12e4,hs=30,at=.3,mr=3,ct=5*6e4,Nn=6e4,Qn=1e3,Hn=2e3,Ft=class{constructor(){P(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,o){let i=this.getOrCreate(t);if(i.consecutiveFailures=0,i.rateLimitStreak=0,r){let s=i.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&i.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(i,n,o??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=mr&&o-i.updatedAt<=ct?i.ewmaMs:void 0}return this.isLatencyUsable(n,o)?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 o=Date.now();if(t.latencyUpdatedAt>0&&o-t.latencyUpdatedAt>ct&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:at*r+(1-at)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=o,n!==void 0){let i=t.apiLatency.get(n);!i||o-i.updatedAt>ct?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:o}):(i.ewmaMs=at*r+(1-at)*i.ewmaMs,i.sampleCount++,i.updatedAt=o);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(i.cooldownUntil>0&&i.cooldownUntil<=o||i.lastFailureTime>0&&o-i.lastFailureTime>3e4)&&(i.count=0,i.cooldownUntil=0),i.count++,i.lastFailureTime=o,i.count>=In&&(i.cooldownUntil=o+qn),n.apiFailures.set(r,i);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};i.count=Math.max(i.count+1,In),i.lastFailureTime=o,i.cooldownUntil=o+qn,i.defective=true,n.apiFailures.set(r,i);}recordRateLimit(t,r){let n=this.getOrCreate(t),o=Date.now();n.rateLimitStreak>0&&o-n.lastRateLimitAt>ys&&(n.rateLimitStreak=0);let i=typeof r=="number"&&Number.isFinite(r)&&r>0,s=i?r:Math.min(ms*2**n.rateLimitStreak,gs);i||n.rateLimitStreak++,n.lastRateLimitAt=o,n.rateLimitedUntil=i?o+s:Math.max(n.rateLimitedUntil,o+s),n.consecutiveFailures++,n.lastFailureTime=o;}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,o)=>n-o),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let o=Date.now();if(n.rateLimitedUntil>o||n.consecutiveFailures>=3&&o-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>o)return false}let i=this.consensusHeadBlock();return !(i>0&&n.headBlock>0&&o-n.headBlockUpdatedAt<=Dn&&i-n.headBlock>hs)}getOrderedNodes(t,r){let n=[],o=[];for(let c of t)this.isNodeHealthy(c,r)?n.push(c):o.push(c);if(n.length<=1)return [...n,...o];let i=Date.now(),s=n.map((c,p)=>({node:c,i:p,score:this.scoreNode(c,i)})).sort((c,p)=>c.score-p.score||c.i-p.i).map(c=>c.node),a=this.pickReprobeCandidate(n,i);return a&&s[0]!==a?[a,...s.filter(c=>c!==a),...o]:[...s,...o]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=mr&&r-t.latencyUpdatedAt<=ct}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:Qn}pickReprobeCandidate(t,r){let n=r-Nn,o,i=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;}},yr=new gr;function It(e,t,r,n,o){let i=E.resilience;if(!i.adaptiveTimeout||o)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(i.adaptiveTimeoutFloorMs,i.adaptiveTimeoutFactor*s)))}function _r(e,t,r,n){r instanceof Be?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof te?e.recordFailure(t,n):e.recordFailure(t);}function Un(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let o=n.head_block_number;typeof o=="number"&&e.recordHeadBlock(t,o);}function _s(){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 br(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(_s()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function qt(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),o=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",o,{once:true});let i=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o);};return {signal:r.signal,cleanup:i}}var ut=async(e,t,r,n=E.timeout,o=false,i)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:c,cleanup:p}=br(n),{signal:l,cleanup:d}=qt(c,i),m=()=>{p(),d();};try{let g=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...hr()},signal:l});if(g.status===429)throw new Be(e,"HTTP 429 Rate Limited",{rateLimitMs:Bn(g.headers.get("Retry-After")),isRateLimit:!0});if(g.status>=500&&g.status<600)throw new Be(e,`HTTP ${g.status} from ${e}`);let h=await g.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 A=h.error;throw "message"in A&&"code"in A?new te(A):h.error}throw h}catch(g){if(g instanceof te||g instanceof Be||i?.aborted)throw g;if(o)return ut(e,t,r,n,false,i);throw g}finally{m();}};function Tt(){return st(50+Math.random()*50)}function bs(e){let{method:t,params:r,api:n,primary:o,hedgePool:i,callerTimeout:s,explicitTimeout:a,deadlineAt:c,externalSignal:p,onHedgeFired:l,validate:d}=e;return new Promise((m,g)=>{let h=false,A=0,x=false,F=false,I,le,O=0,G=[],H=X=>{if(!h){h=true,le!==void 0&&(clearTimeout(le),le=void 0);for(let q of G)q.signal.aborted||q.abort();X();}},U=(X,q)=>{A++;let ye=new AbortController;G.push(ye);let it=qt(ye.signal,p),zi=It($,X,t,s,a),nr=Date.now();q||(O=nr),ut(X,t,r,zi,false,it.signal).then(se=>{if(it.cleanup(),A--,q||(F=true),!h){if(d&&!d(se)){if($.recordDefectiveResponse(X,n),I=new Error(`[hive-tx] response validation failed for ${t} from ${X}`),!q&&!x){H(()=>g(I));return}A===0&&H(()=>g(I));return}$.recordSuccess(X,n,Date.now()-nr,t),Un($,X,t,se),q?F||$.recordCensoredLatency(o,Date.now()-O,t):x||yr.refill(),H(()=>m(se));}}).catch(se=>{if(it.cleanup(),A--,q||(F=true),!h){if(p?.aborted){H(()=>g(se));return}if(se instanceof te&&!fr(se.code,se.message)){H(()=>g(se));return}if(_r($,X,se,n),$.recordSlowFailure(X,Date.now()-nr,t),I=se,!q&&!x){H(()=>g(se));return}A===0&&H(()=>g(I));}});};U(o,false);let Y=$.getUsableLatencyMs(o,t)??0,W=It($,o,t,s,a),ot=Math.min(Math.max(E.resilience.hedgeDelayFloorMs,E.resilience.hedgeDelayFactor*Y),.8*W);le=setTimeout(()=>{if(le=void 0,h||p?.aborted||Date.now()>=c)return;let X=i.filter(ye=>$.isNodeHealthy(ye,n));if(X.length===0)return;let q=X[Math.floor(Math.random()*X.length)];yr.trySpend()&&(x=true,l(q),U(q,true));},ot);})}var y=async(e,t=[],r,n=E.retry,o,i)=>{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=Mn(e),p=St;if(p&&Kn&&p.methodSet.has(e))if(Date.now()=p.failureThreshold&&(Fn=Date.now()+p.cooldownMs,Rt=0);}let l=Date.now()+E.resilience.totalBudgetFactor*a,d=new Set,m;for(let g=0;g<=n&&!(g>0&&Date.now()>=l);g++){let h=$.getOrderedNodes(E.nodes,c),A=h.find(I=>!d.has(I));A||(d.clear(),A=h[0]),d.add(A);let x=[];if(E.resilience.hedge&&$.getUsableLatencyMs(A,e)!==void 0&&(x=h.filter(I=>!d.has(I)&&$.isNodeHealthy(I,c)).slice(0,3)),x.length>0)try{return await bs({method:e,params:t,api:c,primary:A,hedgePool:x,callerTimeout:a,explicitTimeout:s,deadlineAt:l,externalSignal:o,onHedgeFired:I=>d.add(I),validate:i})}catch(I){if(I instanceof te&&!fr(I.code,I.message)||o?.aborted)throw I;m=I,g{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 o=Mn(e),i=new Set,s;for(let a=0;a!i.has(l));if(!p)break;if(i.add(p),n?.aborted)throw new Error("Aborted");try{let l=await ut(p,e,t,r,!1,n);return $.recordSuccess(p,o),l}catch(l){if(l instanceof te||n?.aborted||(_r($,p,l,o),s=l,!fs(l)))throw l}}throw s},ws={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 ne(e,t,r,n,o=E.retry,i){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,d=new Set,m,g=false;for(let h=0;h<=o&&!(h>0&&Date.now()>=c);h++){let A=Re.getOrderedNodes(l,e),x=A.find(q=>!d.has(q));x||(d.clear(),x=A[0]),d.add(x);let F=x+ws[e],I=t,le=r||{},O=new Set;Object.entries(le).forEach(([q,ye])=>{I.includes(`{${q}}`)&&(I=I.replace(`{${q}}`,encodeURIComponent(String(ye))),O.add(q));});let G=new URL(F+I);if(Object.entries(le).forEach(([q,ye])=>{O.has(q)||(Array.isArray(ye)?ye.forEach(it=>G.searchParams.append(q,String(it))):G.searchParams.set(q,String(ye)));}),i?.aborted)throw new Error("Aborted");g=false;let{signal:H,cleanup:U}=br(It(Re,x,p,a,s)),{signal:Y,cleanup:W}=qt(H,i),ot=()=>{U(),W();},X=Date.now();try{let q=await fetch(G.toString(),{signal:Y,headers:hr()});if(q.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(q.status===429)throw Re.recordRateLimit(x,Bn(q.headers.get("Retry-After"))||void 0),g=!0,new Error(`HTTP 429 Rate Limited by ${x}`);if(q.status===503)throw Re.recordFailure(x,e),g=!0,new Error(`HTTP 503 Service Unavailable from ${x}`);if(!q.ok)throw Re.recordFailure(x,e),g=!0,new Error(`HTTP ${q.status} from ${x}`);return Re.recordSuccess(x,e,Date.now()-X,p),q.json()}catch(q){if(q?.message?.includes("HTTP 404")||i?.aborted)throw q;g||Re.recordFailure(x,e),Re.recordSlowFailure(x,Date.now()-X,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 i=(c=>{let p=[...c];for(let l=p.length-1;l>0;l--){let d=Math.floor(Math.random()*(l+1));[p[l],p[d]]=[p[d],p[l]];}return p})(E.nodes),s=Math.min(r,i.length),a=[];for(;s>0&&i.length>0;){let c=i.splice(0,s),p=[],l=[];for(let m=0;ml.push(g)).catch(()=>{}));await Promise.all(p),a.push(...l);let d=vs(a,r);if(d)return d;if(s=Math.min(r,i.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function vs(e,t){let r=new Map;for(let o of e){let i=JSON.stringify(o);r.has(i)||r.set(i,[]),r.get(i).push(o);}let n=Array.from(r.values()).find(o=>o.length>=t);return n?n[0]:null}var As=hexToBytes(E.chain_id),Me=class e{constructor(t){P(this,"transaction");P(this,"expiration",6e4);P(this,"txId");P(this,"createTransaction",async t=>{let r=await y("condenser_api.get_dynamic_global_properties",[]),n=hexToBytes(r.head_block_id),o=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),i=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:i,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:o,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 o of t){let i=o.sign(r);this.transaction.signatures.push(i.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 We("condenser_api.broadcast_transaction",[this.transaction]);}catch(i){if(!(i instanceof te&&i.message.includes("Duplicate transaction check failed")))throw i}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await st(1e3);let n=await this.checkStatus(),o=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&o>6,128|i&63);else if(i>=55296&&i<=56319&&o+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else n.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(n);}return new e(sha256(t))}static fromLogin(t,r,n="active"){let o=t+n+r;return e.fromSeed(o)}sign(t){let r=secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(bytesToHex(r.subarray(0,1)),16);return ke.from((n+31).toString(16)+bytesToHex(r.subarray(1)))}createPublic(t){return new Z(secp256k1.getPublicKey(this.key),t)}toString(){return Es(new Uint8Array([...Gn,...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)}},zn=e=>sha256(sha256(e)),Es=e=>{let t=zn(e);return On.encode(new Uint8Array([...e,...t.slice(0,4)]))},Ss=e=>{let t=On.decode(e);if(!$n(t.slice(0,1),Gn))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),o=zn(n).slice(0,4);if(!$n(r,o))throw new Error("Private key checksum mismatch");return n},$n=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;nZn(e,t,n,r),Xn=(e,t,r,n,o)=>Zn(e,t,r,n,o).message,Zn=(e,t,r,n,o)=>{let i=r,s=e.getSharedSecret(t),a=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);a.writeUint64(i),a.append(s),a.flip();let c=sha512(new Uint8Array(a.toBuffer())),p=c.subarray(32,48),l=c.subarray(0,32),d=sha256(c).subarray(0,4),m=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);m.append(d),m.flip();let g=m.readUint32();if(o!==void 0){if(g!==o)throw new Error("Invalid key");n=Ts(n,l,p);}else n=Fs(n,l,p);return {nonce:i,message:n,checksum:g}},Ts=(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},vr=null,Is=()=>{if(vr===null){let r=secp256k1.utils.randomSecretKey();vr=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++vr%65536;return e=e<{let t=Ns(e,33);return new Z(t)},Ds=e=>e.readUint64(),Ks=e=>e.readUint32(),Bs=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 K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);n.append(t),n.flip();for(let[o,i]of e)try{r[o]=i(n);}catch(s){throw s.message=`${o}: ${s.message}`,s}return r};function Ns(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 Qs=Ms([["from",eo],["to",eo],["nonce",Ds],["check",Ks],["encrypted",Bs]]),to={Memo:Qs};var no=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),io(),e=so(e),t=Hs(t);let o=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);o.writeVString(r);let i=new Uint8Array(o.copy(0,o.offset).toBuffer()),{nonce:s,message:a,checksum:c}=Yn(e,t,i,n),p=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);me.Memo(p,{check:c,encrypted:a,from:e.createPublic(),nonce:s,to:t}),p.flip();let l=new Uint8Array(p.toBuffer());return "#"+On.encode(l)},oo=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),io(),e=so(e);let r=to.Memo(On.decode(t)),{from:n,to:o,nonce:i,check:s,encrypted:a}=r,p=e.createPublic().toString()===new Z(n.key).toString()?new Z(o.key):new Z(n.key);r=Xn(e,p,i,a,s);let l=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},Kt,io=()=>{if(Kt===void 0){let e;Kt=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=no(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=oo(t,n);}finally{Kt=e==="#memo\u7231";}}if(Kt===false)throw new Error("This environment does not support encryption.")},so=e=>typeof e=="string"?V.fromString(e):e,Hs=e=>typeof e=="string"?Z.fromString(e):e,ao={decode:oo,encode:no};var ie={};At(ie,{buildWitnessSetProperties:()=>Ws,makeBitMaskFilter:()=>Ls,operations:()=>js,validateUsername:()=>Vs});var Vs=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("."),o=n.length;for(let i=0;ie.reduce($s,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),$s=([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 o;switch(n){case "key":case "new_signing_key":o=me.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":o=me.UInt32;break;case "hbd_interest_rate":o=me.UInt16;break;case "url":o=me.String;break;case "hbd_exchange_rate":o=me.Price;break;case "account_creation_fee":o=me.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,Gs(o,t[n])]);}return r.props.sort((n,o)=>n[0].localeCompare(o[0])),["witness_set_properties",r]},Gs=(e,t)=>{let r=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);return e(r,t),r.flip(),bytesToHex(new Uint8Array(r.toBuffer()))};function wg(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|o&63);else if(o>=55296&&o<=56319&&n+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else r.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(r);}else t=e;return sha256(t)}function co(e){try{return V.fromString(e),!0}catch{return false}}async function re(e,t){let r=new Me;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),We("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function uo(e,t){let r=new Me;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var Js=432e3;function po(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/Js,o=Math.round(n/e*1e4);return !isFinite(o)||o<0?o=0:o>1e4&&(o=1e4),{current_mana:n,max_mana:e,percentage:o}}function Ys(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),o=parseFloat(e.vesting_withdraw_rate),i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t-s-r+n}function Pr(e){let t=Ys(e)*1e6;return po(t,e.voting_manabar)}function Bt(e){return po(Number(e.max_rc),e.rc_manabar)}var lo=(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))(lo||{});function Ge(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",o=t||r||String(e||""),i=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||o&&a.test(o));if(i(/please wait to transact/i)||i(/insufficient rc/i)||i(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(i(/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(i(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(i(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(i(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(i(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(i(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(i(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(i(/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(i(/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(i(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(i(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(i(/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"||i(/token expired/i)||i(/invalid token/i)||i(/\bunauthorized\b/i)||i(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(i(/has already reblogged/i)||i(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(i(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(i(/econnrefused/i)||i(/connection refused/i)||i(/failed to fetch/i)||i(/\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(i(/timeout/i)||i(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(i(/account.*does not exist/i)||i(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(i(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(i(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(i(/\b(invalid|validation)\b/i))return {message:(e?.message||o).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}`:o&&o!=="[object Object]"?s=o.substring(0,150):s="Unknown error occurred":s=o.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function Xs(e){let t=Ge(e);return [t.message,t.type]}function Pe(e){let{type:t}=Ge(e);return t==="missing_authority"||t==="token_expired"}function Zs(e){let{type:t}=Ge(e);return t==="insufficient_resource_credits"}function ea(e){let{type:t}=Ge(e);return t==="info"}function ta(e){let{type:t}=Ge(e);return t==="network"||t==="timeout"}async function Ae(e,t,r,n,o="posting",i,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=i;if(p===void 0)switch(o){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 ${o} key available for ${t}`);let l=V.fromString(p);return a==="async"?await uo(r,l):await re(r,l)}case "hiveauth":{if(!c?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await c.broadcastWithHiveAuth(t,r,o)}case "hivesigner":{if(!c)throw new Error("No adapter provided for HiveSigner auth");if(o!=="posting"){if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);throw new Error(`HiveSigner access token cannot sign ${o} operations. No platform broadcast available.`)}let p=s!==void 0?s:await c.getAccessToken(t);if(p)try{return (await new fo.Client({accessToken:p}).broadcast(r)).result}catch(l){if(c.broadcastWithHiveSigner&&Pe(l))return await c.broadcastWithHiveSigner(t,r,o);throw l}if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);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,o)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,o)}default:throw new Error(`Unknown auth method: ${e}`)}}async function na(e,t,r,n="posting",o="async"){let i=r?.adapter;if(i?.getLoginType){let l=await i.getLoginType(e,n);if(l){let d=i.hasPostingAuthorization?await i.hasPostingAuthorization(e):false;if(n==="posting"&&d&&l==="key")try{return await Ae("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!Pe(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&d&&l==="keychain")try{return await Ae("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!Pe(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to keychain/snap:",m);}if(n==="posting"&&d&&l==="hiveauth")try{return await Ae("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!Pe(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await Ae(l,e,t,r,n,void 0,void 0,o)}catch(m){if(Pe(m)&&i.showAuthUpgradeUI&&(n==="posting"||n==="active")){let g=t.length>0?t[0][0]:"unknown",h=await i.showAuthUpgradeUI(n,g);if(!h)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await Ae(h,e,t,r,n,void 0,void 0,o)}throw m}}if(n==="posting")try{return await Ae("hivesigner",e,t,r,n,void 0,void 0,o)}catch(d){if(Pe(d)&&i.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",g=await i.showAuthUpgradeUI(n,m);if(!g)throw new Error(`No login type available for ${e}. Please log in again.`);return await Ae(g,e,t,r,n,void 0,void 0,o)}throw d}else if(n==="active"&&i.showAuthUpgradeUI){let d=t.length>0?t[0][0]:"unknown",m=await i.showAuthUpgradeUI(n,d);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await Ae(m,e,t,r,n,void 0,void 0,o)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let d=!1,m="",g,h;switch(l){case "key":if(!i)d=!0,m="No adapter provided";else {let A;switch(n){case "owner":i.getOwnerKey&&(A=await i.getOwnerKey(e));break;case "active":i.getActiveKey&&(A=await i.getActiveKey(e));break;case "memo":i.getMemoKey&&(A=await i.getMemoKey(e));break;default:A=await i.getPostingKey(e);break}A?g=A:(d=!0,m=`No ${n} key available`);}break;case "hiveauth":i?.broadcastWithHiveAuth||(d=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!i)d=!0,m="No adapter provided";else {let A=await i.getAccessToken(e);A&&(h=A);}break;case "keychain":i?.broadcastWithKeychain||(d=!0,m="Keychain not supported by adapter");break;case "custom":r?.broadcast||(d=!0,m="No custom broadcast function provided");break}if(d){a.set(l,new Error(`Skipped: ${m}`));continue}return await Ae(l,e,t,r,n,g,h,o)}catch(d){if(a.set(l,d),!Pe(d))throw d}if(!Array.from(a.values()).some(l=>!l.message.startsWith("Skipped:"))){let l=Array.from(a.entries()).map(([d,m])=>`${d}: ${m.message}`).join(", ");throw new Error(`[SDK][Broadcast] No auth methods attempted for ${e}. ${l}`)}let p=Array.from(a.entries()).map(([l,d])=>`${l}: ${d.message}`).join(", ");throw new Error(`[SDK][Broadcast] All auth methods failed for ${e}. Errors: ${p}`)}function v(e=[],t,r,n=()=>{},o,i="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(o?.enableFallback!==!1&&o?.adapter)return await na(t,p,o,i,a);if(o?.broadcast)return await o.broadcast(p,i);let l=o?.postingKey;if(l){if(i!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${i}' was requested. Use AuthContextV2 with an adapter for ${i} operations.`);let m=V.fromString(l);return await re(p,m)}let d=o?.accessToken;if(d)return (await new fo.Client({accessToken:d}).broadcast(p)).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}catch(l){throw l instanceof te?new Error(l.message):l}}})}async function mo(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let o={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",o]],"posting");let i=n?.postingKey;if(i){let c=V.fromString(i);return re([["custom_json",o]],c)}let s=n?.accessToken;if(s)return (await new fo.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let c=[["custom_json",o]];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 Kg=4e3;function S(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function Oe(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,o=()=>{let i=t.aborted?t.reason:r.reason;n.abort(i),t.removeEventListener("abort",o),r.removeEventListener("abort",o);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",o,{once:true}),r.addEventListener("abort",o,{once:true})),n.signal}var Ne=(()=>{try{return !1}catch{return false}})(),sa=()=>{try{return ""}catch{return}},xe=1e4,go=120*1e3,Mt,aa;function ca(){return Mt?Mt():aa??(aa=new QueryClient)}var f={privateApiHost:"https://ecency.com",defaultObserver:"ecency",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return E.nodes},heliusApiKey:sa(),get queryClient(){return ca()},set queryClient(e){Mt=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false},N;(le=>{function e(O){f.queryClient=O;}le.setQueryClient=e;function t(O){Mt=O;}le.setQueryClientResolver=t;function r(O){f.privateApiHost=O;}le.setPrivateApiHost=r;function n(O){f.clientId=O;}le.setClientId=n;function o(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.");f.defaultObserver=O;}le.setDefaultObserver=o;function i(){return f.privateApiHost?f.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}le.getValidatedBaseUrl=i;function s(O){f.pollsApiHost=O;}le.setPollsApiHost=s;function a(O){f.imageHost=O;}le.setImageHost=a;function c(O){sr(O);}le.setHiveNodes=c;function p(O){ar(O);}le.setRestNodes=p;function l(O){cr(O);}le.setRestNodesByApi=l;function d(O){ur(O);}le.setUserAgent=d;function m(O){pr(O);}le.setResilience=m;function g(O){or(O);}le.setServerRpcProxy=g;function h(){return Te}le.getServerRpcProxyStats=h;function A(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 G=/\.?\{(\d+),(\d+)\}/g,H;for(;(H=G.exec(O))!==null;){let[,U,Y]=H;if(parseInt(Y,10)-parseInt(U,10)>1e3)return {safe:false,reason:`excessive range: {${U},${Y}}`}}return {safe:true}}function x(O){let G=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],H=5;for(let U of G){let Y=Date.now();try{O.test(U);let W=Date.now()-Y;if(W>H)return {safe:!1,reason:`runtime test exceeded ${H}ms (took ${W}ms on input length ${U.length})`}}catch(W){return {safe:false,reason:`runtime test threw error: ${W}`}}}return {safe:true}}function F(O,G=200){try{if(!O)return Ne&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(O.length>G)return Ne&&console.warn(`[SDK] DMCA pattern rejected: length ${O.length} exceeds max ${G} - pattern: ${O.substring(0,50)}...`),null;let H=A(O);if(!H.safe)return Ne&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${H.reason}) - pattern: ${O.substring(0,50)}...`),null;let U;try{U=new RegExp(O);}catch(W){return Ne&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${O.substring(0,50)}...`,W),null}let Y=x(U);return Y.safe?U:(Ne&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${Y.reason}) - pattern: ${O.substring(0,50)}...`),null)}catch(H){return Ne&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${O.substring(0,50)}...`,H),null}}function I(O={}){let G=W=>Array.isArray(W)?W.filter(ot=>typeof ot=="string"):[],H=O||{},U={accounts:G(H.accounts),tags:G(H.tags),patterns:G(H.posts)};f.dmcaAccounts=U.accounts,f.dmcaTags=U.tags,f.dmcaPatterns=U.patterns,f.dmcaTagRegexes=U.tags.map(W=>F(W)).filter(W=>W!==null),f.dmcaPatternRegexes=[];let Y=U.tags.length-f.dmcaTagRegexes.length;!f._dmcaInitialized&&Ne&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${U.accounts.length}`),console.log(` - Tag patterns: ${f.dmcaTagRegexes.length}/${U.tags.length} compiled (${Y} rejected)`),console.log(` - Post patterns: ${U.patterns.length} (using exact string matching)`),Y>0&&console.warn(`[SDK] ${Y} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),f._dmcaInitialized=true;}le.setDmcaLists=I;})(N||(N={}));function Gg(){return new QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var w=()=>f.queryClient,yo;(s=>{function e(a){return w().getQueryData(a)}s.getQueryData=e;function t(a){return w().getQueryData(a)}s.getInfiniteQueryData=t;async function r(a){return await w().prefetchQuery(a),e(a.queryKey)}s.prefetchQuery=r;async function n(a){return await w().prefetchInfiniteQuery(a),t(a.queryKey)}s.prefetchInfiniteQuery=n;function o(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>useQuery(a),fetchAndGet:()=>w().fetchQuery(a)}}s.generateClientServerQuery=o;function i(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>useInfiniteQuery(a),fetchAndGet:()=>w().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=i;})(yo||(yo={}));function Jg(e){return btoa(JSON.stringify(e))}function Yg(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var ho=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(ho||{}),Nt=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(Nt||{});function C(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:ho[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:Nt[e.nai]}}var Ar;function _(){if(!Ar){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");Ar=globalThis.fetch.bind(globalThis);}return Ar}function _o(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function da(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function ce(e,t){return da(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function ze(e,t){return e/1e6*t}function bo(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var wo=60*1e3;function Ee(){return queryOptions({queryKey:u.core.dynamicProps(),refetchInterval:wo,staleTime:wo,queryFn:async({signal:e})=>{let[t,r,n,o,i]=await Promise.all([y("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),y("condenser_api.get_feed_history",[],void 0,void 0,e),y("condenser_api.get_chain_properties",[],void 0,void 0,e),y("condenser_api.get_reward_fund",["post"],void 0,void 0,e),y("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,d=parseFloat(o.recent_claims),m=C(o.reward_balance).amount,g=Number(t.vote_power_reserve_rate??0),h=o.author_reward_curve??"linear",A=Number(o.content_constant??0),x=String(i.current_hardfork_version??"0.0.0"),F=Number(i.last_hardfork??0),I=t.hbd_print_rate,le=t.hbd_interest_rate,O=t.head_block_number,G=a,H=s,U=C(t.virtual_supply).amount,Y=t.vesting_reward_percent||0,W=n.account_creation_fee;return {hivePerMVests:c,base:p,quote:l,fundRecentClaims:d,fundRewardBalance:m,votePowerReserveRate:g,authorRewardCurve:h,contentConstant:A,currentHardforkVersion:x,lastHardfork:F,hbdPrintRate:I,hbdInterestRate:le,headBlock:O,totalVestingFund:G,totalVestingShares:H,virtualSupply:U,vestingRewardPercent:Y,accountCreationFee:W,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:o,hardforkProps:i}}}})}function fy(e="post"){return queryOptions({queryKey:u.core.rewardFund(e),queryFn:()=>y("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 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,o,i)=>["posts","account-posts-page",e,t,r,n,o,i],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,o,i)=>["posts","posts-ranked-page",e,t,r,n,o,i],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,o,i)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,o,i],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,o,i)=>Qe("search","api",e,t,r,n,o,i)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,o)=>["witnesses","voters",e,t,r,n,o],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 lt(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 by(e){return queryOptions({queryKey:u.ai.prices(),queryFn:async()=>{let r=await _()(f.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 Ay(e,t){return queryOptions({queryKey:u.ai.assistPrices(e),queryFn:async()=>{let n=await _()(f.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 Sy(e,t){return queryOptions({queryKey:u.ai.transcribePrice(e),queryFn:async()=>{let n=await _()(f.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 ba(){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 Ty(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 o=await _()(f.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??ba()})});if(!o.ok){let s=await o.text(),a={};try{a=JSON.parse(s);}catch{}let c=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${o.status}${s?`: ${s}`:""}`);throw c.status=o.status,c.data=a,c}if(o.status===202){let s={};try{s=await o.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await o.json()},onSuccess:()=>{e&&w().invalidateQueries({queryKey:u.points._prefix(e)});}})}function va(){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 Dy(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 o=await _()(f.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:va()})});if(!o.ok){let i=await o.text(),s={};try{s=JSON.parse(i);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${o.status}${i?`: ${i}`:""}`);throw a.status=o.status,a.data=s,a}return await o.json()},onSuccess:r=>{e&&(r.cost>0&&w().invalidateQueries({queryKey:u.points._prefix(e)}),w().invalidateQueries({queryKey:u.ai.assistPrices(e)}));}})}function Aa(){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 Ny(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 o=new FormData;o.append("code",n),o.append("duration_ms",String(Math.round(r.durationMs))),o.append("idempotency_key",r.idempotency_key??Aa()),o.append("audio",r.audio,r.fileName??"clip.webm");let s=await _()(f.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:o});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&&w().invalidateQueries({queryKey:u.points._prefix(e)}),w().invalidateQueries({queryKey:u.ai.transcribePrice(e)}));}})}function Or(e){return !e.posting_json_metadata&&!e.json_metadata}function xa(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([y("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),y("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 o=r[0];if(Or(o)&&xa(n?.metadata?.profile)){let p=await y("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!Or(l[0])));if(p[0]&&!Or(p[0]))o=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let i=He(o.posting_json_metadata),s=n?.stats,a=s?{account:o.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,c=n?.reputation??0;return {name:o.name,owner:o.owner,active:o.active,posting:o.posting,memo_key:o.memo_key,post_count:o.post_count,created:o.created,posting_json_metadata:o.posting_json_metadata,last_vote_time:o.last_vote_time,last_post:o.last_post,json_metadata:o.json_metadata,reward_hive_balance:o.reward_hive_balance,reward_hbd_balance:o.reward_hbd_balance,reward_vesting_hive:o.reward_vesting_hive,reward_vesting_balance:o.reward_vesting_balance,balance:o.balance,hbd_balance:o.hbd_balance,savings_balance:o.savings_balance,savings_hbd_balance:o.savings_hbd_balance,savings_hbd_last_interest_payment:o.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:o.savings_hbd_seconds_last_update,savings_hbd_seconds:o.savings_hbd_seconds,next_vesting_withdrawal:o.next_vesting_withdrawal,pending_claimed_accounts:o.pending_claimed_accounts,vesting_shares:o.vesting_shares,delegated_vesting_shares:o.delegated_vesting_shares,received_vesting_shares:o.received_vesting_shares,vesting_withdraw_rate:o.vesting_withdraw_rate,to_withdraw:o.to_withdraw,withdrawn:o.withdrawn,witness_votes:o.witness_votes,proxy:o.proxy,recovery_account:o.recovery_account,proxied_vsf_votes:o.proxied_vsf_votes,voting_manabar:o.voting_manabar,voting_power:o.voting_power,downvote_manabar:o.downvote_manabar,follow_stats:a,reputation:c,profile:i}},enabled:!!e,staleTime:6e4})}var Ea=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 vo(e,t){let r={...e};for(let n of Object.keys(t)){if(Ea.has(n))continue;let o=t[n],i=r[n];Qt(o)&&Qt(i)?r[n]=vo(i,o):r[n]=o;}return r}function Sa(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:o,...i}=t;return {...r,meta:i}})}function He(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 Po(e){return He(e?.posting_json_metadata)}function Ao(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(He(e.posting_json_metadata)).length;return Object.keys(He(t.posting_json_metadata)).length>r?t:e}function ka(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 Oo({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=ka(e),o=Qt(n.profile)?n.profile:{},i=xr({existingProfile:o,profile:t,tokens:r});return JSON.stringify({...n,profile:i})}function xr({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:o,...i}=t??{},s=vo(e??{},i);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=Sa(s.tokens),s.version=2,s}function Ht(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=He(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let o=JSON.parse(t.json_metadata||"{}");o.profile&&(n=o.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function Ca(e){return new TextEncoder().encode(e).length}function Je(e){return e?Ca(e)<=16:false}function th(e){return queryOptions({queryKey:u.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(Je);if(t.length===0)return [];let r=await y("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return Ht(r??[])}})}function sh(e){return queryOptions({queryKey:u.accounts.followCount(e),queryFn:()=>y("condenser_api.get_follow_count",[e])})}function lh(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.followers(e,t,r,n),queryFn:()=>y("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function yh(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.following(e,t,r,n),queryFn:()=>y("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var xo=1e3,Da=20;function vh(e){return queryOptions({queryKey:u.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(i[0]===r&&(i=i.slice(1)),!i.length||(t.push(...i),o.lengthJe(e)?y("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function Fh(e,t=5,r=[]){return queryOptions({queryKey:u.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await y("condenser_api.lookup_accounts",[e,t])).filter(o=>r.length>0?!r.includes(o):true)})}var Na=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function Kh(e,t){return queryOptions({queryKey:u.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await _()(f.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 o=await n.json(),i=Array.isArray(o)?o.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={},d=typeof a.address=="string"&&a.address?a.address:void 0,g=(typeof a.status=="number"?a.status===3:void 0)??false;d&&(l.address=d),l.show=g;let h={symbol:c,currency:c,address:d,show:g,type:"CHAIN",meta:l},A=[];for(let[x,F]of Object.entries(p))typeof x=="string"&&(Na.has(x)||typeof F!="string"||!F||/^[A-Z0-9]{2,10}$/.test(x)&&A.push({symbol:x,currency:x,address:F,show:g,type:"CHAIN",meta:{address:F,show:g}}));return [h,...A]}):[];return {exist:i.length>0,tokens:i.length?i:void 0,wallets:i.length?i:void 0}},refetchOnMount:true})}function Eo(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 y("bridge.get_relationship_between_accounts",[e,t])??r}})}function Lh(e){return queryOptions({queryKey:u.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await y("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function zh(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 _()(f.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Jh(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 i=await _()(`${f.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch bookmarks: ${i.status}`);let s=await i.json();return ce(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function e_(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 _()(f.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function t_(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 i=await _()(`${f.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch favorites: ${i.status}`);let s=await i.json();return ce(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function i_(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 o=await _()(f.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!o.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${o.status}: ${o.statusText}`);let i=await o.json();if(typeof i!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof i}`);return i}})}function u_(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 _()(f.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function m_(e){return queryOptions({enabled:!!e,queryKey:u.accounts.pendingRecovery(e),queryFn:()=>y("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function w_(e,t=50){return queryOptions({queryKey:u.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!Je(e)?[]:y("condenser_api.get_account_reputations",[e,t])})}var B=ie.operations,So={transfers:[B.transfer,B.transfer_to_savings,B.transfer_from_savings,B.cancel_transfer_from_savings,B.fill_transfer_from_savings,B.recurrent_transfer,B.fill_recurrent_transfer,B.escrow_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]},Ya=Array.from(new Set(Object.values(So).flat()));function Xa(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function Za(e){return e.replace(/_operation$/,"")}function ec(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function tc(e){if(!ec(e))return e;let t=C(e),r=Nt[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function rc(e){let t={};for(let[r,n]of Object.entries(e))t[r]=tc(n);return t}function k_(e,t=20,r=""){let n=r?So[r]:Ya;return infiniteQueryOptions({queryKey:u.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:o,signal:i})=>{if(!e)return {entries:[],currentPage:0};let s=async d=>{let m={"account-name":e,"operation-types":n.join(","),"page-size":t};return d!==null&&(m.page=d),await ne("hafah","/accounts/{account-name}/operations",m,void 0,void 0,i)},a=d=>d.operations_result.map(m=>{let g=Za(m.op.type);return {...rc(m.op.value),num:Xa(m),type:g,timestamp:m.timestamp,trx_id:m.trx_id}}),c=await s(o),p=a(c),l=o??c.total_pages;if(o===null&&p.length1)try{let d=await s(c.total_pages-1);p=[...p,...a(d)],l=c.total_pages-1;}catch(d){if(i?.aborted)throw d}return {entries:p,currentPage:l}},getNextPageParam:o=>{let i=o.currentPage-1;return i>=1?i:void 0}})}function F_(){return queryOptions({queryKey:u.accounts.bots(),queryFn:async()=>{let e=await fetch(f.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 K_(e){return infiniteQueryOptions({queryKey:u.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=N.getValidatedBaseUrl(),o=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&o.searchParams.set("max_id",r.toString());let i=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch referrals: ${i.status}`);return i.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function Q_(e){return queryOptions({queryKey:u.accounts.referralsStats(e),queryFn:async()=>{let t=await fetch(f.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 $_(e,t,r){let{followType:n="blog",limit:o=100,enabled:i=true}=r??{};return infiniteQueryOptions({queryKey:u.accounts.friends(e,t,n,o),initialPageParam:{startFollowing:""},enabled:i,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await y(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,o])).map(g=>t==="following"?g.following:g.follower);return (await y("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(g=>({name:g.name,reputation:g.reputation,active:g.active}))},getNextPageParam:s=>s&&s.length===o?{startFollowing:s[s.length-1].name}:void 0})}var cc=30;function Y_(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 y(`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,cc);return (await y("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 rb(e=20){return infiniteQueryOptions({queryKey:u.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>y("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 cb(e=250){return infiniteQueryOptions({queryKey:u.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>y("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!_o(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function Ye(e,t){return queryOptions({queryKey:u.posts.fragments(e),queryFn:async()=>t?(await _()(f.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function db(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 i=await _()(`${f.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch fragments: ${i.status}`);let s=await i.json();return ce(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function yb(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 _()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function vb(e){return queryOptions({queryKey:u.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>y("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function Eb(e,t,r){return queryOptions({queryKey:u.posts.userPostVote(e,t,r),queryFn:async()=>(await y("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function Tb(e,t){return queryOptions({queryKey:u.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content",[e,t])})}function Kb(e,t){return queryOptions({queryKey:u.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content_replies",{author:e,permlink:t})})}function Hb(e,t){return queryOptions({queryKey:u.posts.postHeader(e,t),queryFn:async()=>y("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function oe(e){return Array.isArray(e)?e.map(t=>ko(t)):ko(e)}function ko(e){if(!e)return e;let t=`@${e.author}/${e.permlink}`;return f.dmcaPatterns.includes(t)||f.dmcaPatternRegexes.some(n=>n.test(t))?{...e,body:"This post is not available due to a copyright/fraudulent claim.",title:""}:e}async function Co(e,t,r){try{let n=await Dt("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 Ro(e,t,r="",n){let o=t?.trim(),i=`/@${e}/${o??""}`;return queryOptions({queryKey:u.posts.entry(i),queryFn:async()=>{if(!o||o==="undefined")return null;let s=await y("bridge.get_post",{author:e,permlink:o,observer:r});if(!s){let c=await Co(e,o,r);if(!c)return null;let p=n!==void 0?{...c,num:n}:c;return oe(p)}let a=n!==void 0?{...s,num:n}:s;return oe(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function ue(e,t,r){return y(`bridge.${e}`,t,void 0,void 0,r)}async function To(e,t,r,n){let{json_metadata:o}=e;if(o?.original_author&&o?.original_permlink&&o.tags?.[0]==="cross-post")try{let i=await wc(o.original_author,o.original_permlink,t,r,n);return i?{...e,original_entry:i,num:r}:e}catch{return e}return {...e,num:r}}async function Fo(e,t,r){let n=e.map(dt),o=await Promise.all(n.map(i=>To(i,t,void 0,r)));return oe(o)}async function Io(e,t="",r="",n=20,o="",i="",s){let a=await ue("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:o,observer:i},s);return Array.isArray(a)?Fo(a,i,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 Er(e,t,r="",n="",o=20,i="",s){if(f.dmcaAccounts.includes(t))return [];let a=await ue("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:o,observer:i},s);return Array.isArray(a)?Fo(a,i,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 dt(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 wc(e="",t="",r="",n,o){let i=await ue("get_post",{author:e,permlink:t,observer:r},o);if(i){let s=dt(i),a=await To(s,r,n,o);return oe(a)}}async function rw(e="",t=""){let r=await ue("get_post_header",{author:e,permlink:t});return r&&dt(r)}async function qo(e,t,r){let n=await ue("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let o={};for(let[i,s]of Object.entries(n))o[i]=dt(s);return o}return n}async function Do(e,t=""){return ue("get_community",{name:e,observer:t})}async function nw(e="",t=100,r,n="rank",o=""){return ue("list_communities",{last:e,limit:t,query:r,sort:n,observer:o})}async function Ko(e){let t=await ue("normalize_post",{post:e});return t&&dt(t)}async function ow(e){return ue("list_all_subscriptions",{account:e})}async function iw(e){return ue("list_subscribers",{community:e})}async function sw(e,t){return ue("get_relationship_between_accounts",[e,t])}async function Ut(e,t){return ue("get_profiles",{accounts:e,observer:t})}var Mo=(o=>(o.trending="trending",o.author_reputation="author_reputation",o.votes="votes",o.created="created",o))(Mo||{});function Sr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function vc(e,t,r){let n=l=>Sr(l.pending_payout_value).amount+Sr(l.author_payout_value).amount+Sr(l.curator_payout_value).amount,o=l=>l.net_rshares<0,i=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,d)=>{if(o(l))return 1;if(o(d))return -1;let m=n(l),g=n(d);return m!==g?g-m:0},author_reputation:(l,d)=>{let m=l.author_reputation,g=d.author_reputation;return m>g?-1:m{let m=l.children,g=d.children;return m>g?-1:m{if(o(l))return 1;if(o(d))return -1;let m=Date.parse(l.created),g=Date.parse(d.created);return m>g?-1:mi(l)),p=a[c];return c>=0&&(a.splice(c,1),a.unshift(p)),a}function No(e,t="created",r=true,n){let o=n||f.defaultObserver;return queryOptions({queryKey:u.posts.discussions(e?.author,e?.permlink,t,o),queryFn:async()=>{if(!e)return [];let i=await y("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:o}),s=i?Array.from(Object.values(i)):[];return oe(s)},enabled:r&&!!e,select:i=>vc(e,i,t),structuralSharing:(i,s)=>{if(!i||!s)return s;let a=i.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 fw(e,t,r,n=true){let o=r||f.defaultObserver;return queryOptions({queryKey:u.posts.discussion(e,t,o),enabled:n&&!!e&&!!t,queryFn:async()=>qo(e,t,o)})}function ww(e,t="posts",r=20,n="",o=true){return infiniteQueryOptions({queryKey:u.posts.accountPosts(e??"",t,r,n),enabled:!!e&&o,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:i,signal:s})=>{if(!i?.hasNextPage||!e)return [];let a=await Er(t,e,i.author??"",i.permlink??"",r,n,s);return oe(a??[])},getNextPageParam:i=>{let s=i?.[i.length-1],a=(i?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function vw(e,t="posts",r="",n="",o=20,i="",s=true){return queryOptions({queryKey:u.posts.accountPostsPage(e??"",t,r,n,o,i),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let c=await Er(t,e,r,n,o,i,a);return oe(c??[])}})}var Qo=new Map;function Ec(e){let t=Qo.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>Sc(n,e))}),Qo.set(e,t)),t}function Sc(e,t){let r=e.filter(i=>i.stats?.is_pinned),n=e.filter(i=>!i.stats?.is_pinned);if(t==="hot")return [...r,...n];let o=[...n].sort((i,s)=>new Date(s.created).getTime()-new Date(i.created).getTime());return [...r,...o]}function Cw(e,t,r=20,n="",o=true,i={}){return infiniteQueryOptions({queryKey:u.posts.postsRanked(e,t,r,n),queryFn:async({pageParam:s,signal:a})=>{let c=t;f.dmcaTagRegexes.some(l=>l.test(t))&&(c="");let p=await y("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 oe(p)},select:Ec(e),enabled:o,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 Rw(e,t="",r="",n=20,o="",i="",s=true){return queryOptions({queryKey:u.posts.postsRankedPage(e,t,r,n,o,i),enabled:s,queryFn:async({signal:a}={})=>{let c=o;f.dmcaTagRegexes.some(l=>l.test(o))&&(c="");let p=await Io(e,t,r,n,c,i,a);return oe(p??[])}})}function Dw(e,t,r=200){return queryOptions({queryKey:u.posts.reblogs(e??"",r),queryFn:async()=>(await y("condenser_api.get_blog_entries",[e??t,0,r])).filter(o=>o.author!==t&&!o.reblogged_on.startsWith("1970-")).map(o=>({author:o.author,permlink:o.permlink})),enabled:!!e})}function Qw(e,t){return queryOptions({queryKey:u.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await y("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function jw(e,t){return queryOptions({queryKey:u.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(f.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 Lw(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 i=await _()(`${f.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch schedules: ${i.status}`);let s=await i.json();return ce(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function zw(e,t){return queryOptions({queryKey:u.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(f.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 Jw(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 i=await _()(`${f.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch drafts: ${i.status}`);let s=await i.json();return ce(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function Uo(e){let r=await _()(f.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 ev(e,t){return queryOptions({queryKey:u.posts.images(e),queryFn:async()=>!e||!t?[]:Uo(t),enabled:!!e&&!!t})}function tv(e,t){return queryOptions({queryKey:u.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:Uo(t),enabled:!!e&&!!t})}function rv(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 i=await _()(`${f.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch images: ${i.status}`);let s=await i.json();return ce(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function sv(e,t,r=false){return queryOptions({queryKey:u.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let o=await fetch(f.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(!o.ok)throw new Error(`Failed to fetch comment history: ${o.status}`);return o.json()},enabled:!!e&&!!t})}function Bc(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let o=r.replace(/^@+/,""),i=n.replace(/^\/+/,"");if(!o||!i)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${o}/${i}`}function pv(e,t){let r=t?.trim(),n=e?.trim(),o=!!n&&!!r&&r!=="undefined",i=o?Bc(n,r):"";return queryOptions({queryKey:u.posts.deletedEntry(i),queryFn:async({signal:s})=>{let a=await fetch(f.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:o})}function mv(e,t,r=true){return queryOptions({queryKey:u.posts.tips(e,t),queryFn:async()=>{let n=`/private-api/post-tips/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,o=await fetch(f.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch post tips: ${o.status}`);return o.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function Nc(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function Qc(e){return {...e,id:e.id??e.post_id}}function be(e,t){if(!e)return null;let r=e.container??e,n=Nc(r,t),o=e.parent?Qc(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:o}}function Hc(e){return Array.isArray(e)?e:[]}async function Vo(e){let t=No(e,"created",true),r=await f.queryClient.fetchQuery(t),n=Hc(r);if(n.length<=1)return [];let o=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return o.length===0?[]:o.filter(s=>!s.stats?.gray)}function jo(e,t,r){return e.length===0?[]:e.map(n=>{let o=e.find(i=>i.author===n.parent_author&&i.permlink===n.parent_permlink&&i.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:o}}).filter(n=>n.container.post_id!==n.post_id).sort((n,o)=>new Date(o.created).getTime()-new Date(n.created).getTime())}var jc=20;function Lo(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??jc}}async function $o({containers:e,tag:t,following:r,author:n,observer:o,limit:i},s,a){let c=N.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",c);p.searchParams.set("limit",String(i)),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),o&&p.searchParams.set("observer",o);let l=await fetch(p.toString(),{method:"GET",signal:a});if(!l.ok)throw new Error(`Failed to fetch waves feed: ${l.status}`);let d=await l.json();return !Array.isArray(d)||d.length===0?[]:d.map(m=>{let g=be(m,m.host??"");return g?{...g,_cursor:m._cursor}:null}).filter(m=>!!m)}function Pv(e={}){let t=Lo(e),{containers:r,tag:n,following:o,author:i,observer:s,limit:a}=t;return infiniteQueryOptions({queryKey:u.posts.wavesFeed({containers:r,tag:n,following:o,author:i,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:c,signal:p})=>$o(t,c,p),getNextPageParam:c=>{if(!(c.length$o(t,void 0,c)})}var $c=20;function Wc(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??$c}}async function Gc({containers:e,tag:t,author:r,observer:n,limit:o},i,s){let a=N.getValidatedBaseUrl(),c=new URL("/private-api/waves/shorts",a);c.searchParams.set("limit",String(o)),i&&c.searchParams.set("cursor",i),e.forEach(d=>c.searchParams.append("container",d)),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(d=>{let m=be(d,d.host??"");return m?{...m,active_votes:m.active_votes??[],video:d.video,_cursor:d._cursor}:null}).filter(d=>!!d)}function kv(e={}){let t=Wc(e),{containers:r,tag:n,author:o,observer:i,limit:s}=t;return infiniteQueryOptions({queryKey:u.posts.shortsFeed({containers:r,tag:n,author:o,observer:i,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:c})=>Gc(t,a,c),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of c){if(i&&l.post_id===i){i=void 0;continue}if(o+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let d;try{d=await Vo(l);}catch(m){console.error("[SDK] getThreads get_discussion error:",m),r=l.author,n=l.permlink;continue}if(d.length===0){r=l.author,n=l.permlink;continue}return {entries:jo(d,l,e)}}let p=c[c.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function Dv(e){return infiniteQueryOptions({queryKey:u.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await Xc(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var eu=40;function Qv(e,t,r=eu){return infiniteQueryOptions({queryKey:u.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/tags",o);i.searchParams.set("container",e),i.searchParams.set("tag",t);let s=await fetch(i.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=>be(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves by tag",o),[]}},getNextPageParam:()=>{}})}function Lv(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 o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/following",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>be(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves following feed",o),[]}},getNextPageParam:()=>{}})}function zv(e,t=24){let r=e?.trim()||void 0;return queryOptions({queryKey:u.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/trending/tags",o);r&&i.searchParams.set("container",r),i.searchParams.set("hours",t.toString());let s=await fetch(i.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(o){return console.error("[SDK] Failed to fetch waves trending tags",o),[]}}})}function e0(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 o=N.getValidatedBaseUrl(),i=new URL("/private-api/waves/account",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>be(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){throw console.error("[SDK] Failed to fetch waves for account",o),o}},getNextPageParam:()=>{}})}function o0(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 o=await fetch(n.toString(),{method:"GET",signal:t});if(!o.ok)throw new Error(`Failed to fetch waves trending authors: ${o.status}`);return (await o.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 u0(e,t=true){return queryOptions({queryKey:u.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>Ko(e)})}function au(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Wo(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function h0(e,t){let{limit:r=20,filters:n=[],dayLimit:o=7}=t??{};return infiniteQueryOptions({queryKey:u.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:i})=>{let{start:s}=i,a=await y("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,g])=>({...g.op[1],num:m,timestamp:g.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Wo(m.timestamp)<=o),l=[];for(let m of p){let g=await f.queryClient.fetchQuery(Ro(m.author,m.permlink));au(g)&&l.push(g);}let[d]=a;return {lastDate:d?Wo(d[1].timestamp):0,lastItemFetched:d?d[0]:s,entries:l}},getNextPageParam:i=>({start:i.lastItemFetched})})}function P0(e,t,r=true){return queryOptions({queryKey:u.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Ut(e,t)})}function k0(e,t="HIVE",r=200){return infiniteQueryOptions({queryKey:u.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:o})=>{if(!e)return {entries:[],currentPage:0};let i={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(i.page=n);let s=await ne("balance","/accounts/{account-name}/balance-history",i,void 0,void 0,o);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let o=n.currentPage-1;return o>=1?o:void 0},enabled:!!e})}function I0(e,t="HIVE",r="yearly"){return queryOptions({queryKey:u.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await ne("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function B0(){return queryOptions({queryKey:u.accounts.proMembers(),queryFn:async()=>{let e=await fetch(f.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 M0(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function j0(e,t,r){let n=useQueryClient(),{data:o}=useQuery(Q(e));return v(["accounts","update"],e,i=>{let s=Ao(n.getQueryData(Q(e).queryKey),o);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:Oo({existingPostingJsonMetadata:s.posting_json_metadata,profile:i.profile,tokens:i.tokens})}]]},async(i,s)=>{n.setQueryData(Q(e).queryKey,a=>{if(!a)return a;let c=JSON.parse(JSON.stringify(a));return c.profile=xr({existingProfile:Po(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({...Q(e),staleTime:0});}catch{}}})}function z0(e,t,r,n,o){return useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async i=>{let s=Eo(e,t);await w().prefetchQuery(s);let a=w().getQueryData(s.queryKey);return await mo(e,"follow",["follow",{follower:e,following:t,what:[...i==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...i==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:i==="toggle-ignore"?!a?.ignores:a?.ignores,follows:i==="toggle-follow"?!a?.follows:a?.follows}},onError:o,onSuccess(i){n(i),w().setQueryData(u.accounts.relations(e,t),i),t&&w().invalidateQueries(Q(t));}})}function kr(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 Ue(e,t,r,n,o,i,s){if(!e||!t||n===void 0||!i)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:o,body:i,json_metadata:JSON.stringify(s)}]}function Ve(e,t,r,n,o,i,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:o,allow_curation_rewards:i,extensions:s}]}function Cr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function Rr(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let o={account:e,author:t,permlink:r};return n&&(o.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",o]),required_auths:[],required_posting_auths:[e]}]}function je(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 gu(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(i=>je(e,i.trim(),r,n))}function yu(e,t,r,n,o,i){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(o<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:o,executions:i,extensions:[]}]}function Xe(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 Le(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:o}]}function Go(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 ft(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [Le(e,t,r,n,o),Go(e,o)]}function mt(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 gt(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function yt(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 ht(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 _t(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 Tr(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 $e(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 Fr(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function Ir(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(o=>o.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 qr(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 Vt(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 hu(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 _u(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return Vt(e,t)}function Dr(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]}],o=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,o]}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 Br(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function Mr(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 Nr(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 bu(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,o){if(e==null||typeof e!="number"||!t||!r||!n||!o)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:o,extensions:[]}]}function Qr(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 Hr(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 Ur(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 Vr(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 jr(e,t,r,n,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function Lr(e,t,r,n,o,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:o}]),required_auths:[],required_posting_auths:[e]}]}function vu(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function Pu(e,t,r,n,o){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:o}]),required_auths:[],required_posting_auths:[e]}]}var zo=(r=>(r.Buy="buy",r.Sell="sell",r))(zo||{}),Jo=(r=>(r.EMPTY="",r.SWAP="9",r))(Jo||{});function Lt(e,t,r,n,o,i){if(!e||!t||!r||!o||i===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:i,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:o}]}function jt(e,t=3){return e.toFixed(t)}function Au(e,t,r,n,o=""){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 i=new Date(Date.now());i.setDate(i.getDate()+27);let s=i.toISOString().split(".")[0],a=+`${o}${Math.floor(Date.now()/1e3).toString().slice(2)}`,c=n==="buy"?`${jt(t,3)} HBD`:`${jt(t,3)} HIVE`,p=n==="buy"?`${jt(r,3)} HIVE`:`${jt(r,3)} HBD`;return Lt(e,c,p,false,s,a)}function $r(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function Wr(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,o,i){if(!e||!o)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:o,json_metadata:i}]}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 Gr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let o={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={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:o,active:i,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function zr(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]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},i={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:o,posting:i,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Jr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function Yr(e,t,r,n,o,i){if(!e||!t||!r||!o)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:o,json_metadata:i}]}function Eu(e,t,r,n,o){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let i={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:i,memo_key:n,json_metadata:o}]}function Su(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 ku(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 Cu(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 Xr(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 Zr(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 en(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 Ze(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let o=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:o,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function Ru(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let o=t.trim().split(/[\s,]+/).filter(Boolean);if(o.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return o.map(i=>Ze(e,i.trim(),r,n))}function tn(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 Tu(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 yP(e,t,r){return v(["accounts","follow"],e,({following:n})=>[qr(e,n)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function wP(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[Vt(e,n)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function OP(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:o,permlink:i})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(f.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:o,permlink:i,code:t})})).json()},onSuccess:()=>{r(),w().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function kP(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(f.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:o,code:t})})).json()},onSuccess:()=>{r(),w().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function FP(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await _()(f.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})})).json()},onSuccess:(o,i)=>{r();let s=w();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,i)});},onError:n})}function BP(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await _()(f.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async o=>{if(!e)return;let i=w(),s=u.accounts.favorites(e),a=u.accounts.favoritesInfinite(e),c=u.accounts.checkFavorite(e,o);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a}),i.cancelQueries({queryKey:c})]);let p=i.getQueryData(s);p&&i.setQueryData(s,p.filter(g=>g.account!==o));let l=i.getQueryData(c);i.setQueryData(c,false);let d=i.getQueriesData({queryKey:a}),m=new Map(d);for(let[g,h]of d)h&&i.setQueryData(g,{...h,pages:h.pages.map(A=>({...A,data:A.data.filter(x=>x.account!==o)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(o,i)=>{r();let s=w();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,i)});},onError:(o,i,s)=>{let a=w();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,i),s.previousCheck),n(o);}})}function Nu(e,t){let r=new Map;return e.forEach(([n,o])=>{r.set(n.toString(),o);}),t.forEach(([n,o])=>{r.set(n.toString(),o);}),Array.from(r.entries()).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>[n,o])}function Yo(e,t){let{data:r}=useQuery(Q(e));return useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:o=false,currentKey:i,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:[]],g=o?l.key_auths.filter(([h])=>!m.includes(h.toString())):[];return l.key_auths=Nu(g,n.map((h,A)=>[h[p].createPublic().toString(),A+1])),l};return re([["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()}]],i)},...t})}function WP(e,t){let{data:r}=useQuery(Q(e)),{mutateAsync:n}=Yo(e);return useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:o,currentPassword:i,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=V.fromLogin(e,i,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:V.fromLogin(e,o,"owner"),active:V.fromLogin(e,o,"active"),posting:V.fromLogin(e,o,"posting"),memo_key:V.fromLogin(e,o,"memo")}]})},...t})}function ZP(e,t,r){let n=useQueryClient(),{data:o}=useQuery(Q(e));return useMutation({mutationKey:["accounts","revoke-posting",o?.name],mutationFn:async({accountName:i,type:s,key:a})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let c=JSON.parse(JSON.stringify(o.posting));c.account_auths=c.account_auths.filter(([l])=>l!==i);let p={account:o.name,posting:c,memo_key:o.memo_key,json_metadata:o.json_metadata};if(s==="key"&&a)return re([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(o.name,[["account_update",p]],"active")}else return t.hsCallbackUrl,fo.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(i,s,a)=>{t.onSuccess?.(i,s,a),n.setQueryData(Q(e).queryKey,c=>({...c,posting:{...c?.posting,account_auths:c?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function sA(e,t,r,n){let{data:o}=useQuery(Q(e));return useMutation({mutationKey:["accounts","recovery",o?.name],mutationFn:async({accountName:i,type:s,key:a,email:c})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:o.name,new_recovery_account:i,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let d=await _()(f.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:c,publicKeys:[...o.owner.key_auths,...o.active.key_auths,...o.posting.key_auths,o.memo_key]})});if(!d.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${d.status}`);return d}else {if(s==="key"&&a)return re([["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(o.name,[["change_recovery_account",p]],"owner")}else return r.hsCallbackUrl,fo.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function cA(e,t){let r=e.key_auths.filter(([o])=>!t.has(String(o))).reduce((o,[,i])=>o+i,0),n=(e.account_auths??[]).reduce((o,[,i])=>o+i,0);return r+n>=e.weight_threshold}function Xo(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),o=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([c])=>!r.has(c.toString())),a},i=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:i?o(e.owner):void 0,active:o(e.active),posting:o(e.posting),memo_key:e.memo_key}}function mA(e,t){let{data:r}=useQuery(Q(e));return useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:o})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let i=Array.isArray(o)?o:[o],s=Xo(r,i);return re([["account_update",s]],n)},...t})}function _A(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:o="0.000 HIVE"})=>[Jr(n,o)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(o.creator)]);},t,"active",{broadcastMode:r})}function PA(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[Yr(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 EA(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?zr(e,n.newAccountName,n.keys):Gr(e,n.newAccountName,n.keys,n.fee)],async()=>{await S(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}var rn=300*60*24,Yu=1e4,Xu=5e7;function Zo(e){let t=C(e.vesting_shares).amount,r=C(e.received_vesting_shares).amount,n=C(e.delegated_vesting_shares).amount,o=C(e.vesting_withdraw_rate).amount,i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t+r-n-s}function Zu(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function ep(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 tp(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 o=Zo(e);if(!Number.isFinite(o)||o<=0)return 0;let i=o*1e6,s=Math.ceil(i*r*60*60*24/Yu/(n*rn)),a=Pr(e),c=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(c)||s>c?0:Math.max(s-Xu,0)}function rp(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(ep(t))return tp(e,t,n);let o=0;try{if(o=Zo(e),!Number.isFinite(o))return 0}catch{return 0}return Zu(o,r,n)}function RA(e){return Pr(e).percentage/100}function TA(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*rn/1e4}function FA(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 o=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/rn;o>n&&(o=n);let i=o*100/n;return isNaN(i)?0:i>100?100:i}function IA(e){return Bt(e).percentage/100}function qA(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:o,fundRewardBalance:i,base:s,quote:a}=t;if(!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(a)||o===0||a===0)return 0;let c=rp(e,t,r,n);return Number.isFinite(c)?c/o*i*(s/a):0}var np={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 op(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 ip(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function sp(e){let t=e[0];return t==="custom_json"?op(e):t==="create_proposal"||t==="update_proposal"?ip(e):np[t]??"posting"}function KA(e){let t="posting";for(let r of e){let n=sp(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function HA(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=V.fromLogin(e,r,"active"):co(r)?n=V.fromString(r):n=V.from(r),re([t],n)}})}function jA(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 GA(e="/"){return useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>fo.sendOperation(t,{callback:e},()=>{})})}function XA(){return queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await y("condenser_api.get_chain_properties",[])})}function ei(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function ti(e,t){return {...e??{},title:t.title,body:t.body}}function sO(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 i=await _()(f.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${i.status}`);return i.json()},onSuccess(r,n){let o=w(),i=ti(r,n);o.setQueryData(Ye(e,t).queryKey,s=>[i,...s??[]]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,c)=>c===0?{...a,data:[i,...a.data]}:a)});}})}function fO(e,t){return useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:o})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await _()(f.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:o}),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 o=w(),i=s=>ei(s,r,n);o.setQueryData(Ye(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?i(a):a)??[]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(c=>c.id===n.fragmentId?i(c):c)}))});}})}function bO(e,t){return useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await _()(f.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${o.status}`);return o},onSuccess(r,n){let o=w();o.setQueryData(Ye(e,t).queryKey,i=>[...i??[]].filter(({id:s})=>s!==n.fragmentId)),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},i=>i&&{...i,pages:i.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 PO(e,t,r,n){let i=await _()(f.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(i);return {status:i.status,data:s}}async function AO(e){let r=await _()(f.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 OO(e,t,r="",n=""){let o={code:e,ty:t};r&&(o.bl=r),n&&(o.tx=n);let s=await _()(f.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});await J(s);}async function xO(e,t,r=null,n=null){let o={code:e};t&&(o.filter=t),r&&(o.since=r),n&&(o.user=n);let s=await _()(f.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return J(s)}async function EO(e,t,r,n,o,i){let s={code:e,username:t,token:i,system:r,allows_notify:n,notify_types:o},c=await _()(f.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return J(c)}async function SO(e,t,r){let n={code:e,username:t,token:r},i=await _()(f.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(i)}async function ri(e,t){let r={code:e};t&&(r.id=t);let o=await _()(f.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}async function ni(e,t){let r={code:e,url:t},o=await _()(f.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}var gp="https://i.ecency.com";async function oi(e,t,r){let n=_(),o=new FormData;o.append("file",e);let i=await n(`${gp}/hs/${t}`,{method:"POST",body:o,signal:r});return J(i)}async function kO(e,t,r,n){let o=_(),i=new FormData;i.append("file",e);let s=await o(`${f.imageHost}/${t}/${r}`,{method:"POST",body:i,signal:n});return J(s)}async function ii(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}async function si(e,t,r,n,o){let i={code:e,title:t,body:r,tags:n,meta:o},a=await _()(f.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return J(a)}async function ai(e,t,r,n,o,i){let s={code:e,id:t,title:r,body:n,tags:o,meta:i},c=await _()(f.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return J(c)}async function ci(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}async function ui(e,t,r,n,o,i,s,a){let c={code:e,permlink:t,title:r,body:n,meta:o,schedule:s,reblog:a};i&&(c.options=i);let l=await _()(f.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});return J(l)}async function pi(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}async function li(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}async function CO(e,t,r){let n={code:e,author:t,permlink:r},i=await _()(f.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(i)}async function RO(e,t,r){let n={username:e,email:t,friend:r},i=await _()(f.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(i)}function DO(e,t,r,n){return useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:o,body:i,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return si(t,o,i,s,a)},onSuccess:o=>{r?.();let i=w();o?.drafts?i.setQueryData(u.posts.drafts(e),o.drafts):i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function QO(e,t,r,n){return useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:o,title:i,body:s,tags:a,meta:c})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return ai(t,o,i,s,a,c)},onSuccess:()=>{r?.();let o=w();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function $O(e,t,r,n){return useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return ci(t,o)},onMutate:async({draftId:o})=>{if(!e)return;let i=w(),s=u.posts.drafts(e),a=u.posts.draftsInfinite(e);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a})]);let c=i.getQueryData(s);c&&i.setQueryData(s,c.filter(d=>d._id!==o));let p=i.getQueriesData({queryKey:a}),l=new Map(p);for(let[d,m]of p)m&&i.setQueryData(d,{...m,pages:m.pages.map(g=>({...g,data:g.data.filter(h=>h._id!==o)}))});return {previousList:c,previousInfinite:l}},onSuccess:()=>{r?.();let o=w();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:(o,i,s)=>{let a=w();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?.(o);}})}function YO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:o,title:i,body:s,meta:a,options:c,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return ui(t,o,i,s,a,c,p,l)},onSuccess:()=>{r?.(),w().invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function rx(e,t,r,n){return useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return pi(t,o)},onSuccess:o=>{r?.();let i=w();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function ax(e,t,r,n){return useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return li(t,o)},onSuccess:o=>{r?.();let i=w();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)}),i.invalidateQueries({queryKey:u.posts.drafts(e)});},onError:n})}function dx(e,t,r,n){return useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:o,code:i})=>{let s=i??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return ni(s,o)},onSuccess:()=>{r?.(),w().invalidateQueries({queryKey:u.posts.images(e)});},onError:n})}function hx(e,t,r,n){return useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return ii(t,o)},onSuccess:(o,i)=>{r?.();let s=w(),{imageId:a}=i;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 vx(e,t){return useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:o})=>oi(r,n,o),onSuccess:e,onError:t})}function Wt(e,t){return `/@${e}/${t}`}function xp(e,t,r){return (r??w()).getQueryData(u.posts.entry(Wt(e,t)))}function Ep(e,t){(t??w()).setQueryData(u.posts.entry(Wt(e.author,e.permlink)),e);}function $t(e,t,r,n){let o=n??w(),i=Wt(e,t),s=o.getQueryData(u.posts.entry(i));if(!s)return;let a=r(s);return o.setQueryData(u.posts.entry(i),a),s}var Ie;(a=>{function e(c,p,l,d,m){$t(c,p,g=>({...g,active_votes:l,stats:{...g.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:g.stats?.flag_weight||0},total_votes:l.length,payout:d,pending_payout_value:String(d)}),m);}a.updateVotes=e;function t(c,p,l,d){$t(c,p,m=>({...m,reblogs:l}),d);}a.updateReblogsCount=t;function r(c,p,l,d){$t(c,p,m=>({...m,children:l}),d);}a.updateRepliesCount=r;function n(c,p,l,d){$t(p,l,m=>({...m,children:m.children+1,replies:[c,...m.replies]}),d);}a.addReply=n;function o(c,p){c.forEach(l=>Ep(l,p));}a.updateEntries=o;function i(c,p,l){(l??w()).invalidateQueries({queryKey:u.posts.entry(Wt(c,p))});}a.invalidateEntry=i;function s(c,p,l){return xp(c,p,l)}a.getEntry=s;})(Ie||(Ie={}));function Sp(e,t,r){let n=e.some(o=>o.voter===t);return r!==0?n:!n}function kp(e,t,r){let n=Ie.getEntry(t.author,t.permlink,r);if(!n?.active_votes||Sp(n.active_votes,e,t.weight))return;let o=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],i=n.payout+(t.estimated??0);Ie.updateVotes(t.author,t.permlink,o,i,r);}function kx(e,t,r){return v(["posts","vote"],e,({author:n,permlink:o,weight:i})=>[kr(e,n,o,i)],async(n,o)=>{kp(e,o);let i=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(120,i,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([u.posts.entry(`/@${o.author}/${o.permlink}`),u.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function Ix(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:o,deleteReblog:i})=>[Rr(e,n,o,i??false)],async(n,o)=>{let i=Ie.getEntry(o.author,o.permlink);if(i){let p=Math.max(0,(i.reblogs??0)+(o.deleteReblog?-1:1));Ie.updateReblogsCount(o.author,o.permlink,p);}let s=n?.id??n?.tx_id;t?.adapter?.recordActivity&&s&&t.adapter.recordActivity(130,s,n?.block_num).catch(()=>{});let a=()=>{w().invalidateQueries({queryKey:u.posts.accountPostsBlogPrefix(e)}),t?.adapter?.invalidateQueries&&t.adapter.invalidateQueries([u.posts.entry(`/@${o.author}/${o.permlink}`),u.posts.rebloggedBy(o.author,o.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function Cp(e){return e.isUpdate?null:e.parentAuthor?110:100}function Bx(e,t,r){return v(["posts","comment"],e,n=>{let o=[];if(o.push(Ue(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let d=[...p].sort((m,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:d.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(Ve(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{let i=!o.parentAuthor,s=Cp(o),a=n?.id??n?.tx_id;if(s!==null&&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(!i){c.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let p=o.rootAuthor||o.parentAuthor,l=o.rootPermlink||o.parentPermlink;c.push({predicate:d=>{let m=d.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 Qx(e,t,r,n){let o=n??w(),i=o.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 i)a&&o.setQueryData(s,[e,...a]);}function di(e,t,r,n,o){let i=o??w(),s=new Map,a=i.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),i.setQueryData(c,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function fi(e,t){let r=t??w();for(let[n,o]of e)r.setQueryData(n,o);}function Hx(e,t,r,n){let o=n??w(),i=`/@${e}/${t}`,s=o.getQueryData(u.posts.entry(i));return s&&o.setQueryData(u.posts.entry(i),{...s,...r}),s}function Ux(e,t,r,n){let o=n??w(),i=`/@${e}/${t}`;o.setQueryData(u.posts.entry(i),r);}function Wx(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:o})=>[Cr(n,o)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e)];if(o.parentAuthor&&o.parentPermlink){i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let o=n.rootAuthor||n.parentAuthor,i=n.rootPermlink||n.parentPermlink;return o&&i?{snapshots:di(n.author,n.permlink,o,i)}:{}},onError:(n,o,i)=>{let{snapshots:s}=i??{};s&&fi(s);}})}function Yx(e,t,r){return v(["posts","cross-post"],e,n=>{let o=[];if(o.push(Ue(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true}=n.options;o.push(Ve(n.author,n.permlink,i,s,a,c,[]));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.parentPermlink}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"async"})}function tE(e,t,r){return v(["posts","update-reply"],e,n=>{let o=[];if(o.push(Ue(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let d=[...p].sort((m,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:d.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(Ve(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.resourceCredits.account(e)];i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r})}function iE(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:o,duration:i})=>[en(e,n,o,i)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.posts._promotedPrefix],[...u.points._prefix(e)],u.posts.entry(`/@${o.author}/${o.permlink}`)]);},t,"active",{broadcastMode:r})}var Rp=[3e3,3e3,3e3],Tp=e=>new Promise(t=>setTimeout(t,e));async function Fp(e,t){return y("condenser_api.get_content",[e,t])}async function Ip(e,t,r=0,n){let o=n?.delays??Rp,i;try{i=await Fp(e,t);}catch{i=void 0;}if(i||r>=o.length)return;let s=o[r];return s>0&&await Tp(s),Ip(e,t,r+1,n)}var et={};At(et,{useRecordActivity:()=>nn});function Dp(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function nn(e,t,r){return useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=_(),o=Dp(),i=r?.url??o.url,s=r?.domain??o.domain;try{await n(f.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:i,domain:s,props:{username:e}})});}catch{}}})}function gE(e){return queryOptions({queryKey:["analytics","discover-leaderboard",e],queryFn:async({signal:t})=>{let r=await fetch(f.privateApiHost+`/private-api/leaderboard/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch leaderboard: ${r.status}`);return r.json()}})}function wE(e){return queryOptions({queryKey:["analytics","discover-curation",e],queryFn:async({signal:t})=>{let r=await fetch(f.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(),o=n.map(s=>s.account),i=await y("condenser_api.get_accounts",[o]);for(let s=0;sa.efficiency-s.efficiency),n}})}function OE(e,t=[],r=["visitors","pageviews","visit_duration"],n){let o=[...t].sort(),i=[...r].sort();return queryOptions({queryKey:["analytics","page-stats",e,o,i,n],queryFn:async({signal:s})=>{let a=await fetch(f.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 Gt="threespeakfund",RE=1100;function Np(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function TE(e,t){if(!Np(t))return e;let r=e.find(n=>n.account===Gt);return r&&r.weight===1100?e:r?e.map(n=>n.account===Gt?{...n,weight:1100}:n):[...e,{account:Gt,weight:1100}]}function FE(e){return e===Gt}var an={};At(an,{getAccountTokenQueryOptions:()=>sn,getAccountVideosQueryOptions:()=>Lp});var on={};At(on,{getDecodeMemoQueryOptions:()=>Up});function Up(e,t,r){return queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new fo.Client({accessToken:r}).decode(t)}})}var mi={queries:on};function sn(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"}}),o=mi.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await w().prefetchQuery(o);let{memoDecoded:i}=w().getQueryData(o.queryKey);return i.replace("#","")}})}function Lp(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=sn(e,t);await w().prefetchQuery(r);let n=w().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 zE={queries:an};function tS(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 iS({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:o,enabled:i=true}){return queryOptions({queryKey:["integrations","plausible",e,t,r,n,o],queryFn:async()=>{let a=await _()(`${f.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...o?{date_range:o}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&i,retry:1})}function uS(){return queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await y("rc_api.get_rc_stats",{})).rc_stats})}function fS(e){return queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await y("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}function _S(){return queryOptions({queryKey:u.resourceCredits.resourceParams(),staleTime:1440*60*1e3,gcTime:1/0,queryFn:async()=>await y("rc_api.get_resource_params",{})})}var zt=["resource_history_bytes","resource_new_accounts","resource_market_bytes","resource_state_bytes","resource_execution_time"];var Yp=11,Xp=65,Zp=16,tt=e=>BigInt(typeof e=="string"?e:Math.trunc(e));function cn(e,t,r,n){if(r<=0||n<=0)return 0;let o=tt(e.coeff_a),i=tt(e.coeff_b),s=tt(e.shift),a=tt(n)*o>>s;a+=1n,a*=tt(r);let c=i+(t>0?tt(t):0n);return c===0n?0:Number(a/c+1n)}function un({transactionBytes:e,permlinkLength:t,signatures:r=1,beneficiaries:n=0,hasCommentOptions:o=false},i){let s=i.resource_state_bytes,a=i.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+(o?a.comment_options_time:0)}}var we=e=>{let t=lt(e);return _e(t)+t},el=e=>1+we(e.parent_author)+we(e.parent_permlink)+we(e.author)+we(e.permlink)+we(e.title)+we(e.body)+we(e.json_metadata),tl=(e,t)=>{let r=t.beneficiaries??[],n=1+we(e.author)+we(e.permlink)+Zp+2+2;return n+=_e(r.length>0?1:0),r.length>0&&(n+=1+_e(r.length),r.forEach(o=>{n+=we(o.account)+2;})),n};function pn({op:e,options:t,signatures:r=1}){let n=[el(e)];return t&&n.push(tl(e,t)),Yp+_e(n.length)+n.reduce((o,i)=>o+i,0)+_e(r)+Xp*r}var rl={ready:false,cost:0,transactionBytes:0,breakdown:[]};function AS({op:e,options:t,rcParams:r,rcStats:n,signatures:o=1}){if(!r?.resource_params||!r.size_info||!n?.pool||!n.share)return rl;let i=pn({op:e,options:t,signatures:o}),s=un({transactionBytes:i,permlinkLength:lt(e.permlink),signatures:o,beneficiaries:t?.beneficiaries?.length??0,hasCommentOptions:!!t},r.size_info),a=Number(n.regen),c=0,p=[];return zt.forEach((l,d)=>{let m=r.resource_params[l],g=Number(n.pool[d]??0),h=Number(n.share[d]??0);if(!m||h<=0)return;let A=s[l]*Number(m.resource_dynamics_params.resource_unit??1),x=Number(BigInt(a)*BigInt(h)/10000n),F=cn(m.price_curve_params,g,A,x);c+=F,p.push({resource:l,usage:A,cost:F});}),{ready:true,cost:c,transactionBytes:i,breakdown:p}}function ln(e,t,r){let n=Number(r.regen),o=0,i=[];return zt.forEach((s,a)=>{let c=t.resource_params[s],p=Number(r.pool[a]??0),l=Number(r.share[a]??0);if(!c||l<=0)return;let d=e[s]*Number(c.resource_dynamics_params.resource_unit??1),m=Number(BigInt(n)*BigInt(l)/10000n),g=cn(c.price_curve_params,p,d,m);o+=g,i.push({resource:s,usage:d,cost:g});}),{cost:o,breakdown:i}}var nl=11,ol=65,dn=e=>{let t=lt(e);return _e(t)+t},il=()=>({resource_history_bytes:0,resource_new_accounts:0,resource_market_bytes:0,resource_state_bytes:0,resource_execution_time:0});function gi(e,t=1){let r=1+dn(e.voter)+dn(e.author)+dn(e.permlink)+2;return nl+_e(1)+r+_e(t)+ol*t}function yi({transactionBytes:e,signatures:t=1},r){let n=r.resource_state_bytes,o=r.resource_execution_time;return {...il(),resource_history_bytes:e,resource_state_bytes:n.vote_size+n.transaction_base_size,resource_execution_time:o.vote_time+o.transaction_time+o.verify_authority_time*t}}var hi={ready:false,currentMana:0,maxMana:0,avgCost:0,cost:0,transactionBytes:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function qS({rcAccount:e,rcStats:t,rcParams:r,operation:n,payload:o,fallback:i="minimal",buffer:s=1.2}){if(!e||!t?.ops)return hi;let{current_mana:a,max_mana:c}=Bt(e),p=sl(n,o,i,r,t);if(!p)return {...hi,currentMana:a,maxMana:c};let{cost:l,transactionBytes:d}=p,m=Number.isFinite(s)&&s>0?s:1.2,g=l*m,h=a0?{cost:r,transactionBytes:0}:null}var cl={author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa",parent_author:"",parent_permlink:"hive-100000",title:"",body:"",json_metadata:"{}"},ul={voter:"aaaaaaaaaa",author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa"};function MS(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 _()(f.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}async function dl(e,t,r){let o=await _()(f.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:t,code:e,key:r}),headers:{"Content-Type":"application/json"}}),i=(o.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),s=await o.text();if(!o.ok){let a=s&&i.includes("json")?`: ${s.slice(0,200)}`:"";throw new Error(`[SDK][Games] \u2013 failed with status ${o.status}${a}`)}if(!i.includes("json"))throw new Error(`[SDK][Games] \u2013 expected JSON but received "${i||"empty"}" response (status ${o.status})`);try{return JSON.parse(s)}catch{throw new Error(`[SDK][Games] \u2013 malformed JSON response (status ${o.status})`)}}function VS(e,t,r,n){let{mutateAsync:o}=nn(e,"spin-rolled");return useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return dl(t,r,n)},onSuccess(){o();}})}function WS(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 _()(f.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 ml=[{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 zS(e,t){return ml.find(r=>r.tier===e&&r.id===t)}var gl=25;function yl(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function JS(e){return yl(e)>gl}var YS=300,XS=2;function bl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function wl(e){let r=await _()(f.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:bl()})});if(!r.ok){let n;try{n=await r.json();}catch{}let o=n?.message??`Failed to buy streak freeze: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function rk(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 wl(t)},onSuccess(){n&&r.invalidateQueries({queryKey:u.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:u.quests.status(n)});}})}function sk(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[Qr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"async"})}function pk(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[Hr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"sync"})}function mk(e,t,r){return v(["communities","mutePost"],e,({community:n,author:o,permlink:i,notes:s,mute:a})=>[Lr(e,n,o,i,s,a)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.posts.entry(`/@${o.author}/${o.permlink}`),["community","single",o.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.community}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"sync"})}function _k(e,t,r,n){return v(["communities","set-role",e],t,({account:o,role:i})=>[Ur(t,e,o,i)],async(o,i)=>{w().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>{if(!a)return a;let c=[...a.team??[]],p=c.findIndex(([l])=>l===i.account);return p>=0?c[p]=[c[p][0],i.role,c[p][2]??""]:c.push([i.account,i.role,""]),{...a,team:c}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)],u.communities.context(i.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function Pk(e,t,r,n){return v(["communities","update",e],t,o=>[Vr(t,e,o)],async(o,i)=>{w().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>a&&{...a,...i}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function Ek(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[tn(n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.communities.singlePrefix(o.name)],[...u.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function Rk(e,t,r){return v(["communities","pin-post"],e,({community:n,account:o,permlink:i,pin:s})=>[jr(e,n,o,i,s)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.posts.entry(`/@${o.account}/${o.permlink}`),[...u.communities.singlePrefix(o.community)]]);},t,"posting",{broadcastMode:r??"async"})}function Dk(e,t,r=100,n=void 0,o=true){return queryOptions({queryKey:u.communities.list(e,t??"",r),enabled:o,queryFn:async()=>{let i=await y("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return i?e==="hot"?i.sort(()=>Math.random()-.5):i:[]}})}function Qk(e,t){return queryOptions({queryKey:u.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await y("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function Lk(e,t="",r=true){return queryOptions({queryKey:u.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>Do(e??"",t)})}var _i=100;async function bi(e,t){return await y("bridge.list_subscribers",{community:e,limit:_i,...t?{last:t}:{}})??[]}function Yk(e){return queryOptions({queryKey:u.communities.subscribers(e),queryFn:async()=>bi(e,null),staleTime:6e4})}function Xk(e){return infiniteQueryOptions({queryKey:u.communities.subscribersInfinite(e),initialPageParam:null,queryFn:async({pageParam:t})=>bi(e,t),getNextPageParam:t=>t?.length>=_i?t[t.length-1]?.[0]??null:null,staleTime:6e4})}function oC(e,t){return infiniteQueryOptions({queryKey:u.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await y("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function cC(){return queryOptions({queryKey:u.communities.rewarded(),queryFn:async()=>{let e=await fetch(f.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 kl=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(kl||{}),pC={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function dC(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function fC({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),o=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),i=["owner","admin","mod"].includes(t);return {canPost:n,canComment:o,isModerator:i}}function hC(e,t){return queryOptions({queryKey:u.notifications.unreadCount(e),queryFn:async()=>t?(await(await fetch(`${f.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 vC(e,t,r=void 0){return infiniteQueryOptions({queryKey:u.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let o={code:t,filter:r,since:n,user:void 0},i=await fetch(f.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)return [];try{return await i.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var Tl=(g=>(g.VOTES="rvotes",g.MENTIONS="mentions",g.FAVORITES="nfavorites",g.BOOKMARKS="nbookmarks",g.FOLLOWS="follows",g.REPLIES="replies",g.REBLOGS="reblogs",g.TRANSFERS="transfers",g.DELEGATIONS="delegations",g.PAYOUTS="payouts",g.SCHEDULED_PUBLISHED="scheduled_published",g.ACCOUNT_UPDATES="account_updates",g.WEEKLY_EARNINGS="weekly_earnings",g))(Tl||{});var Fl=(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))(Fl||{}),wi=[1,2,3,4,5,6,10,13,15,19,20,21,22],Il=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(Il||{});function kC(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 o=await fetch(f.privateApiHost+"/private-api/detail-device",{body:JSON.stringify({code:t,username:e,token:n}),method:"POST",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch notification settings: ${o.status}`);return o.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...wi]})})}function FC(){return queryOptions({queryKey:u.notifications.announcements(),queryFn:async()=>{let e=await fetch(f.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 KC(e){return queryOptions({queryKey:u.notifications.spotlights(),queryFn:async()=>{let t=await fetch(f.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 Ml(e,t){return {...e,read:!t||t===e.id?1:e.read}}function vi(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function VC(e,t,r,n){let o=w();return useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:i})=>{if(!(!e||!t))return ri(t,i)},onMutate:async({id:i})=>{if(!e||!t)return {previousData:[]};await o.cancelQueries({queryKey:u.notifications._prefix});let s=[],a=o.getQueriesData({queryKey:u.notifications._prefix,predicate:l=>{let d=l.state.data;return vi(d)}});a.forEach(([l,d])=>{if(d&&vi(d)){s.push([l,d]);let m={...d,pages:d.pages.map(g=>g.map(h=>Ml(h,i)))};o.setQueryData(l,m);}});let c=u.notifications.unreadCount(e),p=o.getQueryData(c);return typeof p=="number"&&p>0&&(s.push([c,p]),i?a.some(([,d])=>d?.pages.some(m=>m.some(g=>g.id===i&&g.read===0)))&&o.setQueryData(c,p-1):o.setQueryData(c,0)),{previousData:s}},onSuccess:i=>{let s=typeof i=="object"&&i!==null?i.unread:void 0;typeof s=="number"&&o.setQueryData(u.notifications.unreadCount(e),s),r?.(s);},onError:(i,s,a)=>{a?.previousData&&a.previousData.forEach(([c,p])=>{o.setQueryData(c,p);}),n?.(i);},onSettled:()=>{o.invalidateQueries({queryKey:u.notifications._prefix});}})}function WC(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>Dr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function YC(e){return queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await y("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 y("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(o=>o.status==="expired");return [...t.filter(o=>o.status!=="expired"),...r]}})}function aR(e,t,r){return infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await y("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 y("condenser_api.get_accounts",[s.map(l=>l.voter)]),c=Ht(a);return s.map(l=>({...l,voterAccount:c.find(d=>l.voter===d.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function lR(e){return queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await y("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 gR(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:o})=>[Nr(e,n,o)],async n=>{try{let o=n?.id??n?.tx_id;t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(150,o,n?.block_num).catch(i=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:o,error:i});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.proposals.list(),u.proposals.votesByUser(e)]);}catch(o){console.warn("[useProposalVote] Post-broadcast side-effect failed:",o);}},t,"active",{broadcastMode:r})}function bR(e,t,r){return v(["proposals","create"],e,n=>[Mr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.proposals.list()]);},t,"active",{broadcastMode:r})}function AR(e,t=50){return infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,o=await y("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&o.length>0&&o[0]?.delegatee===r?o.slice(1,t+1):o},getNextPageParam:r=>!r||r.lengthne("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function TR(e){return queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await y("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function DR(e){return queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>y("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function NR(e){return queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>y("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function VR(e){return queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>y("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function WR(e){return queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function YR(e){return queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>y("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function rT(e,t=100){return infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let o=(await y("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(i=>i)).rc_direct_delegations||[];return r&&(o=o.filter(i=>i.to!==r)),o},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function sT(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 _()(`${f.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function pT(e){return queryOptions({queryKey:["wallet","received-vesting-shares",e],queryFn:async()=>{let t=await fetch(f.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 mT(e){return queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>y("condenser_api.find_recurrent_transfers",[e]),enabled:!!e})}function ge(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}}function pe(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 o=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(o){let i=Number.parseFloat(o[0]);if(Number.isFinite(i))return i}}}function rd(e){if(!e||typeof e!="object")return;let t=e;return {name:ge(t.name)??"",symbol:ge(t.symbol)??"",layer:ge(t.layer)??"hive",balance:pe(t.balance)??0,fiatRate:pe(t.fiatRate)??0,currency:ge(t.currency)??"usd",precision:pe(t.precision)??3,address:ge(t.address),error:ge(t.error),pendingRewards:pe(t.pendingRewards),pendingRewardsFiat:pe(t.pendingRewardsFiat),liquid:pe(t.liquid),liquidFiat:pe(t.liquidFiat),savings:pe(t.savings),savingsFiat:pe(t.savingsFiat),staked:pe(t.staked),stakedFiat:pe(t.stakedFiat),iconUrl:ge(t.iconUrl),actions:t.actions??[],extraData:t.extraData??[],apr:pe(t.apr)}}function nd(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 o of ["wallets","tokens","assets","items","portfolio","balances"]){let i=n[o];if(Array.isArray(i))return i}}return []}function od(e){if(!e||typeof e!="object")return;let t=e;return ge(t.username)??ge(t.name)??ge(t.account)}function Pi(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`,o=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!o.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${o.status})`);let i=await o.json(),s=nd(i).map(a=>rd(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:od(i)??e,currency:ge(i?.fiatCurrency??i?.currency)?.toUpperCase(),wallets:s}}})}function Jt(e){return queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await w().prefetchQuery(Ee()),await w().prefetchQuery(Q(e));let t=w().getQueryData(Ee().queryKey),r=w().getQueryData(Q(e).queryKey),n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:0};let i=C(r.balance).amount,s=C(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:i+s,parts:[{name:"current",balance:i},{name:"savings",balance:s}]}}})}function Ai(e){return queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await w().prefetchQuery(Ee()),await w().prefetchQuery(Q(e));let t=w().getQueryData(Q(e).queryKey),r=w().getQueryData(Ee().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 cd(e){let c=9.5-(e.headBlock-7e6)/25e4*.01;c<.95&&(c=.95);let p=e.vestingRewardPercent/1e4,l=e.virtualSupply,d=e.totalVestingFund;return (l*c*p/d).toFixed(3)}function Oi(e){return queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await w().prefetchQuery(Ee()),await w().prefetchQuery(Q(e));let t=w().getQueryData(Ee().queryKey),r=w().getQueryData(Q(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??""),i=Number.isFinite(o)?o: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),d=bo(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+ze(s,t.hivePerMVests).toFixed(3),g=+ze(a,t.hivePerMVests).toFixed(3),h=+ze(c,t.hivePerMVests).toFixed(3),A=+ze(l,t.hivePerMVests).toFixed(3),x=+ze(d,t.hivePerMVests).toFixed(3),F=Math.max(m-A,0),I=Math.max(m-g,0);return {name:"HP",title:"Hive Power",price:i,accountBalance:+F.toFixed(3),apr:cd(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+I.toFixed(3)},{name:"outgoing_delegations",balance:g},{name:"incoming_delegations",balance:h},...A>0?[{name:"pending_power_down",balance:+A.toFixed(3)}]:[],...x>0&&x!==A?[{name:"next_power_down",balance:+x.toFixed(3)}]:[]]}}})}var M=ie.operations,fn={transfers:[M.transfer,M.transfer_to_savings,M.transfer_from_savings,M.cancel_transfer_from_savings,M.recurrent_transfer,M.fill_recurrent_transfer,M.escrow_transfer,M.fill_recurrent_transfer],"market-orders":[M.fill_convert_request,M.fill_order,M.fill_collateralized_convert_request,M.limit_order_create2,M.limit_order_create,M.limit_order_cancel],interests:[M.interest],"stake-operations":[M.return_vesting_delegation,M.withdraw_vesting,M.transfer_to_vesting,M.set_withdraw_vesting_route,M.update_proposal_votes,M.fill_vesting_withdraw,M.account_witness_proxy,M.delegate_vesting_shares],rewards:[M.author_reward,M.curation_reward,M.producer_reward,M.claim_reward_balance,M.comment_benefactor_reward,M.liquidity_reward,M.proposal_pay],"":[]};var NT=Object.keys(ie.operations);var xi=ie.operations,UT=xi,VT=Object.entries(xi).reduce((e,[t,r])=>(e[r]=t,e),{});var Ei=ie.operations;function pd(e){return Object.prototype.hasOwnProperty.call(Ei,e)}function bt(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),o=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),i=new Set;r||n.forEach(a=>{if(a in fn){fn[a].forEach(c=>i.add(c));return}pd(a)&&i.add(Ei[a]);});let s=fd(Array.from(i));return {filterKey:o,filterArgs:s}}function mn(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function ld(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function dd(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function fd(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await y("condenser_api.get_account_history",[e,s,dd(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 d=C(p.amount);return ["HIVE"].includes(d.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 i.has(p.type)}}))})})}function eF(e,t=20,r=[]){let{filterKey:n}=bt(r),o=mn(r);return infiniteQueryOptions({...Yt(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:i,pageParams:s})=>({pageParams:s,pages:i.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 d=C(c.amount);return ["HBD"].includes(d.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 o.has(c.type)}}))})})}function iF(e,t=20,r=[]){let{filterKey:n}=bt(r),o=new Set(Array.isArray(r)?r:[r]),i=o.has("")||o.size===0;return infiniteQueryOptions({...Yt(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 i||o.has(p.type)}}))})})}function Si(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 gn(e,t){return new Date(e.getTime()-t*1e3)}function uF(e=86400){return infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await y("condenser_api.get_market_history",[e,Si(t),Si(r)])).map(({hive:o,non_hive:i,open:s})=>({close:i.close/o.close,open:i.open/o.open,low:i.low/o.low,high:i.high/o.high,volume:o.volume,time:new Date(s)})),initialPageParam:[gn(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[gn(n,Math.max(100*e,28800)),gn(n,e)]})}function fF(e){return queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function hF(e,t=50){return queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>y("condenser_api.get_vesting_delegations",[e,"",t])})}function PF(e){return queryOptions({queryKey:["assets","hive-power","delegatings",e],queryFn:async()=>(await(await fetch(f.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 EF(e=500){return queryOptions({queryKey:["market","order-book",e],queryFn:()=>y("condenser_api.get_order_book",[e])})}function RF(){return queryOptions({queryKey:["market","statistics"],queryFn:()=>y("condenser_api.get_ticker",[])})}function qF(e,t,r){let n=o=>o.toISOString().replace(/\.\d{3}Z$/,"");return queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>y("condenser_api.get_market_history",[e,n(t),n(r)])})}function MF(){return queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await y("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),o=await y("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:o[0]?o[0].non_hive.open/o[0].hive.open:0,high:o[0]?o[0].non_hive.high/o[0].hive.high:0,low:o[0]?o[0].non_hive.low/o[0].hive.low:0,percent:o[0]?100-o[0].non_hive.open/o[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function UF(e,t,r,n){return queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:o})=>{let i=_(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await i(s,{signal:o});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function ki(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function $F(e=1e3,t,r){let n=r??new Date,o=t??new Date(n.getTime()-600*60*1e3);return queryOptions({queryKey:["market","trade-history",e,o.getTime(),n.getTime()],queryFn:()=>y("condenser_api.get_trade_history",[ki(o),ki(n),e])})}function JF(){return queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await y("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function eI(){return queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await y("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function oI(e,t,r){return v(["market","limit-order-create"],e,n=>[Lt(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 cI(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[$r(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 wt(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 lI(e,t,r,n){let o=_(),i=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await o(i);return wt(s)}async function Ci(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 wt(n)).hive_dollar[e]}async function dI(e,t){let n=await _()(f.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return wt(n)}async function fI(){let t=await _()(f.privateApiHost+"/private-api/market-data/latest");return wt(t)}async function mI(){let t=await _()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return wt(t)}var kd={"Content-type":"application/json"};async function Cd(e){let t=_(),r=N.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:kd});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function qe(e,t){try{return await Cd(e)}catch{return t}}async function hI(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,o]=await Promise.all([qe({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),qe({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),i=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),d=Number(p.price??0);return l-d});return {buy:i(n),sell:s(o)}}async function _I(e,t=50){return qe({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 bI(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},[o,i]=await Promise.all([qe({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),qe({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=o.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=i.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 Rd(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return qe({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function rt(e,t){return Rd(t,e)}async function Xt(e){return qe({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function Zt(e){return qe({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function Ri(e,t,r,n){let o=_(),i=N.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",i);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 o(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 Ti(e,t="daily"){let r=_(),n=N.getValidatedBaseUrl(),o=new URL("/private-api/engine-chart-api",n);o.searchParams.set("symbol",e),o.searchParams.set("interval",t);let i=await r(o.toString(),{headers:{"Content-type":"application/json"}});if(!i.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${i.status}`);return await i.json()}async function Fi(e){let t=_(),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 er(e){return queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Xt(e)})}function EI(){return queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>rt()})}function Ii(e){return queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Zt(e)})}function II(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 Ri(e,t,r,n)},getNextPageParam:(n,o,i)=>(n?.length??0)===r?i+r:void 0,getPreviousPageParam:(n,o,i)=>i>0?i-r:void 0})}function BI(e,t="daily"){return queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ti(e,t)})}function HI(e){return queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await Fi(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function qi(e,t){return queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>rt(e,t)})}function nt(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:o,suffix:i}=r,s="";o&&(s+=o+" ");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}),i&&(s+=" "+i),s}var tr=class{constructor(t){P(this,"symbol");P(this,"name");P(this,"icon");P(this,"precision");P(this,"stakingEnabled");P(this,"delegationEnabled");P(this,"balance");P(this,"stake");P(this,"stakedBalance");P(this,"delegationsIn");P(this,"delegationsOut");P(this,"usdValue");P(this,"hasDelegations",()=>this.delegationEnabled?this.delegationsIn>0&&this.delegationsOut>0:false);P(this,"delegations",()=>this.hasDelegations()?`(${nt(this.stake,{fractionDigits:this.precision})} + ${nt(this.delegationsIn,{fractionDigits:this.precision})} - ${nt(this.delegationsOut,{fractionDigits:this.precision})})`:"");P(this,"staked",()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():nt(this.stakedBalance,{fractionDigits:this.precision}):"-");P(this,"balanced",()=>this.balance<1e-4?this.balance.toString():nt(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 ZI(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 Xt(e),o=await Zt(n.map(p=>p.symbol)),i=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 rt(void 0,a):[]];return n.map(p=>{let l=o.find(x=>x.symbol===p.symbol),d;if(l?.metadata)try{d=JSON.parse(l.metadata);}catch{d=void 0;}let m=c.find(x=>x.symbol===p.symbol),g=Number(m?.lastPrice??"0"),h=Number(p.balance),A=p.symbol==="SWAP.HIVE"?i*h:g===0?0:Number((g*i*h).toFixed(10));return new tr({symbol:p.symbol,name:l?.name??p.symbol,icon:d?.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:A})})},enabled:!!e})}function Di(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=w(),n=Jt(e);await r.prefetchQuery(n);let o=r.getQueryData(n.queryKey),i=await r.ensureQueryData(Ii([t])),s=await r.ensureQueryData(er(e)),a=await r.ensureQueryData(qi(void 0,t)),c=i?.find(x=>x.symbol===t),p=s?.find(x=>x.symbol===t),d=+(a?.find(x=>x.symbol===t)?.lastPrice??"0"),m=parseFloat(p?.balance??"0"),g=parseFloat(p?.stake??"0"),h=parseFloat(p?.pendingUnstake??"0"),A=[{name:"liquid",balance:m},{name:"staked",balance:g}];return h>0&&A.push({name:"unstaking",balance:h}),{name:t,title:c?.name??"",price:d===0?0:Number(d*(o?.price??0)),accountBalance:m+g,layer:"ENGINE",parts:A}}})}function vt(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(f.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 o=await n.json(),i=await fetch(f.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!i.ok)throw new Error(`Failed to fetch point transactions: ${i.status}`);let s=await i.json();return {points:o.points,uPoints:o.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function Ki(e){return queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await w().prefetchQuery(vt(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(w().getQueryData(vt(e).queryKey)?.points??0)})})}function hq(e,t){return queryOptions({queryKey:["assets","points","transactions",e,t],queryFn:async()=>(await(await fetch(`${f.privateApiHost}/private-api/point-list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,type:t??0})})).json()).map(({created:o,type:i,amount:s,id:a,sender:c,receiver:p,memo:l})=>({created:new Date(o),type:i,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=w(),o=r.currency??"usd",i=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||o==="usd")return p;try{let l=await Ci(o);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${o}:`,l),p}},a=Pi(e,o,true),c=async()=>{try{let l=(await n.fetchQuery(a)).wallets.find(m=>m.symbol.toUpperCase()===t.toUpperCase());if(!l)return;let d=[];if(l.liquid!==void 0&&l.liquid!==null&&d.push({name:"liquid",balance:l.liquid}),l.staked!==void 0&&l.staked!==null&&l.staked>0&&d.push({name:"staked",balance:l.staked}),l.savings!==void 0&&l.savings!==null&&l.savings>0&&d.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 g=m.dataKey,h=m.value;if(typeof h=="string"){let x=h.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(x){let F=Math.abs(Number.parseFloat(x[1]));g==="delegated_hive_power"?d.push({name:"outgoing_delegations",balance:F}):g==="received_hive_power"?d.push({name:"incoming_delegations",balance:F}):g==="powering_down_hive_power"&&d.push({name:"pending_power_down",balance:F});}}}return {name:l.symbol,title:l.name,price:l.fiatRate,accountBalance:l.balance,apr:l.apr?.toString(),layer:l.layer,pendingRewards:l.pendingRewards,parts:d}}catch{return}};return queryOptions({queryKey:["ecency-wallets","asset-info",e,t,o],queryFn:async()=>{let p=await c();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await i(Jt(e));else if(t==="HP")l=await i(Oi(e));else if(t==="HBD")l=await i(Ai(e));else if(t==="POINTS")l=await i(Ki(e));else if((await n.ensureQueryData(er(e))).some(m=>m.symbol===t))l=await i(Di(e,t));else {if(p)return p;throw new Error(`[SDK][Wallet] \u2013 unrecognized asset "${t}"`)}if(p&&l&&l.price>0){let d=await s(l);return {...p,price:d.price}}return await s(l)}})}var jd=(F=>(F.Transfer="transfer",F.TransferToSavings="transfer-saving",F.WithdrawFromSavings="withdraw-saving",F.Delegate="delegate",F.PowerUp="power-up",F.PowerDown="power-down",F.WithdrawRoutes="withdraw-routes",F.ClaimInterest="claim-interest",F.Swap="swap",F.Convert="convert",F.Gift="gift",F.Promote="promote",F.Claim="claim",F.Buy="buy",F.Stake="stake",F.Unstake="unstake",F.Undelegate="undelegate",F))(jd||{});function Dq(e,t,r){return v(["wallet","transfer"],e,n=>[je(e,n.to,n.amount,n.memo)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Qq(e,t,r){return v(["wallet","transfer-point"],e,n=>[Ze(e,n.to,n.amount,n.memo)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Lq(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[yt(e,n.delegatee,n.vestingShares)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.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=>[ht(e,n.toAccount,n.percent,n.autoVest)],async(n,o)=>{await S(t?.adapter,r,[u.wallet.withdrawRoutes(e),u.accounts.full(e),u.accounts.full(o.toAccount)]);},t,"active",{broadcastMode:r})}function eD(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function iD(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[Xe(e,n.to,n.amount,n.memo)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function pD(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[Le(e,n.to,n.amount,n.memo,n.requestId)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function gD(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[mt(e,n.to,n.amount)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function wD(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[gt(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 xD(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?Tr(e,n.amount,n.requestId):_t(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 RD(e,t,r){return v(["wallet","claim-interest"],e,n=>ft(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 Ld=5e3,rr=new Map;function DD(e,t,r){return v(["wallet","claim-rewards"],e,n=>[Wr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",o=[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)],i=rr.get(n);i&&(clearTimeout(i),rr.delete(n));let s=setTimeout(async()=>{try{let a=w(),p=(await Promise.allSettled(o.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{rr.delete(n);}},Ld);rr.set(n,s);},t,"posting",{broadcastMode:r})}function ND(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function VD(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let o=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:o}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function WD(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function YD(e,t,r){return v(["wallet","unstake-engine-token"],e,n=>{let o=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:o}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function tK(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let o=JSON.stringify(n.tokens.map(i=>({symbol:i})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:o}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function iK(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let o,i;n.action==="cancel"?(i="cancel",o={type:n.orderType,id:n.orderId}):(i=n.action,o={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:i,contractPayload:o});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 $d(e,t,r){let{from:n,to:o="",amount:i="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [je(n,o,i,s)];case "transfer-saving":return [Xe(n,o,i,s)];case "withdraw-saving":return [Le(n,o,i,s,a)];case "power-up":return [mt(n,o,i)]}break;case "HBD":switch(t){case "transfer":return [je(n,o,i,s)];case "transfer-saving":return [Xe(n,o,i,s)];case "withdraw-saving":return [Le(n,o,i,s,a)];case "claim-interest":return ft(n,o,i,s,a);case "convert":return [_t(n,i,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [gt(n,i)];case "delegate":return [yt(n,o,i)];case "withdraw-routes":return [ht(r.from_account??n,r.to_account??o,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [Ze(n,o,i,s)];break}return null}function Wd(e,t,r){let{from:n,to:o="",amount:i=""}=r,s=typeof i=="string"&&i.includes(" ")?i.split(" ")[0]:String(i);switch(t){case "transfer":return [$e(n,"transfer",{symbol:e,to:o,quantity:s,memo:r.memo??""})];case "stake":return [$e(n,"stake",{symbol:e,to:o,quantity:s})];case "unstake":return [$e(n,"unstake",{symbol:e,to:o,quantity:s})];case "delegate":return [$e(n,"delegate",{symbol:e,to:o,quantity:s})];case "undelegate":return [$e(n,"undelegate",{symbol:e,from:o,quantity:s})];case "claim":return [Fr(n,[e])]}return null}function Gd(e){return e==="claim"?"posting":"active"}function lK(e,t,r,n,o){let{mutateAsync:i}=et.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=$d(t,r,s);if(a)return a;let c=Wd(t,r,s);if(c)return c;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{i();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=>{w().invalidateQueries({queryKey:a});});},5e3);},n,Gd(r),{broadcastMode:o})}function gK(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:o})=>[Ir(e,n,o)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),u.resourceCredits.account(e),u.resourceCredits.account(o.to)]);},t,"active",{broadcastMode:r})}function bK(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:o})=>[Kr(e,n,o)],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 AK(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[Br(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function Jd(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 CK(e){return infiniteQueryOptions({queryKey:u.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await ne("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(Jd),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function RK(e,t,r,n="vests",o="desc"){return queryOptions({queryKey:u.witnesses.voters(e,t,r,n,o),queryFn:async({signal:i})=>await ne("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:o},void 0,void 0,i),enabled:!!e,staleTime:6e4})}function TK(e){return queryOptions({queryKey:u.witnesses.voterCount(e),queryFn:async()=>await ne("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var Yd=(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))(Yd||{});async function Zd(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 _()(f.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),o=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),i=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(i)}catch{return {message:i,code:n.status}}let s=i&&o.includes("json")?`: ${i.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!o.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${o||"empty"}" response (status ${n.status})`);try{return JSON.parse(i)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function MK(e,t,r,n){let{mutateAsync:o}=et.useRecordActivity(e,"points-claimed");return useMutation({mutationFn:()=>Zd(e,t),onError:n,onSuccess:()=>{o(),w().setQueryData(vt(e).queryKey,i=>i&&{...i,points:(parseFloat(i.points)+parseFloat(i.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var Mi=/(^|\s)author:([^\s]+)/g,Ni=/(^|\s)type:([^\s]+)/g,Qi=/(^|\s)category:([^\s]+)/g,Hi=/(^|\s)tag:([^\s]+)/g;var Vi=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(Vi||{}),QK=5,HK=100;function ji(e){return e.trim().split(/\s+/)[0]??""}function ef(e){return ji(e).replace(/^@+/,"").toLowerCase()}function tf(e){return ji(e).replace(/^#+/,"").toLowerCase()}function rf(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 UK({search:e="",author:t="",type:r="",category:n="",tags:o=[]}){let i=e.trim().replace(/\s+/g," "),s=ef(t),a=tf(n),c=rf(Array.isArray(o)?o.join(","):o),p=[i];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:i,author:s,type:r,category:a,tags:c}}var Ui=class{constructor(t){P(this,"query","");P(this,"search","");P(this,"author","");P(this,"type","");P(this,"category","");P(this,"tags",[]);P(this,"grab",t=>{let r=[...this.query.matchAll(t)];return r.length>0?r[0][2].trim():""});P(this,"grabAuthor",()=>{this.author=this.grab(Mi);});P(this,"grabType",()=>{let t=this.grab(Ni);Object.values(Vi).includes(t)&&(this.type=t);});P(this,"grabCategory",()=>{this.category=this.grab(Qi);});P(this,"grabTags",()=>{let t=new Set;this.tags=[...this.query.matchAll(Hi)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));});P(this,"grabSearch",()=>{for([Mi,Ni,Qi,Hi].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 Se(e,t){let n=await(async()=>{let o;try{o=await e.text();}catch{return}if(o!=="")try{return JSON.parse(o)}catch{return e.ok?void 0:o}})();if(!e.ok){let o=new Error(`Request failed with status ${e.status}`);throw o.status=e.status,o.data=n,o}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 De(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var of=isServer?0:3;function Pt(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),o&&(a.scroll_id=o),i&&(a.votes=i);let c=await fetch(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(a),signal:Oe(xe,s)});return Se(c,De)},retry:Pt})}function eB(e,t,r=true){return infiniteQueryOptions({queryKey:u.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:o})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let i,s=new Date;switch(t){case "today":i=new Date(s.getTime()-1440*60*1e3);break;case "week":i=new Date(s.getTime()-10080*60*1e3);break;case "month":i=new Date(s.getTime()-720*60*60*1e3);break;case "year":i=new Date(s.getTime()-365*24*60*60*1e3);break;default:i=void 0;}let a="* type:post",c=e==="rising"?"children":e,p=i?i.toISOString().split(".")[0]:void 0,l="0",d=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=d);let g=await fetch(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(m),signal:Oe(xe,o)});return Se(g,De)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:Pt})}async function oB(e,t,r,n,o,i,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),o&&(a.scroll_id=o),i&&(a.votes=i);let p=await _()(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(a),signal:Oe(xe,s)});return Se(p,De)}async function Li(e,t,r=xe){let o=await _()(f.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(e),signal:Oe(r,t)});return Se(o,De)}async function iB(e,t){let n=await _()(f.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify({q:e}),signal:Oe(xe,t)}),o=await Se(n,Array.isArray);return o?.length>0?o:[e]}var uf=4368*60*60*1e3,pf=4,lf=3e3,df=2e3,ff=4e3,pB=2;function mf(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function gf(e){let t=5381;for(let r=0;r>>0).toString(36)}function lB(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),o=mf(e.body??"",lf),i=gf(`${t}|${n.join(",")}|${o}`);return queryOptions({queryKey:u.search.similarEntries(e.author,e.permlink,i),queryFn:async({signal:s})=>{let a=new Date(Date.now()-uf).toISOString().slice(0,19),c=await Li({author:e.author,permlink:e.permlink,title:t,body:o,tags:n,since:a},s,typeof window>"u"?df:ff),p=[],l=new Set;for(let d of c.results){if(p.length>=pf)break;d.permlink!==e.permlink&&(d.tags??[]).indexOf("nsfw")===-1&&(l.has(d.author)||(l.add(d.author),p.push(d)));}return p},staleTime:300*1e3,retry:false})}function hB(e,t=5){let r=e.trim();return queryOptions({queryKey:u.search.account(r,t),queryFn:async()=>{let n=await y("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Ut(n)},enabled:!!r})}function PB(e,t=10){let r=e.trim();return queryOptions({queryKey:u.search.topics(r,t),queryFn:async()=>(await y("condenser_api.get_trending_tags",[r,t+1])).map(o=>o.name).filter(o=>o!==""&&!o.startsWith("hive-")).slice(0,t),enabled:!!r})}function kB(e,t,r,n,o,i){return infiniteQueryOptions({queryKey:u.search.api(e,t,r,n,o,i),queryFn:async({pageParam:s,signal:a})=>{let c={q:e,sort:t,hide_low:r};n&&(c.since=n),s&&(c.scroll_id=s),o!==void 0&&(c.votes=o),i&&(c.include_nsfw=1);let p=await fetch(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(c),signal:Oe(xe,a)});return Se(p,De)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:Pt})}function FB(e){return queryOptions({queryKey:["search","path",e],queryFn:async()=>{let t=await fetch(f.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.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 vf(e){let r=await _()(f.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 o=n?.message??`Failed to fetch support settings: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function KB(e,t){let r=e?.replace("@","");return queryOptions({queryKey:u.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return vf(t)},enabled:!!r&&!!t})}async function Of(e,t){let n=await _()(f.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 o;try{o=await n.json();}catch{}let i=o?.message??`Failed to update support settings: ${n.status}`,s=new Error(i);throw s.status=n.status,s.data=o,s}return await n.json()}function xf(e,t,r){return e.setQueryData(u.support.settings(t),r),e.invalidateQueries({queryKey:u.support.settings(t)})}function HB(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["support","settings-update",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return Of(t,o)},onSuccess(o){n&&xf(r,n,o);}})}function LB(e){return queryOptions({queryKey:["promotions","boost-plus-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(f.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 zB(e){return queryOptions({queryKey:["promotions","rc-delegation-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(f.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 ZB(e,t){return queryOptions({queryKey:["promotions","rc-delegation-active",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(f.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 nM(e){return queryOptions({queryKey:["promotions","promote-price"],queryFn:async()=>{let t=await fetch(f.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 aM(e,t){return queryOptions({queryKey:["promotions","boost-plus-accounts",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(f.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 lM(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:o})=>[Xr(e,n,o)],async(n,{account:o})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.promotions.boostPlusAccounts(o)]);},t,"active",{broadcastMode:r})}function gM(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[Zr(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 _M(e){let r=await _()(f.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let o;try{o=await r.json();}catch{o=void 0;}let i=new Error(`Failed to refresh token: ${r.status}`);throw i.status=r.status,i.data=o,i}return await r.json()}var Ff="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function PM(){return queryOptions({queryKey:u.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(Ff,{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 OM=1.1,If=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(If||{});function xM(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 Kf(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,o=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}}),i=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:o,poll_voters:i,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 RM(e,t){return queryOptions({queryKey:u.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:isServer?go:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=_(),n=`${f.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,o=await r(n);if(!o.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${o.status}`);let i=await o.json();if(!Array.isArray(i)||!i[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return Kf(i[0])}})}function IM(e,t,r){return v(u.polls.vote(),e??"",({pollTrxId:n,choices:o})=>{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:o})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}var Bf=-1e10,Mf=5,Nf=30;var $i=e=>Math.abs(e)>0&&Math.abs(e)<=100;function Wi(e){if(typeof e=="number"&&$i(e)||typeof e=="string"&&(e=Number(e),$i(e)))return Math.floor(e);if(e===0)return 25;let t=false;e<0&&(t=true);let r=Math.log10(Math.abs(e));return r=Math.max(r-9,0),r<0&&(r=0),t&&(r*=-1),r=r*9+25,Math.floor(r)}var Qf=["ecency.com","ecency.app","hive.blog","hive.io","hiveblocks.com","peakd.com","snapie.io","hivesuite.app","leofinance.io","inleo.io","3speak.tv","d.buzz","waivio.com"],Hf=["imgur.com","images.hive.blog","files.peakd.com","i.ecency.com","images.ecency.com","steemitimages.com","cdn.steemitimages.com","media.giphy.com"],Uf=/\.(jpe?g|png|gif|webp|svg|bmp|avif)(\?|#|$)/i,Vf=/(?:https?:)?\/\/[^\s)<>"'\]]+/gi,jf=/[.,;:!?'"]+$/;function Lf(e){let t=/^(?:https?:)?\/\/([^/?#]+)/i.exec(e);return t?t[1].toLowerCase().replace(/^www\./,""):""}function $f(e){let t=e.replace(jf,"");if(Uf.test(t))return false;let r=Lf(t);if(!r.includes("."))return false;let n=o=>r===o||r.endsWith("."+o);return !(Qf.some(n)||Hf.some(n))}function Gi(e){if(!e)return false;let t=e.match(Vf);return t?t.some($f):false}var Wf=(n=>(n.MOD_MUTED="mod_muted",n.DOWNVOTED="downvoted",n.LOW_TRUST="low_trust",n))(Wf||{});function Gf(e){return e?.stats?.total_votes??e?.active_votes?.length??0}function zf(e,t){return (e??0)<-1e10&&t>=5}function Jf(e){let t=e?.author_reputation;return t==null?false:Wi(t)<30&&Gi(e?.body)}function QM(e,t){return !!e&&!!t?.includes(e)}function HM(e){return e?e.stats?.gray||e.stats?.hide?"mod_muted":zf(e.net_rshares,Gf(e))?"downvoted":Jf(e)?"low_trust":null:null}/** +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 kn 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 ho from'hivesigner';var bn=Object.defineProperty;var ls=(e,t,r)=>t in e?bn(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var St=(e,t)=>{for(var r in t)bn(e,r,{get:t[r],enumerable:true});};var P=(e,t,r)=>ls(e,typeof t!="symbol"?t+"":t,r);var Et=new ArrayBuffer(0),kt=null,Ct=null;function ds(){return kt||(typeof TextEncoder<"u"?kt=new TextEncoder:kt={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)}}),kt}function vn(){return Ct||(typeof TextDecoder<"u"?Ct=new TextDecoder:Ct={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+(i&1023)));}return r}}),Ct}var j=class j{constructor(t=j.DEFAULT_CAPACITY,r=j.DEFAULT_ENDIAN){P(this,"buffer");P(this,"view");P(this,"offset");P(this,"markedOffset");P(this,"limit");P(this,"littleEndian");P(this,"readUInt32",this.readUint32);this.buffer=t===0?Et:new ArrayBuffer(t),this.view=t===0?new DataView(Et):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(Et));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 o;return t instanceof j?(o=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=o.length):t instanceof Uint8Array?o=t:t instanceof ArrayBuffer?o=new Uint8Array(t):o=new Uint8Array(t),o.length<=0?this:(r+o.length>this.buffer.byteLength&&this.resize(r+o.length),new Uint8Array(this.buffer).set(o,r),n&&(this.offset+=o.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,o=new j(n,this.littleEndian);return o.offset=0,o.limit=n,new Uint8Array(o.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),o}copyTo(t,r,n,o){let i=typeof r>"u",s=typeof n>"u";r=i?t.offset:r,n=s?this.offset:n,o=o===void 0?this.limit:o;let a=o-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,o),r),s&&(this.offset+=a),i&&(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?Et: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 o=this.calculateVarint32(t);for(r+o>this.buffer.byteLength&&this.resize(r+o),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):o}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,o=0,i;do i=this.view.getUint8(t++),n<5&&(o|=(i&127)<<7*n),++n;while((i&128)!==0);return o|=0,r?(this.offset=t,o):{value:o,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",o=n?this.offset:r,i=ds().encode(t),s=i.length,a=this.calculateVarint32(s);return o+a+s>this.buffer.byteLength&&this.resize(o+a+s),this.writeVarint32(s,o),o+=a,new Uint8Array(this.buffer).set(i,o),o+=s,n?(this.offset=o,this):o-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,o=this.readVarint32(t),i=o.value,s=o.length;t+=s;let a=vn().decode(new Uint8Array(this.buffer,t,i));return t+=i,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 o=vn().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,o):{string:o,length:t}}};P(j,"LITTLE_ENDIAN",true),P(j,"BIG_ENDIAN",false),P(j,"DEFAULT_CAPACITY",16),P(j,"DEFAULT_ENDIAN",j.BIG_ENDIAN);var K=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}},Pn=["bridge.get_ranked_posts","bridge.get_account_posts","bridge.get_post","bridge.get_discussion","bridge.get_profile","bridge.get_profiles","bridge.get_community","bridge.list_communities","condenser_api.get_accounts","condenser_api.get_content","condenser_api.get_dynamic_global_properties","condenser_api.get_trending_tags"],Rt=null,ur=e=>{if(e===null){Rt=null;return}if(!e||typeof e!="object")return;let t=typeof e.url=="string"?e.url.trim():"";if(!/^https?:\/\//i.test(t))return;let r={};if(e.headers&&typeof e.headers=="object")for(let[s,a]of Object.entries(e.headers))typeof a=="string"&&a&&!/[\u0000-\u001f\u007f]/.test(a)&&!/[\u0000-\u001f\u007f]/.test(s)&&(r[s]=a);let n=typeof e.timeoutMs=="number"&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:2e3,o=e.methods===void 0?[...Pn]:Array.isArray(e.methods)?e.methods.filter(s=>typeof s=="string"&&s.includes(".")):[];if(o.length===0)return;let i=(s,a)=>typeof s=="number"&&Number.isFinite(s)&&s>0?s:a;Rt={url:t,headers:r,timeoutMs:n,methods:o,failureThreshold:Math.floor(i(e.failureThreshold,3)),cooldownMs:i(e.cooldownMs,1e4),methodSet:new Set(o)};},cr=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)))]:[],pr=e=>{let t=cr(e);t.length&&(S.nodes=t);},lr=e=>{let t=cr(e);t.length&&(S.restNodes=t);},dr=e=>{if(!e||typeof e!="object")return;let t={...S.restNodesByApi};for(let[r,n]of Object.entries(e)){let o=cr(n);o.length?t[r]=o:delete t[r];}S.restNodesByApi=t;},fr=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(S.userAgent=t);},mr=e=>{if(!e||typeof e!="object")return;let t=S.resilience,r=o=>typeof o=="boolean",n=o=>typeof o=="number"&&Number.isFinite(o)&&o>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 ke=class e{constructor(t,r,n){P(this,"data");P(this,"recovery");P(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,o=true;n<0&&(o=false,n=n+4);let i=r.subarray(1);return new e(i,n,o)}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 Z(n.recoverPublicKey(t).toBytes())}};var Z=class e{constructor(t,r){P(this,"key");P(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 o;try{o=kn.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(o.length!==37)throw new Error("Invalid public key length");let i=o.subarray(0,33),s=o.subarray(33,37),a=ripemd160(i).subarray(0,4);if(!ms(s,a))throw new Error("Public key checksum mismatch");try{secp256k1.Point.fromBytes(i);}catch{throw new Error("Invalid public key")}return new e(i,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=ke.from(r)),secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return fs(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},fs=(e,t)=>{let r=ripemd160(e);return t+kn.encode(new Uint8Array([...e,...r.subarray(0,4)]))},ms=(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);},hs=(e,t)=>{e.writeInt16(t);},Rn=(e,t)=>{e.writeInt64(t);},Cn=(e,t)=>{e.writeUint8(t);},de=(e,t)=>{e.writeUint16(t);},ee=(e,t)=>{e.writeUint32(t);},Tn=(e,t)=>{e.writeUint64(t);},ve=(e,t)=>{e.writeByte(t?1:0);},qn=e=>(t,r)=>{let[n,o]=r;t.writeVarint32(n),e[n](t,o);},D=(e,t)=>{let r=Tt.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let o=0;o<7;o++)e.writeUint8(r.symbol.charCodeAt(o)||0);},Ce=(e,t)=>{e.writeUint32(Math.floor(new Date(t+"Z").getTime()/1e3));},he=(e,t)=>{t===null||typeof t=="string"&&t.slice(-39)==="1111111111111111111111111111111114T1Anm"?e.append(new Uint8Array(33).fill(0)):e.append(Z.from(t).key);},Fn=(e=null)=>(t,r)=>{r=qt.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);},In=Fn(),gr=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[o,i]of n)e(r,o),t(r,i);},L=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},fe=e=>(t,r)=>{for(let[n,o]of e)try{o(t,r[n]);}catch(i){throw i.message=`${n}: ${i.message}`,i}},Ne=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},z=fe([["weight_threshold",ee],["account_auths",gr(w,de)],["key_auths",gr(he,de)]]),_s=fe([["account",w],["weight",de]]),yr=fe([["base",D],["quote",D]]),ws=fe([["account_creation_fee",D],["maximum_block_size",ee],["hbd_interest_rate",de]]),T=(e,t)=>{let r=fe(t);return (n,o)=>{n.writeVarint32(e),r(n,o);}},k={};k.account_create=T(R.account_create,[["fee",D],["creator",w],["new_account_name",w],["owner",z],["active",z],["posting",z],["memo_key",he],["json_metadata",w]]);k.account_create_with_delegation=T(R.account_create_with_delegation,[["fee",D],["delegation",D],["creator",w],["new_account_name",w],["owner",z],["active",z],["posting",z],["memo_key",he],["json_metadata",w],["extensions",L(ae)]]);k.account_update=T(R.account_update,[["account",w],["owner",Ne(z)],["active",Ne(z)],["posting",Ne(z)],["memo_key",he],["json_metadata",w]]);k.account_witness_proxy=T(R.account_witness_proxy,[["account",w],["proxy",w]]);k.account_witness_vote=T(R.account_witness_vote,[["account",w],["witness",w],["approve",ve]]);k.cancel_transfer_from_savings=T(R.cancel_transfer_from_savings,[["from",w],["request_id",ee]]);k.change_recovery_account=T(R.change_recovery_account,[["account_to_recover",w],["new_recovery_account",w],["extensions",L(ae)]]);k.claim_account=T(R.claim_account,[["creator",w],["fee",D],["extensions",L(ae)]]);k.claim_reward_balance=T(R.claim_reward_balance,[["account",w],["reward_hive",D],["reward_hbd",D],["reward_vests",D]]);k.comment=T(R.comment,[["parent_author",w],["parent_permlink",w],["author",w],["permlink",w],["title",w],["body",w],["json_metadata",w]]);k.comment_options=T(R.comment_options,[["author",w],["permlink",w],["max_accepted_payout",D],["percent_hbd",de],["allow_votes",ve],["allow_curation_rewards",ve],["extensions",L(qn([fe([["beneficiaries",L(_s)]])]))]]);k.convert=T(R.convert,[["owner",w],["requestid",ee],["amount",D]]);k.create_claimed_account=T(R.create_claimed_account,[["creator",w],["new_account_name",w],["owner",z],["active",z],["posting",z],["memo_key",he],["json_metadata",w],["extensions",L(ae)]]);k.custom=T(R.custom,[["required_auths",L(w)],["id",de],["data",In]]);k.custom_json=T(R.custom_json,[["required_auths",L(w)],["required_posting_auths",L(w)],["id",w],["json",w]]);k.decline_voting_rights=T(R.decline_voting_rights,[["account",w],["decline",ve]]);k.delegate_vesting_shares=T(R.delegate_vesting_shares,[["delegator",w],["delegatee",w],["vesting_shares",D]]);k.delete_comment=T(R.delete_comment,[["author",w],["permlink",w]]);k.escrow_approve=T(R.escrow_approve,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",ee],["approve",ve]]);k.escrow_dispute=T(R.escrow_dispute,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",ee]]);k.escrow_release=T(R.escrow_release,[["from",w],["to",w],["agent",w],["who",w],["receiver",w],["escrow_id",ee],["hbd_amount",D],["hive_amount",D]]);k.escrow_transfer=T(R.escrow_transfer,[["from",w],["to",w],["hbd_amount",D],["hive_amount",D],["escrow_id",ee],["agent",w],["fee",D],["json_meta",w],["ratification_deadline",Ce],["escrow_expiration",Ce]]);k.feed_publish=T(R.feed_publish,[["publisher",w],["exchange_rate",yr]]);k.limit_order_cancel=T(R.limit_order_cancel,[["owner",w],["orderid",ee]]);k.limit_order_create=T(R.limit_order_create,[["owner",w],["orderid",ee],["amount_to_sell",D],["min_to_receive",D],["fill_or_kill",ve],["expiration",Ce]]);k.limit_order_create2=T(R.limit_order_create2,[["owner",w],["orderid",ee],["amount_to_sell",D],["exchange_rate",yr],["fill_or_kill",ve],["expiration",Ce]]);k.recover_account=T(R.recover_account,[["account_to_recover",w],["new_owner_authority",z],["recent_owner_authority",z],["extensions",L(ae)]]);k.request_account_recovery=T(R.request_account_recovery,[["recovery_account",w],["account_to_recover",w],["new_owner_authority",z],["extensions",L(ae)]]);k.reset_account=T(R.reset_account,[["reset_account",w],["account_to_reset",w],["new_owner_authority",z]]);k.set_reset_account=T(R.set_reset_account,[["account",w],["current_reset_account",w],["reset_account",w]]);k.set_withdraw_vesting_route=T(R.set_withdraw_vesting_route,[["from_account",w],["to_account",w],["percent",de],["auto_vest",ve]]);k.transfer=T(R.transfer,[["from",w],["to",w],["amount",D],["memo",w]]);k.transfer_from_savings=T(R.transfer_from_savings,[["from",w],["request_id",ee],["to",w],["amount",D],["memo",w]]);k.transfer_to_savings=T(R.transfer_to_savings,[["from",w],["to",w],["amount",D],["memo",w]]);k.transfer_to_vesting=T(R.transfer_to_vesting,[["from",w],["to",w],["amount",D]]);k.vote=T(R.vote,[["voter",w],["author",w],["permlink",w],["weight",hs]]);k.withdraw_vesting=T(R.withdraw_vesting,[["account",w],["vesting_shares",D]]);k.witness_update=T(R.witness_update,[["owner",w],["url",w],["block_signing_key",he],["props",ws],["fee",D]]);k.witness_set_properties=T(R.witness_set_properties,[["owner",w],["props",gr(w,In)],["extensions",L(ae)]]);k.account_update2=T(R.account_update2,[["account",w],["owner",Ne(z)],["active",Ne(z)],["posting",Ne(z)],["memo_key",Ne(he)],["json_metadata",w],["posting_json_metadata",w],["extensions",L(ae)]]);k.create_proposal=T(R.create_proposal,[["creator",w],["receiver",w],["start_date",Ce],["end_date",Ce],["daily_pay",D],["subject",w],["permlink",w],["extensions",L(ae)]]);k.update_proposal_votes=T(R.update_proposal_votes,[["voter",w],["proposal_ids",L(Rn)],["approve",ve],["extensions",L(ae)]]);k.remove_proposal=T(R.remove_proposal,[["proposal_owner",w],["proposal_ids",L(Rn)],["extensions",L(ae)]]);var bs=fe([["end_date",Ce]]);k.update_proposal=T(R.update_proposal,[["proposal_id",Tn],["creator",w],["daily_pay",D],["subject",w],["permlink",w],["extensions",L(qn([ae,bs]))]]);k.collateralized_convert=T(R.collateralized_convert,[["owner",w],["requestid",ee],["amount",D]]);k.recurrent_transfer=T(R.recurrent_transfer,[["from",w],["to",w],["amount",D],["memo",w],["recurrence",de],["executions",de],["extensions",L(fe([["type",Cn],["value",fe([["pair_id",Cn]])]]))]]);var vs=(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}},Ps=fe([["ref_block_num",de],["ref_block_prefix",ee],["expiration",Ce],["operations",L(vs)],["extensions",L(w)]]),As=fe([["from",he],["to",he],["nonce",Tn],["check",ee],["encrypted",Fn()]]),me={Asset:D,Memo:As,Price:yr,PublicKey:he,String:w,Transaction:Ps,UInt16:de,UInt32:ee};var ut=e=>new Promise(t=>setTimeout(t,e));var Qn=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function vr(){return Qn?{"User-Agent":S.userAgent}:{}}var Te={served:0,fallback:0,skipped:0,fallbackByReason:{status:0,rpcerror:0,timeout:0,transport:0,validate:0,parse:0}},qe=class extends Error{constructor(r,n){super(n);P(this,"reason",r);}},Dn=e=>e instanceof Error?e.message:typeof e=="string"?e:String(e),Ft=0,Kn=0;async function Os(e,t,r,n,o,i){let s=t.indexOf(".");if(s<=0||s===t.length-1)throw new qe("transport",`method without an api prefix: ${t}`);let{signal:a,cleanup:c}=Ar(Math.min(e.timeoutMs,n)),{signal:p,cleanup:l}=Nt(a,o);try{let f;try{f=await fetch(e.url,{method:"POST",body:JSON.stringify({api:t.slice(0,s),method:t.slice(s+1),params:r}),headers:{"Content-Type":"application/json",...vr(),...e.headers},signal:p});}catch(g){throw o?.aborted?g:new qe(a.aborted?"timeout":"transport",Dn(g))}if(f.status!==200){try{await f.body?.cancel();}catch{}let g=f.status===502&&(f.headers.get("x-ssr-cache")??"").toUpperCase()==="RPCERROR";throw new qe(g?"rpcerror":"status",g?"proxy relayed a node error":`proxy answered ${f.status}`)}let m;try{m=await f.json();}catch(g){throw o?.aborted?g:new qe(a.aborted?"timeout":"parse",Dn(g))}if(i&&!i(m))throw new qe("validate","proxy result rejected by validator");return m}finally{c(),l();}}var te=class extends Error{constructor(r){super(r.message);P(this,"name","RPCError");P(this,"data");P(this,"code");P(this,"stack");this.code=r.code,"data"in r&&(this.data=r.data);}},Be=class extends Error{constructor(r,n,o={}){super(n);P(this,"node");P(this,"rateLimitMs");P(this,"isRateLimit");this.node=r,this.rateLimitMs=o.rateLimitMs??0,this.isRateLimit=o.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 xs=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],Ss=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function Es(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 ks(e){if(!e)return false;if(e instanceof Be)return true;if(e instanceof te)return false;let t=Es(e);return !!(xs.some(r=>t.includes(r))||Ss.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function hr(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function Un(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var Cs=1e4,Rs=6e4,Ts=12e4,Nn=2,Bn=6e4,Mn=12e4,qs=30,ct=.3,_r=3,pt=5*6e4,Vn=6e4,jn=1e3,Ln=2e3,Dt=class{constructor(){P(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,o){let i=this.getOrCreate(t);if(i.consecutiveFailures=0,i.rateLimitStreak=0,r){let s=i.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&i.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(i,n,o??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=_r&&o-i.updatedAt<=pt?i.ewmaMs:void 0}return this.isLatencyUsable(n,o)?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 o=Date.now();if(t.latencyUpdatedAt>0&&o-t.latencyUpdatedAt>pt&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:ct*r+(1-ct)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=o,n!==void 0){let i=t.apiLatency.get(n);!i||o-i.updatedAt>pt?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:o}):(i.ewmaMs=ct*r+(1-ct)*i.ewmaMs,i.sampleCount++,i.updatedAt=o);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(i.cooldownUntil>0&&i.cooldownUntil<=o||i.lastFailureTime>0&&o-i.lastFailureTime>3e4)&&(i.count=0,i.cooldownUntil=0),i.count++,i.lastFailureTime=o,i.count>=Nn&&(i.cooldownUntil=o+Bn),n.apiFailures.set(r,i);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};i.count=Math.max(i.count+1,Nn),i.lastFailureTime=o,i.cooldownUntil=o+Bn,i.defective=true,n.apiFailures.set(r,i);}recordRateLimit(t,r){let n=this.getOrCreate(t),o=Date.now();n.rateLimitStreak>0&&o-n.lastRateLimitAt>Ts&&(n.rateLimitStreak=0);let i=typeof r=="number"&&Number.isFinite(r)&&r>0,s=i?r:Math.min(Cs*2**n.rateLimitStreak,Rs);i||n.rateLimitStreak++,n.lastRateLimitAt=o,n.rateLimitedUntil=i?o+s:Math.max(n.rateLimitedUntil,o+s),n.consecutiveFailures++,n.lastFailureTime=o;}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<=Mn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,o)=>n-o),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let o=Date.now();if(n.rateLimitedUntil>o||n.consecutiveFailures>=3&&o-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>o)return false}let i=this.consensusHeadBlock();return !(i>0&&n.headBlock>0&&o-n.headBlockUpdatedAt<=Mn&&i-n.headBlock>qs)}getOrderedNodes(t,r){let n=[],o=[];for(let c of t)this.isNodeHealthy(c,r)?n.push(c):o.push(c);if(n.length<=1)return [...n,...o];let i=Date.now(),s=n.map((c,p)=>({node:c,i:p,score:this.scoreNode(c,i)})).sort((c,p)=>c.score-p.score||c.i-p.i).map(c=>c.node),a=this.pickReprobeCandidate(n,i);return a&&s[0]!==a?[a,...s.filter(c=>c!==a),...o]:[...s,...o]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=_r&&r-t.latencyUpdatedAt<=pt}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:jn}pickReprobeCandidate(t,r){let n=r-Vn,o,i=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(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;}},br=new wr;function Kt(e,t,r,n,o){let i=S.resilience;if(!i.adaptiveTimeout||o)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(i.adaptiveTimeoutFloorMs,i.adaptiveTimeoutFactor*s)))}function Pr(e,t,r,n){r instanceof Be?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof te?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 o=n.head_block_number;typeof o=="number"&&e.recordHeadBlock(t,o);}function Fs(){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 Ar(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(Fs()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function Nt(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),o=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",o,{once:true});let i=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o);};return {signal:r.signal,cleanup:i}}var lt=async(e,t,r,n=S.timeout,o=false,i)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:c,cleanup:p}=Ar(n),{signal:l,cleanup:f}=Nt(c,i),m=()=>{p(),f();};try{let g=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...vr()},signal:l});if(g.status===429)throw new Be(e,"HTTP 429 Rate Limited",{rateLimitMs:Hn(g.headers.get("Retry-After")),isRateLimit:!0});if(g.status>=500&&g.status<600)throw new Be(e,`HTTP ${g.status} from ${e}`);let _=await g.json();if(!_||typeof _.id>"u"||_.id!==s||_.jsonrpc!=="2.0")throw new Error("JSONRPC id mismatch");if("result"in _)return _.result;if("error"in _){let A=_.error;throw "message"in A&&"code"in A?new te(A):_.error}throw _}catch(g){if(g instanceof te||g instanceof Be||i?.aborted)throw g;if(o)return lt(e,t,r,n,false,i);throw g}finally{m();}};function It(){return ut(50+Math.random()*50)}function Is(e){let{method:t,params:r,api:n,primary:o,hedgePool:i,callerTimeout:s,explicitTimeout:a,deadlineAt:c,externalSignal:p,onHedgeFired:l,validate:f}=e;return new Promise((m,g)=>{let _=false,A=0,x=false,q=false,F,le,O=0,G=[],H=X=>{if(!_){_=true,le!==void 0&&(clearTimeout(le),le=void 0);for(let I of G)I.signal.aborted||I.abort();X();}},U=(X,I)=>{A++;let ye=new AbortController;G.push(ye);let at=Nt(ye.signal,p),ps=Kt($,X,t,s,a),ar=Date.now();I||(O=ar),lt(X,t,r,ps,false,at.signal).then(se=>{if(at.cleanup(),A--,I||(q=true),!_){if(f&&!f(se)){if($.recordDefectiveResponse(X,n),F=new Error(`[hive-tx] response validation failed for ${t} from ${X}`),!I&&!x){H(()=>g(F));return}A===0&&H(()=>g(F));return}$.recordSuccess(X,n,Date.now()-ar,t),$n($,X,t,se),I?q||$.recordCensoredLatency(o,Date.now()-O,t):x||br.refill(),H(()=>m(se));}}).catch(se=>{if(at.cleanup(),A--,I||(q=true),!_){if(p?.aborted){H(()=>g(se));return}if(se instanceof te&&!hr(se.code,se.message)){H(()=>g(se));return}if(Pr($,X,se,n),$.recordSlowFailure(X,Date.now()-ar,t),F=se,!I&&!x){H(()=>g(se));return}A===0&&H(()=>g(F));}});};U(o,false);let Y=$.getUsableLatencyMs(o,t)??0,W=Kt($,o,t,s,a),st=Math.min(Math.max(S.resilience.hedgeDelayFloorMs,S.resilience.hedgeDelayFactor*Y),.8*W);le=setTimeout(()=>{if(le=void 0,_||p?.aborted||Date.now()>=c)return;let X=i.filter(ye=>$.isNodeHealthy(ye,n));if(X.length===0)return;let I=X[Math.floor(Math.random()*X.length)];br.trySpend()&&(x=true,l(I),U(I,true));},st);})}var y=async(e,t=[],r,n=S.retry,o,i)=>{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,c=Un(e),p=Rt;if(p&&Qn&&p.methodSet.has(e))if(Date.now()=p.failureThreshold&&(Kn=Date.now()+p.cooldownMs,Ft=0);}let l=Date.now()+S.resilience.totalBudgetFactor*a,f=new Set,m;for(let g=0;g<=n&&!(g>0&&Date.now()>=l);g++){let _=$.getOrderedNodes(S.nodes,c),A=_.find(F=>!f.has(F));A||(f.clear(),A=_[0]),f.add(A);let x=[];if(S.resilience.hedge&&$.getUsableLatencyMs(A,e)!==void 0&&(x=_.filter(F=>!f.has(F)&&$.isNodeHealthy(F,c)).slice(0,3)),x.length>0)try{return await Is({method:e,params:t,api:c,primary:A,hedgePool:x,callerTimeout:a,explicitTimeout:s,deadlineAt:l,externalSignal:o,onHedgeFired:F=>f.add(F),validate:i})}catch(F){if(F instanceof te&&!hr(F.code,F.message)||o?.aborted)throw F;m=F,g{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 o=Un(e),i=new Set,s;for(let a=0;a!i.has(l));if(!p)break;if(i.add(p),n?.aborted)throw new Error("Aborted");try{let l=await lt(p,e,t,r,!1,n);return $.recordSuccess(p,o),l}catch(l){if(l instanceof te||n?.aborted||(Pr($,p,l,o),s=l,!ks(l)))throw l}}throw s},Ds={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 ne(e,t,r,n,o=S.retry,i){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,c=Date.now()+S.resilience.totalBudgetFactor*a,p=`${e}:${t}`,l=S.restNodesByApi?.[e]?.length?S.restNodesByApi[e]:S.restNodes,f=new Set,m,g=false;for(let _=0;_<=o&&!(_>0&&Date.now()>=c);_++){let A=Re.getOrderedNodes(l,e),x=A.find(I=>!f.has(I));x||(f.clear(),x=A[0]),f.add(x);let q=x+Ds[e],F=t,le=r||{},O=new Set;Object.entries(le).forEach(([I,ye])=>{F.includes(`{${I}}`)&&(F=F.replace(`{${I}}`,encodeURIComponent(String(ye))),O.add(I));});let G=new URL(q+F);if(Object.entries(le).forEach(([I,ye])=>{O.has(I)||(Array.isArray(ye)?ye.forEach(at=>G.searchParams.append(I,String(at))):G.searchParams.set(I,String(ye)));}),i?.aborted)throw new Error("Aborted");g=false;let{signal:H,cleanup:U}=Ar(Kt(Re,x,p,a,s)),{signal:Y,cleanup:W}=Nt(H,i),st=()=>{U(),W();},X=Date.now();try{let I=await fetch(G.toString(),{signal:Y,headers:vr()});if(I.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(I.status===429)throw Re.recordRateLimit(x,Hn(I.headers.get("Retry-After"))||void 0),g=!0,new Error(`HTTP 429 Rate Limited by ${x}`);if(I.status===503)throw Re.recordFailure(x,e),g=!0,new Error(`HTTP 503 Service Unavailable from ${x}`);if(!I.ok)throw Re.recordFailure(x,e),g=!0,new Error(`HTTP ${I.status} from ${x}`);return Re.recordSuccess(x,e,Date.now()-X,p),I.json()}catch(I){if(I?.message?.includes("HTTP 404")||i?.aborted)throw I;g||Re.recordFailure(x,e),Re.recordSlowFailure(x,Date.now()-X,p),m=I,_{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 i=(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})(S.nodes),s=Math.min(r,i.length),a=[];for(;s>0&&i.length>0;){let c=i.splice(0,s),p=[],l=[];for(let m=0;ml.push(g)).catch(()=>{}));await Promise.all(p),a.push(...l);let f=Ks(a,r);if(f)return f;if(s=Math.min(r,i.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function Ks(e,t){let r=new Map;for(let o of e){let i=JSON.stringify(o);r.has(i)||r.set(i,[]),r.get(i).push(o);}let n=Array.from(r.values()).find(o=>o.length>=t);return n?n[0]:null}var Bs=hexToBytes(S.chain_id),Me=class e{constructor(t){P(this,"transaction");P(this,"expiration",6e4);P(this,"txId");P(this,"createTransaction",async t=>{let r=await y("condenser_api.get_dynamic_global_properties",[]),n=hexToBytes(r.head_block_id),o=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),i=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:i,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:o,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 o of t){let i=o.sign(r);this.transaction.signatures.push(i.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 ze("condenser_api.broadcast_transaction",[this.transaction]);}catch(i){if(!(i instanceof te&&i.message.includes("Duplicate transaction check failed")))throw i}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await ut(1e3);let n=await this.checkStatus(),o=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&o>6,128|i&63);else if(i>=55296&&i<=56319&&o+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else n.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(n);}return new e(sha256(t))}static fromLogin(t,r,n="active"){let o=t+n+r;return e.fromSeed(o)}sign(t){let r=secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(bytesToHex(r.subarray(0,1)),16);return ke.from((n+31).toString(16)+bytesToHex(r.subarray(1)))}createPublic(t){return new Z(secp256k1.getPublicKey(this.key),t)}toString(){return Hs(new Uint8Array([...Xn,...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)}},Zn=e=>sha256(sha256(e)),Hs=e=>{let t=Zn(e);return kn.encode(new Uint8Array([...e,...t.slice(0,4)]))},Us=e=>{let t=kn.decode(e);if(!Jn(t.slice(0,1),Xn))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),o=Zn(n).slice(0,4);if(!Jn(r,o))throw new Error("Private key checksum mismatch");return n},Jn=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;nno(e,t,n,r),ro=(e,t,r,n,o)=>no(e,t,r,n,o).message,no=(e,t,r,n,o)=>{let i=r,s=e.getSharedSecret(t),a=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);a.writeUint64(i),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 K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);m.append(f),m.flip();let g=m.readUint32();if(o!==void 0){if(g!==o)throw new Error("Invalid key");n=$s(n,l,p);}else n=Ws(n,l,p);return {nonce:i,message:n,checksum:g}},$s=(e,t,r)=>{let n=e;return n=cbc(t,r).decrypt(n),n},Ws=(e,t,r)=>{let n=e;return n=cbc(t,r).encrypt(n),n},xr=null,Gs=()=>{if(xr===null){let r=secp256k1.utils.randomSecretKey();xr=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++xr%65536;return e=e<{let t=ea(e,33);return new Z(t)},Js=e=>e.readUint64(),Ys=e=>e.readUint32(),Xs=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},Zs=e=>t=>{let r={},n=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);n.append(t),n.flip();for(let[o,i]of e)try{r[o]=i(n);}catch(s){throw s.message=`${o}: ${s.message}`,s}return r};function ea(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 ta=Zs([["from",oo],["to",oo],["nonce",Js],["check",Ys],["encrypted",Xs]]),io={Memo:ta};var ao=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),co(),e=po(e),t=ra(t);let o=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);o.writeVString(r);let i=new Uint8Array(o.copy(0,o.offset).toBuffer()),{nonce:s,message:a,checksum:c}=to(e,t,i,n),p=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);me.Memo(p,{check:c,encrypted:a,from:e.createPublic(),nonce:s,to:t}),p.flip();let l=new Uint8Array(p.toBuffer());return "#"+kn.encode(l)},uo=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),co(),e=po(e);let r=io.Memo(kn.decode(t)),{from:n,to:o,nonce:i,check:s,encrypted:a}=r,p=e.createPublic().toString()===new Z(n.key).toString()?new Z(o.key):new Z(n.key);r=ro(e,p,i,a,s);let l=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},Mt,co=()=>{if(Mt===void 0){let e;Mt=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=ao(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=uo(t,n);}finally{Mt=e==="#memo\u7231";}}if(Mt===false)throw new Error("This environment does not support encryption.")},po=e=>typeof e=="string"?V.fromString(e):e,ra=e=>typeof e=="string"?Z.fromString(e):e,lo={decode:uo,encode:ao};var ie={};St(ie,{buildWitnessSetProperties:()=>ua,makeBitMaskFilter:()=>sa,operations:()=>ia,validateUsername:()=>oa});var oa=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("."),o=n.length;for(let i=0;ie.reduce(aa,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),aa=([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 o;switch(n){case "key":case "new_signing_key":o=me.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":o=me.UInt32;break;case "hbd_interest_rate":o=me.UInt16;break;case "url":o=me.String;break;case "hbd_exchange_rate":o=me.Price;break;case "account_creation_fee":o=me.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,ca(o,t[n])]);}return r.props.sort((n,o)=>n[0].localeCompare(o[0])),["witness_set_properties",r]},ca=(e,t)=>{let r=new K(K.DEFAULT_CAPACITY,K.LITTLE_ENDIAN);return e(r,t),r.flip(),bytesToHex(new Uint8Array(r.toBuffer()))};function $g(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|o&63);else if(o>=55296&&o<=56319&&n+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else r.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(r);}else t=e;return sha256(t)}function fo(e){try{return V.fromString(e),!0}catch{return false}}async function re(e,t){let r=new Me;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),ze("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function mo(e,t){let r=new Me;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var la=432e3;function go(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/la,o=Math.round(n/e*1e4);return !isFinite(o)||o<0?o=0:o>1e4&&(o=1e4),{current_mana:n,max_mana:e,percentage:o}}function da(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),o=parseFloat(e.vesting_withdraw_rate),i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t-s-r+n}function Sr(e){let t=da(e)*1e6;return go(t,e.voting_manabar)}function Qt(e){return go(Number(e.max_rc),e.rc_manabar)}var yo=(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))(yo||{});function Je(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",o=t||r||String(e||""),i=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||o&&a.test(o));if(i(/please wait to transact/i)||i(/insufficient rc/i)||i(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(i(/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(i(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(i(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(i(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(i(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(i(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(i(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(i(/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(i(/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(i(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(i(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(i(/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"||i(/token expired/i)||i(/invalid token/i)||i(/\bunauthorized\b/i)||i(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(i(/has already reblogged/i)||i(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(i(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(i(/econnrefused/i)||i(/connection refused/i)||i(/failed to fetch/i)||i(/\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(i(/timeout/i)||i(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(i(/account.*does not exist/i)||i(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(i(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(i(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(i(/\b(invalid|validation)\b/i))return {message:(e?.message||o).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}`:o&&o!=="[object Object]"?s=o.substring(0,150):s="Unknown error occurred":s=o.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function fa(e){let t=Je(e);return [t.message,t.type]}function Pe(e){let{type:t}=Je(e);return t==="missing_authority"||t==="token_expired"}function ma(e){let{type:t}=Je(e);return t==="insufficient_resource_credits"}function ga(e){let{type:t}=Je(e);return t==="info"}function ya(e){let{type:t}=Je(e);return t==="network"||t==="timeout"}async function Ae(e,t,r,n,o="posting",i,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=i;if(p===void 0)switch(o){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 ${o} key available for ${t}`);let l=V.fromString(p);return a==="async"?await mo(r,l):await re(r,l)}case "hiveauth":{if(!c?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await c.broadcastWithHiveAuth(t,r,o)}case "hivesigner":{if(!c)throw new Error("No adapter provided for HiveSigner auth");if(o!=="posting"){if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);throw new Error(`HiveSigner access token cannot sign ${o} operations. No platform broadcast available.`)}let p=s!==void 0?s:await c.getAccessToken(t);if(p)try{return (await new ho.Client({accessToken:p}).broadcast(r)).result}catch(l){if(c.broadcastWithHiveSigner&&Pe(l))return await c.broadcastWithHiveSigner(t,r,o);throw l}if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);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,o)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,o)}default:throw new Error(`Unknown auth method: ${e}`)}}async function _a(e,t,r,n="posting",o="async"){let i=r?.adapter;if(i?.getLoginType){let l=await i.getLoginType(e,n);if(l){let f=i.hasPostingAuthorization?await i.hasPostingAuthorization(e):false;if(n==="posting"&&f&&l==="key")try{return await Ae("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!Pe(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&f&&l==="keychain")try{return await Ae("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!Pe(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 Ae("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!Pe(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await Ae(l,e,t,r,n,void 0,void 0,o)}catch(m){if(Pe(m)&&i.showAuthUpgradeUI&&(n==="posting"||n==="active")){let g=t.length>0?t[0][0]:"unknown",_=await i.showAuthUpgradeUI(n,g);if(!_)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await Ae(_,e,t,r,n,void 0,void 0,o)}throw m}}if(n==="posting")try{return await Ae("hivesigner",e,t,r,n,void 0,void 0,o)}catch(f){if(Pe(f)&&i.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",g=await i.showAuthUpgradeUI(n,m);if(!g)throw new Error(`No login type available for ${e}. Please log in again.`);return await Ae(g,e,t,r,n,void 0,void 0,o)}throw f}else if(n==="active"&&i.showAuthUpgradeUI){let f=t.length>0?t[0][0]:"unknown",m=await i.showAuthUpgradeUI(n,f);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await Ae(m,e,t,r,n,void 0,void 0,o)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let f=!1,m="",g,_;switch(l){case "key":if(!i)f=!0,m="No adapter provided";else {let A;switch(n){case "owner":i.getOwnerKey&&(A=await i.getOwnerKey(e));break;case "active":i.getActiveKey&&(A=await i.getActiveKey(e));break;case "memo":i.getMemoKey&&(A=await i.getMemoKey(e));break;default:A=await i.getPostingKey(e);break}A?g=A:(f=!0,m=`No ${n} key available`);}break;case "hiveauth":i?.broadcastWithHiveAuth||(f=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!i)f=!0,m="No adapter provided";else {let A=await i.getAccessToken(e);A&&(_=A);}break;case "keychain":i?.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 Ae(l,e,t,r,n,g,_,o)}catch(f){if(a.set(l,f),!Pe(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=()=>{},o,i="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(o?.enableFallback!==!1&&o?.adapter)return await _a(t,p,o,i,a);if(o?.broadcast)return await o.broadcast(p,i);let l=o?.postingKey;if(l){if(i!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${i}' was requested. Use AuthContextV2 with an adapter for ${i} operations.`);let m=V.fromString(l);return await re(p,m)}let f=o?.accessToken;if(f)return (await new ho.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 te?new Error(l.message):l}}})}async function _o(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let o={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",o]],"posting");let i=n?.postingKey;if(i){let c=V.fromString(i);return re([["custom_json",o]],c)}let s=n?.accessToken;if(s)return (await new ho.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let c=[["custom_json",o]];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 uy=4e3;function E(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function Oe(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,o=()=>{let i=t.aborted?t.reason:r.reason;n.abort(i),t.removeEventListener("abort",o),r.removeEventListener("abort",o);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",o,{once:true}),r.addEventListener("abort",o,{once:true})),n.signal}var Qe=(()=>{try{return !1}catch{return false}})(),va=()=>{try{return ""}catch{return}},xe=1e4,wo=120*1e3,Ht,Pa;function Aa(){return Ht?Ht():Pa??(Pa=new QueryClient)}var d={privateApiHost:"https://ecency.com",defaultObserver:"ecency",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return S.nodes},heliusApiKey:va(),get queryClient(){return Aa()},set queryClient(e){Ht=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false},M;(le=>{function e(O){d.queryClient=O;}le.setQueryClient=e;function t(O){Ht=O;}le.setQueryClientResolver=t;function r(O){d.privateApiHost=O;}le.setPrivateApiHost=r;function n(O){d.clientId=O;}le.setClientId=n;function o(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;}le.setDefaultObserver=o;function i(){return d.privateApiHost?d.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}le.getValidatedBaseUrl=i;function s(O){d.pollsApiHost=O;}le.setPollsApiHost=s;function a(O){d.imageHost=O;}le.setImageHost=a;function c(O){pr(O);}le.setHiveNodes=c;function p(O){lr(O);}le.setRestNodes=p;function l(O){dr(O);}le.setRestNodesByApi=l;function f(O){fr(O);}le.setUserAgent=f;function m(O){mr(O);}le.setResilience=m;function g(O){ur(O);}le.setServerRpcProxy=g;function _(){return Te}le.getServerRpcProxyStats=_;function A(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 G=/\.?\{(\d+),(\d+)\}/g,H;for(;(H=G.exec(O))!==null;){let[,U,Y]=H;if(parseInt(Y,10)-parseInt(U,10)>1e3)return {safe:false,reason:`excessive range: {${U},${Y}}`}}return {safe:true}}function x(O){let G=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],H=5;for(let U of G){let Y=Date.now();try{O.test(U);let W=Date.now()-Y;if(W>H)return {safe:!1,reason:`runtime test exceeded ${H}ms (took ${W}ms on input length ${U.length})`}}catch(W){return {safe:false,reason:`runtime test threw error: ${W}`}}}return {safe:true}}function q(O,G=200){try{if(!O)return Qe&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(O.length>G)return Qe&&console.warn(`[SDK] DMCA pattern rejected: length ${O.length} exceeds max ${G} - pattern: ${O.substring(0,50)}...`),null;let H=A(O);if(!H.safe)return Qe&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${H.reason}) - pattern: ${O.substring(0,50)}...`),null;let U;try{U=new RegExp(O);}catch(W){return Qe&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${O.substring(0,50)}...`,W),null}let Y=x(U);return Y.safe?U:(Qe&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${Y.reason}) - pattern: ${O.substring(0,50)}...`),null)}catch(H){return Qe&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${O.substring(0,50)}...`,H),null}}function F(O={}){let G=W=>Array.isArray(W)?W.filter(st=>typeof st=="string"):[],H=O||{},U={accounts:G(H.accounts),tags:G(H.tags),patterns:G(H.posts)};d.dmcaAccounts=U.accounts,d.dmcaTags=U.tags,d.dmcaPatterns=U.patterns,d.dmcaTagRegexes=U.tags.map(W=>q(W)).filter(W=>W!==null),d.dmcaPatternRegexes=[];let Y=U.tags.length-d.dmcaTagRegexes.length;!d._dmcaInitialized&&Qe&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${U.accounts.length}`),console.log(` - Tag patterns: ${d.dmcaTagRegexes.length}/${U.tags.length} compiled (${Y} rejected)`),console.log(` - Post patterns: ${U.patterns.length} (using exact string matching)`),Y>0&&console.warn(`[SDK] ${Y} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),d._dmcaInitialized=true;}le.setDmcaLists=F;})(M||(M={}));function by(){return new QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var b=()=>d.queryClient,bo;(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 o(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>useQuery(a),fetchAndGet:()=>b().fetchQuery(a)}}s.generateClientServerQuery=o;function i(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>useInfiniteQuery(a),fetchAndGet:()=>b().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=i;})(bo||(bo={}));function Py(e){return btoa(JSON.stringify(e))}function Ay(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var vo=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(vo||{}),Ut=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(Ut||{});function C(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:vo[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:Ut[e.nai]}}var Er;function h(){if(!Er){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");Er=globalThis.fetch.bind(globalThis);}return Er}function Po(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function Ea(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function ue(e,t){return Ea(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function Ye(e,t){return e/1e6*t}function Ao(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var Oo=60*1e3;function Se(){return queryOptions({queryKey:u.core.dynamicProps(),refetchInterval:Oo,staleTime:Oo,queryFn:async({signal:e})=>{let[t,r,n,o,i]=await Promise.all([y("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),y("condenser_api.get_feed_history",[],void 0,void 0,e),y("condenser_api.get_chain_properties",[],void 0,void 0,e),y("condenser_api.get_reward_fund",["post"],void 0,void 0,e),y("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(o.recent_claims),m=C(o.reward_balance).amount,g=Number(t.vote_power_reserve_rate??0),_=o.author_reward_curve??"linear",A=Number(o.content_constant??0),x=String(i.current_hardfork_version??"0.0.0"),q=Number(i.last_hardfork??0),F=t.hbd_print_rate,le=t.hbd_interest_rate,O=t.head_block_number,G=a,H=s,U=C(t.virtual_supply).amount,Y=t.vesting_reward_percent||0,W=n.account_creation_fee;return {hivePerMVests:c,base:p,quote:l,fundRecentClaims:f,fundRewardBalance:m,votePowerReserveRate:g,authorRewardCurve:_,contentConstant:A,currentHardforkVersion:x,lastHardfork:q,hbdPrintRate:F,hbdInterestRate:le,headBlock:O,totalVestingFund:G,totalVestingShares:H,virtualSupply:U,vestingRewardPercent:Y,accountCreationFee:W,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:o,hardforkProps:i}}}})}function My(e="post"){return queryOptions({queryKey:u.core.rewardFund(e),queryFn:()=>y("condenser_api.get_reward_fund",[e])})}function He(...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,o,i)=>["posts","account-posts-page",e,t,r,n,o,i],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)=>He("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>He("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>He("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>He("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,o,i)=>["posts","posts-ranked-page",e,t,r,n,o,i],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)=>He("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)=>He("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,o,i)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,o,i],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,o,i)=>He("search","api",e,t,r,n,o,i)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,o)=>["witnesses","voters",e,t,r,n,o],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]},newsletter:{subscriptions:e=>["newsletter","subscriptions",e],sender:(e,t,r)=>["newsletter","sender",e,t,r],issues:(e,t,r)=>["newsletter","issues",e,t,r],posts:(e,t,r,n)=>["newsletter","posts",e,t,r,n],_prefix:["newsletter"]},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 ft(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 Ly(e){return queryOptions({queryKey:u.ai.prices(),queryFn:async()=>{let r=await h()(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 zy(e,t){return queryOptions({queryKey:u.ai.assistPrices(e),queryFn:async()=>{let n=await h()(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 Zy(e,t){return queryOptions({queryKey:u.ai.transcribePrice(e),queryFn:async()=>{let n=await h()(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 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 nh(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 o=await h()(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??Ia()})});if(!o.ok){let s=await o.text(),a={};try{a=JSON.parse(s);}catch{}let c=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${o.status}${s?`: ${s}`:""}`);throw c.status=o.status,c.data=a,c}if(o.status===202){let s={};try{s=await o.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await o.json()},onSuccess:()=>{e&&b().invalidateQueries({queryKey:u.points._prefix(e)});}})}function Ka(){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 ah(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 o=await h()(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:Ka()})});if(!o.ok){let i=await o.text(),s={};try{s=JSON.parse(i);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${o.status}${i?`: ${i}`:""}`);throw a.status=o.status,a.data=s,a}return await o.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:u.points._prefix(e)}),b().invalidateQueries({queryKey:u.ai.assistPrices(e)}));}})}function Ba(){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 lh(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 o=new FormData;o.append("code",n),o.append("duration_ms",String(Math.round(r.durationMs))),o.append("idempotency_key",r.idempotency_key??Ba()),o.append("audio",r.audio,r.fileName??"clip.webm");let s=await h()(d.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:o});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 kr(e){return !e.posting_json_metadata&&!e.json_metadata}function Qa(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([y("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),y("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 o=r[0];if(kr(o)&&Qa(n?.metadata?.profile)){let p=await y("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!kr(l[0])));if(p[0]&&!kr(p[0]))o=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let i=Ue(o.posting_json_metadata),s=n?.stats,a=s?{account:o.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,c=n?.reputation??0;return {name:o.name,owner:o.owner,active:o.active,posting:o.posting,memo_key:o.memo_key,post_count:o.post_count,created:o.created,posting_json_metadata:o.posting_json_metadata,last_vote_time:o.last_vote_time,last_post:o.last_post,json_metadata:o.json_metadata,reward_hive_balance:o.reward_hive_balance,reward_hbd_balance:o.reward_hbd_balance,reward_vesting_hive:o.reward_vesting_hive,reward_vesting_balance:o.reward_vesting_balance,balance:o.balance,hbd_balance:o.hbd_balance,savings_balance:o.savings_balance,savings_hbd_balance:o.savings_hbd_balance,savings_hbd_last_interest_payment:o.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:o.savings_hbd_seconds_last_update,savings_hbd_seconds:o.savings_hbd_seconds,next_vesting_withdrawal:o.next_vesting_withdrawal,pending_claimed_accounts:o.pending_claimed_accounts,vesting_shares:o.vesting_shares,delegated_vesting_shares:o.delegated_vesting_shares,received_vesting_shares:o.received_vesting_shares,vesting_withdraw_rate:o.vesting_withdraw_rate,to_withdraw:o.to_withdraw,withdrawn:o.withdrawn,witness_votes:o.witness_votes,proxy:o.proxy,recovery_account:o.recovery_account,proxied_vsf_votes:o.proxied_vsf_votes,voting_manabar:o.voting_manabar,voting_power:o.voting_power,downvote_manabar:o.downvote_manabar,follow_stats:a,reputation:c,profile:i}},enabled:!!e,staleTime:6e4})}var Ha=new Set(["__proto__","constructor","prototype"]);function Vt(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function xo(e,t){let r={...e};for(let n of Object.keys(t)){if(Ha.has(n))continue;let o=t[n],i=r[n];Vt(o)&&Vt(i)?r[n]=xo(i,o):r[n]=o;}return r}function Ua(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:o,...i}=t;return {...r,meta:i}})}function Ue(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 So(e){return Ue(e?.posting_json_metadata)}function Eo(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(Ue(e.posting_json_metadata)).length;return Object.keys(Ue(t.posting_json_metadata)).length>r?t:e}function Va(e){if(!e)return {};try{let t=JSON.parse(e);if(Vt(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function ko({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=Va(e),o=Vt(n.profile)?n.profile:{},i=Cr({existingProfile:o,profile:t,tokens:r});return JSON.stringify({...n,profile:i})}function Cr({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:o,...i}=t??{},s=xo(e??{},i);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=Ua(s.tokens),s.version=2,s}function jt(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=Ue(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let o=JSON.parse(t.json_metadata||"{}");o.profile&&(n=o.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function ja(e){return new TextEncoder().encode(e).length}function Xe(e){return e?ja(e)<=16:false}function Eh(e){return queryOptions({queryKey:u.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(Xe);if(t.length===0)return [];let r=await y("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return jt(r??[])}})}function qh(e){return queryOptions({queryKey:u.accounts.followCount(e),queryFn:()=>y("condenser_api.get_follow_count",[e])})}function Nh(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.followers(e,t,r,n),queryFn:()=>y("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function Uh(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.following(e,t,r,n),queryFn:()=>y("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var Co=1e3,Ja=20;function Wh(e){return queryOptions({queryKey:u.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(i[0]===r&&(i=i.slice(1)),!i.length||(t.push(...i),o.lengthXe(e)?y("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function o_(e,t=5,r=[]){return queryOptions({queryKey:u.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await y("condenser_api.lookup_accounts",[e,t])).filter(o=>r.length>0?!r.includes(o):true)})}var eu=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function u_(e,t){return queryOptions({queryKey:u.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await h()(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 o=await n.json(),i=Array.isArray(o)?o.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,g=(typeof a.status=="number"?a.status===3:void 0)??false;f&&(l.address=f),l.show=g;let _={symbol:c,currency:c,address:f,show:g,type:"CHAIN",meta:l},A=[];for(let[x,q]of Object.entries(p))typeof x=="string"&&(eu.has(x)||typeof q!="string"||!q||/^[A-Z0-9]{2,10}$/.test(x)&&A.push({symbol:x,currency:x,address:q,show:g,type:"CHAIN",meta:{address:q,show:g}}));return [_,...A]}):[];return {exist:i.length>0,tokens:i.length?i:void 0,wallets:i.length?i:void 0}},refetchOnMount:true})}function Ro(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 y("bridge.get_relationship_between_accounts",[e,t])??r}})}function h_(e){return queryOptions({queryKey:u.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await y("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function v_(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 h()(d.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function P_(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 i=await h()(`${d.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch bookmarks: ${i.status}`);let s=await i.json();return ue(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function S_(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 h()(d.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function E_(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 i=await h()(`${d.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch favorites: ${i.status}`);let s=await i.json();return ue(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function T_(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 o=await h()(d.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!o.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${o.status}: ${o.statusText}`);let i=await o.json();if(typeof i!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof i}`);return i}})}function D_(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 h()(d.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Q_(e){return queryOptions({enabled:!!e,queryKey:u.accounts.pendingRecovery(e),queryFn:()=>y("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function $_(e,t=50){return queryOptions({queryKey:u.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!Xe(e)?[]:y("condenser_api.get_account_reputations",[e,t])})}var N=ie.operations,To={transfers:[N.transfer,N.transfer_to_savings,N.transfer_from_savings,N.cancel_transfer_from_savings,N.fill_transfer_from_savings,N.recurrent_transfer,N.fill_recurrent_transfer,N.escrow_transfer],"market-orders":[N.fill_convert_request,N.fill_order,N.fill_collateralized_convert_request,N.limit_order_create2,N.limit_order_create,N.limit_order_cancel],interests:[N.interest],"stake-operations":[N.return_vesting_delegation,N.withdraw_vesting,N.transfer_to_vesting,N.set_withdraw_vesting_route,N.update_proposal_votes,N.fill_vesting_withdraw,N.account_witness_proxy,N.delegate_vesting_shares],rewards:[N.author_reward,N.curation_reward,N.producer_reward,N.claim_reward_balance,N.comment_benefactor_reward,N.liquidity_reward,N.proposal_pay]},du=Array.from(new Set(Object.values(To).flat()));function fu(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function mu(e){return e.replace(/_operation$/,"")}function gu(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function yu(e){if(!gu(e))return e;let t=C(e),r=Ut[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function hu(e){let t={};for(let[r,n]of Object.entries(e))t[r]=yu(n);return t}function ew(e,t=20,r=""){let n=r?To[r]:du;return infiniteQueryOptions({queryKey:u.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:o,signal:i})=>{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 ne("hafah","/accounts/{account-name}/operations",m,void 0,void 0,i)},a=f=>f.operations_result.map(m=>{let g=mu(m.op.type);return {...hu(m.op.value),num:fu(m),type:g,timestamp:m.timestamp,trx_id:m.trx_id}}),c=await s(o),p=a(c),l=o??c.total_pages;if(o===null&&p.length1)try{let f=await s(c.total_pages-1);p=[...p,...a(f)],l=c.total_pages-1;}catch(f){if(i?.aborted)throw f}return {entries:p,currentPage:l}},getNextPageParam:o=>{let i=o.currentPage-1;return i>=1?i:void 0}})}function ow(){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 uw(e){return infiniteQueryOptions({queryKey:u.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=M.getValidatedBaseUrl(),o=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&o.searchParams.set("max_id",r.toString());let i=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch referrals: ${i.status}`);return i.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function dw(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 _w(e,t,r){let{followType:n="blog",limit:o=100,enabled:i=true}=r??{};return infiniteQueryOptions({queryKey:u.accounts.friends(e,t,n,o),initialPageParam:{startFollowing:""},enabled:i,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await y(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,o])).map(g=>t==="following"?g.following:g.follower);return (await y("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(g=>({name:g.name,reputation:g.reputation,active:g.active}))},getNextPageParam:s=>s&&s.length===o?{startFollowing:s[s.length-1].name}:void 0})}var Au=30;function Aw(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 y(`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,Au);return (await y("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 kw(e=20){return infiniteQueryOptions({queryKey:u.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>y("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 Iw(e=250){return infiniteQueryOptions({queryKey:u.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>y("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!Po(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function Ze(e,t){return queryOptions({queryKey:u.posts.fragments(e),queryFn:async()=>t?(await h()(d.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function Bw(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 i=await h()(`${d.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch fragments: ${i.status}`);let s=await i.json();return ue(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Uw(e="feed"){return queryOptions({queryKey:u.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 h()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function Ww(e){return queryOptions({queryKey:u.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>y("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function Xw(e,t,r){return queryOptions({queryKey:u.posts.userPostVote(e,t,r),queryFn:async()=>(await y("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function nb(e,t){return queryOptions({queryKey:u.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content",[e,t])})}function ub(e,t){return queryOptions({queryKey:u.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content_replies",{author:e,permlink:t})})}function fb(e,t){return queryOptions({queryKey:u.posts.postHeader(e,t),queryFn:async()=>y("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function oe(e){return Array.isArray(e)?e.map(t=>qo(t)):qo(e)}function qo(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 Fo(e,t,r){try{let n=await Bt("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 Io(e,t,r="",n){let o=t?.trim(),i=`/@${e}/${o??""}`;return queryOptions({queryKey:u.posts.entry(i),queryFn:async()=>{if(!o||o==="undefined")return null;let s=await y("bridge.get_post",{author:e,permlink:o,observer:r});if(!s){let c=await Fo(e,o,r);if(!c)return null;let p=n!==void 0?{...c,num:n}:c;return oe(p)}let a=n!==void 0?{...s,num:n}:s;return oe(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function ce(e,t,r){return y(`bridge.${e}`,t,void 0,void 0,r)}async function Do(e,t,r,n){let{json_metadata:o}=e;if(o?.original_author&&o?.original_permlink&&o.tags?.[0]==="cross-post")try{let i=await Du(o.original_author,o.original_permlink,t,r,n);return i?{...e,original_entry:i,num:r}:e}catch{return e}return {...e,num:r}}async function Ko(e,t,r){let n=e.map(mt),o=await Promise.all(n.map(i=>Do(i,t,void 0,r)));return oe(o)}async function No(e,t="",r="",n=20,o="",i="",s){let a=await ce("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:o,observer:i},s);return Array.isArray(a)?Ko(a,i,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 Rr(e,t,r="",n="",o=20,i="",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:o,observer:i},s);return Array.isArray(a)?Ko(a,i,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 mt(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 Du(e="",t="",r="",n,o){let i=await ce("get_post",{author:e,permlink:t,observer:r},o);if(i){let s=mt(i),a=await Do(s,r,n,o);return oe(a)}}async function kb(e="",t=""){let r=await ce("get_post_header",{author:e,permlink:t});return r&&mt(r)}async function Bo(e,t,r){let n=await ce("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let o={};for(let[i,s]of Object.entries(n))o[i]=mt(s);return o}return n}async function Mo(e,t=""){return ce("get_community",{name:e,observer:t})}async function Cb(e="",t=100,r,n="rank",o=""){return ce("list_communities",{last:e,limit:t,query:r,sort:n,observer:o})}async function Qo(e){let t=await ce("normalize_post",{post:e});return t&&mt(t)}async function Rb(e){return ce("list_all_subscriptions",{account:e})}async function Tb(e){return ce("list_subscribers",{community:e})}async function qb(e,t){return ce("get_relationship_between_accounts",[e,t])}async function Lt(e,t){return ce("get_profiles",{accounts:e,observer:t})}var Uo=(o=>(o.trending="trending",o.author_reputation="author_reputation",o.votes="votes",o.created="created",o))(Uo||{});function Tr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function Ku(e,t,r){let n=l=>Tr(l.pending_payout_value).amount+Tr(l.author_payout_value).amount+Tr(l.curator_payout_value).amount,o=l=>l.net_rshares<0,i=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,f)=>{if(o(l))return 1;if(o(f))return -1;let m=n(l),g=n(f);return m!==g?g-m:0},author_reputation:(l,f)=>{let m=l.author_reputation,g=f.author_reputation;return m>g?-1:m{let m=l.children,g=f.children;return m>g?-1:m{if(o(l))return 1;if(o(f))return -1;let m=Date.parse(l.created),g=Date.parse(f.created);return m>g?-1:mi(l)),p=a[c];return c>=0&&(a.splice(c,1),a.unshift(p)),a}function Vo(e,t="created",r=true,n){let o=n||d.defaultObserver;return queryOptions({queryKey:u.posts.discussions(e?.author,e?.permlink,t,o),queryFn:async()=>{if(!e)return [];let i=await y("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:o}),s=i?Array.from(Object.values(i)):[];return oe(s)},enabled:r&&!!e,select:i=>Ku(e,i,t),structuralSharing:(i,s)=>{if(!i||!s)return s;let a=i.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 Mb(e,t,r,n=true){let o=r||d.defaultObserver;return queryOptions({queryKey:u.posts.discussion(e,t,o),enabled:n&&!!e&&!!t,queryFn:async()=>Bo(e,t,o)})}function $b(e,t="posts",r=20,n="",o=true){return infiniteQueryOptions({queryKey:u.posts.accountPosts(e??"",t,r,n),enabled:!!e&&o,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:i,signal:s})=>{if(!i?.hasNextPage||!e)return [];let a=await Rr(t,e,i.author??"",i.permlink??"",r,n,s);return oe(a??[])},getNextPageParam:i=>{let s=i?.[i.length-1],a=(i?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function Wb(e,t="posts",r="",n="",o=20,i="",s=true){return queryOptions({queryKey:u.posts.accountPostsPage(e??"",t,r,n,o,i),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let c=await Rr(t,e,r,n,o,i,a);return oe(c??[])}})}var jo=new Map;function Hu(e){let t=jo.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>Uu(n,e))}),jo.set(e,t)),t}function Uu(e,t){let r=e.filter(i=>i.stats?.is_pinned),n=e.filter(i=>!i.stats?.is_pinned);if(t==="hot")return [...r,...n];let o=[...n].sort((i,s)=>new Date(s.created).getTime()-new Date(i.created).getTime());return [...r,...o]}function tv(e,t,r=20,n="",o=true,i={}){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 y("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 oe(p)},select:Hu(e),enabled:o,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 rv(e,t="",r="",n=20,o="",i="",s=true){return queryOptions({queryKey:u.posts.postsRankedPage(e,t,r,n,o,i),enabled:s,queryFn:async({signal:a}={})=>{let c=o;d.dmcaTagRegexes.some(l=>l.test(o))&&(c="");let p=await No(e,t,r,n,c,i,a);return oe(p??[])}})}function av(e,t,r=200){return queryOptions({queryKey:u.posts.reblogs(e??"",r),queryFn:async()=>(await y("condenser_api.get_blog_entries",[e??t,0,r])).filter(o=>o.author!==t&&!o.reblogged_on.startsWith("1970-")).map(o=>({author:o.author,permlink:o.permlink})),enabled:!!e})}function dv(e,t){return queryOptions({queryKey:u.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await y("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function yv(e,t){return queryOptions({queryKey:u.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await h()(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 hv(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 i=await h()(`${d.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch schedules: ${i.status}`);let s=await i.json();return ue(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function vv(e,t){return queryOptions({queryKey:u.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await h()(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 Pv(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 i=await h()(`${d.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch drafts: ${i.status}`);let s=await i.json();return ue(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function $o(e){let r=await h()(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 Sv(e,t){return queryOptions({queryKey:u.posts.images(e),queryFn:async()=>!e||!t?[]:$o(t),enabled:!!e&&!!t})}function Ev(e,t){return queryOptions({queryKey:u.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:$o(t),enabled:!!e&&!!t})}function kv(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 i=await h()(`${d.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch images: ${i.status}`);let s=await i.json();return ue(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function qv(e,t,r=false){return queryOptions({queryKey:u.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let o=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(!o.ok)throw new Error(`Failed to fetch comment history: ${o.status}`);return o.json()},enabled:!!e&&!!t})}function Xu(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let o=r.replace(/^@+/,""),i=n.replace(/^\/+/,"");if(!o||!i)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${o}/${i}`}function Kv(e,t){let r=t?.trim(),n=e?.trim(),o=!!n&&!!r&&r!=="undefined",i=o?Xu(n,r):"";return queryOptions({queryKey:u.posts.deletedEntry(i),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:o})}function Qv(e,t,r=true){return queryOptions({queryKey:u.posts.tips(e,t),queryFn:async()=>{let n=`/private-api/post-tips/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,o=await fetch(d.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch post tips: ${o.status}`);return o.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function ec(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function tc(e){return {...e,id:e.id??e.post_id}}function we(e,t){if(!e)return null;let r=e.container??e,n=ec(r,t),o=e.parent?tc(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:o}}function rc(e){return Array.isArray(e)?e:[]}async function Wo(e){let t=Vo(e,"created",true),r=await d.queryClient.fetchQuery(t),n=rc(r);if(n.length<=1)return [];let o=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return o.length===0?[]:o.filter(s=>!s.stats?.gray)}function Go(e,t,r){return e.length===0?[]:e.map(n=>{let o=e.find(i=>i.author===n.parent_author&&i.permlink===n.parent_permlink&&i.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:o}}).filter(n=>n.container.post_id!==n.post_id).sort((n,o)=>new Date(o.created).getTime()-new Date(n.created).getTime())}var ic=20;function zo(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??ic}}async function Jo({containers:e,tag:t,following:r,author:n,observer:o,limit:i},s,a){let c=M.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",c);p.searchParams.set("limit",String(i)),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),o&&p.searchParams.set("observer",o);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 g=we(m,m.host??"");return g?{...g,_cursor:m._cursor}:null}).filter(m=>!!m)}function Gv(e={}){let t=zo(e),{containers:r,tag:n,following:o,author:i,observer:s,limit:a}=t;return infiniteQueryOptions({queryKey:u.posts.wavesFeed({containers:r,tag:n,following:o,author:i,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:c,signal:p})=>Jo(t,c,p),getNextPageParam:c=>{if(!(c.lengthJo(t,void 0,c)})}var ac=20;function uc(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??ac}}async function cc({containers:e,tag:t,author:r,observer:n,limit:o},i,s){let a=M.getValidatedBaseUrl(),c=new URL("/private-api/waves/shorts",a);c.searchParams.set("limit",String(o)),i&&c.searchParams.set("cursor",i),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=we(f,f.host??"");return m?{...m,active_votes:m.active_votes??[],video:f.video,_cursor:f._cursor}:null}).filter(f=>!!f)}function e0(e={}){let t=uc(e),{containers:r,tag:n,author:o,observer:i,limit:s}=t;return infiniteQueryOptions({queryKey:u.posts.shortsFeed({containers:r,tag:n,author:o,observer:i,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:c})=>cc(t,a,c),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of c){if(i&&l.post_id===i){i=void 0;continue}if(o+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let f;try{f=await Wo(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:Go(f,l,e)}}let p=c[c.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function a0(e){return infiniteQueryOptions({queryKey:u.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await fc(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var gc=40;function d0(e,t,r=gc){return infiniteQueryOptions({queryKey:u.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let o=M.getValidatedBaseUrl(),i=new URL("/private-api/waves/tags",o);i.searchParams.set("container",e),i.searchParams.set("tag",t);let s=await fetch(i.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=>we(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves by tag",o),[]}},getNextPageParam:()=>{}})}function h0(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 o=M.getValidatedBaseUrl(),i=new URL("/private-api/waves/following",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>we(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves following feed",o),[]}},getNextPageParam:()=>{}})}function v0(e,t=24){let r=e?.trim()||void 0;return queryOptions({queryKey:u.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let o=M.getValidatedBaseUrl(),i=new URL("/private-api/waves/trending/tags",o);r&&i.searchParams.set("container",r),i.searchParams.set("hours",t.toString());let s=await fetch(i.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(o){return console.error("[SDK] Failed to fetch waves trending tags",o),[]}}})}function S0(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 o=M.getValidatedBaseUrl(),i=new URL("/private-api/waves/account",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>we(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){throw console.error("[SDK] Failed to fetch waves for account",o),o}},getNextPageParam:()=>{}})}function R0(e){return queryOptions({queryKey:u.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 o=await fetch(n.toString(),{method:"GET",signal:t});if(!o.ok)throw new Error(`Failed to fetch waves trending authors: ${o.status}`);return (await o.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 D0(e,t=true){return queryOptions({queryKey:u.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>Qo(e)})}function Pc(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Yo(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function V0(e,t){let{limit:r=20,filters:n=[],dayLimit:o=7}=t??{};return infiniteQueryOptions({queryKey:u.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:i})=>{let{start:s}=i,a=await y("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,g])=>({...g.op[1],num:m,timestamp:g.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Yo(m.timestamp)<=o),l=[];for(let m of p){let g=await d.queryClient.fetchQuery(Io(m.author,m.permlink));Pc(g)&&l.push(g);}let[f]=a;return {lastDate:f?Yo(f[1].timestamp):0,lastItemFetched:f?f[0]:s,entries:l}},getNextPageParam:i=>({start:i.lastItemFetched})})}function G0(e,t,r=true){return queryOptions({queryKey:u.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Lt(e,t)})}function eP(e,t="HIVE",r=200){return infiniteQueryOptions({queryKey:u.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:o})=>{if(!e)return {entries:[],currentPage:0};let i={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(i.page=n);let s=await ne("balance","/accounts/{account-name}/balance-history",i,void 0,void 0,o);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let o=n.currentPage-1;return o>=1?o:void 0},enabled:!!e})}function iP(e,t="HIVE",r="yearly"){return queryOptions({queryKey:u.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await ne("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function cP(){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 pP(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function yP(e,t,r){let n=useQueryClient(),{data:o}=useQuery(Q(e));return v(["accounts","update"],e,i=>{let s=Eo(n.getQueryData(Q(e).queryKey),o);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:ko({existingPostingJsonMetadata:s.posting_json_metadata,profile:i.profile,tokens:i.tokens})}]]},async(i,s)=>{n.setQueryData(Q(e).queryKey,a=>{if(!a)return a;let c=JSON.parse(JSON.stringify(a));return c.profile=Cr({existingProfile:So(a),profile:s.profile,tokens:s.tokens}),c}),await E(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 vP(e,t,r,n,o){return useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async i=>{let s=Ro(e,t);await b().prefetchQuery(s);let a=b().getQueryData(s.queryKey);return await _o(e,"follow",["follow",{follower:e,following:t,what:[...i==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...i==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:i==="toggle-ignore"?!a?.ignores:a?.ignores,follows:i==="toggle-follow"?!a?.follows:a?.follows}},onError:o,onSuccess(i){n(i),b().setQueryData(u.accounts.relations(e,t),i),t&&b().invalidateQueries(Q(t));}})}function qr(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 Ve(e,t,r,n,o,i,s){if(!e||!t||n===void 0||!i)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:o,body:i,json_metadata:JSON.stringify(s)}]}function je(e,t,r,n,o,i,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:o,allow_curation_rewards:i,extensions:s}]}function Fr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function Ir(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let o={account:e,author:t,permlink:r};return n&&(o.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",o]),required_auths:[],required_posting_auths:[e]}]}function Le(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 Rc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(i=>Le(e,i.trim(),r,n))}function Tc(e,t,r,n,o,i){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(o<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:o,executions:i,extensions:[]}]}function et(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 $e(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:o}]}function Xo(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 gt(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [$e(e,t,r,n,o),Xo(e,o)]}function yt(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 ht(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function _t(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 wt(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 bt(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 Dr(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 We(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 Kr(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function Nr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(o=>o.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 $t(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 qc(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 Fc(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return $t(e,t)}function Mr(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]}],o=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,o]}function Qr(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 Hr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function Ur(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 Vr(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 Ic(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 Dc(e,t,r,n,o){if(e==null||typeof e!="number"||!t||!r||!n||!o)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:o,extensions:[]}]}function jr(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 Lr(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 $r(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 Wr(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 Gr(e,t,r,n,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function zr(e,t,r,n,o,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:o}]),required_auths:[],required_posting_auths:[e]}]}function Kc(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function Nc(e,t,r,n,o){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:o}]),required_auths:[],required_posting_auths:[e]}]}var Zo=(r=>(r.Buy="buy",r.Sell="sell",r))(Zo||{}),ei=(r=>(r.EMPTY="",r.SWAP="9",r))(ei||{});function Gt(e,t,r,n,o,i){if(!e||!t||!r||!o||i===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:i,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:o}]}function Wt(e,t=3){return e.toFixed(t)}function Bc(e,t,r,n,o=""){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 i=new Date(Date.now());i.setDate(i.getDate()+27);let s=i.toISOString().split(".")[0],a=+`${o}${Math.floor(Date.now()/1e3).toString().slice(2)}`,c=n==="buy"?`${Wt(t,3)} HBD`:`${Wt(t,3)} HIVE`,p=n==="buy"?`${Wt(r,3)} HIVE`:`${Wt(r,3)} HBD`;return Gt(e,c,p,false,s,a)}function Jr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function Yr(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 Mc(e,t,r,n,o,i){if(!e||!o)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:o,json_metadata:i}]}function Qc(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 Xr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let o={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={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:o,active:i,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Zr(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]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},i={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:o,posting:i,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function en(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function tn(e,t,r,n,o,i){if(!e||!t||!r||!o)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:o,json_metadata:i}]}function Hc(e,t,r,n,o){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let i={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:i,memo_key:n,json_metadata:o}]}function Uc(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 Vc(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 jc(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 rn(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 nn(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 on(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 tt(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let o=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:o,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function Lc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let o=t.trim().split(/[\s,]+/).filter(Boolean);if(o.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return o.map(i=>tt(e,i.trim(),r,n))}function sn(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 $c(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 Wc(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 UP(e,t,r){return v(["accounts","follow"],e,({following:n})=>[Br(e,n)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function $P(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[$t(e,n)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function JP(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:o,permlink:i})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:o,permlink:i,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 o=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:o,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function oA(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})})).json()},onSuccess:(o,i)=>{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,i)});},onError:n})}function cA(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await h()(d.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async o=>{if(!e)return;let i=b(),s=u.accounts.favorites(e),a=u.accounts.favoritesInfinite(e),c=u.accounts.checkFavorite(e,o);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a}),i.cancelQueries({queryKey:c})]);let p=i.getQueryData(s);p&&i.setQueryData(s,p.filter(g=>g.account!==o));let l=i.getQueryData(c);i.setQueryData(c,false);let f=i.getQueriesData({queryKey:a}),m=new Map(f);for(let[g,_]of f)_&&i.setQueryData(g,{..._,pages:_.pages.map(A=>({...A,data:A.data.filter(x=>x.account!==o)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(o,i)=>{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,i)});},onError:(o,i,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,i),s.previousCheck),n(o);}})}function ep(e,t){let r=new Map;return e.forEach(([n,o])=>{r.set(n.toString(),o);}),t.forEach(([n,o])=>{r.set(n.toString(),o);}),Array.from(r.entries()).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>[n,o])}function ti(e,t){let{data:r}=useQuery(Q(e));return useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:o=false,currentKey:i,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:[]],g=o?l.key_auths.filter(([_])=>!m.includes(_.toString())):[];return l.key_auths=ep(g,n.map((_,A)=>[_[p].createPublic().toString(),A+1])),l};return re([["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()}]],i)},...t})}function wA(e,t){let{data:r}=useQuery(Q(e)),{mutateAsync:n}=ti(e);return useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:o,currentPassword:i,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=V.fromLogin(e,i,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:V.fromLogin(e,o,"owner"),active:V.fromLogin(e,o,"active"),posting:V.fromLogin(e,o,"posting"),memo_key:V.fromLogin(e,o,"memo")}]})},...t})}function xA(e,t,r){let n=useQueryClient(),{data:o}=useQuery(Q(e));return useMutation({mutationKey:["accounts","revoke-posting",o?.name],mutationFn:async({accountName:i,type:s,key:a})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let c=JSON.parse(JSON.stringify(o.posting));c.account_auths=c.account_auths.filter(([l])=>l!==i);let p={account:o.name,posting:c,memo_key:o.memo_key,json_metadata:o.json_metadata};if(s==="key"&&a)return re([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(o.name,[["account_update",p]],"active")}else return t.hsCallbackUrl,ho.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(i,s,a)=>{t.onSuccess?.(i,s,a),n.setQueryData(Q(e).queryKey,c=>({...c,posting:{...c?.posting,account_auths:c?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function qA(e,t,r,n){let{data:o}=useQuery(Q(e));return useMutation({mutationKey:["accounts","recovery",o?.name],mutationFn:async({accountName:i,type:s,key:a,email:c})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:o.name,new_recovery_account:i,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let f=await h()(d.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:c,publicKeys:[...o.owner.key_auths,...o.active.key_auths,...o.posting.key_auths,o.memo_key]})});if(!f.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${f.status}`);return f}else {if(s==="key"&&a)return re([["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(o.name,[["change_recovery_account",p]],"owner")}else return r.hsCallbackUrl,ho.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function IA(e,t){let r=e.key_auths.filter(([o])=>!t.has(String(o))).reduce((o,[,i])=>o+i,0),n=(e.account_auths??[]).reduce((o,[,i])=>o+i,0);return r+n>=e.weight_threshold}function ri(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),o=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([c])=>!r.has(c.toString())),a},i=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:i?o(e.owner):void 0,active:o(e.active),posting:o(e.posting),memo_key:e.memo_key}}function QA(e,t){let{data:r}=useQuery(Q(e));return useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:o})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let i=Array.isArray(o)?o:[o],s=ri(r,i);return re([["account_update",s]],n)},...t})}function jA(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:o="0.000 HIVE"})=>[en(n,o)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(o.creator)]);},t,"active",{broadcastMode:r})}function GA(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[tn(e,n.currentPosting,n.grantedAccount,n.weightThreshold,n.memoKey,n.jsonMetadata)],async()=>{await E(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}function XA(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?Zr(e,n.newAccountName,n.keys):Xr(e,n.newAccountName,n.keys,n.fee)],async()=>{await E(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}var an=300*60*24,dp=1e4,fp=5e7;function ni(e){let t=C(e.vesting_shares).amount,r=C(e.received_vesting_shares).amount,n=C(e.delegated_vesting_shares).amount,o=C(e.vesting_withdraw_rate).amount,i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t+r-n-s}function mp(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function gp(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 yp(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 o=ni(e);if(!Number.isFinite(o)||o<=0)return 0;let i=o*1e6,s=Math.ceil(i*r*60*60*24/dp/(n*an)),a=Sr(e),c=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(c)||s>c?0:Math.max(s-fp,0)}function hp(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(gp(t))return yp(e,t,n);let o=0;try{if(o=ni(e),!Number.isFinite(o))return 0}catch{return 0}return mp(o,r,n)}function rO(e){return Sr(e).percentage/100}function nO(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*an/1e4}function oO(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 o=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/an;o>n&&(o=n);let i=o*100/n;return isNaN(i)?0:i>100?100:i}function iO(e){return Qt(e).percentage/100}function sO(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:o,fundRewardBalance:i,base:s,quote:a}=t;if(!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(a)||o===0||a===0)return 0;let c=hp(e,t,r,n);return Number.isFinite(c)?c/o*i*(s/a):0}var _p={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 wp(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 bp(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function vp(e){let t=e[0];return t==="custom_json"?wp(e):t==="create_proposal"||t==="update_proposal"?bp(e):_p[t]??"posting"}function uO(e){let t="posting";for(let r of e){let n=vp(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function fO(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=V.fromLogin(e,r,"active"):fo(r)?n=V.fromString(r):n=V.from(r),re([t],n)}})}function yO(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 bO(e="/"){return useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>ho.sendOperation(t,{callback:e},()=>{})})}function OO(){return queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await y("condenser_api.get_chain_properties",[])})}function oi(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function ii(e,t){return {...e??{},title:t.title,body:t.body}}function qO(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 i=await h()(d.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${i.status}`);return i.json()},onSuccess(r,n){let o=b(),i=ii(r,n);o.setQueryData(Ze(e,t).queryKey,s=>[i,...s??[]]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,c)=>c===0?{...a,data:[i,...a.data]}:a)});}})}function MO(e,t){return useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:o})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await h()(d.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:o}),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 o=b(),i=s=>oi(s,r,n);o.setQueryData(Ze(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?i(a):a)??[]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(c=>c.id===n.fragmentId?i(c):c)}))});}})}function LO(e,t){return useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await h()(d.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${o.status}`);return o},onSuccess(r,n){let o=b();o.setQueryData(Ze(e,t).queryKey,i=>[...i??[]].filter(({id:s})=>s!==n.fragmentId)),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},i=>i&&{...i,pages:i.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 GO(e,t,r,n){let i=await h()(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(i);return {status:i.status,data:s}}async function zO(e){let r=await h()(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 JO(e,t,r="",n=""){let o={code:e,ty:t};r&&(o.bl=r),n&&(o.tx=n);let s=await h()(d.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});await J(s);}async function YO(e,t,r=null,n=null){let o={code:e};t&&(o.filter=t),r&&(o.since=r),n&&(o.user=n);let s=await h()(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return J(s)}async function XO(e,t,r,n,o,i){let s={code:e,username:t,token:i,system:r,allows_notify:n,notify_types:o},c=await h()(d.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return J(c)}async function ZO(e,t,r){let n={code:e,username:t,token:r},i=await h()(d.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(i)}async function si(e,t){let r={code:e};t&&(r.id=t);let o=await h()(d.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}async function ai(e,t){let r={code:e,url:t},o=await h()(d.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}var Rp="https://i.ecency.com";async function ui(e,t,r){let n=h(),o=new FormData;o.append("file",e);let i=await n(`${Rp}/hs/${t}`,{method:"POST",body:o,signal:r});return J(i)}async function ex(e,t,r,n){let o=h(),i=new FormData;i.append("file",e);let s=await o(`${d.imageHost}/${t}/${r}`,{method:"POST",body:i,signal:n});return J(s)}async function ci(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}async function pi(e,t,r,n,o){let i={code:e,title:t,body:r,tags:n,meta:o},a=await h()(d.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return J(a)}async function li(e,t,r,n,o,i){let s={code:e,id:t,title:r,body:n,tags:o,meta:i},c=await h()(d.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return J(c)}async function di(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}async function fi(e,t,r,n,o,i,s,a){let c={code:e,permlink:t,title:r,body:n,meta:o,schedule:s,reblog:a};i&&(c.options=i);let l=await h()(d.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});return J(l)}async function mi(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}async function gi(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return J(o)}async function tx(e,t,r){let n={code:e,author:t,permlink:r},i=await h()(d.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(i)}async function rx(e,t,r){let n={username:e,email:t,friend:r},i=await h()(d.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return J(i)}function ax(e,t,r,n){return useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:o,body:i,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return pi(t,o,i,s,a)},onSuccess:o=>{r?.();let i=b();o?.drafts?i.setQueryData(u.posts.drafts(e),o.drafts):i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function dx(e,t,r,n){return useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:o,title:i,body:s,tags:a,meta:c})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return li(t,o,i,s,a,c)},onSuccess:()=>{r?.();let o=b();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function _x(e,t,r,n){return useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return di(t,o)},onMutate:async({draftId:o})=>{if(!e)return;let i=b(),s=u.posts.drafts(e),a=u.posts.draftsInfinite(e);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a})]);let c=i.getQueryData(s);c&&i.setQueryData(s,c.filter(f=>f._id!==o));let p=i.getQueriesData({queryKey:a}),l=new Map(p);for(let[f,m]of p)m&&i.setQueryData(f,{...m,pages:m.pages.map(g=>({...g,data:g.data.filter(_=>_._id!==o)}))});return {previousList:c,previousInfinite:l}},onSuccess:()=>{r?.();let o=b();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:(o,i,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?.(o);}})}function Ax(e,t,r,n){return useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:o,title:i,body:s,meta:a,options:c,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return fi(t,o,i,s,a,c,p,l)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function kx(e,t,r,n){return useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return mi(t,o)},onSuccess:o=>{r?.();let i=b();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function Fx(e,t,r,n){return useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return gi(t,o)},onSuccess:o=>{r?.();let i=b();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)}),i.invalidateQueries({queryKey:u.posts.drafts(e)});},onError:n})}function Bx(e,t,r,n){return useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:o,code:i})=>{let s=i??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return ai(s,o)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.images(e)});},onError:n})}function Vx(e,t,r,n){return useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return ci(t,o)},onSuccess:(o,i)=>{r?.();let s=b(),{imageId:a}=i;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 Wx(e,t){return useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:o})=>ui(r,n,o),onSuccess:e,onError:t})}function Jt(e,t){return `/@${e}/${t}`}function Qp(e,t,r){return (r??b()).getQueryData(u.posts.entry(Jt(e,t)))}function Hp(e,t){(t??b()).setQueryData(u.posts.entry(Jt(e.author,e.permlink)),e);}function zt(e,t,r,n){let o=n??b(),i=Jt(e,t),s=o.getQueryData(u.posts.entry(i));if(!s)return;let a=r(s);return o.setQueryData(u.posts.entry(i),a),s}var Fe;(a=>{function e(c,p,l,f,m){zt(c,p,g=>({...g,active_votes:l,stats:{...g.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:g.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){zt(c,p,m=>({...m,reblogs:l}),f);}a.updateReblogsCount=t;function r(c,p,l,f){zt(c,p,m=>({...m,children:l}),f);}a.updateRepliesCount=r;function n(c,p,l,f){zt(p,l,m=>({...m,children:m.children+1,replies:[c,...m.replies]}),f);}a.addReply=n;function o(c,p){c.forEach(l=>Hp(l,p));}a.updateEntries=o;function i(c,p,l){(l??b()).invalidateQueries({queryKey:u.posts.entry(Jt(c,p))});}a.invalidateEntry=i;function s(c,p,l){return Qp(c,p,l)}a.getEntry=s;})(Fe||(Fe={}));function Up(e,t,r){let n=e.some(o=>o.voter===t);return r!==0?n:!n}function Vp(e,t,r){let n=Fe.getEntry(t.author,t.permlink,r);if(!n?.active_votes||Up(n.active_votes,e,t.weight))return;let o=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],i=n.payout+(t.estimated??0);Fe.updateVotes(t.author,t.permlink,o,i,r);}function eS(e,t,r){return v(["posts","vote"],e,({author:n,permlink:o,weight:i})=>[qr(e,n,o,i)],async(n,o)=>{Vp(e,o);let i=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(120,i,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([u.posts.entry(`/@${o.author}/${o.permlink}`),u.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function iS(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:o,deleteReblog:i})=>[Ir(e,n,o,i??false)],async(n,o)=>{let i=Fe.getEntry(o.author,o.permlink);if(i){let p=Math.max(0,(i.reblogs??0)+(o.deleteReblog?-1:1));Fe.updateReblogsCount(o.author,o.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(`/@${o.author}/${o.permlink}`),u.posts.rebloggedBy(o.author,o.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function jp(e){return e.isUpdate?null:e.parentAuthor?110:100}function cS(e,t,r){return v(["posts","comment"],e,n=>{let o=[];if(o.push(Ve(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="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,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(je(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{let i=!o.parentAuthor,s=jp(o),a=n?.id??n?.tx_id;if(s!==null&&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(!i){c.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let p=o.rootAuthor||o.parentAuthor,l=o.rootPermlink||o.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 dS(e,t,r,n){let o=n??b(),i=o.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 i)a&&o.setQueryData(s,[e,...a]);}function yi(e,t,r,n,o){let i=o??b(),s=new Map,a=i.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),i.setQueryData(c,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function hi(e,t){let r=t??b();for(let[n,o]of e)r.setQueryData(n,o);}function fS(e,t,r,n){let o=n??b(),i=`/@${e}/${t}`,s=o.getQueryData(u.posts.entry(i));return s&&o.setQueryData(u.posts.entry(i),{...s,...r}),s}function mS(e,t,r,n){let o=n??b(),i=`/@${e}/${t}`;o.setQueryData(u.posts.entry(i),r);}function wS(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:o})=>[Fr(n,o)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e)];if(o.parentAuthor&&o.parentPermlink){i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let o=n.rootAuthor||n.parentAuthor,i=n.rootPermlink||n.parentPermlink;return o&&i?{snapshots:yi(n.author,n.permlink,o,i)}:{}},onError:(n,o,i)=>{let{snapshots:s}=i??{};s&&hi(s);}})}function AS(e,t,r){return v(["posts","cross-post"],e,n=>{let o=[];if(o.push(Ve(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true}=n.options;o.push(je(n.author,n.permlink,i,s,a,c,[]));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.parentPermlink}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"async"})}function ES(e,t,r){return v(["posts","update-reply"],e,n=>{let o=[];if(o.push(Ve(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="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,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(je(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.resourceCredits.account(e)];i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r})}function TS(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:o,duration:i})=>[on(e,n,o,i)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.posts._promotedPrefix],[...u.points._prefix(e)],u.posts.entry(`/@${o.author}/${o.permlink}`)]);},t,"active",{broadcastMode:r})}var Lp=[3e3,3e3,3e3],$p=e=>new Promise(t=>setTimeout(t,e));async function Wp(e,t){return y("condenser_api.get_content",[e,t])}async function Gp(e,t,r=0,n){let o=n?.delays??Lp,i;try{i=await Wp(e,t);}catch{i=void 0;}if(i||r>=o.length)return;let s=o[r];return s>0&&await $p(s),Gp(e,t,r+1,n)}var rt={};St(rt,{useRecordActivity:()=>un});function Jp(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function un(e,t,r){return useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=h(),o=Jp(),i=r?.url??o.url,s=r?.domain??o.domain;try{await n(d.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:i,domain:s,props:{username:e}})});}catch{}}})}function HS(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 $S(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(),o=n.map(s=>s.account),i=await y("condenser_api.get_accounts",[o]);for(let s=0;sa.efficiency-s.efficiency),n}})}function JS(e,t=[],r=["visitors","pageviews","visit_duration"],n){let o=[...t].sort(),i=[...r].sort();return queryOptions({queryKey:["analytics","page-stats",e,o,i,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 Yt="threespeakfund",rE=1100;function el(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function nE(e,t){if(!el(t))return e;let r=e.find(n=>n.account===Yt);return r&&r.weight===1100?e:r?e.map(n=>n.account===Yt?{...n,weight:1100}:n):[...e,{account:Yt,weight:1100}]}function oE(e){return e===Yt}var ln={};St(ln,{getAccountTokenQueryOptions:()=>pn,getAccountVideosQueryOptions:()=>sl});var cn={};St(cn,{getDecodeMemoQueryOptions:()=>nl});function nl(e,t,r){return queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new ho.Client({accessToken:r}).decode(t)}})}var _i={queries:cn};function pn(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 h()(`https://studio.3speak.tv/mobile/login?username=${e}&hivesigner=true`,{headers:{"Content-Type":"application/json"}}),o=_i.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await b().prefetchQuery(o);let{memoDecoded:i}=b().getQueryData(o.queryKey);return i.replace("#","")}})}function sl(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=pn(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 h()("https://studio.3speak.tv/mobile/api/my-videos",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})).json()}})}var vE={queries:ln};function EE(e){return queryOptions({queryKey:["integrations","hiveposh","links",e],retry:false,queryFn:async()=>{try{let r=await h()(`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 TE({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:o,enabled:i=true}){return queryOptions({queryKey:["integrations","plausible",e,t,r,n,o],queryFn:async()=>{let a=await h()(`${d.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...o?{date_range:o}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&i,retry:1})}function DE(){return queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await y("rc_api.get_rc_stats",{})).rc_stats})}function ME(e){return queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await y("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}function jE(){return queryOptions({queryKey:u.resourceCredits.resourceParams(),staleTime:1440*60*1e3,gcTime:1/0,queryFn:async()=>await y("rc_api.get_resource_params",{})})}var Xt=["resource_history_bytes","resource_new_accounts","resource_market_bytes","resource_state_bytes","resource_execution_time"];var dl=11,fl=65,ml=16,nt=e=>BigInt(typeof e=="string"?e:Math.trunc(e));function dn(e,t,r,n){if(r<=0||n<=0)return 0;let o=nt(e.coeff_a),i=nt(e.coeff_b),s=nt(e.shift),a=nt(n)*o>>s;a+=1n,a*=nt(r);let c=i+(t>0?nt(t):0n);return c===0n?0:Number(a/c+1n)}function fn({transactionBytes:e,permlinkLength:t,signatures:r=1,beneficiaries:n=0,hasCommentOptions:o=false},i){let s=i.resource_state_bytes,a=i.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+(o?a.comment_options_time:0)}}var be=e=>{let t=ft(e);return _e(t)+t},gl=e=>1+be(e.parent_author)+be(e.parent_permlink)+be(e.author)+be(e.permlink)+be(e.title)+be(e.body)+be(e.json_metadata),yl=(e,t)=>{let r=t.beneficiaries??[],n=1+be(e.author)+be(e.permlink)+ml+2+2;return n+=_e(r.length>0?1:0),r.length>0&&(n+=1+_e(r.length),r.forEach(o=>{n+=be(o.account)+2;})),n};function mn({op:e,options:t,signatures:r=1}){let n=[gl(e)];return t&&n.push(yl(e,t)),dl+_e(n.length)+n.reduce((o,i)=>o+i,0)+_e(r)+fl*r}var hl={ready:false,cost:0,transactionBytes:0,breakdown:[]};function zE({op:e,options:t,rcParams:r,rcStats:n,signatures:o=1}){if(!r?.resource_params||!r.size_info||!n?.pool||!n.share)return hl;let i=mn({op:e,options:t,signatures:o}),s=fn({transactionBytes:i,permlinkLength:ft(e.permlink),signatures:o,beneficiaries:t?.beneficiaries?.length??0,hasCommentOptions:!!t},r.size_info),a=Number(n.regen),c=0,p=[];return Xt.forEach((l,f)=>{let m=r.resource_params[l],g=Number(n.pool[f]??0),_=Number(n.share[f]??0);if(!m||_<=0)return;let A=s[l]*Number(m.resource_dynamics_params.resource_unit??1),x=Number(BigInt(a)*BigInt(_)/10000n),q=dn(m.price_curve_params,g,A,x);c+=q,p.push({resource:l,usage:A,cost:q});}),{ready:true,cost:c,transactionBytes:i,breakdown:p}}function gn(e,t,r){let n=Number(r.regen),o=0,i=[];return Xt.forEach((s,a)=>{let c=t.resource_params[s],p=Number(r.pool[a]??0),l=Number(r.share[a]??0);if(!c||l<=0)return;let f=e[s]*Number(c.resource_dynamics_params.resource_unit??1),m=Number(BigInt(n)*BigInt(l)/10000n),g=dn(c.price_curve_params,p,f,m);o+=g,i.push({resource:s,usage:f,cost:g});}),{cost:o,breakdown:i}}var _l=11,wl=65,yn=e=>{let t=ft(e);return _e(t)+t},bl=()=>({resource_history_bytes:0,resource_new_accounts:0,resource_market_bytes:0,resource_state_bytes:0,resource_execution_time:0});function wi(e,t=1){let r=1+yn(e.voter)+yn(e.author)+yn(e.permlink)+2;return _l+_e(1)+r+_e(t)+wl*t}function bi({transactionBytes:e,signatures:t=1},r){let n=r.resource_state_bytes,o=r.resource_execution_time;return {...bl(),resource_history_bytes:e,resource_state_bytes:n.vote_size+n.transaction_base_size,resource_execution_time:o.vote_time+o.transaction_time+o.verify_authority_time*t}}var vi={ready:false,currentMana:0,maxMana:0,avgCost:0,cost:0,transactionBytes:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function sk({rcAccount:e,rcStats:t,rcParams:r,operation:n,payload:o,fallback:i="minimal",buffer:s=1.2}){if(!e||!t?.ops)return vi;let{current_mana:a,max_mana:c}=Qt(e),p=vl(n,o,i,r,t);if(!p)return {...vi,currentMana:a,maxMana:c};let{cost:l,transactionBytes:f}=p,m=Number.isFinite(s)&&s>0?s:1.2,g=l*m,_=a0?{cost:r,transactionBytes:0}:null}var Al={author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa",parent_author:"",parent_permlink:"hive-100000",title:"",body:"",json_metadata:"{}"},Ol={voter:"aaaaaaaaaa",author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa"};function pk(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 h()(d.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}async function El(e,t,r){let o=await h()(d.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:t,code:e,key:r}),headers:{"Content-Type":"application/json"}}),i=(o.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),s=await o.text();if(!o.ok){let a=s&&i.includes("json")?`: ${s.slice(0,200)}`:"";throw new Error(`[SDK][Games] \u2013 failed with status ${o.status}${a}`)}if(!i.includes("json"))throw new Error(`[SDK][Games] \u2013 expected JSON but received "${i||"empty"}" response (status ${o.status})`);try{return JSON.parse(s)}catch{throw new Error(`[SDK][Games] \u2013 malformed JSON response (status ${o.status})`)}}function gk(e,t,r,n){let{mutateAsync:o}=un(e,"spin-rolled");return useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return El(t,r,n)},onSuccess(){o();}})}function wk(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 h()(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 Cl=[{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 vk(e,t){return Cl.find(r=>r.tier===e&&r.id===t)}var Rl=25;function Tl(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function Pk(e){return Tl(e)>Rl}var Ak=300,Ok=2;function Il(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function Dl(e){let r=await h()(d.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:Il()})});if(!r.ok){let n;try{n=await r.json();}catch{}let o=n?.message??`Failed to buy streak freeze: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function kk(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 Dl(t)},onSuccess(){n&&r.invalidateQueries({queryKey:u.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:u.quests.status(n)});}})}function qk(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[jr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"async"})}function Kk(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[Lr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"sync"})}function Qk(e,t,r){return v(["communities","mutePost"],e,({community:n,author:o,permlink:i,notes:s,mute:a})=>[zr(e,n,o,i,s,a)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.posts.entry(`/@${o.author}/${o.permlink}`),["community","single",o.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.community}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"sync"})}function jk(e,t,r,n){return v(["communities","set-role",e],t,({account:o,role:i})=>[$r(t,e,o,i)],async(o,i)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>{if(!a)return a;let c=[...a.team??[]],p=c.findIndex(([l])=>l===i.account);return p>=0?c[p]=[c[p][0],i.role,c[p][2]??""]:c.push([i.account,i.role,""]),{...a,team:c}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)],u.communities.context(i.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function Gk(e,t,r,n){return v(["communities","update",e],t,o=>[Wr(t,e,o)],async(o,i)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>a&&{...a,...i}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function Xk(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[sn(n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.communities.singlePrefix(o.name)],[...u.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function rC(e,t,r){return v(["communities","pin-post"],e,({community:n,account:o,permlink:i,pin:s})=>[Gr(e,n,o,i,s)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.posts.entry(`/@${o.account}/${o.permlink}`),[...u.communities.singlePrefix(o.community)]]);},t,"posting",{broadcastMode:r??"async"})}function aC(e,t,r=100,n=void 0,o=true){return queryOptions({queryKey:u.communities.list(e,t??"",r),enabled:o,queryFn:async()=>{let i=await y("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return i?e==="hot"?i.sort(()=>Math.random()-.5):i:[]}})}function dC(e,t){return queryOptions({queryKey:u.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await y("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function hC(e,t="",r=true){return queryOptions({queryKey:u.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>Mo(e??"",t)})}var Pi=100;async function Ai(e,t){return await y("bridge.list_subscribers",{community:e,limit:Pi,...t?{last:t}:{}})??[]}function AC(e){return queryOptions({queryKey:u.communities.subscribers(e),queryFn:async()=>Ai(e,null),staleTime:6e4})}function OC(e){return infiniteQueryOptions({queryKey:u.communities.subscribersInfinite(e),initialPageParam:null,queryFn:async({pageParam:t})=>Ai(e,t),getNextPageParam:t=>t?.length>=Pi?t[t.length-1]?.[0]??null:null,staleTime:6e4})}function RC(e,t){return infiniteQueryOptions({queryKey:u.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await y("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function IC(){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 Vl=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(Vl||{}),KC={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function BC(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function MC({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),o=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),i=["owner","admin","mod"].includes(t);return {canPost:n,canComment:o,isModerator:i}}function VC(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 WC(e,t,r=void 0){return infiniteQueryOptions({queryKey:u.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let o={code:t,filter:r,since:n,user:void 0},i=await fetch(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)return [];try{return await i.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var $l=(g=>(g.VOTES="rvotes",g.MENTIONS="mentions",g.FAVORITES="nfavorites",g.BOOKMARKS="nbookmarks",g.FOLLOWS="follows",g.REPLIES="replies",g.REBLOGS="reblogs",g.TRANSFERS="transfers",g.DELEGATIONS="delegations",g.PAYOUTS="payouts",g.SCHEDULED_PUBLISHED="scheduled_published",g.ACCOUNT_UPDATES="account_updates",g.WEEKLY_EARNINGS="weekly_earnings",g))($l||{});var Wl=(_=>(_[_.VOTE=1]="VOTE",_[_.MENTION=2]="MENTION",_[_.FOLLOW=3]="FOLLOW",_[_.COMMENT=4]="COMMENT",_[_.RE_BLOG=5]="RE_BLOG",_[_.TRANSFERS=6]="TRANSFERS",_[_.DELEGATIONS=10]="DELEGATIONS",_[_.FAVORITES=13]="FAVORITES",_[_.BOOKMARKS=15]="BOOKMARKS",_[_.PAYOUTS=19]="PAYOUTS",_[_.ACCOUNT_UPDATE=20]="ACCOUNT_UPDATE",_[_.WEEKLY_EARNINGS=21]="WEEKLY_EARNINGS",_[_.SCHEDULED_PUBLISHED=22]="SCHEDULED_PUBLISHED",_.ALLOW_NOTIFY="ALLOW_NOTIFY",_))(Wl||{}),Oi=[1,2,3,4,5,6,10,13,15,19,20,21,22],Gl=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(Gl||{});function eR(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 o=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(!o.ok)throw new Error(`Failed to fetch notification settings: ${o.status}`);return o.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...Oi]})})}function oR(){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 uR(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 Zl(e,t){return {...e,read:!t||t===e.id?1:e.read}}function xi(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function gR(e,t,r,n){let o=b();return useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:i})=>{if(!(!e||!t))return si(t,i)},onMutate:async({id:i})=>{if(!e||!t)return {previousData:[]};await o.cancelQueries({queryKey:u.notifications._prefix});let s=[],a=o.getQueriesData({queryKey:u.notifications._prefix,predicate:l=>{let f=l.state.data;return xi(f)}});a.forEach(([l,f])=>{if(f&&xi(f)){s.push([l,f]);let m={...f,pages:f.pages.map(g=>g.map(_=>Zl(_,i)))};o.setQueryData(l,m);}});let c=u.notifications.unreadCount(e),p=o.getQueryData(c);return typeof p=="number"&&p>0&&(s.push([c,p]),i?a.some(([,f])=>f?.pages.some(m=>m.some(g=>g.id===i&&g.read===0)))&&o.setQueryData(c,p-1):o.setQueryData(c,0)),{previousData:s}},onSuccess:i=>{let s=typeof i=="object"&&i!==null?i.unread:void 0;typeof s=="number"&&o.setQueryData(u.notifications.unreadCount(e),s),r?.(s);},onError:(i,s,a)=>{a?.previousData&&a.previousData.forEach(([c,p])=>{o.setQueryData(c,p);}),n?.(i);},onSettled:()=>{o.invalidateQueries({queryKey:u.notifications._prefix});}})}function wR(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>Mr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function AR(e){return queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await y("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 y("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(o=>o.status==="expired");return [...t.filter(o=>o.status!=="expired"),...r]}})}function FR(e,t,r){return infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await y("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 y("condenser_api.get_accounts",[s.map(l=>l.voter)]),c=jt(a);return s.map(l=>({...l,voterAccount:c.find(f=>l.voter===f.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function NR(e){return queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await y("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 HR(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:o})=>[Vr(e,n,o)],async n=>{try{let o=n?.id??n?.tx_id;t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(150,o,n?.block_num).catch(i=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:o,error:i});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.proposals.list(),u.proposals.votesByUser(e)]);}catch(o){console.warn("[useProposalVote] Post-broadcast side-effect failed:",o);}},t,"active",{broadcastMode:r})}function LR(e,t,r){return v(["proposals","create"],e,n=>[Ur(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.proposals.list()]);},t,"active",{broadcastMode:r})}function zR(e,t=50){return infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,o=await y("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&o.length>0&&o[0]?.delegatee===r?o.slice(1,t+1):o},getNextPageParam:r=>!r||r.lengthne("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function nT(e){return queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await y("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function aT(e){return queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>y("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function lT(e){return queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>y("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function gT(e){return queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>y("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function wT(e){return queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function AT(e){return queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>y("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function kT(e,t=100){return infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let o=(await y("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(i=>i)).rc_direct_delegations||[];return r&&(o=o.filter(i=>i.to!==r)),o},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function qT(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 h()(`${d.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function KT(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 QT(e){return queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>y("condenser_api.find_recurrent_transfers",[e]),enabled:!!e})}function ge(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:void 0}}function pe(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 o=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(o){let i=Number.parseFloat(o[0]);if(Number.isFinite(i))return i}}}function hd(e){if(!e||typeof e!="object")return;let t=e;return {name:ge(t.name)??"",symbol:ge(t.symbol)??"",layer:ge(t.layer)??"hive",balance:pe(t.balance)??0,fiatRate:pe(t.fiatRate)??0,currency:ge(t.currency)??"usd",precision:pe(t.precision)??3,address:ge(t.address),error:ge(t.error),pendingRewards:pe(t.pendingRewards),pendingRewardsFiat:pe(t.pendingRewardsFiat),liquid:pe(t.liquid),liquidFiat:pe(t.liquidFiat),savings:pe(t.savings),savingsFiat:pe(t.savingsFiat),staked:pe(t.staked),stakedFiat:pe(t.stakedFiat),iconUrl:ge(t.iconUrl),actions:t.actions??[],extraData:t.extraData??[],apr:pe(t.apr)}}function _d(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 o of ["wallets","tokens","assets","items","portfolio","balances"]){let i=n[o];if(Array.isArray(i))return i}}return []}function wd(e){if(!e||typeof e!="object")return;let t=e;return ge(t.username)??ge(t.name)??ge(t.account)}function Si(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`,o=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!o.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${o.status})`);let i=await o.json(),s=_d(i).map(a=>hd(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:wd(i)??e,currency:ge(i?.fiatCurrency??i?.currency)?.toUpperCase(),wallets:s}}})}function Zt(e){return queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Se()),await b().prefetchQuery(Q(e));let t=b().getQueryData(Se().queryKey),r=b().getQueryData(Q(e).queryKey),n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:0};let i=C(r.balance).amount,s=C(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:i+s,parts:[{name:"current",balance:i},{name:"savings",balance:s}]}}})}function Ei(e){return queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Se()),await b().prefetchQuery(Q(e));let t=b().getQueryData(Q(e).queryKey),r=b().getQueryData(Se().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 Ad(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 ki(e){return queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Se()),await b().prefetchQuery(Q(e));let t=b().getQueryData(Se().queryKey),r=b().getQueryData(Q(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??""),i=Number.isFinite(o)?o: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=Ao(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+Ye(s,t.hivePerMVests).toFixed(3),g=+Ye(a,t.hivePerMVests).toFixed(3),_=+Ye(c,t.hivePerMVests).toFixed(3),A=+Ye(l,t.hivePerMVests).toFixed(3),x=+Ye(f,t.hivePerMVests).toFixed(3),q=Math.max(m-A,0),F=Math.max(m-g,0);return {name:"HP",title:"Hive Power",price:i,accountBalance:+q.toFixed(3),apr:Ad(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+F.toFixed(3)},{name:"outgoing_delegations",balance:g},{name:"incoming_delegations",balance:_},...A>0?[{name:"pending_power_down",balance:+A.toFixed(3)}]:[],...x>0&&x!==A?[{name:"next_power_down",balance:+x.toFixed(3)}]:[]]}}})}var B=ie.operations,hn={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 lq=Object.keys(ie.operations);var Ci=ie.operations,mq=Ci,gq=Object.entries(Ci).reduce((e,[t,r])=>(e[r]=t,e),{});var Ri=ie.operations;function xd(e){return Object.prototype.hasOwnProperty.call(Ri,e)}function vt(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),o=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),i=new Set;r||n.forEach(a=>{if(a in hn){hn[a].forEach(c=>i.add(c));return}xd(a)&&i.add(Ri[a]);});let s=kd(Array.from(i));return {filterKey:o,filterArgs:s}}function _n(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function Sd(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function Ed(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function kd(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await y("condenser_api.get_account_history",[e,s,Ed(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 i.has(p.type)}}))})})}function Sq(e,t=20,r=[]){let{filterKey:n}=vt(r),o=_n(r);return infiniteQueryOptions({...er(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:i,pageParams:s})=>({pageParams:s,pages:i.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 o.has(c.type)}}))})})}function Tq(e,t=20,r=[]){let{filterKey:n}=vt(r),o=new Set(Array.isArray(r)?r:[r]),i=o.has("")||o.size===0;return infiniteQueryOptions({...er(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 i||o.has(p.type)}}))})})}function Ti(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 wn(e,t){return new Date(e.getTime()-t*1e3)}function Dq(e=86400){return infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await y("condenser_api.get_market_history",[e,Ti(t),Ti(r)])).map(({hive:o,non_hive:i,open:s})=>({close:i.close/o.close,open:i.open/o.open,low:i.low/o.low,high:i.high/o.high,volume:o.volume,time:new Date(s)})),initialPageParam:[wn(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[wn(n,Math.max(100*e,28800)),wn(n,e)]})}function Mq(e){return queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function Vq(e,t=50){return queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>y("condenser_api.get_vesting_delegations",[e,"",t])})}function Gq(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 Xq(e=500){return queryOptions({queryKey:["market","order-book",e],queryFn:()=>y("condenser_api.get_order_book",[e])})}function rF(){return queryOptions({queryKey:["market","statistics"],queryFn:()=>y("condenser_api.get_ticker",[])})}function sF(e,t,r){let n=o=>o.toISOString().replace(/\.\d{3}Z$/,"");return queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>y("condenser_api.get_market_history",[e,n(t),n(r)])})}function pF(){return queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await y("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),o=await y("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:o[0]?o[0].non_hive.open/o[0].hive.open:0,high:o[0]?o[0].non_hive.high/o[0].hive.high:0,low:o[0]?o[0].non_hive.low/o[0].hive.low:0,percent:o[0]?100-o[0].non_hive.open/o[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function mF(e,t,r,n){return queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:o})=>{let i=h(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await i(s,{signal:o});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function qi(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function _F(e=1e3,t,r){let n=r??new Date,o=t??new Date(n.getTime()-600*60*1e3);return queryOptions({queryKey:["market","trade-history",e,o.getTime(),n.getTime()],queryFn:()=>y("condenser_api.get_trade_history",[qi(o),qi(n),e])})}function PF(){return queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await y("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function SF(){return queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await y("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function RF(e,t,r){return v(["market","limit-order-create"],e,n=>[Gt(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 IF(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[Jr(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 Pt(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 NF(e,t,r,n){let o=h(),i=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await o(i);return Pt(s)}async function Fi(e){if(e==="hbd")return 1;let t=h(),r=`https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${e}`,n=await t(r);return (await Pt(n)).hive_dollar[e]}async function BF(e,t){let n=await h()(d.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return Pt(n)}async function MF(){let t=await h()(d.privateApiHost+"/private-api/market-data/latest");return Pt(t)}async function QF(){let t=await h()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return Pt(t)}var Vd={"Content-type":"application/json"};async function jd(e){let t=h(),r=M.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:Vd});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function Ie(e,t){try{return await jd(e)}catch{return t}}async function VF(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,o]=await Promise.all([Ie({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),Ie({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),i=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:i(n),sell:s(o)}}async function jF(e,t=50){return Ie({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 LF(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},[o,i]=await Promise.all([Ie({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),Ie({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=o.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=i.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 Ld(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return Ie({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function ot(e,t){return Ld(t,e)}async function tr(e){return Ie({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function rr(e){return Ie({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function Ii(e,t,r,n){let o=h(),i=M.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",i);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 o(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 Di(e,t="daily"){let r=h(),n=M.getValidatedBaseUrl(),o=new URL("/private-api/engine-chart-api",n);o.searchParams.set("symbol",e),o.searchParams.set("interval",t);let i=await r(o.toString(),{headers:{"Content-type":"application/json"}});if(!i.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${i.status}`);return await i.json()}async function Ki(e){let t=h(),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 nr(e){return queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>tr(e)})}function XF(){return queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>ot()})}function Ni(e){return queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>rr(e)})}function iI(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 Ii(e,t,r,n)},getNextPageParam:(n,o,i)=>(n?.length??0)===r?i+r:void 0,getPreviousPageParam:(n,o,i)=>i>0?i-r:void 0})}function cI(e,t="daily"){return queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Di(e,t)})}function fI(e){return queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await Ki(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function Bi(e,t){return queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>ot(e,t)})}function it(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:o,suffix:i}=r,s="";o&&(s+=o+" ");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}),i&&(s+=" "+i),s}var or=class{constructor(t){P(this,"symbol");P(this,"name");P(this,"icon");P(this,"precision");P(this,"stakingEnabled");P(this,"delegationEnabled");P(this,"balance");P(this,"stake");P(this,"stakedBalance");P(this,"delegationsIn");P(this,"delegationsOut");P(this,"usdValue");P(this,"hasDelegations",()=>this.delegationEnabled?this.delegationsIn>0&&this.delegationsOut>0:false);P(this,"delegations",()=>this.hasDelegations()?`(${it(this.stake,{fractionDigits:this.precision})} + ${it(this.delegationsIn,{fractionDigits:this.precision})} - ${it(this.delegationsOut,{fractionDigits:this.precision})})`:"");P(this,"staked",()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():it(this.stakedBalance,{fractionDigits:this.precision}):"-");P(this,"balanced",()=>this.balance<1e-4?this.balance.toString():it(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 xI(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 tr(e),o=await rr(n.map(p=>p.symbol)),i=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 ot(void 0,a):[]];return n.map(p=>{let l=o.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),g=Number(m?.lastPrice??"0"),_=Number(p.balance),A=p.symbol==="SWAP.HIVE"?i*_:g===0?0:Number((g*i*_).toFixed(10));return new or({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:A})})},enabled:!!e})}function Mi(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=Zt(e);await r.prefetchQuery(n);let o=r.getQueryData(n.queryKey),i=await r.ensureQueryData(Ni([t])),s=await r.ensureQueryData(nr(e)),a=await r.ensureQueryData(Bi(void 0,t)),c=i?.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"),g=parseFloat(p?.stake??"0"),_=parseFloat(p?.pendingUnstake??"0"),A=[{name:"liquid",balance:m},{name:"staked",balance:g}];return _>0&&A.push({name:"unstaking",balance:_}),{name:t,title:c?.name??"",price:f===0?0:Number(f*(o?.price??0)),accountBalance:m+g,layer:"ENGINE",parts:A}}})}function At(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 o=await n.json(),i=await fetch(d.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!i.ok)throw new Error(`Failed to fetch point transactions: ${i.status}`);let s=await i.json();return {points:o.points,uPoints:o.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function Qi(e){return queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await b().prefetchQuery(At(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(b().getQueryData(At(e).queryKey)?.points??0)})})}function VI(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:o,type:i,amount:s,id:a,sender:c,receiver:p,memo:l})=>({created:new Date(o),type:i,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:c??void 0,to:p??void 0,memo:l??void 0}))})}function tD(e,t,r={refetch:false}){let n=b(),o=r.currency??"usd",i=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||o==="usd")return p;try{let l=await Fi(o);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${o}:`,l),p}},a=Si(e,o,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 g=m.dataKey,_=m.value;if(typeof _=="string"){let x=_.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(x){let q=Math.abs(Number.parseFloat(x[1]));g==="delegated_hive_power"?f.push({name:"outgoing_delegations",balance:q}):g==="received_hive_power"?f.push({name:"incoming_delegations",balance:q}):g==="powering_down_hive_power"&&f.push({name:"pending_power_down",balance:q});}}}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,o],queryFn:async()=>{let p=await c();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await i(Zt(e));else if(t==="HP")l=await i(ki(e));else if(t==="HBD")l=await i(Ei(e));else if(t==="POINTS")l=await i(Qi(e));else if((await n.ensureQueryData(nr(e))).some(m=>m.symbol===t))l=await i(Mi(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 sf=(q=>(q.Transfer="transfer",q.TransferToSavings="transfer-saving",q.WithdrawFromSavings="withdraw-saving",q.Delegate="delegate",q.PowerUp="power-up",q.PowerDown="power-down",q.WithdrawRoutes="withdraw-routes",q.ClaimInterest="claim-interest",q.Swap="swap",q.Convert="convert",q.Gift="gift",q.Promote="promote",q.Claim="claim",q.Buy="buy",q.Stake="stake",q.Unstake="unstake",q.Undelegate="undelegate",q))(sf||{});function aD(e,t,r){return v(["wallet","transfer"],e,n=>[Le(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function dD(e,t,r){return v(["wallet","transfer-point"],e,n=>[tt(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function hD(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[_t(e,n.delegatee,n.vestingShares)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function PD(e,t,r){return v(["wallet","set-withdraw-vesting-route"],e,n=>[wt(e,n.toAccount,n.percent,n.autoVest)],async(n,o)=>{await E(t?.adapter,r,[u.wallet.withdrawRoutes(e),u.accounts.full(e),u.accounts.full(o.toAccount)]);},t,"active",{broadcastMode:r})}function SD(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function TD(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[et(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function KD(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[$e(e,n.to,n.amount,n.memo,n.requestId)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function HD(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[yt(e,n.to,n.amount)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function $D(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[ht(e,n.vestingShares)],async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function YD(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?Dr(e,n.amount,n.requestId):bt(e,n.amount,n.requestId)],async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function rK(e,t,r){return v(["wallet","claim-interest"],e,n=>gt(e,n.to,n.amount,n.memo,n.requestId),async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}var af=5e3,ir=new Map;function aK(e,t,r){return v(["wallet","claim-rewards"],e,n=>[Yr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",o=[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)],i=ir.get(n);i&&(clearTimeout(i),ir.delete(n));let s=setTimeout(async()=>{try{let a=b(),p=(await Promise.allSettled(o.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{ir.delete(n);}},af);ir.set(n,s);},t,"posting",{broadcastMode:r})}function lK(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function gK(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let o=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:o}]]},async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function wK(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function AK(e,t,r){return v(["wallet","unstake-engine-token"],e,n=>{let o=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:o}]]},async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function EK(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let o=JSON.stringify(n.tokens.map(i=>({symbol:i})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:o}]]},async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function TK(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let o,i;n.action==="cancel"?(i="cancel",o={type:n.orderType,id:n.orderId}):(i=n.action,o={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:i,contractPayload:o});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:s}]]},async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function uf(e,t,r){let{from:n,to:o="",amount:i="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [Le(n,o,i,s)];case "transfer-saving":return [et(n,o,i,s)];case "withdraw-saving":return [$e(n,o,i,s,a)];case "power-up":return [yt(n,o,i)]}break;case "HBD":switch(t){case "transfer":return [Le(n,o,i,s)];case "transfer-saving":return [et(n,o,i,s)];case "withdraw-saving":return [$e(n,o,i,s,a)];case "claim-interest":return gt(n,o,i,s,a);case "convert":return [bt(n,i,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [ht(n,i)];case "delegate":return [_t(n,o,i)];case "withdraw-routes":return [wt(r.from_account??n,r.to_account??o,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [tt(n,o,i,s)];break}return null}function cf(e,t,r){let{from:n,to:o="",amount:i=""}=r,s=typeof i=="string"&&i.includes(" ")?i.split(" ")[0]:String(i);switch(t){case "transfer":return [We(n,"transfer",{symbol:e,to:o,quantity:s,memo:r.memo??""})];case "stake":return [We(n,"stake",{symbol:e,to:o,quantity:s})];case "unstake":return [We(n,"unstake",{symbol:e,to:o,quantity:s})];case "delegate":return [We(n,"delegate",{symbol:e,to:o,quantity:s})];case "undelegate":return [We(n,"undelegate",{symbol:e,from:o,quantity:s})];case "claim":return [Kr(n,[e])]}return null}function pf(e){return e==="claim"?"posting":"active"}function NK(e,t,r,n,o){let{mutateAsync:i}=rt.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=uf(t,r,s);if(a)return a;let c=cf(t,r,s);if(c)return c;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{i();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,pf(r),{broadcastMode:o})}function HK(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:o})=>[Nr(e,n,o)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),u.resourceCredits.account(e),u.resourceCredits.account(o.to)]);},t,"active",{broadcastMode:r})}function LK(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:o})=>[Qr(e,n,o)],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 zK(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[Hr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function df(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 tN(e){return infiniteQueryOptions({queryKey:u.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await ne("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(df),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function rN(e,t,r,n="vests",o="desc"){return queryOptions({queryKey:u.witnesses.voters(e,t,r,n,o),queryFn:async({signal:i})=>await ne("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:o},void 0,void 0,i),enabled:!!e,staleTime:6e4})}function nN(e){return queryOptions({queryKey:u.witnesses.voterCount(e),queryFn:async()=>await ne("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var ff=(_=>(_[_.CHECKIN=10]="CHECKIN",_[_.LOGIN=20]="LOGIN",_[_.CHECKIN_EXTRA=30]="CHECKIN_EXTRA",_[_.POST=100]="POST",_[_.COMMENT=110]="COMMENT",_[_.VOTE=120]="VOTE",_[_.REBLOG=130]="REBLOG",_[_.DELEGATION=150]="DELEGATION",_[_.REFERRAL=160]="REFERRAL",_[_.COMMUNITY=170]="COMMUNITY",_[_.TRANSFER_SENT=998]="TRANSFER_SENT",_[_.TRANSFER_INCOMING=999]="TRANSFER_INCOMING",_[_.MINTED=991]="MINTED",_[_.BURNED=997]="BURNED",_))(ff||{});async function gf(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 h()(d.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),o=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),i=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(i)}catch{return {message:i,code:n.status}}let s=i&&o.includes("json")?`: ${i.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!o.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${o||"empty"}" response (status ${n.status})`);try{return JSON.parse(i)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function pN(e,t,r,n){let{mutateAsync:o}=rt.useRecordActivity(e,"points-claimed");return useMutation({mutationFn:()=>gf(e,t),onError:n,onSuccess:()=>{o(),b().setQueryData(At(e).queryKey,i=>i&&{...i,points:(parseFloat(i.points)+parseFloat(i.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var Ui=/(^|\s)author:([^\s]+)/g,Vi=/(^|\s)type:([^\s]+)/g,ji=/(^|\s)category:([^\s]+)/g,Li=/(^|\s)tag:([^\s]+)/g;var Wi=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(Wi||{}),dN=5,fN=100;function Gi(e){return e.trim().split(/\s+/)[0]??""}function yf(e){return Gi(e).replace(/^@+/,"").toLowerCase()}function hf(e){return Gi(e).replace(/^#+/,"").toLowerCase()}function _f(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 mN({search:e="",author:t="",type:r="",category:n="",tags:o=[]}){let i=e.trim().replace(/\s+/g," "),s=yf(t),a=hf(n),c=_f(Array.isArray(o)?o.join(","):o),p=[i];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:i,author:s,type:r,category:a,tags:c}}var $i=class{constructor(t){P(this,"query","");P(this,"search","");P(this,"author","");P(this,"type","");P(this,"category","");P(this,"tags",[]);P(this,"grab",t=>{let r=[...this.query.matchAll(t)];return r.length>0?r[0][2].trim():""});P(this,"grabAuthor",()=>{this.author=this.grab(Ui);});P(this,"grabType",()=>{let t=this.grab(Vi);Object.values(Wi).includes(t)&&(this.type=t);});P(this,"grabCategory",()=>{this.category=this.grab(ji);});P(this,"grabTags",()=>{let t=new Set;this.tags=[...this.query.matchAll(Li)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));});P(this,"grabSearch",()=>{for([Ui,Vi,ji,Li].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 Ee(e,t){let n=await(async()=>{let o;try{o=await e.text();}catch{return}if(o!=="")try{return JSON.parse(o)}catch{return e.ok?void 0:o}})();if(!e.ok){let o=new Error(`Request failed with status ${e.status}`);throw o.status=e.status,o.data=n,o}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 De(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var bf=isServer?0:3;function Ot(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),o&&(a.scroll_id=o),i&&(a.votes=i);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:Oe(xe,s)});return Ee(c,De)},retry:Ot})}function SN(e,t,r=true){return infiniteQueryOptions({queryKey:u.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:o})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let i,s=new Date;switch(t){case "today":i=new Date(s.getTime()-1440*60*1e3);break;case "week":i=new Date(s.getTime()-10080*60*1e3);break;case "month":i=new Date(s.getTime()-720*60*60*1e3);break;case "year":i=new Date(s.getTime()-365*24*60*60*1e3);break;default:i=void 0;}let a="* type:post",c=e==="rising"?"children":e,p=i?i.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 g=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(m),signal:Oe(xe,o)});return Ee(g,De)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:Ot})}async function RN(e,t,r,n,o,i,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),o&&(a.scroll_id=o),i&&(a.votes=i);let p=await h()(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:Oe(xe,s)});return Ee(p,De)}async function zi(e,t,r=xe){let o=await h()(d.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(e),signal:Oe(r,t)});return Ee(o,De)}async function TN(e,t){let n=await h()(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e}),signal:Oe(xe,t)}),o=await Ee(n,Array.isArray);return o?.length>0?o:[e]}var Of=4368*60*60*1e3,xf=4,Sf=3e3,Ef=2e3,kf=4e3,KN=2;function Cf(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function Rf(e){let t=5381;for(let r=0;r>>0).toString(36)}function NN(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),o=Cf(e.body??"",Sf),i=Rf(`${t}|${n.join(",")}|${o}`);return queryOptions({queryKey:u.search.similarEntries(e.author,e.permlink,i),queryFn:async({signal:s})=>{let a=new Date(Date.now()-Of).toISOString().slice(0,19),c=await zi({author:e.author,permlink:e.permlink,title:t,body:o,tags:n,since:a},s,typeof window>"u"?Ef:kf),p=[],l=new Set;for(let f of c.results){if(p.length>=xf)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 VN(e,t=5){let r=e.trim();return queryOptions({queryKey:u.search.account(r,t),queryFn:async()=>{let n=await y("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Lt(n)},enabled:!!r})}function GN(e,t=10){let r=e.trim();return queryOptions({queryKey:u.search.topics(r,t),queryFn:async()=>(await y("condenser_api.get_trending_tags",[r,t+1])).map(o=>o.name).filter(o=>o!==""&&!o.startsWith("hive-")).slice(0,t),enabled:!!r})}function eB(e,t,r,n,o,i){return infiniteQueryOptions({queryKey:u.search.api(e,t,r,n,o,i),queryFn:async({pageParam:s,signal:a})=>{let c={q:e,sort:t,hide_low:r};n&&(c.since=n),s&&(c.scroll_id=s),o!==void 0&&(c.votes=o),i&&(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:Oe(xe,a)});return Ee(p,De)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:Ot})}function oB(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 Kf(e){let r=await h()(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 o=n?.message??`Failed to fetch support settings: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function uB(e,t){let r=e?.replace("@","");return queryOptions({queryKey:u.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return Kf(t)},enabled:!!r&&!!t})}async function Mf(e,t){let n=await h()(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 o;try{o=await n.json();}catch{}let i=o?.message??`Failed to update support settings: ${n.status}`,s=new Error(i);throw s.status=n.status,s.data=o,s}return await n.json()}function Qf(e,t,r){return e.setQueryData(u.support.settings(t),r),e.invalidateQueries({queryKey:u.support.settings(t)})}function fB(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["support","settings-update",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return Mf(t,o)},onSuccess(o){n&&Qf(r,n,o);}})}function hB(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 vB(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 xB(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 CB(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 NB(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:o})=>[rn(e,n,o)],async(n,{account:o})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.promotions.boostPlusAccounts(o)]);},t,"active",{broadcastMode:r})}function HB(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[nn(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 jB(e){let r=await h()(d.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let o;try{o=await r.json();}catch{o=void 0;}let i=new Error(`Failed to refresh token: ${r.status}`);throw i.status=r.status,i.data=o,i}return await r.json()}var Wf="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function GB(){return queryOptions({queryKey:u.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(Wf,{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 JB=1.1,Gf=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(Gf||{});function YB(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 Yf(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,o=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}}),i=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:o,poll_voters:i,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 rM(e,t){return queryOptions({queryKey:u.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:isServer?wo:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=h(),n=`${d.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,o=await r(n);if(!o.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${o.status}`);let i=await o.json();if(!Array.isArray(i)||!i[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return Yf(i[0])}})}function iM(e,t,r){return v(u.polls.vote(),e??"",({pollTrxId:n,choices:o})=>{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:o})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}var Xf=-1e10,Zf=5,em=30;var Ji=e=>Math.abs(e)>0&&Math.abs(e)<=100;function Yi(e){if(typeof e=="number"&&Ji(e)||typeof e=="string"&&(e=Number(e),Ji(e)))return Math.floor(e);if(e===0)return 25;let t=false;e<0&&(t=true);let r=Math.log10(Math.abs(e));return r=Math.max(r-9,0),r<0&&(r=0),t&&(r*=-1),r=r*9+25,Math.floor(r)}var tm=["ecency.com","ecency.app","hive.blog","hive.io","hiveblocks.com","peakd.com","snapie.io","hivesuite.app","leofinance.io","inleo.io","3speak.tv","d.buzz","waivio.com"],rm=["imgur.com","images.hive.blog","files.peakd.com","i.ecency.com","images.ecency.com","steemitimages.com","cdn.steemitimages.com","media.giphy.com"],nm=/\.(jpe?g|png|gif|webp|svg|bmp|avif)(\?|#|$)/i,om=/(?:https?:)?\/\/[^\s)<>"'\]]+/gi,im=/[.,;:!?'"]+$/;function sm(e){let t=/^(?:https?:)?\/\/([^/?#]+)/i.exec(e);return t?t[1].toLowerCase().replace(/^www\./,""):""}function am(e){let t=e.replace(im,"");if(nm.test(t))return false;let r=sm(t);if(!r.includes("."))return false;let n=o=>r===o||r.endsWith("."+o);return !(tm.some(n)||rm.some(n))}function Xi(e){if(!e)return false;let t=e.match(om);return t?t.some(am):false}var um=(n=>(n.MOD_MUTED="mod_muted",n.DOWNVOTED="downvoted",n.LOW_TRUST="low_trust",n))(um||{});function cm(e){return e?.stats?.total_votes??e?.active_votes?.length??0}function pm(e,t){return (e??0)<-1e10&&t>=5}function lm(e){let t=e?.author_reputation;return t==null?false:Yi(t)<30&&Xi(e?.body)}function dM(e,t){return !!e&&!!t?.includes(e)}function fM(e){return e?e.stats?.gray||e.stats?.hide?"mod_muted":pm(e.net_rshares,cm(e))?"downvoted":lm(e)?"low_trust":null:null}var xt=class extends Error{constructor(r,n,o){super(r);P(this,"status",n);P(this,"data",o);}},sr=class extends xt{constructor(r,n,o,i,s){super(r,n,s);P(this,"code",o);P(this,"taken",i);}};function Ke(e){return `${d.privateApiHost}/api/newsletter${e}`}async function Ge(e){let t=await e.json().catch(()=>{});if(!e.ok)throw new xt(t?.error||`Request failed (${e.status})`,e.status,t);if(!t||typeof t!="object")throw new xt(`Unexpected response (${e.status})`,e.status);return t}async function Zi(e,t){let n=await h()(Ke("/subscribe"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,...t?{code:t}:{}})});return Ge(n)}async function es(e){let r=await h()(Ke("/subscriptions"),{headers:{"X-HS-Token":e}});return (await Ge(r)).subscriptions??[]}async function ts(e,t){let n=await h()(Ke(`/subscriptions/${encodeURIComponent(e)}`),{method:"DELETE",headers:{"X-HS-Token":t}});await Ge(n);}async function rs(e,t){let n=await h()(Ke("/unsubscribe-all"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,code:t})});await Ge(n);}async function ns(e,t,r){let o=await h()(Ke(`/sender?type=${e}&target=${encodeURIComponent(t)}`),{headers:{"X-HS-Token":r}});return Ge(o)}async function os(e,t,r){let o=await h()(Ke(`/issues?type=${e}&target=${encodeURIComponent(t)}`),{headers:{"X-HS-Token":r}});return (await Ge(o)).issues??[]}async function is(e,t,r,n=20){let i=await h()(Ke(`/posts?type=${e}&target=${encodeURIComponent(t)}&limit=${n}`),{headers:{"X-HS-Token":r}});return (await Ge(i)).posts??[]}async function ss(e,t,r){let o=await h()(Ke(e),{method:"POST",headers:{"Content-Type":"application/json","X-HS-Token":r},body:JSON.stringify(t)}),i=await o.json().catch(()=>{});if(!o.ok)throw new sr(i?.error||`Request failed (${o.status})`,o.status,i?.code,i?.taken,i);if(!i||typeof i!="object")throw new sr(`Unexpected response (${o.status})`,o.status);return i}function as(e,t){return ss("/send/preview",e,t)}function us(e,t){return ss("/send",e,t)}function vM(e,t){let r=e?.replace("@","");return queryOptions({queryKey:u.newsletter.subscriptions(r),enabled:!!r&&!!t,queryFn:async()=>{if(!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return es(t)},staleTime:6e4,retry:false})}function SM(e,t,r,n){let o=r?.replace("@","");return queryOptions({queryKey:u.newsletter.sender(e,t,o),enabled:!!o&&!!n&&!!t,queryFn:async()=>{if(!n)throw new Error("[SDK][Newsletter] \u2013 missing auth");return ns(e,t,n)},staleTime:5*6e4})}function TM(e,t,r,n){let o=r?.replace("@","");return queryOptions({queryKey:u.newsletter.issues(e,t,o),enabled:!!o&&!!n&&!!t,queryFn:async()=>{if(!n)throw new Error("[SDK][Newsletter] \u2013 missing auth");return os(e,t,n)},staleTime:6e4})}function KM(e,t,r,n,o=20){let i=r?.replace("@","");return queryOptions({queryKey:u.newsletter.posts(e,t,i,o),enabled:!!i&&!!n&&!!t,queryFn:async()=>{if(!n)throw new Error("[SDK][Newsletter] \u2013 missing auth");return is(e,t,n,o)},staleTime:6e4})}function HM(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["newsletter","subscribe",n],mutationFn:o=>Zi(o,t),onSuccess(){n&&r.invalidateQueries({queryKey:u.newsletter.subscriptions(n)});}})}function $M(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["newsletter","leave",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return ts(o,t)},onSuccess(o,i){r.setQueryData(u.newsletter.subscriptions(n),s=>(s??[]).filter(a=>a.id!==i));}})}function YM(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["newsletter","unsubscribe-all",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return rs(o,t)},onSuccess(o,i){r.setQueryData(u.newsletter.subscriptions(n),s=>(s??[]).filter(a=>a.email.toLowerCase()!==i.toLowerCase()));}})}function rQ(e,t){let r=e?.replace("@","");return useMutation({mutationKey:["newsletter","send-preview",r],mutationFn:async n=>{if(!r||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return as(n,t)}})}function nQ(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["newsletter","send",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return us(o,t)},onSuccess(o,i){r.invalidateQueries({queryKey:u.newsletter.issues(i.type,i.target,n)}),r.invalidateQueries({queryKey:u.newsletter.sender(i.type,i.target,n)});}})}/** * @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{So as ACCOUNT_OPERATION_GROUPS,Ya as ALL_ACCOUNT_OPERATIONS,wi as ALL_NOTIFY_TYPES,jd as AssetOperation,Kg as BROADCAST_INCLUSION_DELAY_MS,zo as BuySellTransactionType,f as CONFIG,N as ConfigManager,Wf as ContentModerationReason,et as EcencyAnalytics,yo as EcencyQueriesManager,Ie as EntriesCacheManagement,lo as ErrorType,Mf as HIDDEN_POST_MIN_VOTES,Bf as HIDDEN_POST_RSHARES_THRESHOLD,fn as HIVE_ACCOUNT_OPERATION_GROUPS,NT as HIVE_OPERATION_LIST,VT as HIVE_OPERATION_NAME_BY_ID,UT as HIVE_OPERATION_ORDERS,tr as HiveEngineToken,mi as HiveSignerIntegration,Me as HiveTxTransaction,xe as INTERNAL_API_TIMEOUT_MS,Nf as LOW_TRUST_REPUTATION_THRESHOLD,HK as MAX_SEARCH_QUERY_LENGTH,QK as MAX_SEARCH_TAGS,ao as Memo,Nt as NaiMap,Tl as NotificationFilter,Il as NotificationViewType,Fl as NotifyTypes,np as OPERATION_AUTHORITY_MAP,Jo as OrderIdPrefix,OM as POLLS_PROTOCOL_VERSION,Yd as PointTransactionType,If as PollPreferredInterpretation,V as PrivateKey,Z as PublicKey,ml as QUEST_CATALOG,gl as QUEST_MIN_CONTENT_LENGTH,u as QueryKeys,zt as RC_RESOURCE_NAMES,kl as ROLES,go as SERVER_GC_TIME_MS,ol as SIGNATURE_BYTES,pB as SIMILAR_ENTRIES_MIN_RENDER,XS as STREAK_FREEZE_MAX_OWNED,YS as STREAK_FREEZE_PRICE,_i as SUBSCRIBERS_PAGE_SIZE,Ui as SearchQuery,Vi as SearchType,ke as Signature,Mo as SortOrder,ho as Symbol,Gt as THREESPEAK_BENEFICIARY_ACCOUNT,RE as THREESPEAK_BENEFICIARY_WEIGHT,nl as TRANSACTION_HEADER_BYTES,zE as ThreeSpeakIntegration,Ca as accountNameByteLength,si as addDraft,ni as addImage,Qx as addOptimisticDiscussionEntry,ui as addSchedule,xf as applySupportSettingsUpdate,kp as applyVoteCacheUpdate,ue as bridgeApiCall,mo as broadcastJson,re as broadcastOperations,uo as broadcastOperationsAsync,Gr as buildAccountCreateOp,xu as buildAccountUpdate2Op,Ou as buildAccountUpdateOp,Tu as buildActiveCustomJsonOp,Xr as buildBoostPlusOp,Go as buildCancelTransferFromSavingsOp,Su as buildChangeRecoveryAccountOp,Jr as buildClaimAccountOp,ft as buildClaimInterestOps,Wr as buildClaimRewardBalanceOp,Tr as buildCollateralizedConvertOp,Ue as buildCommentOp,Ve as buildCommentOptionsOp,tn as buildCommunityRegistrationOp,_t as buildConvertOp,zr as buildCreateClaimedAccountOp,Ir as buildDelegateRcOp,yt as buildDelegateVestingSharesOp,Cr as buildDeleteCommentOp,Fr as buildEngineClaimOp,$e as buildEngineOp,Pu as buildFlagPostOp,qr as buildFollowOp,Yr as buildGrantPostingPermissionOp,hu as buildIgnoreOp,$r as buildLimitOrderCancelOp,Lt as buildLimitOrderCreateOp,Au as buildLimitOrderCreateOpWithType,Ru as buildMultiPointTransferOps,gu as buildMultiTransferOps,Lr as buildMutePostOp,vu as buildMuteUserOp,jr as buildPinPostOp,Ze as buildPointTransferOp,Fu as buildPostingCustomJsonOp,Oo as buildPostingJsonMetadata,xr as buildProfileMetadata,en as buildPromoteOp,Mr as buildProposalCreateOp,Nr as buildProposalVoteOp,Zr as buildRcDelegationOp,Rr as buildReblogOp,Cu as buildRecoverAccountOp,yu as buildRecurrentTransferOp,bu as buildRemoveProposalOp,ku as buildRequestAccountRecoveryOp,Xo as buildRevokeKeysOp,Eu as buildRevokePostingPermissionOp,UK as buildSearchQuery,Dr as buildSetLastReadOps,Ur as buildSetRoleOp,ht as buildSetWithdrawVestingRouteOp,Qr as buildSubscribeOp,Le as buildTransferFromSavingsOp,je as buildTransferOp,Xe as buildTransferToSavingsOp,mt as buildTransferToVestingOp,Vt as buildUnfollowOp,_u as buildUnignoreOp,Hr as buildUnsubscribeOp,Vr as buildUpdateCommunityOp,wu as buildUpdateProposalOp,kr as buildVoteOp,gt as buildWithdrawVestingOp,Br as buildWitnessProxyOp,Kr as buildWitnessVoteOp,wl as buyStreakFreezeRequest,Bt as calculateRCMana,Pr as calculateVPMana,ne as callREST,y as callRPC,We as callRPCBroadcast,Dt as callWithQuorum,cA as canRevokeFromAuthority,i_ as checkFavoriteQueryOptions,Kh as checkUsernameWalletsPendingQueryOptions,Zd as claimPointsRequest,mn as collectRequestedOperations,cn as computeResourceCost,un as countCommentResourceUsage,yi as countVoteResourceUsage,Yg as decodeObj,Nu as dedupeAndSortKeyAuths,ci as deleteDraft,ii as deleteImage,pi as deleteSchedule,FA as downVotingPower,JS as earnsQuestContentCredit,Jg as encodeObj,TE as enforceThreeSpeakBeneficiary,AS as estimateCommentRcCost,pn as estimateCommentTransactionBytes,qS as estimateRcPrecheck,gi as estimateVoteTransactionBytes,Po as extractAccountProfile,Xs as formatError,nt as formattedNumber,dl as gameClaimRequest,SR as getAccountDelegationsQueryOptions,Q as getAccountFullQueryOptions,oC as getAccountNotificationsInfiniteQueryOptions,m_ as getAccountPendingRecoveryQueryOptions,Er as getAccountPosts,ww as getAccountPostsInfiniteQueryOptions,vw as getAccountPostsQueryOptions,fS as getAccountRcQueryOptions,u_ as getAccountRecoveriesQueryOptions,w_ as getAccountReputationsQueryOptions,Lh as getAccountSubscriptionsQueryOptions,h0 as getAccountVoteHistoryInfiniteQueryOptions,Cq as getAccountWalletAssetInfoQueryOptions,th as getAccountsQueryOptions,I0 as getAggregatedBalanceQueryOptions,Ay as getAiAssistPriceQueryOptions,by as getAiGeneratePriceQueryOptions,Sy as getAiTranscribePriceQueryOptions,qi as getAllHiveEngineTokensQueryOptions,FC as getAnnouncementsQueryOptions,PM as getBadActorsQueryOptions,k0 as getBalanceHistoryInfiniteQueryOptions,Jh as getBookmarksInfiniteQueryOptions,zh as getBookmarksQueryOptions,aM as getBoostPlusAccountPricesQueryOptions,LB as getBoostPlusPricesQueryOptions,F_ as getBotsQueryOptions,_ as getBoundFetch,XA as getChainPropertiesQueryOptions,NR as getCollateralizedConversionRequestsQueryOptions,sv as getCommentHistoryQueryOptions,nw as getCommunities,Dk as getCommunitiesQueryOptions,Do as getCommunity,Qk as getCommunityContextQueryOptions,fC as getCommunityPermissions,Lk as getCommunityQueryOptions,Xk as getCommunitySubscribersInfiniteQueryOptions,Yk as getCommunitySubscribersQueryOptions,dC as getCommunityType,HM as getContentModerationReason,Tb as getContentQueryOptions,Kb as getContentRepliesQueryOptions,eB as getControversialRisingInfiniteQueryOptions,DR as getConversionRequestsQueryOptions,Ci as getCurrencyRate,fI as getCurrencyRates,dI as getCurrencyTokenRate,eI as getCurrentMedianHistoryPriceQueryOptions,op as getCustomJsonAuthority,pv as getDeletedEntryQueryOptions,wE as getDiscoverCurationQueryOptions,gE as getDiscoverLeaderboardQueryOptions,qo as getDiscussion,fw as getDiscussionQueryOptions,No as getDiscussionsQueryOptions,Jw as getDraftsInfiniteQueryOptions,zw as getDraftsQueryOptions,Ee as getDynamicPropsQueryOptions,vb as getEntryActiveVotesQueryOptions,t_ as getFavoritesInfiniteQueryOptions,e_ as getFavoritesQueryOptions,JF as getFeedHistoryQueryOptions,sh as getFollowCountQueryOptions,lh as getFollowersQueryOptions,yh as getFollowingQueryOptions,db as getFragmentsInfiniteQueryOptions,Ye as getFragmentsQueryOptions,$_ as getFriendsInfiniteQueryOptions,tv as getGalleryImagesQueryOptions,MS as getGameStatusCheckQueryOptions,Ai as getHbdAssetGeneralInfoQueryOptions,eF as getHbdAssetTransactionsQueryOptions,Jt as getHiveAssetGeneralInfoQueryOptions,uF as getHiveAssetMetricQueryOptions,Yt as getHiveAssetTransactionsQueryOptions,fF as getHiveAssetWithdrawalRoutesQueryOptions,ZI as getHiveEngineBalancesWithUsdQueryOptions,Rd as getHiveEngineMetrics,bI as getHiveEngineOpenOrders,hI as getHiveEngineOrderBook,Di as getHiveEngineTokenGeneralInfoQueryOptions,Ti as getHiveEngineTokenMetrics,Ri as getHiveEngineTokenTransactions,II as getHiveEngineTokenTransactionsQueryOptions,Xt as getHiveEngineTokensBalances,er as getHiveEngineTokensBalancesQueryOptions,rt as getHiveEngineTokensMarket,EI as getHiveEngineTokensMarketQueryOptions,Zt as getHiveEngineTokensMetadata,Ii as getHiveEngineTokensMetadataQueryOptions,BI as getHiveEngineTokensMetricsQueryOptions,_I as getHiveEngineTradeHistory,Fi as getHiveEngineUnclaimedRewards,HI as getHiveEngineUnclaimedRewardsQueryOptions,MF as getHiveHbdStatsQueryOptions,tS as getHivePoshLinksQueryOptions,Oi as getHivePowerAssetGeneralInfoQueryOptions,iF as getHivePowerAssetTransactionsQueryOptions,hF as getHivePowerDelegatesInfiniteQueryOptions,PF as getHivePowerDelegatingsQueryOptions,mI as getHivePrice,rv as getImagesInfiniteQueryOptions,ev as getImagesQueryOptions,sT as getIncomingRcQueryOptions,lI as getMarketData,UF as getMarketDataQueryOptions,qF as getMarketHistoryQueryOptions,RF as getMarketStatisticsQueryOptions,vh as getMutedUsersQueryOptions,ld as getNextAccountHistoryPageParam,u0 as getNormalizePostQueryOptions,SO as getNotificationSetting,xO as getNotifications,vC as getNotificationsInfiniteQueryOptions,kC as getNotificationsSettingsQueryOptions,hC as getNotificationsUnreadCountQueryOptions,YR as getOpenOrdersQueryOptions,sp as getOperationAuthority,EF as getOrderBookQueryOptions,rT as getOutgoingRcDelegationsInfiniteQueryOptions,OE as getPageStatsQueryOptions,Ki as getPointsAssetGeneralInfoQueryOptions,hq as getPointsAssetTransactionsQueryOptions,vt as getPointsQueryOptions,RM as getPollQueryOptions,Pi as getPortfolioQueryOptions,wc as getPost,rw as getPostHeader,Hb as getPostHeaderQueryOptions,Ro as getPostQueryOptions,mv as getPostTipsQueryOptions,Io as getPostsRanked,Cw as getPostsRankedInfiniteQueryOptions,Rw as getPostsRankedQueryOptions,B0 as getProMembersQueryOptions,Ut as getProfiles,P0 as getProfilesQueryOptions,nM as getPromotePriceQueryOptions,CO as getPromotedPost,yb as getPromotedPostsQuery,ip as getProposalAuthority,YC as getProposalQueryOptions,aR as getProposalVotesInfiniteQueryOptions,tR as getProposalsQueryOptions,w as getQueryClient,zS as getQuestCatalogEntry,WS as getQuestsQueryOptions,ZB as getRcDelegationActiveQueryOptions,zB as getRcDelegationPricesQueryOptions,_S as getRcResourceParamsQueryOptions,uS as getRcStatsQueryOptions,Qw as getRebloggedByQueryOptions,Dw as getReblogsQueryOptions,pT as getReceivedVestingSharesQueryOptions,mT as getRecurrentTransfersQueryOptions,K_ as getReferralsInfiniteQueryOptions,Q_ as getReferralsStatsQueryOptions,sw as getRelationshipBetweenAccounts,Eo as getRelationshipBetweenAccountsQueryOptions,KA as getRequiredAuthority,fy as getRewardFundQueryOptions,cC as getRewardedCommunitiesQueryOptions,VR as getSavingsWithdrawFromQueryOptions,Lw as getSchedulesInfiniteQueryOptions,jw as getSchedulesQueryOptions,hB as getSearchAccountQueryOptions,Fh as getSearchAccountsByUsernameQueryOptions,kB as getSearchApiInfiniteQueryOptions,Y_ as getSearchFriendsQueryOptions,FB as getSearchPathQueryOptions,PB as getSearchTopicsQueryOptions,kv as getShortsFeedQueryOptions,lB as getSimilarEntriesQueryOptions,KC as getSpotlightsQueryOptions,iS as getStatsQueryOptions,iw as getSubscribers,ow as getSubscriptions,KB as getSupportSettingsQueryOptions,vf as getSupportSettingsRequest,$F as getTradeHistoryQueryOptions,k_ as getTransactionsInfiniteQueryOptions,rb as getTrendingTagsQueryOptions,cb as getTrendingTagsWithStatsQueryOptions,Eb as getUserPostVoteQueryOptions,lR as getUserProposalVotesQueryOptions,TR as getVestingDelegationExpirationsQueryOptions,AR as getVestingDelegationsQueryOptions,Vo as getVisibleFirstLevelThreadItems,e0 as getWavesByAccountQueryOptions,Dv as getWavesByHostQueryOptions,Qv as getWavesByTagQueryOptions,Pv as getWavesFeedQueryOptions,Lv as getWavesFollowingQueryOptions,Av as getWavesLatestFeedQueryOptions,o0 as getWavesTrendingAuthorsQueryOptions,zv as getWavesTrendingTagsQueryOptions,WR as getWithdrawRoutesQueryOptions,TK as getWitnessVoterCountQueryOptions,RK as getWitnessVotersPageQueryOptions,CK as getWitnessesInfiniteQueryOptions,Gi as hasExternalLink,Np as hasThreeSpeakEmbed,E as hiveTxConfig,ie as hiveTxUtils,_M as hsTokenRenew,S as invalidateAfterBroadcast,QM as isAuthorMuted,_o as isCommunity,bo as isEmptyDate,zf as isHiddenPost,ea as isInfoError,Jf as isLowTrustSeoPost,ta as isNetworkError,Je as isQueryableAccountName,Zs as isResourceCreditsError,FE as isThreeSpeakBeneficiary,Sp as isVoteAlreadyReflected,co as isWif,da as isWrappedResponse,Sh as lookupAccountsQueryOptions,Gg as makeQueryClient,xM as mapMetaChoicesToPollChoices,jo as mapThreadItemsToWaveEntries,ri as markNotifications,yl as measureQuestContentLength,li as moveSchedule,Ko as normalizePost,ef as normalizeSearchAuthor,tf as normalizeSearchCategory,rf as normalizeSearchTags,ce as normalizeToWrappedResponse,be as normalizeWaveEntryFromApi,RO as onboardEmail,Ht as parseAccounts,C as parseAsset,Ge as parseChainError,ka as parsePostingMetadataRoot,He as parseProfileMetadata,Ao as pickRicherMetadataSnapshot,TA as powerRechargeTime,ln as priceRcUsage,M0 as proMembersSet,IA as rcPower,di as removeOptimisticDiscussionEntry,dd as resolveAccountHistoryLimit,Cp as resolveContentActivityType,bt as resolveHiveOperationFilters,To as resolvePost,fi as restoreDiscussionSnapshots,Ux as restoreEntryInCache,pC as roleMap,EO as saveNotificationSetting,oB as search,iB as searchPath,ZK as searchQueryOptions,wg as sha256,Pe as shouldTriggerAuthFallback,PO as signUp,Li as similar,vc as sortDiscussions,dn as stringFieldBytes,AO as subscribeEmail,Hc as toEntryArray,ai as updateDraft,Hx as updateEntryInCache,Of as updateSupportSettingsRequest,oi as uploadImage,kO as uploadImageWithSignature,FP as useAccountFavoriteAdd,BP as useAccountFavoriteDelete,z0 as useAccountRelationsUpdate,mA as useAccountRevokeKey,ZP as useAccountRevokePosting,j0 as useAccountUpdate,Yo as useAccountUpdateKeyAuths,WP as useAccountUpdatePassword,sA as useAccountUpdateRecovery,DO as useAddDraft,sO as useAddFragment,dx as useAddImage,YO as useAddSchedule,Dy as useAiAssist,Ny as useAiTranscribe,OP as useBookmarkAdd,kP as useBookmarkDelete,lM as useBoostPlus,v as useBroadcastMutation,rk as useBuyStreakFreeze,_A as useClaimAccount,tK as useClaimEngineRewards,RD as useClaimInterest,MK as useClaimPoints,DD as useClaimRewards,Bx as useComment,xD as useConvert,EA as useCreateAccount,Yx as useCrossPost,ND as useDelegateEngineToken,gK as useDelegateRc,Lq as useDelegateVestingShares,Wx as useDeleteComment,$O as useDeleteDraft,hx as useDeleteImage,rx as useDeleteSchedule,fO as useEditFragment,iK as useEngineMarketOrder,yP as useFollow,VS as useGameClaim,Ty as useGenerateImage,PA as useGrantPostingPermission,cI as useLimitOrderCancel,oI as useLimitOrderCreate,VC as useMarkNotificationsRead,ax as useMoveSchedule,mk as useMutePost,Rk as usePinPost,IM as usePollVote,iE as usePromote,bR as useProposalCreate,gR as useProposalVote,gM as useRcDelegation,Ix as useReblog,nn as useRecordActivity,Ek as useRegisterCommunityRewards,bO as useRemoveFragment,_k as useSetCommunityRole,WC as useSetLastRead,Jq as useSetWithdrawVestingRoute,GA as useSignOperationByHivesigner,HA as useSignOperationByKey,jA as useSignOperationByKeychain,WD as useStakeEngineToken,sk as useSubscribeCommunity,Dq as useTransfer,eD as useTransferEngineToken,pD as useTransferFromSavings,Qq as useTransferPoint,iD as useTransferToSavings,gD as useTransferToVesting,VD as useUndelegateEngineToken,wP as useUnfollow,YD as useUnstakeEngineToken,pk as useUnsubscribeCommunity,Pk as useUpdateCommunity,QO as useUpdateDraft,tE as useUpdateReply,HB as useUpdateSupportSettings,vx as useUploadImage,kx as useVote,lK as useWalletOperation,wD as useWithdrawVesting,AK as useWitnessProxy,bK as useWitnessVote,OO as usrActivity,lt as utf8ByteLength,Ip as validatePostCreating,_e as varintByteLength,Co as verifyPostOnAlternateNode,ze as vestsToHp,RA as votingPower,rp as votingRshares,qA as votingValue,Oe as withTimeoutSignal};//# sourceMappingURL=index.js.map + */export{To as ACCOUNT_OPERATION_GROUPS,du as ALL_ACCOUNT_OPERATIONS,Oi as ALL_NOTIFY_TYPES,sf as AssetOperation,uy as BROADCAST_INCLUSION_DELAY_MS,Zo as BuySellTransactionType,d as CONFIG,M as ConfigManager,um as ContentModerationReason,rt as EcencyAnalytics,bo as EcencyQueriesManager,Fe as EntriesCacheManagement,yo as ErrorType,Zf as HIDDEN_POST_MIN_VOTES,Xf as HIDDEN_POST_RSHARES_THRESHOLD,hn as HIVE_ACCOUNT_OPERATION_GROUPS,lq as HIVE_OPERATION_LIST,gq as HIVE_OPERATION_NAME_BY_ID,mq as HIVE_OPERATION_ORDERS,or as HiveEngineToken,_i as HiveSignerIntegration,Me as HiveTxTransaction,xe as INTERNAL_API_TIMEOUT_MS,em as LOW_TRUST_REPUTATION_THRESHOLD,fN as MAX_SEARCH_QUERY_LENGTH,dN as MAX_SEARCH_TAGS,lo as Memo,Ut as NaiMap,xt as NewsletterApiError,sr as NewsletterSendRefusedError,$l as NotificationFilter,Gl as NotificationViewType,Wl as NotifyTypes,_p as OPERATION_AUTHORITY_MAP,ei as OrderIdPrefix,JB as POLLS_PROTOCOL_VERSION,ff as PointTransactionType,Gf as PollPreferredInterpretation,V as PrivateKey,Z as PublicKey,Cl as QUEST_CATALOG,Rl as QUEST_MIN_CONTENT_LENGTH,u as QueryKeys,Xt as RC_RESOURCE_NAMES,Vl as ROLES,wo as SERVER_GC_TIME_MS,wl as SIGNATURE_BYTES,KN as SIMILAR_ENTRIES_MIN_RENDER,Ok as STREAK_FREEZE_MAX_OWNED,Ak as STREAK_FREEZE_PRICE,Pi as SUBSCRIBERS_PAGE_SIZE,$i as SearchQuery,Wi as SearchType,ke as Signature,Uo as SortOrder,vo as Symbol,Yt as THREESPEAK_BENEFICIARY_ACCOUNT,rE as THREESPEAK_BENEFICIARY_WEIGHT,_l as TRANSACTION_HEADER_BYTES,vE as ThreeSpeakIntegration,ja as accountNameByteLength,pi as addDraft,ai as addImage,dS as addOptimisticDiscussionEntry,fi as addSchedule,Qf as applySupportSettingsUpdate,Vp as applyVoteCacheUpdate,ce as bridgeApiCall,_o as broadcastJson,re as broadcastOperations,mo as broadcastOperationsAsync,Xr as buildAccountCreateOp,Qc as buildAccountUpdate2Op,Mc as buildAccountUpdateOp,$c as buildActiveCustomJsonOp,rn as buildBoostPlusOp,Xo as buildCancelTransferFromSavingsOp,Uc as buildChangeRecoveryAccountOp,en as buildClaimAccountOp,gt as buildClaimInterestOps,Yr as buildClaimRewardBalanceOp,Dr as buildCollateralizedConvertOp,Ve as buildCommentOp,je as buildCommentOptionsOp,sn as buildCommunityRegistrationOp,bt as buildConvertOp,Zr as buildCreateClaimedAccountOp,Nr as buildDelegateRcOp,_t as buildDelegateVestingSharesOp,Fr as buildDeleteCommentOp,Kr as buildEngineClaimOp,We as buildEngineOp,Nc as buildFlagPostOp,Br as buildFollowOp,tn as buildGrantPostingPermissionOp,qc as buildIgnoreOp,Jr as buildLimitOrderCancelOp,Gt as buildLimitOrderCreateOp,Bc as buildLimitOrderCreateOpWithType,Lc as buildMultiPointTransferOps,Rc as buildMultiTransferOps,zr as buildMutePostOp,Kc as buildMuteUserOp,Gr as buildPinPostOp,tt as buildPointTransferOp,Wc as buildPostingCustomJsonOp,ko as buildPostingJsonMetadata,Cr as buildProfileMetadata,on as buildPromoteOp,Ur as buildProposalCreateOp,Vr as buildProposalVoteOp,nn as buildRcDelegationOp,Ir as buildReblogOp,jc as buildRecoverAccountOp,Tc as buildRecurrentTransferOp,Ic as buildRemoveProposalOp,Vc as buildRequestAccountRecoveryOp,ri as buildRevokeKeysOp,Hc as buildRevokePostingPermissionOp,mN as buildSearchQuery,Mr as buildSetLastReadOps,$r as buildSetRoleOp,wt as buildSetWithdrawVestingRouteOp,jr as buildSubscribeOp,$e as buildTransferFromSavingsOp,Le as buildTransferOp,et as buildTransferToSavingsOp,yt as buildTransferToVestingOp,$t as buildUnfollowOp,Fc as buildUnignoreOp,Lr as buildUnsubscribeOp,Wr as buildUpdateCommunityOp,Dc as buildUpdateProposalOp,qr as buildVoteOp,ht as buildWithdrawVestingOp,Hr as buildWitnessProxyOp,Qr as buildWitnessVoteOp,Dl as buyStreakFreezeRequest,Qt as calculateRCMana,Sr as calculateVPMana,ne as callREST,y as callRPC,ze as callRPCBroadcast,Bt as callWithQuorum,IA as canRevokeFromAuthority,T_ as checkFavoriteQueryOptions,u_ as checkUsernameWalletsPendingQueryOptions,gf as claimPointsRequest,_n as collectRequestedOperations,dn as computeResourceCost,fn as countCommentResourceUsage,bi as countVoteResourceUsage,Ay as decodeObj,ep as dedupeAndSortKeyAuths,di as deleteDraft,ci as deleteImage,mi as deleteSchedule,oO as downVotingPower,Pk as earnsQuestContentCredit,Py as encodeObj,nE as enforceThreeSpeakBeneficiary,zE as estimateCommentRcCost,mn as estimateCommentTransactionBytes,sk as estimateRcPrecheck,wi as estimateVoteTransactionBytes,So as extractAccountProfile,fa as formatError,it as formattedNumber,El as gameClaimRequest,ZR as getAccountDelegationsQueryOptions,Q as getAccountFullQueryOptions,RC as getAccountNotificationsInfiniteQueryOptions,Q_ as getAccountPendingRecoveryQueryOptions,Rr as getAccountPosts,$b as getAccountPostsInfiniteQueryOptions,Wb as getAccountPostsQueryOptions,ME as getAccountRcQueryOptions,D_ as getAccountRecoveriesQueryOptions,$_ as getAccountReputationsQueryOptions,h_ as getAccountSubscriptionsQueryOptions,V0 as getAccountVoteHistoryInfiniteQueryOptions,tD as getAccountWalletAssetInfoQueryOptions,Eh as getAccountsQueryOptions,iP as getAggregatedBalanceQueryOptions,zy as getAiAssistPriceQueryOptions,Ly as getAiGeneratePriceQueryOptions,Zy as getAiTranscribePriceQueryOptions,Bi as getAllHiveEngineTokensQueryOptions,oR as getAnnouncementsQueryOptions,GB as getBadActorsQueryOptions,eP as getBalanceHistoryInfiniteQueryOptions,P_ as getBookmarksInfiniteQueryOptions,v_ as getBookmarksQueryOptions,FB as getBoostPlusAccountPricesQueryOptions,hB as getBoostPlusPricesQueryOptions,ow as getBotsQueryOptions,h as getBoundFetch,OO as getChainPropertiesQueryOptions,lT as getCollateralizedConversionRequestsQueryOptions,qv as getCommentHistoryQueryOptions,Cb as getCommunities,aC as getCommunitiesQueryOptions,Mo as getCommunity,dC as getCommunityContextQueryOptions,MC as getCommunityPermissions,hC as getCommunityQueryOptions,OC as getCommunitySubscribersInfiniteQueryOptions,AC as getCommunitySubscribersQueryOptions,BC as getCommunityType,fM as getContentModerationReason,nb as getContentQueryOptions,ub as getContentRepliesQueryOptions,SN as getControversialRisingInfiniteQueryOptions,aT as getConversionRequestsQueryOptions,Fi as getCurrencyRate,MF as getCurrencyRates,BF as getCurrencyTokenRate,SF as getCurrentMedianHistoryPriceQueryOptions,wp as getCustomJsonAuthority,Kv as getDeletedEntryQueryOptions,vM as getDigestSubscriptionsQueryOptions,es as getDigestSubscriptionsRequest,$S as getDiscoverCurationQueryOptions,HS as getDiscoverLeaderboardQueryOptions,Bo as getDiscussion,Mb as getDiscussionQueryOptions,Vo as getDiscussionsQueryOptions,Pv as getDraftsInfiniteQueryOptions,vv as getDraftsQueryOptions,Se as getDynamicPropsQueryOptions,Ww as getEntryActiveVotesQueryOptions,E_ as getFavoritesInfiniteQueryOptions,S_ as getFavoritesQueryOptions,PF as getFeedHistoryQueryOptions,qh as getFollowCountQueryOptions,Nh as getFollowersQueryOptions,Uh as getFollowingQueryOptions,Bw as getFragmentsInfiniteQueryOptions,Ze as getFragmentsQueryOptions,_w as getFriendsInfiniteQueryOptions,Ev as getGalleryImagesQueryOptions,pk as getGameStatusCheckQueryOptions,Ei as getHbdAssetGeneralInfoQueryOptions,Sq as getHbdAssetTransactionsQueryOptions,Zt as getHiveAssetGeneralInfoQueryOptions,Dq as getHiveAssetMetricQueryOptions,er as getHiveAssetTransactionsQueryOptions,Mq as getHiveAssetWithdrawalRoutesQueryOptions,xI as getHiveEngineBalancesWithUsdQueryOptions,Ld as getHiveEngineMetrics,LF as getHiveEngineOpenOrders,VF as getHiveEngineOrderBook,Mi as getHiveEngineTokenGeneralInfoQueryOptions,Di as getHiveEngineTokenMetrics,Ii as getHiveEngineTokenTransactions,iI as getHiveEngineTokenTransactionsQueryOptions,tr as getHiveEngineTokensBalances,nr as getHiveEngineTokensBalancesQueryOptions,ot as getHiveEngineTokensMarket,XF as getHiveEngineTokensMarketQueryOptions,rr as getHiveEngineTokensMetadata,Ni as getHiveEngineTokensMetadataQueryOptions,cI as getHiveEngineTokensMetricsQueryOptions,jF as getHiveEngineTradeHistory,Ki as getHiveEngineUnclaimedRewards,fI as getHiveEngineUnclaimedRewardsQueryOptions,pF as getHiveHbdStatsQueryOptions,EE as getHivePoshLinksQueryOptions,ki as getHivePowerAssetGeneralInfoQueryOptions,Tq as getHivePowerAssetTransactionsQueryOptions,Vq as getHivePowerDelegatesInfiniteQueryOptions,Gq as getHivePowerDelegatingsQueryOptions,QF as getHivePrice,kv as getImagesInfiniteQueryOptions,Sv as getImagesQueryOptions,qT as getIncomingRcQueryOptions,NF as getMarketData,mF as getMarketDataQueryOptions,sF as getMarketHistoryQueryOptions,rF as getMarketStatisticsQueryOptions,Wh as getMutedUsersQueryOptions,TM as getNewsletterIssuesQueryOptions,os as getNewsletterIssuesRequest,KM as getNewsletterPostsQueryOptions,is as getNewsletterPostsRequest,SM as getNewsletterSenderQueryOptions,ns as getNewsletterSenderRequest,Sd as getNextAccountHistoryPageParam,D0 as getNormalizePostQueryOptions,ZO as getNotificationSetting,YO as getNotifications,WC as getNotificationsInfiniteQueryOptions,eR as getNotificationsSettingsQueryOptions,VC as getNotificationsUnreadCountQueryOptions,AT as getOpenOrdersQueryOptions,vp as getOperationAuthority,Xq as getOrderBookQueryOptions,kT as getOutgoingRcDelegationsInfiniteQueryOptions,JS as getPageStatsQueryOptions,Qi as getPointsAssetGeneralInfoQueryOptions,VI as getPointsAssetTransactionsQueryOptions,At as getPointsQueryOptions,rM as getPollQueryOptions,Si as getPortfolioQueryOptions,Du as getPost,kb as getPostHeader,fb as getPostHeaderQueryOptions,Io as getPostQueryOptions,Qv as getPostTipsQueryOptions,No as getPostsRanked,tv as getPostsRankedInfiniteQueryOptions,rv as getPostsRankedQueryOptions,cP as getProMembersQueryOptions,Lt as getProfiles,G0 as getProfilesQueryOptions,CB as getPromotePriceQueryOptions,tx as getPromotedPost,Uw as getPromotedPostsQuery,bp as getProposalAuthority,AR as getProposalQueryOptions,FR as getProposalVotesInfiniteQueryOptions,ER as getProposalsQueryOptions,b as getQueryClient,vk as getQuestCatalogEntry,wk as getQuestsQueryOptions,xB as getRcDelegationActiveQueryOptions,vB as getRcDelegationPricesQueryOptions,jE as getRcResourceParamsQueryOptions,DE as getRcStatsQueryOptions,dv as getRebloggedByQueryOptions,av as getReblogsQueryOptions,KT as getReceivedVestingSharesQueryOptions,QT as getRecurrentTransfersQueryOptions,uw as getReferralsInfiniteQueryOptions,dw as getReferralsStatsQueryOptions,qb as getRelationshipBetweenAccounts,Ro as getRelationshipBetweenAccountsQueryOptions,uO as getRequiredAuthority,My as getRewardFundQueryOptions,IC as getRewardedCommunitiesQueryOptions,gT as getSavingsWithdrawFromQueryOptions,hv as getSchedulesInfiniteQueryOptions,yv as getSchedulesQueryOptions,VN as getSearchAccountQueryOptions,o_ as getSearchAccountsByUsernameQueryOptions,eB as getSearchApiInfiniteQueryOptions,Aw as getSearchFriendsQueryOptions,oB as getSearchPathQueryOptions,GN as getSearchTopicsQueryOptions,e0 as getShortsFeedQueryOptions,NN as getSimilarEntriesQueryOptions,uR as getSpotlightsQueryOptions,TE as getStatsQueryOptions,Tb as getSubscribers,Rb as getSubscriptions,uB as getSupportSettingsQueryOptions,Kf as getSupportSettingsRequest,_F as getTradeHistoryQueryOptions,ew as getTransactionsInfiniteQueryOptions,kw as getTrendingTagsQueryOptions,Iw as getTrendingTagsWithStatsQueryOptions,Xw as getUserPostVoteQueryOptions,NR as getUserProposalVotesQueryOptions,nT as getVestingDelegationExpirationsQueryOptions,zR as getVestingDelegationsQueryOptions,Wo as getVisibleFirstLevelThreadItems,S0 as getWavesByAccountQueryOptions,a0 as getWavesByHostQueryOptions,d0 as getWavesByTagQueryOptions,Gv as getWavesFeedQueryOptions,h0 as getWavesFollowingQueryOptions,zv as getWavesLatestFeedQueryOptions,R0 as getWavesTrendingAuthorsQueryOptions,v0 as getWavesTrendingTagsQueryOptions,wT as getWithdrawRoutesQueryOptions,nN as getWitnessVoterCountQueryOptions,rN as getWitnessVotersPageQueryOptions,tN as getWitnessesInfiniteQueryOptions,Xi as hasExternalLink,el as hasThreeSpeakEmbed,S as hiveTxConfig,ie as hiveTxUtils,jB as hsTokenRenew,E as invalidateAfterBroadcast,dM as isAuthorMuted,Po as isCommunity,Ao as isEmptyDate,pm as isHiddenPost,ga as isInfoError,lm as isLowTrustSeoPost,ya as isNetworkError,Xe as isQueryableAccountName,ma as isResourceCreditsError,oE as isThreeSpeakBeneficiary,Up as isVoteAlreadyReflected,fo as isWif,Ea as isWrappedResponse,ts as leaveDigestRequest,Zh as lookupAccountsQueryOptions,by as makeQueryClient,YB as mapMetaChoicesToPollChoices,Go as mapThreadItemsToWaveEntries,si as markNotifications,Tl as measureQuestContentLength,gi as moveSchedule,Qo as normalizePost,yf as normalizeSearchAuthor,hf as normalizeSearchCategory,_f as normalizeSearchTags,ue as normalizeToWrappedResponse,we as normalizeWaveEntryFromApi,rx as onboardEmail,jt as parseAccounts,C as parseAsset,Je as parseChainError,Va as parsePostingMetadataRoot,Ue as parseProfileMetadata,Eo as pickRicherMetadataSnapshot,nO as powerRechargeTime,as as previewNewsletterSendRequest,gn as priceRcUsage,pP as proMembersSet,iO as rcPower,yi as removeOptimisticDiscussionEntry,Ed as resolveAccountHistoryLimit,jp as resolveContentActivityType,vt as resolveHiveOperationFilters,Do as resolvePost,hi as restoreDiscussionSnapshots,mS as restoreEntryInCache,KC as roleMap,XO as saveNotificationSetting,RN as search,TN as searchPath,xN as searchQueryOptions,us as sendNewsletterIssueRequest,$g as sha256,Pe as shouldTriggerAuthFallback,GO as signUp,zi as similar,Ku as sortDiscussions,yn as stringFieldBytes,Zi as subscribeDigestRequest,zO as subscribeEmail,rc as toEntryArray,rs as unsubscribeAllDigestsRequest,li as updateDraft,fS as updateEntryInCache,Mf as updateSupportSettingsRequest,ui as uploadImage,ex as uploadImageWithSignature,oA as useAccountFavoriteAdd,cA as useAccountFavoriteDelete,vP as useAccountRelationsUpdate,QA as useAccountRevokeKey,xA as useAccountRevokePosting,yP as useAccountUpdate,ti as useAccountUpdateKeyAuths,wA as useAccountUpdatePassword,qA as useAccountUpdateRecovery,ax as useAddDraft,qO as useAddFragment,Bx as useAddImage,Ax as useAddSchedule,ah as useAiAssist,lh as useAiTranscribe,JP as useBookmarkAdd,eA as useBookmarkDelete,NB as useBoostPlus,v as useBroadcastMutation,kk as useBuyStreakFreeze,jA as useClaimAccount,EK as useClaimEngineRewards,rK as useClaimInterest,pN as useClaimPoints,aK as useClaimRewards,cS as useComment,YD as useConvert,XA as useCreateAccount,AS as useCrossPost,lK as useDelegateEngineToken,HK as useDelegateRc,hD as useDelegateVestingShares,wS as useDeleteComment,_x as useDeleteDraft,Vx as useDeleteImage,kx as useDeleteSchedule,MO as useEditFragment,TK as useEngineMarketOrder,UP as useFollow,gk as useGameClaim,nh as useGenerateImage,GA as useGrantPostingPermission,$M as useLeaveDigest,IF as useLimitOrderCancel,RF as useLimitOrderCreate,gR as useMarkNotificationsRead,Fx as useMoveSchedule,Qk as useMutePost,rC as usePinPost,iM as usePollVote,rQ as usePreviewNewsletterIssue,TS as usePromote,LR as useProposalCreate,HR as useProposalVote,HB as useRcDelegation,iS as useReblog,un as useRecordActivity,Xk as useRegisterCommunityRewards,LO as useRemoveFragment,nQ as useSendNewsletterIssue,jk as useSetCommunityRole,wR as useSetLastRead,PD as useSetWithdrawVestingRoute,bO as useSignOperationByHivesigner,fO as useSignOperationByKey,yO as useSignOperationByKeychain,wK as useStakeEngineToken,qk as useSubscribeCommunity,HM as useSubscribeDigest,aD as useTransfer,SD as useTransferEngineToken,KD as useTransferFromSavings,dD as useTransferPoint,TD as useTransferToSavings,HD as useTransferToVesting,gK as useUndelegateEngineToken,$P as useUnfollow,AK as useUnstakeEngineToken,YM as useUnsubscribeAllDigests,Kk as useUnsubscribeCommunity,Gk as useUpdateCommunity,dx as useUpdateDraft,ES as useUpdateReply,fB as useUpdateSupportSettings,Wx as useUploadImage,eS as useVote,NK as useWalletOperation,$D as useWithdrawVesting,zK as useWitnessProxy,LK as useWitnessVote,JO as usrActivity,ft as utf8ByteLength,Gp as validatePostCreating,_e as varintByteLength,Fo as verifyPostOnAlternateNode,Ye as vestsToHp,rO as votingPower,hp as votingRshares,sO as votingValue,Oe 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 0633c55e3d..d8d6240449 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/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-comment-rc-cost.ts","../../src/modules/resource-credits/utils/price-rc-usage.ts","../../src/modules/resource-credits/utils/count-operation-usage.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","../../src/modules/moderation/constants.ts","../../src/modules/moderation/account-reputation.ts","../../src/modules/moderation/external-links.ts","../../src/modules/moderation/content-moderation.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","DEFAULT_SERVER_RPC_PROXY_METHODS","serverRpcProxy","setServerRpcProxy","opts","url","headers","k","v","timeoutMs","methods","m","pos","fallback","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","r","bool","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","rpcProxyStats","ProxyMiss","reason","errorMessage","proxyConsecutiveMisses","proxyOpenUntil","proxyRpcCall","proxy","method","params","callerTimeoutMs","externalSignal","validate","dot","tSignal","cleanupTimeout","createTimeoutSignal","signal","cleanupMerge","mergeSignals","res","e","relayed","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","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","tryRecordHeadBlock","block","createTimeoutReason","err","controller","timer","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","timeout","shouldRetry","body","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","served","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","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","timeoutSignal","ac","onAbort","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","getServerRpcProxyStats","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","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","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","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","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","resolveContentActivityType","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","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","EMPTY","estimateCommentRcCost","rcParams","rcStats","usage","regen","cost","breakdown","share","scaled","resourceCost","priceRcUsage","emptyUsage","estimateVoteTransactionBytes","operationBytes","countVoteResourceUsage","estimateRcPrecheck","priced","priceOperation","safeBuffer","estimatedCost","willLikelyFail","average","averageCost","MINIMAL_VOTE","MINIMAL_COMMENT","getGameStatusCheckQueryOptions","gameClaimRequest","contentType","detail","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","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","HIDDEN_POST_RSHARES_THRESHOLD","HIDDEN_POST_MIN_VOTES","LOW_TRUST_REPUTATION_THRESHOLD","isHumanReadable","accountReputation","neg","reputationLevel","INTERNAL_HOSTS","IMAGE_HOSTS","IMAGE_EXT_RE","URL_RE","TRAILING_PUNCT_RE","hostOf","isExternalPromoLink","rawUrl","hasExternalLink","ContentModerationReason","countVotes","isHiddenPost","netRshares","activeVotesLength","isLowTrustSeoPost","reputation","isAuthorMuted","mutedAuthors","getContentModerationReason"],"mappings":"yqBASA,IAAMA,GAAe,IAAI,WAAA,CAAY,CAAC,CAAA,CAIlCC,EAAAA,CAAqD,IAAA,CACrDC,EAAAA,CAAuD,IAAA,CAE3D,SAASC,IAAgD,CACvD,OAAKF,KACC,OAAO,WAAA,CAAgB,IACzBA,EAAAA,CAAW,IAAI,WAAA,CAEfA,EAAAA,CAAW,CACT,MAAA,CAAOG,EAAuB,CAE5B,IAAMC,EAAiB,EAAC,CACxB,QAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAE,MAAA,CAAQE,CAAAA,EAAAA,CAAK,CACjC,IAAIC,CAAAA,CAAIH,EAAE,UAAA,CAAWE,CAAC,EACtB,GAAIC,CAAAA,CAAI,GAAA,CACNF,CAAAA,CAAK,IAAA,CAAKE,CAAC,UACFA,CAAAA,CAAI,IAAA,CACbF,EAAK,IAAA,CAAK,GAAA,CAAQE,GAAK,CAAA,CAAI,GAAA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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 * Server-side read-through proxy for RPC reads (see `setServerRpcProxy`).\n * `methods` is the allowlist the proxy serves; a read outside it goes straight\n * to the node pool as before.\n */\nexport interface ServerRpcProxyOptions {\n /** Absolute URL of the proxy endpoint (POST `{api, method, params}`). */\n url: string\n /** Headers sent with every proxy call (the shared internal secret). */\n headers: Record\n /** Per-call timeout in ms; on expiry the read falls back to the node pool. */\n timeoutMs: number\n /** Fully qualified method names (`bridge.get_post`) the proxy may answer;\n * omitted = DEFAULT_SERVER_RPC_PROXY_METHODS. An empty list is ignored. */\n methods?: string[]\n /**\n * After this many consecutive proxy misses the proxy is skipped for\n * `cooldownMs`, so a proxy that is down costs one failed call per cooldown\n * window rather than one per read. Default 3 / 10s. A served call resets it.\n */\n failureThreshold?: number\n cooldownMs?: number\n}\n\n/** Default allowlist: the reads a server render makes and the proxy caches. */\nexport const DEFAULT_SERVER_RPC_PROXY_METHODS: readonly string[] = [\n 'bridge.get_ranked_posts',\n 'bridge.get_account_posts',\n 'bridge.get_post',\n 'bridge.get_discussion',\n 'bridge.get_profile',\n 'bridge.get_profiles',\n 'bridge.get_community',\n 'bridge.list_communities',\n 'condenser_api.get_accounts',\n 'condenser_api.get_content',\n 'condenser_api.get_dynamic_global_properties',\n 'condenser_api.get_trending_tags'\n]\n\n/**\n * Active proxy configuration, or null (the default: every read goes to the node\n * pool). Lives outside `config` so the browser bundle never carries it; it is\n * only ever consulted under Node.\n */\nexport interface ServerRpcProxyState extends Required {\n methodSet: Set\n}\n\nexport let serverRpcProxy: ServerRpcProxyState | null = null\n\n/**\n * Route allowlisted server-side reads through a read-through cache in front\n * of the node pool. One cache per host answers the reads every renderer\n * process used to make on its own; a miss there is one upstream call shared by\n * every concurrent reader. The proxy is an optimization, never a dependency:\n * any failure (non-200, timeout, transport error, a response the caller's\n * validator rejects) falls straight through to the existing node loop, so the\n * worst case is the latency of a failed proxy call on top of what happens\n * today. Has no effect outside Node. Pass null to switch it off.\n */\nexport const setServerRpcProxy = (opts: ServerRpcProxyOptions | null): void => {\n if (opts === null) {\n serverRpcProxy = null\n return\n }\n if (!opts || typeof opts !== 'object') return\n const url = typeof opts.url === 'string' ? opts.url.trim() : ''\n if (!/^https?:\\/\\//i.test(url)) return\n const headers: Record = {}\n if (opts.headers && typeof opts.headers === 'object') {\n for (const [k, v] of Object.entries(opts.headers)) {\n if (typeof v === 'string' && v && !/[\\u0000-\\u001f\\u007f]/.test(v) && !/[\\u0000-\\u001f\\u007f]/.test(k)) {\n headers[k] = v\n }\n }\n }\n const timeoutMs =\n typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0\n ? opts.timeoutMs\n : 2_000\n const methods =\n opts.methods === undefined\n ? [...DEFAULT_SERVER_RPC_PROXY_METHODS]\n : Array.isArray(opts.methods)\n ? opts.methods.filter((m): m is string => typeof m === 'string' && m.includes('.'))\n : []\n // Nothing to route through the proxy: keep whatever was configured before.\n if (methods.length === 0) return\n const pos = (v: unknown, fallback: number): number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : fallback\n serverRpcProxy = {\n url,\n headers,\n timeoutMs,\n methods,\n failureThreshold: Math.floor(pos(opts.failureThreshold, 3)),\n cooldownMs: pos(opts.cooldownMs, 10_000),\n methodSet: new Set(methods)\n }\n}\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, serverRpcProxy, type ServerRpcProxyState } 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// ── Server-side read-through proxy ──────────────────────────────────────────\n\n/**\n * Counters for the proxy path, readable by a host's diagnostics (the web\n * tier's event-loop monitor prints them). `served` = answered by the proxy,\n * `fallback` = proxy configured and eligible but the read went to the node\n * pool, with the reason.\n */\nexport const rpcProxyStats = {\n served: 0,\n fallback: 0,\n /** Reads that went straight to the nodes because the breaker was open. */\n skipped: 0,\n fallbackByReason: { status: 0, rpcerror: 0, timeout: 0, transport: 0, validate: 0, parse: 0 } as Record\n}\n\n/**\n * `rpcerror` is a 502 tagged `X-Ssr-Cache: RPCERROR`: the proxy reached a node\n * and relayed the node's own error (a tag or post that does not exist, a bad\n * argument). The read still falls back so the caller sees the node's answer\n * unchanged, but the proxy was healthy, so it does not count toward the\n * breaker; the other reasons do.\n */\ntype ProxyMissReason = 'status' | 'rpcerror' | 'timeout' | 'transport' | 'validate' | 'parse'\n\nclass ProxyMiss extends Error {\n constructor(\n public reason: ProxyMissReason,\n message: string\n ) {\n super(message)\n }\n}\n\nconst errorMessage = (e: unknown): string =>\n e instanceof Error ? e.message : typeof e === 'string' ? e : String(e)\n\n// Breaker: consecutive misses open it for the configured cooldown, a served\n// call closes it. Module state, like the health tracker: one per process.\nlet proxyConsecutiveMisses = 0\nlet proxyOpenUntil = 0\n\n/** Test seam: forget breaker state. */\nexport function resetRpcProxyBreaker(): void {\n proxyConsecutiveMisses = 0\n proxyOpenUntil = 0\n}\n\n/**\n * One proxy call for an eligible read. Resolves with the upstream `result` the\n * proxy served, or throws ProxyMiss; the caller then continues with the node\n * loop exactly as if the proxy did not exist. Never throws anything else,\n * except the caller's own abort.\n */\nasync function proxyRpcCall(\n proxy: ServerRpcProxyState,\n method: string,\n params: unknown,\n callerTimeoutMs: number,\n externalSignal: AbortSignal | undefined,\n validate?: (result: unknown) => boolean\n): Promise {\n const dot = method.indexOf('.')\n if (dot <= 0 || dot === method.length - 1) {\n // Unreachable through setServerRpcProxy (it keeps only dotted names), kept\n // so a future allowlist change fails as a miss rather than a malformed call.\n throw new ProxyMiss('transport', `method without an api prefix: ${method}`)\n }\n // Never wait longer for the proxy than the caller would for one node.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n Math.min(proxy.timeoutMs, callerTimeoutMs)\n )\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n try {\n let res: Response\n try {\n res = await fetch(proxy.url, {\n method: 'POST',\n body: JSON.stringify({ api: method.slice(0, dot), method: method.slice(dot + 1), params }),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders(), ...proxy.headers },\n signal\n })\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'transport', errorMessage(e))\n }\n if (res.status !== 200) {\n // Release the connection: an unconsumed body pins a pooled socket.\n try {\n await res.body?.cancel()\n } catch {\n // nothing to release\n }\n const relayed = res.status === 502 && (res.headers.get('x-ssr-cache') ?? '').toUpperCase() === 'RPCERROR'\n throw new ProxyMiss(relayed ? 'rpcerror' : 'status', relayed ? 'proxy relayed a node error' : `proxy answered ${res.status}`)\n }\n let result: unknown\n try {\n result = await res.json()\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'parse', errorMessage(e))\n }\n if (validate && !validate(result)) {\n throw new ProxyMiss('validate', 'proxy result rejected by validator')\n }\n return result as T\n } finally {\n cleanupTimeout()\n cleanupMerge()\n }\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 // Server-side read-through proxy, when configured and the method is on its\n // allowlist: one call, and on any miss the node loop below runs unchanged.\n // It runs BEFORE the node deadline is taken, so a slow proxy costs its own\n // timeout and nothing of the failover budget the nodes get today.\n // Snapshot: the binding can be cleared by the host while this call awaits.\n const proxy = serverRpcProxy\n if (proxy && isNodeRuntime && proxy.methodSet.has(method)) {\n if (Date.now() < proxyOpenUntil) {\n rpcProxyStats.skipped++\n } else {\n try {\n const served = await proxyRpcCall(proxy, method, params, ceiling, signal, validate)\n rpcProxyStats.served++\n proxyConsecutiveMisses = 0\n return served\n } catch (e: unknown) {\n if (signal?.aborted) throw e\n rpcProxyStats.fallback++\n const reason: string = e instanceof ProxyMiss ? e.reason : 'transport'\n rpcProxyStats.fallbackByReason[reason] = (rpcProxyStats.fallbackByReason[reason] ?? 0) + 1\n if (reason === 'rpcerror') {\n // A relayed node error is a healthy proxy answer: it closes the\n // count like a served call. Crawler-made feed URLs produce these in\n // runs, and counting them opened the breaker on a working proxy.\n proxyConsecutiveMisses = 0\n } else if (++proxyConsecutiveMisses >= proxy.failureThreshold) {\n proxyOpenUntil = Date.now() + proxy.cooldownMs\n proxyConsecutiveMisses = 0\n }\n }\n }\n }\n\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n\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 setServerRpcProxy as setHiveTxServerRpcProxy,\n rpcProxyStats,\n type ResilienceOptions,\n type ServerRpcProxyOptions,\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 * Route allowlisted server-side RPC reads through a read-through cache in\n * front of the node pool (one cache per host, shared by every renderer\n * process). An optimization, never a dependency: any proxy failure falls\n * straight through to the node loop. No effect outside Node; null switches\n * it off. Delegates to the unified hive-tx `setServerRpcProxy`.\n * @param opts - `{ url, headers, timeoutMs, methods }` or null\n */\n export function setServerRpcProxy(opts: ServerRpcProxyOptions | null) {\n setHiveTxServerRpcProxy(opts);\n }\n\n /**\n * The live counters of that proxy path: `served` (answered by the proxy),\n * `fallback` with a per-reason breakdown (the read went to the node pool\n * after a proxy failure) and `skipped` (breaker open). The same object the\n * call path increments, exposed here because the root build carries its own\n * copy of the hive-tx internals; a consumer importing `rpcProxyStats` from\n * the `/hive` entry would read a different, never-incremented instance.\n * Read-only by contract: the web tier prints it, nothing resets it.\n */\n export function getServerRpcProxyStats(): Readonly {\n return rpcProxyStats;\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 /**\n * Optional: set when this operation edits existing content rather than creating it.\n *\n * A `comment` operation is byte-identical for a create and an update, so only the\n * caller knows which it is. When set, no content activity is recorded. Activity\n * rewards content creation. Without this, an edit of content published elsewhere\n * is credited as content created here. Never broadcast.\n */\n isUpdate?: boolean;\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\n * available, unless the payload sets `isUpdate`\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 */\n/**\n * Resolve which content activity a broadcast earns, or `null` for none.\n *\n * Content activity rewards publishing, so an update earns nothing: the `comment`\n * operation an edit broadcasts is indistinguishable from a create on chain, which\n * leaves the caller as the only party that can tell them apart. Without this, editing\n * a post first published on another frontend is credited here as a post.\n */\nexport function resolveContentActivityType(\n payload: Pick\n): 100 | 110 | null {\n if (payload.isUpdate) {\n return null;\n }\n\n return payload.parentAuthor ? 110 : 100;\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 = resolveContentActivityType(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 (activityType !== null && 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 // No activity is recorded here. Activity rewards creating content. Every\n // broadcast from this mutation edits content that already exists.\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 vote_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 vote_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 { 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 {\n RC_RESOURCE_NAMES,\n type RcCostBreakdown,\n type RcResourceName,\n type RcResourceParams\n} from \"../types/resource-params\";\nimport type { RcStats } from \"../types/stats\";\nimport { computeResourceCost } from \"./estimate-comment-rc-cost\";\n\nexport type RcResourceUsage = Record;\n\nexport interface RcPricedUsage {\n cost: number;\n breakdown: RcCostBreakdown[];\n}\n\n/**\n * Turns per-resource usage into an RC cost.\n *\n * This is the single pricing path. Every RC figure the app shows, the publish\n * warning, the comment warning, the vote warning and the credits tooltip, goes\n * through here, so they cannot disagree with each other or with the chain.\n */\nexport function priceRcUsage(\n usage: RcResourceUsage,\n rcParams: RcResourceParams,\n rcStats: Pick\n): RcPricedUsage {\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 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 leaves the safe-integer range.\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 { cost, breakdown };\n}\n","import { utf8ByteLength, varintByteLength } from \"@/modules/core/utf8\";\nimport type { RcResourceName, RcSizeInfo } from \"../types/resource-params\";\nimport type { RcResourceUsage } from \"./price-rc-usage\";\n\n/**\n * Ports of the per-operation arms of `count_resources`\n * (hive/libraries/chain/rc/resource_count.cpp).\n *\n * Every operation charges three things: the serialized transaction size as\n * history_bytes, a per-operation state footprint, and execution time. Only the\n * middle two differ per operation, which is why they live together here.\n */\n\n/** Fixed header: ref_block_num(2) + ref_block_prefix(4) + expiration(4) + extensions varint(1). */\nexport const TRANSACTION_HEADER_BYTES = 11;\nexport const SIGNATURE_BYTES = 65;\n\nexport const stringFieldBytes = (value: string): number => {\n const length = utf8ByteLength(value);\n return varintByteLength(length) + length;\n};\n\nconst emptyUsage = (): RcResourceUsage => ({\n resource_history_bytes: 0,\n resource_new_accounts: 0,\n resource_market_bytes: 0,\n resource_state_bytes: 0,\n resource_execution_time: 0\n});\n\nexport interface VoteLike {\n voter: string;\n author: string;\n permlink: string;\n}\n\n/** Serialized size of a transaction carrying a single vote. */\nexport function estimateVoteTransactionBytes(op: VoteLike, signatures = 1): number {\n const operationBytes =\n 1 + // operation variant id\n stringFieldBytes(op.voter) +\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n 2; // weight, int16\n\n return (\n TRANSACTION_HEADER_BYTES +\n varintByteLength(1) +\n operationBytes +\n varintByteLength(signatures) +\n SIGNATURE_BYTES * signatures\n );\n}\n\n/**\n * A vote's footprint is fixed: `vote_size` state bytes and `vote_time`\n * execution time, regardless of the post being voted on.\n */\nexport function countVoteResourceUsage(\n { transactionBytes, signatures = 1 }: { transactionBytes: number; signatures?: number },\n sizeInfo: RcSizeInfo\n): RcResourceUsage {\n const state = sizeInfo.resource_state_bytes;\n const exec = sizeInfo.resource_execution_time;\n\n return {\n ...emptyUsage(),\n resource_history_bytes: transactionBytes,\n resource_state_bytes: state.vote_size + state.transaction_base_size,\n resource_execution_time:\n exec.vote_time + exec.transaction_time + exec.verify_authority_time * signatures\n };\n}\n\n/** Resource names, re-exported so callers do not reach into the types module. */\nexport type { RcResourceName };\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\nimport type { RcResourceParams } from \"../types/resource-params\";\nimport { priceRcUsage } from \"./price-rc-usage\";\nimport {\n countVoteResourceUsage,\n estimateVoteTransactionBytes,\n type VoteLike\n} from \"./count-operation-usage\";\nimport {\n countCommentResourceUsage,\n estimateCommentTransactionBytes,\n type CommentLike,\n type CommentOptionsLike\n} from \"./estimate-comment-rc-cost\";\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\n/** The operation about to be broadcast, when the caller has it. */\nexport type RcPrecheckPayload =\n | { kind: \"comment\"; op: CommentLike; options?: CommentOptionsLike }\n | { kind: \"vote\"; op: VoteLike };\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 * From `getRcResourceParamsQueryOptions()`. Required for an exact estimate;\n * without it the result is not ready rather than silently approximate.\n */\n rcParams?: RcResourceParams | null;\n /**\n * The actual operation about to be broadcast. Supplying it is what makes the\n * estimate exact, because cost is dominated by the serialized transaction\n * size. Without it a minimal operation of that type is priced instead, which\n * is a lower bound: it can miss a marginal case but never invents one.\n */\n payload?: RcPrecheckPayload;\n /**\n * What to price when no payload is supplied.\n *\n * - `\"minimal\"` (default) prices the smallest operation of that type. It is\n * a lower bound, so a pre-submit warning is never invented for an\n * operation that would have succeeded.\n * - `\"average\"` prices the network average the chain publishes. Right for\n * \"how many of these can I afford\" displays, where there is no specific\n * operation in hand and the smallest conceivable one would flatter the\n * count.\n */\n fallback?: \"minimal\" | \"average\";\n /**\n * Safety multiplier applied to the 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 /**\n * RC cost of the operation itself.\n *\n * Named `avgCost` for backwards compatibility; it is no longer an average.\n * @deprecated prefer `cost`.\n */\n avgCost: number;\n /** RC cost of the operation, computed the way the chain computes it. */\n cost: number;\n /** Serialized transaction size, the dominant term for a comment. */\n transactionBytes: 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 cost: 0,\n transactionBytes: 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 * Costs are computed the way the chain computes them, from the actual\n * operation, not from the network-wide average. The average is dominated by\n * short replies and badly misleads on posts: it once told an account holding\n * 21.3B RC that it could afford 17 posts, and the next post it tried needed\n * 23.3B.\n *\n * Still a hint, never a hard gate: the buffer covers pool drift between the\n * estimate and the broadcast, and the publish/comment/vote action must stay\n * non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n rcParams,\n operation,\n payload,\n fallback = \"minimal\",\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\n const priced = priceOperation(operation, payload, fallback, rcParams, rcStats);\n if (!priced) {\n // Nothing to price against: reporting \"ready\" here would be a silent\n // all-clear, which is the one answer a pre-check must never invent.\n return { ...EMPTY, currentMana, maxMana };\n }\n\n const { cost, transactionBytes } = priced;\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = cost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost: cost,\n cost,\n transactionBytes,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / cost),\n };\n}\n\n/**\n * Prices whichever operation the caller is about to broadcast.\n *\n * Comments and votes are the two operations whose cost swings with what the\n * user wrote, so they are priced from the payload, and pricing them needs the\n * curve parameters. Every other operation the type advertises (transfer,\n * custom_json, ...) is fixed-shape and takes the network average the chain\n * publishes, which needs nothing else.\n *\n * When no payload is supplied a minimal operation is priced. That is\n * deliberately a lower bound: it can miss a marginal case, but it never warns\n * about one that would have succeeded.\n *\n * Returns null when the answer would have to be invented, so the caller\n * reports \"not ready\" rather than a zero-cost all-clear.\n */\nfunction priceOperation(\n operation: RcPrecheckOperation,\n payload: RcPrecheckPayload | undefined,\n fallback: \"minimal\" | \"average\",\n rcParams: RcResourceParams | null | undefined,\n rcStats: RcStats\n): { cost: number; transactionBytes: number } | null {\n const average = averageCost(rcStats, operation);\n const pricedFromPayload =\n operation === \"comment_operation\" || operation === \"vote_operation\";\n\n // The average is a number the node already returned. It needs no curve\n // parameters, so a caller pricing a transfer must not be blocked waiting on\n // them, which is how every operation outside these two is priced.\n if (!pricedFromPayload || (!payload && fallback === \"average\")) {\n return average;\n }\n\n // Asked to price a real comment or vote without the inputs to do it. The\n // honest answer is \"not ready\": falling back to the average here is exactly\n // what told an account holding 21.3B RC it could afford 17 more posts.\n if (!rcParams?.resource_params || !rcParams.size_info || !rcStats.pool || !rcStats.share) {\n return null;\n }\n\n const stats = { pool: rcStats.pool, regen: rcStats.regen, share: rcStats.share };\n\n if (operation === \"vote_operation\") {\n const op: VoteLike = payload?.kind === \"vote\" ? payload.op : MINIMAL_VOTE;\n const transactionBytes = estimateVoteTransactionBytes(op);\n const usage = countVoteResourceUsage({ transactionBytes }, rcParams.size_info);\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n }\n\n const op: CommentLike = payload?.kind === \"comment\" ? payload.op : MINIMAL_COMMENT;\n const options = payload?.kind === \"comment\" ? payload.options : undefined;\n const transactionBytes = estimateCommentTransactionBytes({ op, options });\n const usage = countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength: op.permlink.length,\n beneficiaries: options?.beneficiaries?.length ?? 0,\n hasCommentOptions: !!options\n },\n rcParams.size_info\n );\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n}\n\n/** The network average the chain publishes for an operation, when it has one. */\nfunction averageCost(\n rcStats: RcStats,\n operation: RcPrecheckOperation\n): { cost: number; transactionBytes: number } | null {\n const cost = rcStats.ops[operation]?.avg_cost;\n return typeof cost === \"number\" && cost > 0 ? { cost, transactionBytes: 0 } : null;\n}\n\n/** Smallest realistic operations, used only when the caller has no payload yet. */\nconst MINIMAL_COMMENT: CommentLike = {\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\",\n parent_author: \"\",\n parent_permlink: \"hive-100000\",\n title: \"\",\n body: \"\",\n json_metadata: \"{}\"\n};\n\nconst MINIMAL_VOTE: VoteLike = {\n voter: \"aaaaaaaaaa\",\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\"\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\n/**\n * POST a single game claim and return the parsed JSON body.\n *\n * A failed post-game comes back from the edge as an HTML gateway page (a 502 was\n * the trail on ECENCY-NEXT-1FCJ), and `response.json()` on that throws a bare\n * `SyntaxError` naming neither the endpoint nor the cause. Check the status and\n * the content type first, then fail with a STABLE, low-cardinality message\n * (content type + status, never the raw body) so these group as a single Sentry\n * issue instead of fragmenting on every distinct error page.\n *\n * Exported for unit testing; the hook below wraps it.\n */\nexport async function gameClaimRequest(\n code: string,\n gameType: \"spin\",\n key: string\n): Promise {\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 // 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 // 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 page.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Games] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Games] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body) as GameClaim;\n } catch {\n throw new Error(\n `[SDK][Games] – malformed JSON response (status ${response.status})`\n );\n }\n}\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 return gameClaimRequest(code, gameType, key);\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","/**\n * Thresholds behind the content moderation treatment. Single source of truth for\n * every client: web and mobile previously carried their own copies, which drifted\n * (mobile flagged downvoted content at -7B rshares and 4 voters where web used\n * -10B and 5), so the same post read differently depending on the app.\n */\n\n/** Sum of rshares below which a post counts as heavily downvoted. */\nexport const HIDDEN_POST_RSHARES_THRESHOLD = -10000000000;\n\n/** Downvoting is only conclusive once enough accounts have voted. */\nexport const HIDDEN_POST_MIN_VOTES = 5;\n\n/**\n * Reputation (human-readable 0-100 scale) below which an author counts as\n * low-trust. New Hive accounts start around 25.\n *\n * NOTE: reputation is the only input. Account age is NOT part of the check, so a\n * years-old account that never earned reputation trips it exactly like a fresh\n * one. User-facing copy must say \"low reputation\", never \"new account\".\n */\nexport const LOW_TRUST_REPUTATION_THRESHOLD = 30;\n","/**\n * Converts Hive's raw reputation to the human-readable 0-100 scale, passing\n * through values that are already on it (the bridge returns both shapes\n * depending on the endpoint).\n */\nconst isHumanReadable = (input: number): boolean =>\n Math.abs(input) > 0 && Math.abs(input) <= 100;\n\nexport function accountReputation(input: string | number): number {\n if (typeof input === \"number\" && isHumanReadable(input)) {\n return Math.floor(input);\n }\n\n if (typeof input === \"string\") {\n input = Number(input);\n\n if (isHumanReadable(input)) {\n return Math.floor(input);\n }\n }\n\n if (input === 0) {\n return 25;\n }\n\n let neg = false;\n\n if (input < 0) {\n neg = true;\n }\n\n let reputationLevel = Math.log10(Math.abs(input as number));\n reputationLevel = Math.max(reputationLevel - 9, 0);\n\n if (reputationLevel < 0) {\n reputationLevel = 0;\n }\n\n if (neg) {\n reputationLevel *= -1;\n }\n\n reputationLevel = reputationLevel * 9 + 25;\n\n return Math.floor(reputationLevel);\n}\n","/**\n * Outbound-link detection for the SEO/backlink-farm signal.\n *\n * A link only counts as outbound promotion when it leaves the Hive/Ecency\n * ecosystem and is not an embedded image, so ordinary on-platform references and\n * post illustrations never trip the check.\n */\n\n// Hosts that are part of the Hive/Ecency ecosystem.\nconst INTERNAL_HOSTS = [\n \"ecency.com\",\n \"ecency.app\",\n \"hive.blog\",\n \"hive.io\",\n \"hiveblocks.com\",\n \"peakd.com\",\n \"snapie.io\",\n \"hivesuite.app\",\n \"leofinance.io\",\n \"inleo.io\",\n \"3speak.tv\",\n \"d.buzz\",\n \"waivio.com\"\n];\n\n// Image/media hosts: an embedded image is content, not a backlink.\nconst IMAGE_HOSTS = [\n \"imgur.com\",\n \"images.hive.blog\",\n \"files.peakd.com\",\n \"i.ecency.com\",\n \"images.ecency.com\",\n \"steemitimages.com\",\n \"cdn.steemitimages.com\",\n \"media.giphy.com\"\n];\n\nconst IMAGE_EXT_RE = /\\.(jpe?g|png|gif|webp|svg|bmp|avif)(\\?|#|$)/i;\n// Match absolute AND protocol-relative URLs (\"//host/...\"), so the check can't be\n// evaded with `[promo](//shop.example)` (the renderer allows protocol-relative hrefs).\nconst URL_RE = /(?:https?:)?\\/\\/[^\\s)<>\"'\\]]+/gi;\n// URLs in prose are commonly followed by punctuation (\"https://ecency.com, and...\");\n// strip it so the host parses correctly and internal links do not false-positive.\nconst TRAILING_PUNCT_RE = /[.,;:!?'\"]+$/;\n\nfunction hostOf(url: string): string {\n const m = /^(?:https?:)?\\/\\/([^/?#]+)/i.exec(url);\n return m ? m[1].toLowerCase().replace(/^www\\./, \"\") : \"\";\n}\n\nfunction isExternalPromoLink(rawUrl: string): boolean {\n const url = rawUrl.replace(TRAILING_PUNCT_RE, \"\");\n if (IMAGE_EXT_RE.test(url)) {\n return false; // embedded image, not a backlink\n }\n const host = hostOf(url);\n if (!host.includes(\".\")) {\n return false; // not a real domain (e.g. a stray \"//something\")\n }\n const matches = (h: string) => host === h || host.endsWith(\".\" + h);\n if (INTERNAL_HOSTS.some(matches) || IMAGE_HOSTS.some(matches)) {\n return false; // Hive/Ecency or image host\n }\n return true;\n}\n\n/** True if the post body contains an outbound (non-Hive, non-image) link. */\nexport function hasExternalLink(body: string | undefined | null): boolean {\n if (!body) {\n return false;\n }\n const matches = body.match(URL_RE);\n if (!matches) {\n return false;\n }\n return matches.some(isExternalPromoLink);\n}\n","import { accountReputation } from \"./account-reputation\";\nimport {\n HIDDEN_POST_MIN_VOTES,\n HIDDEN_POST_RSHARES_THRESHOLD,\n LOW_TRUST_REPUTATION_THRESHOLD\n} from \"./constants\";\nimport { hasExternalLink } from \"./external-links\";\n\n/**\n * Why a piece of content gets the moderation treatment. Clients render their own\n * copy per reason; the rules that pick the reason live here so web and mobile\n * always agree on which one fired.\n */\nexport enum ContentModerationReason {\n /**\n * `stats.gray` / `stats.hide` from hivemind: community moderator mutes, mutes\n * applied by the observer account, and authors hivemind itself grays out.\n */\n MOD_MUTED = \"mod_muted\",\n /** Heavily downvoted by enough distinct accounts to be conclusive. */\n DOWNVOTED = \"downvoted\",\n /** Low-reputation author whose post carries an outbound promotional link. */\n LOW_TRUST = \"low_trust\"\n}\n\n/**\n * The fields of a post or comment the rules read. Deliberately structural: web\n * passes an `Entry`, mobile passes a raw bridge post, and neither has to convert.\n */\nexport interface ModerationCandidate {\n author?: string;\n author_reputation?: string | number;\n body?: string | null;\n net_rshares?: number;\n active_votes?: unknown[] | null;\n stats?: {\n gray?: boolean;\n hide?: boolean;\n total_votes?: number;\n } | null;\n}\n\n/**\n * hivemind's `total_votes` is the authoritative count when present; `active_votes`\n * is the fallback for the feeds that omit stats.\n */\nfunction countVotes(content: ModerationCandidate): number {\n return content?.stats?.total_votes ?? content?.active_votes?.length ?? 0;\n}\n\n/** Heavily downvoted: strongly negative rshares from more than a handful of voters. */\nexport function isHiddenPost(\n netRshares: number | undefined,\n activeVotesLength: number\n): boolean {\n return (\n (netRshares ?? 0) < HIDDEN_POST_RSHARES_THRESHOLD &&\n activeVotesLength >= HIDDEN_POST_MIN_VOTES\n );\n}\n\n/**\n * Content-moderation signal for SEO/backlink-farm abuse: low-reputation accounts\n * publishing an outbound link are the signature of free-faucet SEO spam.\n *\n * Such posts are not blocked, they are de-emphasized and their outbound link is\n * flagged as unverified, so the promotional payoff drops to zero. Low reputation\n * on its own is NOT a moderation signal: plenty of small accounts post ordinary\n * content, and dimming all of them punishes newcomers for existing.\n */\nexport function isLowTrustSeoPost(\n content: Pick\n): boolean {\n const reputation = content?.author_reputation;\n // Some feeds omit reputation entirely. An unknown value is not evidence of\n // anything, so it must not be read as \"brand new account\" (raw 0 scales to 25,\n // which is below the threshold and would flag every post carrying a link).\n if (reputation === undefined || reputation === null) {\n return false;\n }\n return (\n accountReputation(reputation) < LOW_TRUST_REPUTATION_THRESHOLD &&\n hasExternalLink(content?.body)\n );\n}\n\n/** True when the viewer has personally muted this author. */\nexport function isAuthorMuted(\n author: string | undefined,\n mutedAuthors: string[] | undefined | null\n): boolean {\n return !!author && !!mutedAuthors?.includes(author);\n}\n\n/**\n * The reason a post or comment should be de-emphasized, or null when it is fine.\n *\n * Precedence, most authoritative first: an explicit moderation action outranks\n * the vote heuristic, which outranks the spam heuristic. Order matters because a\n * heavily downvoted post usually also has a battered reputation, and labelling\n * that \"low trust\" would hide why the content was actually flagged.\n *\n * A viewer's personal mute list is NOT an input here. Muting an author removes\n * their content from the viewer's lists entirely (see `isAuthorMuted`), rather\n * than labelling it.\n */\nexport function getContentModerationReason(\n content: ModerationCandidate | undefined | null\n): ContentModerationReason | null {\n if (!content) {\n return null;\n }\n if (content.stats?.gray || content.stats?.hide) {\n return ContentModerationReason.MOD_MUTED;\n }\n if (isHiddenPost(content.net_rshares, countVotes(content))) {\n return ContentModerationReason.DOWNVOTED;\n }\n if (isLowTrustSeoPost(content)) {\n return ContentModerationReason.LOW_TRUST;\n }\n return null;\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-comment-rc-cost.ts","../../src/modules/resource-credits/utils/price-rc-usage.ts","../../src/modules/resource-credits/utils/count-operation-usage.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","../../src/modules/moderation/constants.ts","../../src/modules/moderation/account-reputation.ts","../../src/modules/moderation/external-links.ts","../../src/modules/moderation/content-moderation.ts","../../src/modules/newsletter/api.ts","../../src/modules/newsletter/queries/get-digest-subscriptions-query-options.ts","../../src/modules/newsletter/queries/get-newsletter-sender-query-options.ts","../../src/modules/newsletter/queries/get-newsletter-issues-query-options.ts","../../src/modules/newsletter/queries/get-newsletter-posts-query-options.ts","../../src/modules/newsletter/mutations/use-subscribe-digest.ts","../../src/modules/newsletter/mutations/use-leave-digest.ts","../../src/modules/newsletter/mutations/use-unsubscribe-all-digests.ts","../../src/modules/newsletter/mutations/use-send-newsletter-issue.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","DEFAULT_SERVER_RPC_PROXY_METHODS","serverRpcProxy","setServerRpcProxy","opts","url","headers","k","v","timeoutMs","methods","m","pos","fallback","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","r","bool","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","rpcProxyStats","ProxyMiss","reason","errorMessage","proxyConsecutiveMisses","proxyOpenUntil","proxyRpcCall","proxy","method","params","callerTimeoutMs","externalSignal","validate","dot","tSignal","cleanupTimeout","createTimeoutSignal","signal","cleanupMerge","mergeSignals","res","e","relayed","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","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","tryRecordHeadBlock","block","createTimeoutReason","err","controller","timer","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","timeout","shouldRetry","body","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","served","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","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","timeoutSignal","ac","onAbort","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","getServerRpcProxyStats","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","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","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","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","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","resolveContentActivityType","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","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","EMPTY","estimateCommentRcCost","rcParams","rcStats","usage","regen","cost","breakdown","share","scaled","resourceCost","priceRcUsage","emptyUsage","estimateVoteTransactionBytes","operationBytes","countVoteResourceUsage","estimateRcPrecheck","priced","priceOperation","safeBuffer","estimatedCost","willLikelyFail","average","averageCost","MINIMAL_VOTE","MINIMAL_COMMENT","getGameStatusCheckQueryOptions","gameClaimRequest","contentType","detail","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","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","HIDDEN_POST_RSHARES_THRESHOLD","HIDDEN_POST_MIN_VOTES","LOW_TRUST_REPUTATION_THRESHOLD","isHumanReadable","accountReputation","neg","reputationLevel","INTERNAL_HOSTS","IMAGE_HOSTS","IMAGE_EXT_RE","URL_RE","TRAILING_PUNCT_RE","hostOf","isExternalPromoLink","rawUrl","hasExternalLink","ContentModerationReason","countVotes","isHiddenPost","netRshares","activeVotesLength","isLowTrustSeoPost","reputation","isAuthorMuted","mutedAuthors","getContentModerationReason","NewsletterApiError","NewsletterSendRefusedError","taken","newsletterUrl","parse","subscribeDigestRequest","getDigestSubscriptionsRequest","leaveDigestRequest","unsubscribeAllDigestsRequest","getNewsletterSenderRequest","getNewsletterIssuesRequest","getNewsletterPostsRequest","postSend","request","previewNewsletterSendRequest","sendNewsletterIssueRequest","getDigestSubscriptionsQueryOptions","getNewsletterSenderQueryOptions","getNewsletterIssuesQueryOptions","getNewsletterPostsQueryOptions","useSubscribeDigest","useLeaveDigest","useUnsubscribeAllDigests","usePreviewNewsletterIssue","useSendNewsletterIssue"],"mappings":"yqBASA,IAAMA,GAAe,IAAI,WAAA,CAAY,CAAC,CAAA,CAIlCC,EAAAA,CAAqD,IAAA,CACrDC,EAAAA,CAAuD,IAAA,CAE3D,SAASC,IAAgD,CACvD,OAAKF,KACC,OAAO,WAAA,CAAgB,IACzBA,EAAAA,CAAW,IAAI,WAAA,CAEfA,EAAAA,CAAW,CACT,MAAA,CAAOG,EAAuB,CAE5B,IAAMC,EAAiB,EAAC,CACxB,QAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAE,MAAA,CAAQE,CAAAA,EAAAA,CAAK,CACjC,IAAIC,CAAAA,CAAIH,EAAE,UAAA,CAAWE,CAAC,EACtB,GAAIC,CAAAA,CAAI,GAAA,CACNF,CAAAA,CAAK,IAAA,CAAKE,CAAC,UACFA,CAAAA,CAAI,IAAA,CACbF,EAAK,IAAA,CAAK,GAAA,CAAQE,GAAK,CAAA,CAAI,GAAA,CAAQA,CAAAA,CAAI,EAAK,CAAA,CAAA,KAAA,GACnCA,CAAAA,EAAK,OAAUA,CAAAA,EAAK,KAAA,EAAUD,EAAI,CAAA,CAAIF,CAAAA,CAAE,OAAQ,CACzD,IAAMI,CAAAA,CAAOJ,CAAAA,CAAE,UAAA,CAAW,EAAEE,CAAC,CAAA,CAC7BC,CAAAA,CAAI,KAAA,EAAA,CAAYA,CAAAA,CAAI,IAAA,GAAU,EAAA,CAAA,EAAOC,EAAO,IAAA,CAAA,CAC5CH,CAAAA,CAAK,IAAA,CAAK,GAAA,CAAQE,CAAAA,EAAK,EAAA,CAAK,IAASA,CAAAA,EAAK,EAAA,CAAM,GAAO,GAAA,CAASA,CAAAA,EAAK,EAAK,EAAA,CA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AEtC,OAAOiJ,WAAAA,CAAY,CACjB,WAAA,CAAa,CAAC,YAAA,CAAc,MAAA,CAAQ0I,CAAI,CAAA,CACxC,UAAA,CAAY,MAAO6rC,CAAAA,EAAmC,CACpD,GAAI,CAAC7rC,CAAAA,EAAQ,CAACtb,EACZ,MAAM,IAAI,KAAA,CAAM,uCAAkC,CAAA,CAEpD,OAAOqnD,GAA2BF,CAAAA,CAASnnD,CAAI,CACjD,CAAA,CACA,SAAA,CAAU+4B,CAAAA,CAASouB,EAAS,CAC1B13B,CAAAA,CAAY,iBAAA,CAAkB,CAC5B,QAAA,CAAUrX,CAAAA,CAAU,WAAW,MAAA,CAAO+uC,CAAAA,CAAQ,IAAA,CAAMA,CAAAA,CAAQ,MAAA,CAAQ7rC,CAAI,CAC1E,CAAC,CAAA,CACDmU,CAAAA,CAAY,iBAAA,CAAkB,CAC5B,QAAA,CAAUrX,EAAU,UAAA,CAAW,MAAA,CAAO+uC,CAAAA,CAAQ,IAAA,CAAMA,CAAAA,CAAQ,MAAA,CAAQ7rC,CAAI,CAC1E,CAAC,EACH,CACF,CAAC,CACH","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 * Server-side read-through proxy for RPC reads (see `setServerRpcProxy`).\n * `methods` is the allowlist the proxy serves; a read outside it goes straight\n * to the node pool as before.\n */\nexport interface ServerRpcProxyOptions {\n /** Absolute URL of the proxy endpoint (POST `{api, method, params}`). */\n url: string\n /** Headers sent with every proxy call (the shared internal secret). */\n headers: Record\n /** Per-call timeout in ms; on expiry the read falls back to the node pool. */\n timeoutMs: number\n /** Fully qualified method names (`bridge.get_post`) the proxy may answer;\n * omitted = DEFAULT_SERVER_RPC_PROXY_METHODS. An empty list is ignored. */\n methods?: string[]\n /**\n * After this many consecutive proxy misses the proxy is skipped for\n * `cooldownMs`, so a proxy that is down costs one failed call per cooldown\n * window rather than one per read. Default 3 / 10s. A served call resets it.\n */\n failureThreshold?: number\n cooldownMs?: number\n}\n\n/** Default allowlist: the reads a server render makes and the proxy caches. */\nexport const DEFAULT_SERVER_RPC_PROXY_METHODS: readonly string[] = [\n 'bridge.get_ranked_posts',\n 'bridge.get_account_posts',\n 'bridge.get_post',\n 'bridge.get_discussion',\n 'bridge.get_profile',\n 'bridge.get_profiles',\n 'bridge.get_community',\n 'bridge.list_communities',\n 'condenser_api.get_accounts',\n 'condenser_api.get_content',\n 'condenser_api.get_dynamic_global_properties',\n 'condenser_api.get_trending_tags'\n]\n\n/**\n * Active proxy configuration, or null (the default: every read goes to the node\n * pool). Lives outside `config` so the browser bundle never carries it; it is\n * only ever consulted under Node.\n */\nexport interface ServerRpcProxyState extends Required {\n methodSet: Set\n}\n\nexport let serverRpcProxy: ServerRpcProxyState | null = null\n\n/**\n * Route allowlisted server-side reads through a read-through cache in front\n * of the node pool. One cache per host answers the reads every renderer\n * process used to make on its own; a miss there is one upstream call shared by\n * every concurrent reader. The proxy is an optimization, never a dependency:\n * any failure (non-200, timeout, transport error, a response the caller's\n * validator rejects) falls straight through to the existing node loop, so the\n * worst case is the latency of a failed proxy call on top of what happens\n * today. Has no effect outside Node. Pass null to switch it off.\n */\nexport const setServerRpcProxy = (opts: ServerRpcProxyOptions | null): void => {\n if (opts === null) {\n serverRpcProxy = null\n return\n }\n if (!opts || typeof opts !== 'object') return\n const url = typeof opts.url === 'string' ? opts.url.trim() : ''\n if (!/^https?:\\/\\//i.test(url)) return\n const headers: Record = {}\n if (opts.headers && typeof opts.headers === 'object') {\n for (const [k, v] of Object.entries(opts.headers)) {\n if (typeof v === 'string' && v && !/[\\u0000-\\u001f\\u007f]/.test(v) && !/[\\u0000-\\u001f\\u007f]/.test(k)) {\n headers[k] = v\n }\n }\n }\n const timeoutMs =\n typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0\n ? opts.timeoutMs\n : 2_000\n const methods =\n opts.methods === undefined\n ? [...DEFAULT_SERVER_RPC_PROXY_METHODS]\n : Array.isArray(opts.methods)\n ? opts.methods.filter((m): m is string => typeof m === 'string' && m.includes('.'))\n : []\n // Nothing to route through the proxy: keep whatever was configured before.\n if (methods.length === 0) return\n const pos = (v: unknown, fallback: number): number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : fallback\n serverRpcProxy = {\n url,\n headers,\n timeoutMs,\n methods,\n failureThreshold: Math.floor(pos(opts.failureThreshold, 3)),\n cooldownMs: pos(opts.cooldownMs, 10_000),\n methodSet: new Set(methods)\n }\n}\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, serverRpcProxy, type ServerRpcProxyState } 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// ── Server-side read-through proxy ──────────────────────────────────────────\n\n/**\n * Counters for the proxy path, readable by a host's diagnostics (the web\n * tier's event-loop monitor prints them). `served` = answered by the proxy,\n * `fallback` = proxy configured and eligible but the read went to the node\n * pool, with the reason.\n */\nexport const rpcProxyStats = {\n served: 0,\n fallback: 0,\n /** Reads that went straight to the nodes because the breaker was open. */\n skipped: 0,\n fallbackByReason: { status: 0, rpcerror: 0, timeout: 0, transport: 0, validate: 0, parse: 0 } as Record\n}\n\n/**\n * `rpcerror` is a 502 tagged `X-Ssr-Cache: RPCERROR`: the proxy reached a node\n * and relayed the node's own error (a tag or post that does not exist, a bad\n * argument). The read still falls back so the caller sees the node's answer\n * unchanged, but the proxy was healthy, so it does not count toward the\n * breaker; the other reasons do.\n */\ntype ProxyMissReason = 'status' | 'rpcerror' | 'timeout' | 'transport' | 'validate' | 'parse'\n\nclass ProxyMiss extends Error {\n constructor(\n public reason: ProxyMissReason,\n message: string\n ) {\n super(message)\n }\n}\n\nconst errorMessage = (e: unknown): string =>\n e instanceof Error ? e.message : typeof e === 'string' ? e : String(e)\n\n// Breaker: consecutive misses open it for the configured cooldown, a served\n// call closes it. Module state, like the health tracker: one per process.\nlet proxyConsecutiveMisses = 0\nlet proxyOpenUntil = 0\n\n/** Test seam: forget breaker state. */\nexport function resetRpcProxyBreaker(): void {\n proxyConsecutiveMisses = 0\n proxyOpenUntil = 0\n}\n\n/**\n * One proxy call for an eligible read. Resolves with the upstream `result` the\n * proxy served, or throws ProxyMiss; the caller then continues with the node\n * loop exactly as if the proxy did not exist. Never throws anything else,\n * except the caller's own abort.\n */\nasync function proxyRpcCall(\n proxy: ServerRpcProxyState,\n method: string,\n params: unknown,\n callerTimeoutMs: number,\n externalSignal: AbortSignal | undefined,\n validate?: (result: unknown) => boolean\n): Promise {\n const dot = method.indexOf('.')\n if (dot <= 0 || dot === method.length - 1) {\n // Unreachable through setServerRpcProxy (it keeps only dotted names), kept\n // so a future allowlist change fails as a miss rather than a malformed call.\n throw new ProxyMiss('transport', `method without an api prefix: ${method}`)\n }\n // Never wait longer for the proxy than the caller would for one node.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n Math.min(proxy.timeoutMs, callerTimeoutMs)\n )\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n try {\n let res: Response\n try {\n res = await fetch(proxy.url, {\n method: 'POST',\n body: JSON.stringify({ api: method.slice(0, dot), method: method.slice(dot + 1), params }),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders(), ...proxy.headers },\n signal\n })\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'transport', errorMessage(e))\n }\n if (res.status !== 200) {\n // Release the connection: an unconsumed body pins a pooled socket.\n try {\n await res.body?.cancel()\n } catch {\n // nothing to release\n }\n const relayed = res.status === 502 && (res.headers.get('x-ssr-cache') ?? '').toUpperCase() === 'RPCERROR'\n throw new ProxyMiss(relayed ? 'rpcerror' : 'status', relayed ? 'proxy relayed a node error' : `proxy answered ${res.status}`)\n }\n let result: unknown\n try {\n result = await res.json()\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'parse', errorMessage(e))\n }\n if (validate && !validate(result)) {\n throw new ProxyMiss('validate', 'proxy result rejected by validator')\n }\n return result as T\n } finally {\n cleanupTimeout()\n cleanupMerge()\n }\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 // Server-side read-through proxy, when configured and the method is on its\n // allowlist: one call, and on any miss the node loop below runs unchanged.\n // It runs BEFORE the node deadline is taken, so a slow proxy costs its own\n // timeout and nothing of the failover budget the nodes get today.\n // Snapshot: the binding can be cleared by the host while this call awaits.\n const proxy = serverRpcProxy\n if (proxy && isNodeRuntime && proxy.methodSet.has(method)) {\n if (Date.now() < proxyOpenUntil) {\n rpcProxyStats.skipped++\n } else {\n try {\n const served = await proxyRpcCall(proxy, method, params, ceiling, signal, validate)\n rpcProxyStats.served++\n proxyConsecutiveMisses = 0\n return served\n } catch (e: unknown) {\n if (signal?.aborted) throw e\n rpcProxyStats.fallback++\n const reason: string = e instanceof ProxyMiss ? e.reason : 'transport'\n rpcProxyStats.fallbackByReason[reason] = (rpcProxyStats.fallbackByReason[reason] ?? 0) + 1\n if (reason === 'rpcerror') {\n // A relayed node error is a healthy proxy answer: it closes the\n // count like a served call. Crawler-made feed URLs produce these in\n // runs, and counting them opened the breaker on a working proxy.\n proxyConsecutiveMisses = 0\n } else if (++proxyConsecutiveMisses >= proxy.failureThreshold) {\n proxyOpenUntil = Date.now() + proxy.cooldownMs\n proxyConsecutiveMisses = 0\n }\n }\n }\n }\n\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n\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 setServerRpcProxy as setHiveTxServerRpcProxy,\n rpcProxyStats,\n type ResilienceOptions,\n type ServerRpcProxyOptions,\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 * Route allowlisted server-side RPC reads through a read-through cache in\n * front of the node pool (one cache per host, shared by every renderer\n * process). An optimization, never a dependency: any proxy failure falls\n * straight through to the node loop. No effect outside Node; null switches\n * it off. Delegates to the unified hive-tx `setServerRpcProxy`.\n * @param opts - `{ url, headers, timeoutMs, methods }` or null\n */\n export function setServerRpcProxy(opts: ServerRpcProxyOptions | null) {\n setHiveTxServerRpcProxy(opts);\n }\n\n /**\n * The live counters of that proxy path: `served` (answered by the proxy),\n * `fallback` with a per-reason breakdown (the read went to the node pool\n * after a proxy failure) and `skipped` (breaker open). The same object the\n * call path increments, exposed here because the root build carries its own\n * copy of the hive-tx internals; a consumer importing `rpcProxyStats` from\n * the `/hive` entry would read a different, never-incremented instance.\n * Read-only by contract: the web tier prints it, nothing resets it.\n */\n export function getServerRpcProxyStats(): Readonly {\n return rpcProxyStats;\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 // Newsletter (digest subscriptions + sender API)\n // ===========================================================================\n newsletter: {\n subscriptions: (username: string | undefined) => [\n \"newsletter\",\n \"subscriptions\",\n username,\n ],\n sender: (type: string, target: string, username: string | undefined) => [\n \"newsletter\",\n \"sender\",\n type,\n target,\n username,\n ],\n issues: (type: string, target: string, username: string | undefined) => [\n \"newsletter\",\n \"issues\",\n type,\n target,\n username,\n ],\n posts: (\n type: string,\n target: string,\n username: string | undefined,\n limit: number,\n ) => [\"newsletter\", \"posts\", type, target, username, limit],\n _prefix: [\"newsletter\"],\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 /**\n * The viewing user; exclude authors they currently mute. Ecency's own\n * moderation mutes are applied by esync regardless of this value, so leaving\n * it unset drops the viewer's personal mutes, not the platform ones.\n */\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 /**\n * The viewing user; exclude authors they currently mute. Ecency's own\n * moderation mutes are applied by esync regardless of this value.\n */\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 /**\n * Optional: set when this operation edits existing content rather than creating it.\n *\n * A `comment` operation is byte-identical for a create and an update, so only the\n * caller knows which it is. When set, no content activity is recorded. Activity\n * rewards content creation. Without this, an edit of content published elsewhere\n * is credited as content created here. Never broadcast.\n */\n isUpdate?: boolean;\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\n * available, unless the payload sets `isUpdate`\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 */\n/**\n * Resolve which content activity a broadcast earns, or `null` for none.\n *\n * Content activity rewards publishing, so an update earns nothing: the `comment`\n * operation an edit broadcasts is indistinguishable from a create on chain, which\n * leaves the caller as the only party that can tell them apart. Without this, editing\n * a post first published on another frontend is credited here as a post.\n */\nexport function resolveContentActivityType(\n payload: Pick\n): 100 | 110 | null {\n if (payload.isUpdate) {\n return null;\n }\n\n return payload.parentAuthor ? 110 : 100;\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 = resolveContentActivityType(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 (activityType !== null && 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 // No activity is recorded here. Activity rewards creating content. Every\n // broadcast from this mutation edits content that already exists.\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 vote_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 vote_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 { 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 {\n RC_RESOURCE_NAMES,\n type RcCostBreakdown,\n type RcResourceName,\n type RcResourceParams\n} from \"../types/resource-params\";\nimport type { RcStats } from \"../types/stats\";\nimport { computeResourceCost } from \"./estimate-comment-rc-cost\";\n\nexport type RcResourceUsage = Record;\n\nexport interface RcPricedUsage {\n cost: number;\n breakdown: RcCostBreakdown[];\n}\n\n/**\n * Turns per-resource usage into an RC cost.\n *\n * This is the single pricing path. Every RC figure the app shows, the publish\n * warning, the comment warning, the vote warning and the credits tooltip, goes\n * through here, so they cannot disagree with each other or with the chain.\n */\nexport function priceRcUsage(\n usage: RcResourceUsage,\n rcParams: RcResourceParams,\n rcStats: Pick\n): RcPricedUsage {\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 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 leaves the safe-integer range.\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 { cost, breakdown };\n}\n","import { utf8ByteLength, varintByteLength } from \"@/modules/core/utf8\";\nimport type { RcResourceName, RcSizeInfo } from \"../types/resource-params\";\nimport type { RcResourceUsage } from \"./price-rc-usage\";\n\n/**\n * Ports of the per-operation arms of `count_resources`\n * (hive/libraries/chain/rc/resource_count.cpp).\n *\n * Every operation charges three things: the serialized transaction size as\n * history_bytes, a per-operation state footprint, and execution time. Only the\n * middle two differ per operation, which is why they live together here.\n */\n\n/** Fixed header: ref_block_num(2) + ref_block_prefix(4) + expiration(4) + extensions varint(1). */\nexport const TRANSACTION_HEADER_BYTES = 11;\nexport const SIGNATURE_BYTES = 65;\n\nexport const stringFieldBytes = (value: string): number => {\n const length = utf8ByteLength(value);\n return varintByteLength(length) + length;\n};\n\nconst emptyUsage = (): RcResourceUsage => ({\n resource_history_bytes: 0,\n resource_new_accounts: 0,\n resource_market_bytes: 0,\n resource_state_bytes: 0,\n resource_execution_time: 0\n});\n\nexport interface VoteLike {\n voter: string;\n author: string;\n permlink: string;\n}\n\n/** Serialized size of a transaction carrying a single vote. */\nexport function estimateVoteTransactionBytes(op: VoteLike, signatures = 1): number {\n const operationBytes =\n 1 + // operation variant id\n stringFieldBytes(op.voter) +\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n 2; // weight, int16\n\n return (\n TRANSACTION_HEADER_BYTES +\n varintByteLength(1) +\n operationBytes +\n varintByteLength(signatures) +\n SIGNATURE_BYTES * signatures\n );\n}\n\n/**\n * A vote's footprint is fixed: `vote_size` state bytes and `vote_time`\n * execution time, regardless of the post being voted on.\n */\nexport function countVoteResourceUsage(\n { transactionBytes, signatures = 1 }: { transactionBytes: number; signatures?: number },\n sizeInfo: RcSizeInfo\n): RcResourceUsage {\n const state = sizeInfo.resource_state_bytes;\n const exec = sizeInfo.resource_execution_time;\n\n return {\n ...emptyUsage(),\n resource_history_bytes: transactionBytes,\n resource_state_bytes: state.vote_size + state.transaction_base_size,\n resource_execution_time:\n exec.vote_time + exec.transaction_time + exec.verify_authority_time * signatures\n };\n}\n\n/** Resource names, re-exported so callers do not reach into the types module. */\nexport type { RcResourceName };\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\nimport type { RcResourceParams } from \"../types/resource-params\";\nimport { priceRcUsage } from \"./price-rc-usage\";\nimport {\n countVoteResourceUsage,\n estimateVoteTransactionBytes,\n type VoteLike\n} from \"./count-operation-usage\";\nimport {\n countCommentResourceUsage,\n estimateCommentTransactionBytes,\n type CommentLike,\n type CommentOptionsLike\n} from \"./estimate-comment-rc-cost\";\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\n/** The operation about to be broadcast, when the caller has it. */\nexport type RcPrecheckPayload =\n | { kind: \"comment\"; op: CommentLike; options?: CommentOptionsLike }\n | { kind: \"vote\"; op: VoteLike };\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 * From `getRcResourceParamsQueryOptions()`. Required for an exact estimate;\n * without it the result is not ready rather than silently approximate.\n */\n rcParams?: RcResourceParams | null;\n /**\n * The actual operation about to be broadcast. Supplying it is what makes the\n * estimate exact, because cost is dominated by the serialized transaction\n * size. Without it a minimal operation of that type is priced instead, which\n * is a lower bound: it can miss a marginal case but never invents one.\n */\n payload?: RcPrecheckPayload;\n /**\n * What to price when no payload is supplied.\n *\n * - `\"minimal\"` (default) prices the smallest operation of that type. It is\n * a lower bound, so a pre-submit warning is never invented for an\n * operation that would have succeeded.\n * - `\"average\"` prices the network average the chain publishes. Right for\n * \"how many of these can I afford\" displays, where there is no specific\n * operation in hand and the smallest conceivable one would flatter the\n * count.\n */\n fallback?: \"minimal\" | \"average\";\n /**\n * Safety multiplier applied to the 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 /**\n * RC cost of the operation itself.\n *\n * Named `avgCost` for backwards compatibility; it is no longer an average.\n * @deprecated prefer `cost`.\n */\n avgCost: number;\n /** RC cost of the operation, computed the way the chain computes it. */\n cost: number;\n /** Serialized transaction size, the dominant term for a comment. */\n transactionBytes: 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 cost: 0,\n transactionBytes: 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 * Costs are computed the way the chain computes them, from the actual\n * operation, not from the network-wide average. The average is dominated by\n * short replies and badly misleads on posts: it once told an account holding\n * 21.3B RC that it could afford 17 posts, and the next post it tried needed\n * 23.3B.\n *\n * Still a hint, never a hard gate: the buffer covers pool drift between the\n * estimate and the broadcast, and the publish/comment/vote action must stay\n * non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n rcParams,\n operation,\n payload,\n fallback = \"minimal\",\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\n const priced = priceOperation(operation, payload, fallback, rcParams, rcStats);\n if (!priced) {\n // Nothing to price against: reporting \"ready\" here would be a silent\n // all-clear, which is the one answer a pre-check must never invent.\n return { ...EMPTY, currentMana, maxMana };\n }\n\n const { cost, transactionBytes } = priced;\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = cost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost: cost,\n cost,\n transactionBytes,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / cost),\n };\n}\n\n/**\n * Prices whichever operation the caller is about to broadcast.\n *\n * Comments and votes are the two operations whose cost swings with what the\n * user wrote, so they are priced from the payload, and pricing them needs the\n * curve parameters. Every other operation the type advertises (transfer,\n * custom_json, ...) is fixed-shape and takes the network average the chain\n * publishes, which needs nothing else.\n *\n * When no payload is supplied a minimal operation is priced. That is\n * deliberately a lower bound: it can miss a marginal case, but it never warns\n * about one that would have succeeded.\n *\n * Returns null when the answer would have to be invented, so the caller\n * reports \"not ready\" rather than a zero-cost all-clear.\n */\nfunction priceOperation(\n operation: RcPrecheckOperation,\n payload: RcPrecheckPayload | undefined,\n fallback: \"minimal\" | \"average\",\n rcParams: RcResourceParams | null | undefined,\n rcStats: RcStats\n): { cost: number; transactionBytes: number } | null {\n const average = averageCost(rcStats, operation);\n const pricedFromPayload =\n operation === \"comment_operation\" || operation === \"vote_operation\";\n\n // The average is a number the node already returned. It needs no curve\n // parameters, so a caller pricing a transfer must not be blocked waiting on\n // them, which is how every operation outside these two is priced.\n if (!pricedFromPayload || (!payload && fallback === \"average\")) {\n return average;\n }\n\n // Asked to price a real comment or vote without the inputs to do it. The\n // honest answer is \"not ready\": falling back to the average here is exactly\n // what told an account holding 21.3B RC it could afford 17 more posts.\n if (!rcParams?.resource_params || !rcParams.size_info || !rcStats.pool || !rcStats.share) {\n return null;\n }\n\n const stats = { pool: rcStats.pool, regen: rcStats.regen, share: rcStats.share };\n\n if (operation === \"vote_operation\") {\n const op: VoteLike = payload?.kind === \"vote\" ? payload.op : MINIMAL_VOTE;\n const transactionBytes = estimateVoteTransactionBytes(op);\n const usage = countVoteResourceUsage({ transactionBytes }, rcParams.size_info);\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n }\n\n const op: CommentLike = payload?.kind === \"comment\" ? payload.op : MINIMAL_COMMENT;\n const options = payload?.kind === \"comment\" ? payload.options : undefined;\n const transactionBytes = estimateCommentTransactionBytes({ op, options });\n const usage = countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength: op.permlink.length,\n beneficiaries: options?.beneficiaries?.length ?? 0,\n hasCommentOptions: !!options\n },\n rcParams.size_info\n );\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n}\n\n/** The network average the chain publishes for an operation, when it has one. */\nfunction averageCost(\n rcStats: RcStats,\n operation: RcPrecheckOperation\n): { cost: number; transactionBytes: number } | null {\n const cost = rcStats.ops[operation]?.avg_cost;\n return typeof cost === \"number\" && cost > 0 ? { cost, transactionBytes: 0 } : null;\n}\n\n/** Smallest realistic operations, used only when the caller has no payload yet. */\nconst MINIMAL_COMMENT: CommentLike = {\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\",\n parent_author: \"\",\n parent_permlink: \"hive-100000\",\n title: \"\",\n body: \"\",\n json_metadata: \"{}\"\n};\n\nconst MINIMAL_VOTE: VoteLike = {\n voter: \"aaaaaaaaaa\",\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\"\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\n/**\n * POST a single game claim and return the parsed JSON body.\n *\n * A failed post-game comes back from the edge as an HTML gateway page (a 502 was\n * the trail on ECENCY-NEXT-1FCJ), and `response.json()` on that throws a bare\n * `SyntaxError` naming neither the endpoint nor the cause. Check the status and\n * the content type first, then fail with a STABLE, low-cardinality message\n * (content type + status, never the raw body) so these group as a single Sentry\n * issue instead of fragmenting on every distinct error page.\n *\n * Exported for unit testing; the hook below wraps it.\n */\nexport async function gameClaimRequest(\n code: string,\n gameType: \"spin\",\n key: string\n): Promise {\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 // 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 // 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 page.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Games] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Games] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body) as GameClaim;\n } catch {\n throw new Error(\n `[SDK][Games] – malformed JSON response (status ${response.status})`\n );\n }\n}\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 return gameClaimRequest(code, gameType, key);\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","/**\n * Thresholds behind the content moderation treatment. Single source of truth for\n * every client: web and mobile previously carried their own copies, which drifted\n * (mobile flagged downvoted content at -7B rshares and 4 voters where web used\n * -10B and 5), so the same post read differently depending on the app.\n */\n\n/** Sum of rshares below which a post counts as heavily downvoted. */\nexport const HIDDEN_POST_RSHARES_THRESHOLD = -10000000000;\n\n/** Downvoting is only conclusive once enough accounts have voted. */\nexport const HIDDEN_POST_MIN_VOTES = 5;\n\n/**\n * Reputation (human-readable 0-100 scale) below which an author counts as\n * low-trust. New Hive accounts start around 25.\n *\n * NOTE: reputation is the only input. Account age is NOT part of the check, so a\n * years-old account that never earned reputation trips it exactly like a fresh\n * one. User-facing copy must say \"low reputation\", never \"new account\".\n */\nexport const LOW_TRUST_REPUTATION_THRESHOLD = 30;\n","/**\n * Converts Hive's raw reputation to the human-readable 0-100 scale, passing\n * through values that are already on it (the bridge returns both shapes\n * depending on the endpoint).\n */\nconst isHumanReadable = (input: number): boolean =>\n Math.abs(input) > 0 && Math.abs(input) <= 100;\n\nexport function accountReputation(input: string | number): number {\n if (typeof input === \"number\" && isHumanReadable(input)) {\n return Math.floor(input);\n }\n\n if (typeof input === \"string\") {\n input = Number(input);\n\n if (isHumanReadable(input)) {\n return Math.floor(input);\n }\n }\n\n if (input === 0) {\n return 25;\n }\n\n let neg = false;\n\n if (input < 0) {\n neg = true;\n }\n\n let reputationLevel = Math.log10(Math.abs(input as number));\n reputationLevel = Math.max(reputationLevel - 9, 0);\n\n if (reputationLevel < 0) {\n reputationLevel = 0;\n }\n\n if (neg) {\n reputationLevel *= -1;\n }\n\n reputationLevel = reputationLevel * 9 + 25;\n\n return Math.floor(reputationLevel);\n}\n","/**\n * Outbound-link detection for the SEO/backlink-farm signal.\n *\n * A link only counts as outbound promotion when it leaves the Hive/Ecency\n * ecosystem and is not an embedded image, so ordinary on-platform references and\n * post illustrations never trip the check.\n */\n\n// Hosts that are part of the Hive/Ecency ecosystem.\nconst INTERNAL_HOSTS = [\n \"ecency.com\",\n \"ecency.app\",\n \"hive.blog\",\n \"hive.io\",\n \"hiveblocks.com\",\n \"peakd.com\",\n \"snapie.io\",\n \"hivesuite.app\",\n \"leofinance.io\",\n \"inleo.io\",\n \"3speak.tv\",\n \"d.buzz\",\n \"waivio.com\"\n];\n\n// Image/media hosts: an embedded image is content, not a backlink.\nconst IMAGE_HOSTS = [\n \"imgur.com\",\n \"images.hive.blog\",\n \"files.peakd.com\",\n \"i.ecency.com\",\n \"images.ecency.com\",\n \"steemitimages.com\",\n \"cdn.steemitimages.com\",\n \"media.giphy.com\"\n];\n\nconst IMAGE_EXT_RE = /\\.(jpe?g|png|gif|webp|svg|bmp|avif)(\\?|#|$)/i;\n// Match absolute AND protocol-relative URLs (\"//host/...\"), so the check can't be\n// evaded with `[promo](//shop.example)` (the renderer allows protocol-relative hrefs).\nconst URL_RE = /(?:https?:)?\\/\\/[^\\s)<>\"'\\]]+/gi;\n// URLs in prose are commonly followed by punctuation (\"https://ecency.com, and...\");\n// strip it so the host parses correctly and internal links do not false-positive.\nconst TRAILING_PUNCT_RE = /[.,;:!?'\"]+$/;\n\nfunction hostOf(url: string): string {\n const m = /^(?:https?:)?\\/\\/([^/?#]+)/i.exec(url);\n return m ? m[1].toLowerCase().replace(/^www\\./, \"\") : \"\";\n}\n\nfunction isExternalPromoLink(rawUrl: string): boolean {\n const url = rawUrl.replace(TRAILING_PUNCT_RE, \"\");\n if (IMAGE_EXT_RE.test(url)) {\n return false; // embedded image, not a backlink\n }\n const host = hostOf(url);\n if (!host.includes(\".\")) {\n return false; // not a real domain (e.g. a stray \"//something\")\n }\n const matches = (h: string) => host === h || host.endsWith(\".\" + h);\n if (INTERNAL_HOSTS.some(matches) || IMAGE_HOSTS.some(matches)) {\n return false; // Hive/Ecency or image host\n }\n return true;\n}\n\n/** True if the post body contains an outbound (non-Hive, non-image) link. */\nexport function hasExternalLink(body: string | undefined | null): boolean {\n if (!body) {\n return false;\n }\n const matches = body.match(URL_RE);\n if (!matches) {\n return false;\n }\n return matches.some(isExternalPromoLink);\n}\n","import { accountReputation } from \"./account-reputation\";\nimport {\n HIDDEN_POST_MIN_VOTES,\n HIDDEN_POST_RSHARES_THRESHOLD,\n LOW_TRUST_REPUTATION_THRESHOLD\n} from \"./constants\";\nimport { hasExternalLink } from \"./external-links\";\n\n/**\n * Why a piece of content gets the moderation treatment. Clients render their own\n * copy per reason; the rules that pick the reason live here so web and mobile\n * always agree on which one fired.\n */\nexport enum ContentModerationReason {\n /**\n * `stats.gray` / `stats.hide` from hivemind: community moderator mutes, mutes\n * applied by the observer account, and authors hivemind itself grays out.\n */\n MOD_MUTED = \"mod_muted\",\n /** Heavily downvoted by enough distinct accounts to be conclusive. */\n DOWNVOTED = \"downvoted\",\n /** Low-reputation author whose post carries an outbound promotional link. */\n LOW_TRUST = \"low_trust\"\n}\n\n/**\n * The fields of a post or comment the rules read. Deliberately structural: web\n * passes an `Entry`, mobile passes a raw bridge post, and neither has to convert.\n */\nexport interface ModerationCandidate {\n author?: string;\n author_reputation?: string | number;\n body?: string | null;\n net_rshares?: number;\n active_votes?: unknown[] | null;\n stats?: {\n gray?: boolean;\n hide?: boolean;\n total_votes?: number;\n } | null;\n}\n\n/**\n * hivemind's `total_votes` is the authoritative count when present; `active_votes`\n * is the fallback for the feeds that omit stats.\n */\nfunction countVotes(content: ModerationCandidate): number {\n return content?.stats?.total_votes ?? content?.active_votes?.length ?? 0;\n}\n\n/** Heavily downvoted: strongly negative rshares from more than a handful of voters. */\nexport function isHiddenPost(\n netRshares: number | undefined,\n activeVotesLength: number\n): boolean {\n return (\n (netRshares ?? 0) < HIDDEN_POST_RSHARES_THRESHOLD &&\n activeVotesLength >= HIDDEN_POST_MIN_VOTES\n );\n}\n\n/**\n * Content-moderation signal for SEO/backlink-farm abuse: low-reputation accounts\n * publishing an outbound link are the signature of free-faucet SEO spam.\n *\n * Such posts are not blocked, they are de-emphasized and their outbound link is\n * flagged as unverified, so the promotional payoff drops to zero. Low reputation\n * on its own is NOT a moderation signal: plenty of small accounts post ordinary\n * content, and dimming all of them punishes newcomers for existing.\n */\nexport function isLowTrustSeoPost(\n content: Pick\n): boolean {\n const reputation = content?.author_reputation;\n // Some feeds omit reputation entirely. An unknown value is not evidence of\n // anything, so it must not be read as \"brand new account\" (raw 0 scales to 25,\n // which is below the threshold and would flag every post carrying a link).\n if (reputation === undefined || reputation === null) {\n return false;\n }\n return (\n accountReputation(reputation) < LOW_TRUST_REPUTATION_THRESHOLD &&\n hasExternalLink(content?.body)\n );\n}\n\n/** True when the viewer has personally muted this author. */\nexport function isAuthorMuted(\n author: string | undefined,\n mutedAuthors: string[] | undefined | null\n): boolean {\n return !!author && !!mutedAuthors?.includes(author);\n}\n\n/**\n * The reason a post or comment should be de-emphasized, or null when it is fine.\n *\n * Precedence, most authoritative first: an explicit moderation action outranks\n * the vote heuristic, which outranks the spam heuristic. Order matters because a\n * heavily downvoted post usually also has a battered reputation, and labelling\n * that \"low trust\" would hide why the content was actually flagged.\n *\n * A viewer's personal mute list is NOT an input here. Muting an author removes\n * their content from the viewer's lists entirely (see `isAuthorMuted`), rather\n * than labelling it.\n */\nexport function getContentModerationReason(\n content: ModerationCandidate | undefined | null\n): ContentModerationReason | null {\n if (!content) {\n return null;\n }\n if (content.stats?.gray || content.stats?.hide) {\n return ContentModerationReason.MOD_MUTED;\n }\n if (isHiddenPost(content.net_rshares, countVotes(content))) {\n return ContentModerationReason.DOWNVOTED;\n }\n if (isLowTrustSeoPost(content)) {\n return ContentModerationReason.LOW_TRUST;\n }\n return null;\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport type {\n DigestSubscribeInput,\n DigestSubscribeResult,\n DigestSubscription,\n NewsletterCandidatePost,\n NewsletterListType,\n NewsletterSendPreview,\n NewsletterSendRequest,\n NewsletterSendResult,\n NewsletterSenderStanding,\n NewsletterSentIssue,\n} from \"./types\";\n\n/**\n * Client for the newsletter relay at {privateApiHost}/api/newsletter/*\n * (Next.js route handlers on ecency.com, which alone hold the news-service\n * credentials — clients never talk to the service directly).\n *\n * Identity is the HiveSigner access token, passed here as the explicit `code`\n * argument. Transport mirrors the deployed web client per route: subscribe and\n * unsubscribe-all carry it in the POST body as `code` (the subscribe route\n * authenticates ONLY from the body — a header alone is treated as anonymous);\n * every other call, the send/preview POSTs included, uses the `X-HS-Token`\n * header. The relay verifies it upstream and derives the account from it, so\n * a stale token 401s — callers are responsible for supplying a fresh one\n * (web: ensureValidToken; mobile: the token-refresh wrapper).\n *\n * The email-token confirm/unsubscribe flows are deliberately absent: those\n * links land on web pages.\n */\nexport class NewsletterApiError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly data?: unknown,\n ) {\n super(message);\n }\n}\n\n/** A refused send, carrying the relay's routing `code` (already_sent, suspended, ...). */\nexport class NewsletterSendRefusedError extends NewsletterApiError {\n constructor(\n message: string,\n status: number,\n public readonly code?: string,\n public readonly taken?: Array<{ cadence: string; period: string; kind: string }>,\n data?: unknown,\n ) {\n super(message, status, data);\n }\n}\n\nfunction newsletterUrl(path: string): string {\n return `${CONFIG.privateApiHost}/api/newsletter${path}`;\n}\n\nasync function parse(response: Response): Promise {\n const data = (await response.json().catch(() => undefined)) as\n | (T & { error?: string })\n | undefined;\n if (!response.ok) {\n throw new NewsletterApiError(\n data?.error || `Request failed (${response.status})`,\n response.status,\n data,\n );\n }\n // A 2xx without a JSON body is not a result; saying so beats returning blanks.\n if (!data || typeof data !== \"object\") {\n throw new NewsletterApiError(\n `Unexpected response (${response.status})`,\n response.status,\n );\n }\n return data;\n}\n\n/**\n * Subscribe an address to a digest. Authenticated callers (code given) skip\n * the captcha; anonymous callers must supply `captchaToken` in the input and\n * get double opt-in. The `own` digest type is always authenticated.\n */\nexport async function subscribeDigestRequest(\n input: DigestSubscribeInput,\n code?: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(\"/subscribe\"), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ ...input, ...(code ? { code } : {}) }),\n });\n return parse(response);\n}\n\n/** Every live digest subscription attributed to the token's account. */\nexport async function getDigestSubscriptionsRequest(\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(\"/subscriptions\"), {\n headers: { \"X-HS-Token\": code },\n });\n const data = await parse<{ subscriptions?: DigestSubscription[] }>(response);\n return data.subscriptions ?? [];\n}\n\n/** Leave one digest by subscription id. */\nexport async function leaveDigestRequest(\n id: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(`/subscriptions/${encodeURIComponent(id)}`),\n { method: \"DELETE\", headers: { \"X-HS-Token\": code } },\n );\n await parse<{ left: boolean }>(response);\n}\n\n/**\n * Suppress ONE address entirely (no Ecency bulk mail to it again). Only that\n * address stops: an account can hold subscriptions under several addresses.\n */\nexport async function unsubscribeAllDigestsRequest(\n email: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(\"/unsubscribe-all\"), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email, code }),\n });\n await parse<{ suppressed: boolean }>(response);\n}\n\n/** Sender standing (status, complaint/bounce stats, subscriber counts) for a list. */\nexport async function getNewsletterSenderRequest(\n type: NewsletterListType,\n target: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(`/sender?type=${type}&target=${encodeURIComponent(target)}`),\n { headers: { \"X-HS-Token\": code } },\n );\n return parse(response);\n}\n\n/** Already-sent issues for a list, newest first. */\nexport async function getNewsletterIssuesRequest(\n type: NewsletterListType,\n target: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(`/issues?type=${type}&target=${encodeURIComponent(target)}`),\n { headers: { \"X-HS-Token\": code } },\n );\n const data = await parse<{ issues?: NewsletterSentIssue[] }>(response);\n return data.issues ?? [];\n}\n\n/** Candidate posts for composing a digest issue. */\nexport async function getNewsletterPostsRequest(\n type: NewsletterListType,\n target: string,\n code: string,\n limit = 20,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(\n `/posts?type=${type}&target=${encodeURIComponent(target)}&limit=${limit}`,\n ),\n { headers: { \"X-HS-Token\": code } },\n );\n const data = await parse<{ posts?: NewsletterCandidatePost[] }>(response);\n return data.posts ?? [];\n}\n\nasync function postSend(\n path: string,\n request: NewsletterSendRequest,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(path), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-HS-Token\": code },\n body: JSON.stringify(request),\n });\n const data = (await response.json().catch(() => undefined)) as\n | (T & {\n error?: string;\n code?: string;\n taken?: NewsletterSendRefusedError[\"taken\"];\n })\n | undefined;\n if (!response.ok) {\n throw new NewsletterSendRefusedError(\n data?.error || `Request failed (${response.status})`,\n response.status,\n data?.code,\n data?.taken,\n data,\n );\n }\n if (!data || typeof data !== \"object\") {\n throw new NewsletterSendRefusedError(\n `Unexpected response (${response.status})`,\n response.status,\n );\n }\n return data;\n}\n\n/** Render the would-be issue (subject/html/text, counts, taken periods) without sending. */\nexport function previewNewsletterSendRequest(\n request: NewsletterSendRequest,\n code: string,\n): Promise {\n return postSend(\"/send/preview\", request, code);\n}\n\n/** Send a post or composed digest to the list's subscribers. Pro/team gated by the relay. */\nexport function sendNewsletterIssueRequest(\n request: NewsletterSendRequest,\n code: string,\n): Promise {\n return postSend(\"/send\", request, code);\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getDigestSubscriptionsRequest } from \"../api\";\n\n/**\n * The signed-in account's live digest subscriptions. Disabled without a\n * username + token: callers render nothing then, and a request that\n * predictably 401s is noise. `retry: false` because the common failure is a\n * stale token, which a retry with the same token cannot fix.\n */\nexport function getDigestSubscriptionsQueryOptions(\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.subscriptions(name),\n enabled: !!name && !!code,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getDigestSubscriptionsRequest(code);\n },\n staleTime: 60_000,\n retry: false,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getNewsletterSenderRequest } from \"../api\";\nimport type { NewsletterListType } from \"../types\";\n\n/**\n * Sender standing for a creator/community list. View access is the list's\n * owner (creator) or the community team, decided by the relay — enable this\n * only for callers already known to be the sender.\n */\nexport function getNewsletterSenderQueryOptions(\n type: NewsletterListType,\n target: string,\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.sender(type, target, name),\n enabled: !!name && !!code && !!target,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getNewsletterSenderRequest(type, target, code);\n },\n staleTime: 5 * 60_000,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getNewsletterIssuesRequest } from \"../api\";\nimport type { NewsletterListType } from \"../types\";\n\n/** Already-sent issues for a creator/community list (sender-only view). */\nexport function getNewsletterIssuesQueryOptions(\n type: NewsletterListType,\n target: string,\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.issues(type, target, name),\n enabled: !!name && !!code && !!target,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getNewsletterIssuesRequest(type, target, code);\n },\n staleTime: 60_000,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getNewsletterPostsRequest } from \"../api\";\nimport type { NewsletterListType } from \"../types\";\n\n/** Candidate posts for composing a digest issue (send-gated by the relay). */\nexport function getNewsletterPostsQueryOptions(\n type: NewsletterListType,\n target: string,\n username: string | undefined,\n code: string | undefined,\n limit = 20,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.posts(type, target, name, limit),\n enabled: !!name && !!code && !!target,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getNewsletterPostsRequest(type, target, code, limit);\n },\n staleTime: 60_000,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { subscribeDigestRequest } from \"../api\";\nimport type { DigestSubscribeInput } from \"../types\";\n\n/**\n * Subscribe to a digest (also re-used to change cadence: same list + address\n * with a new cadence updates the row). Works signed-in (code) and anonymous\n * (input.captchaToken); the signed-in path refreshes the account's\n * subscriptions list on success.\n */\nexport function useSubscribeDigest(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"subscribe\", name],\n mutationFn: (input: DigestSubscribeInput) =>\n subscribeDigestRequest(input, code),\n onSuccess() {\n if (name) {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.newsletter.subscriptions(name),\n });\n }\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { leaveDigestRequest } from \"../api\";\nimport type { DigestSubscription } from \"../types\";\n\n/** Leave one digest by subscription id; drops the row from the cached list. */\nexport function useLeaveDigest(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"leave\", name],\n mutationFn: async (id: string) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return leaveDigestRequest(id, code);\n },\n onSuccess(_result, id) {\n queryClient.setQueryData(\n QueryKeys.newsletter.subscriptions(name),\n (prev) => (prev ?? []).filter((s) => s.id !== id),\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { unsubscribeAllDigestsRequest } from \"../api\";\nimport type { DigestSubscription } from \"../types\";\n\n/**\n * Stop all Ecency mail to ONE address. Only that address's rows leave the\n * cached list: an account can hold subscriptions under more than one address,\n * and those stay visible.\n */\nexport function useUnsubscribeAllDigests(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"unsubscribe-all\", name],\n mutationFn: async (email: string) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return unsubscribeAllDigestsRequest(email, code);\n },\n onSuccess(_result, email) {\n queryClient.setQueryData(\n QueryKeys.newsletter.subscriptions(name),\n (prev) =>\n (prev ?? []).filter(\n (s) => s.email.toLowerCase() !== email.toLowerCase(),\n ),\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport {\n previewNewsletterSendRequest,\n sendNewsletterIssueRequest,\n} from \"../api\";\nimport type { NewsletterSendRequest } from \"../types\";\n\n/**\n * Preview the would-be issue. No cache side effects: a preview changes\n * nothing server-side.\n */\nexport function usePreviewNewsletterIssue(\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return useMutation({\n mutationKey: [\"newsletter\", \"send-preview\", name],\n mutationFn: async (request: NewsletterSendRequest) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return previewNewsletterSendRequest(request, code);\n },\n });\n}\n\n/**\n * Send a post or composed digest to a list. Errors are\n * NewsletterSendRefusedError with the relay's routing `code`\n * (already_sent + taken periods, suspended, post_refused, ...). On success the\n * list's issues + sender standing refresh.\n */\nexport function useSendNewsletterIssue(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"send\", name],\n mutationFn: async (request: NewsletterSendRequest) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return sendNewsletterIssueRequest(request, code);\n },\n onSuccess(_result, request) {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.newsletter.issues(request.type, request.target, name),\n });\n queryClient.invalidateQueries({\n queryKey: QueryKeys.newsletter.sender(request.type, request.target, name),\n });\n },\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 15b3daa3ec..098cf6ae5b 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'),vn=require('bs58'),secp256k1_js=require('@noble/curves/secp256k1.js'),sha2_js=require('@noble/hashes/sha2.js'),aes_js=require('@noble/ciphers/aes.js'),uo=require('hivesigner');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var vn__default=/*#__PURE__*/_interopDefault(vn);var uo__default=/*#__PURE__*/_interopDefault(uo);var $i=Object.defineProperty;var vt=(e,t)=>{for(var r in t)$i(e,r,{get:t[r],enumerable:true});};var Pt=new ArrayBuffer(0),At=null,Ot=null;function Wi(){return At||(typeof TextEncoder<"u"?At=new TextEncoder:At={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)}}),At}function mn(){return Ot||(typeof TextDecoder<"u"?Ot=new TextDecoder:Ot={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+(i&1023)));}return r}}),Ot}var D=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?Pt:new ArrayBuffer(t),this.view=t===0?new DataView(Pt):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(Pt));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 o;return t instanceof e?(o=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=o.length):t instanceof Uint8Array?o=t:t instanceof ArrayBuffer?o=new Uint8Array(t):o=new Uint8Array(t),o.length<=0?this:(r+o.length>this.buffer.byteLength&&this.resize(r+o.length),new Uint8Array(this.buffer).set(o,r),n&&(this.offset+=o.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,o=new e(n,this.littleEndian);return o.offset=0,o.limit=n,new Uint8Array(o.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),o}copyTo(t,r,n,o){let i=typeof r>"u",s=typeof n>"u";r=i?t.offset:r,n=s?this.offset:n,o=o===void 0?this.limit:o;let a=o-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,o),r),s&&(this.offset+=a),i&&(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?Pt: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 o=this.calculateVarint32(t);for(r+o>this.buffer.byteLength&&this.resize(r+o),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):o}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,o=0,i;do i=this.view.getUint8(t++),n<5&&(o|=(i&127)<<7*n),++n;while((i&128)!==0);return o|=0,r?(this.offset=t,o):{value:o,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",o=n?this.offset:r,i=Wi().encode(t),s=i.length,a=this.calculateVarint32(s);return o+a+s>this.buffer.byteLength&&this.resize(o+a+s),this.writeVarint32(s,o),o+=a,new Uint8Array(this.buffer).set(i,o),o+=s,n?(this.offset=o,this):o-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,o=this.readVarint32(t),i=o.value,s=o.length;t+=s;let a=mn().decode(new Uint8Array(this.buffer,t,i));return t+=i,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 o=mn().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,o):{string:o,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}},gn=["bridge.get_ranked_posts","bridge.get_account_posts","bridge.get_post","bridge.get_discussion","bridge.get_profile","bridge.get_profiles","bridge.get_community","bridge.list_communities","condenser_api.get_accounts","condenser_api.get_content","condenser_api.get_dynamic_global_properties","condenser_api.get_trending_tags"],xt=null,rr=e=>{if(e===null){xt=null;return}if(!e||typeof e!="object")return;let t=typeof e.url=="string"?e.url.trim():"";if(!/^https?:\/\//i.test(t))return;let r={};if(e.headers&&typeof e.headers=="object")for(let[s,a]of Object.entries(e.headers))typeof a=="string"&&a&&!/[\u0000-\u001f\u007f]/.test(a)&&!/[\u0000-\u001f\u007f]/.test(s)&&(r[s]=a);let n=typeof e.timeoutMs=="number"&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:2e3,o=e.methods===void 0?[...gn]:Array.isArray(e.methods)?e.methods.filter(s=>typeof s=="string"&&s.includes(".")):[];if(o.length===0)return;let i=(s,a)=>typeof s=="number"&&Number.isFinite(s)&&s>0?s:a;xt={url:t,headers:r,timeoutMs:n,methods:o,failureThreshold:Math.floor(i(e.failureThreshold,3)),cooldownMs:i(e.cooldownMs,1e4),methodSet:new Set(o)};},nr=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)))]:[],or=e=>{let t=nr(e);t.length&&(x.nodes=t);},ir=e=>{let t=nr(e);t.length&&(x.restNodes=t);},sr=e=>{if(!e||typeof e!="object")return;let t={...x.restNodesByApi};for(let[r,n]of Object.entries(e)){let o=nr(n);o.length?t[r]=o:delete t[r];}x.restNodesByApi=t;},ar=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(x.userAgent=t);},cr=e=>{if(!e||typeof e!="object")return;let t=x.resilience,r=o=>typeof o=="boolean",n=o=>typeof o=="number"&&Number.isFinite(o)&&o>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 Ee=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,o=true;n<0&&(o=false,n=n+4);let i=r.subarray(1);return new e(i,n,o)}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 Y(n.recoverPublicKey(t).toBytes())}};var Y=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 o;try{o=vn__default.default.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(o.length!==37)throw new Error("Invalid public key length");let i=o.subarray(0,33),s=o.subarray(33,37),a=legacy_js.ripemd160(i).subarray(0,4);if(!zi(s,a))throw new Error("Public key checksum mismatch");try{secp256k1_js.secp256k1.Point.fromBytes(i);}catch{throw new Error("Invalid public key")}return new e(i,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=Ee.from(r)),secp256k1_js.secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return Gi(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},Gi=(e,t)=>{let r=legacy_js.ripemd160(e);return t+vn__default.default.encode(new Uint8Array([...e,...r.subarray(0,4)]))},zi=(e,t)=>{if(e.byteLength!==t.byteLength)return false;for(let r=0;r{throw new Error("Void can not be serialized")},b=(e,t)=>{e.writeVString(t);},Xi=(e,t)=>{e.writeInt16(t);},An=(e,t)=>{e.writeInt64(t);},Pn=(e,t)=>{e.writeUint8(t);},pe=(e,t)=>{e.writeUint16(t);},X=(e,t)=>{e.writeUint32(t);},On=(e,t)=>{e.writeUint64(t);},be=(e,t)=>{e.writeByte(t?1:0);},xn=e=>(t,r)=>{let[n,o]=r;t.writeVarint32(n),e[n](t,o);},q=(e,t)=>{let r=Et.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let o=0;o<7;o++)e.writeUint8(r.symbol.charCodeAt(o)||0);},Se=(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(Y.from(t).key);},En=(e=null)=>(t,r)=>{r=St.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);},Sn=En(),ur=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[o,i]of n)e(r,o),t(r,i);},V=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},le=e=>(t,r)=>{for(let[n,o]of e)try{o(t,r[n]);}catch(i){throw i.message=`${n}: ${i.message}`,i}},Ie=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},W=le([["weight_threshold",X],["account_auths",ur(b,pe)],["key_auths",ur(ge,pe)]]),Zi=le([["account",b],["weight",pe]]),pr=le([["base",q],["quote",q]]),es=le([["account_creation_fee",q],["maximum_block_size",X],["hbd_interest_rate",pe]]),R=(e,t)=>{let r=le(t);return (n,o)=>{n.writeVarint32(e),r(n,o);}},S={};S.account_create=R(C.account_create,[["fee",q],["creator",b],["new_account_name",b],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",b]]);S.account_create_with_delegation=R(C.account_create_with_delegation,[["fee",q],["delegation",q],["creator",b],["new_account_name",b],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",b],["extensions",V(ie)]]);S.account_update=R(C.account_update,[["account",b],["owner",Ie(W)],["active",Ie(W)],["posting",Ie(W)],["memo_key",ge],["json_metadata",b]]);S.account_witness_proxy=R(C.account_witness_proxy,[["account",b],["proxy",b]]);S.account_witness_vote=R(C.account_witness_vote,[["account",b],["witness",b],["approve",be]]);S.cancel_transfer_from_savings=R(C.cancel_transfer_from_savings,[["from",b],["request_id",X]]);S.change_recovery_account=R(C.change_recovery_account,[["account_to_recover",b],["new_recovery_account",b],["extensions",V(ie)]]);S.claim_account=R(C.claim_account,[["creator",b],["fee",q],["extensions",V(ie)]]);S.claim_reward_balance=R(C.claim_reward_balance,[["account",b],["reward_hive",q],["reward_hbd",q],["reward_vests",q]]);S.comment=R(C.comment,[["parent_author",b],["parent_permlink",b],["author",b],["permlink",b],["title",b],["body",b],["json_metadata",b]]);S.comment_options=R(C.comment_options,[["author",b],["permlink",b],["max_accepted_payout",q],["percent_hbd",pe],["allow_votes",be],["allow_curation_rewards",be],["extensions",V(xn([le([["beneficiaries",V(Zi)]])]))]]);S.convert=R(C.convert,[["owner",b],["requestid",X],["amount",q]]);S.create_claimed_account=R(C.create_claimed_account,[["creator",b],["new_account_name",b],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",b],["extensions",V(ie)]]);S.custom=R(C.custom,[["required_auths",V(b)],["id",pe],["data",Sn]]);S.custom_json=R(C.custom_json,[["required_auths",V(b)],["required_posting_auths",V(b)],["id",b],["json",b]]);S.decline_voting_rights=R(C.decline_voting_rights,[["account",b],["decline",be]]);S.delegate_vesting_shares=R(C.delegate_vesting_shares,[["delegator",b],["delegatee",b],["vesting_shares",q]]);S.delete_comment=R(C.delete_comment,[["author",b],["permlink",b]]);S.escrow_approve=R(C.escrow_approve,[["from",b],["to",b],["agent",b],["who",b],["escrow_id",X],["approve",be]]);S.escrow_dispute=R(C.escrow_dispute,[["from",b],["to",b],["agent",b],["who",b],["escrow_id",X]]);S.escrow_release=R(C.escrow_release,[["from",b],["to",b],["agent",b],["who",b],["receiver",b],["escrow_id",X],["hbd_amount",q],["hive_amount",q]]);S.escrow_transfer=R(C.escrow_transfer,[["from",b],["to",b],["hbd_amount",q],["hive_amount",q],["escrow_id",X],["agent",b],["fee",q],["json_meta",b],["ratification_deadline",Se],["escrow_expiration",Se]]);S.feed_publish=R(C.feed_publish,[["publisher",b],["exchange_rate",pr]]);S.limit_order_cancel=R(C.limit_order_cancel,[["owner",b],["orderid",X]]);S.limit_order_create=R(C.limit_order_create,[["owner",b],["orderid",X],["amount_to_sell",q],["min_to_receive",q],["fill_or_kill",be],["expiration",Se]]);S.limit_order_create2=R(C.limit_order_create2,[["owner",b],["orderid",X],["amount_to_sell",q],["exchange_rate",pr],["fill_or_kill",be],["expiration",Se]]);S.recover_account=R(C.recover_account,[["account_to_recover",b],["new_owner_authority",W],["recent_owner_authority",W],["extensions",V(ie)]]);S.request_account_recovery=R(C.request_account_recovery,[["recovery_account",b],["account_to_recover",b],["new_owner_authority",W],["extensions",V(ie)]]);S.reset_account=R(C.reset_account,[["reset_account",b],["account_to_reset",b],["new_owner_authority",W]]);S.set_reset_account=R(C.set_reset_account,[["account",b],["current_reset_account",b],["reset_account",b]]);S.set_withdraw_vesting_route=R(C.set_withdraw_vesting_route,[["from_account",b],["to_account",b],["percent",pe],["auto_vest",be]]);S.transfer=R(C.transfer,[["from",b],["to",b],["amount",q],["memo",b]]);S.transfer_from_savings=R(C.transfer_from_savings,[["from",b],["request_id",X],["to",b],["amount",q],["memo",b]]);S.transfer_to_savings=R(C.transfer_to_savings,[["from",b],["to",b],["amount",q],["memo",b]]);S.transfer_to_vesting=R(C.transfer_to_vesting,[["from",b],["to",b],["amount",q]]);S.vote=R(C.vote,[["voter",b],["author",b],["permlink",b],["weight",Xi]]);S.withdraw_vesting=R(C.withdraw_vesting,[["account",b],["vesting_shares",q]]);S.witness_update=R(C.witness_update,[["owner",b],["url",b],["block_signing_key",ge],["props",es],["fee",q]]);S.witness_set_properties=R(C.witness_set_properties,[["owner",b],["props",ur(b,Sn)],["extensions",V(ie)]]);S.account_update2=R(C.account_update2,[["account",b],["owner",Ie(W)],["active",Ie(W)],["posting",Ie(W)],["memo_key",Ie(ge)],["json_metadata",b],["posting_json_metadata",b],["extensions",V(ie)]]);S.create_proposal=R(C.create_proposal,[["creator",b],["receiver",b],["start_date",Se],["end_date",Se],["daily_pay",q],["subject",b],["permlink",b],["extensions",V(ie)]]);S.update_proposal_votes=R(C.update_proposal_votes,[["voter",b],["proposal_ids",V(An)],["approve",be],["extensions",V(ie)]]);S.remove_proposal=R(C.remove_proposal,[["proposal_owner",b],["proposal_ids",V(An)],["extensions",V(ie)]]);var ts=le([["end_date",Se]]);S.update_proposal=R(C.update_proposal,[["proposal_id",On],["creator",b],["daily_pay",q],["subject",b],["permlink",b],["extensions",V(xn([ie,ts]))]]);S.collateralized_convert=R(C.collateralized_convert,[["owner",b],["requestid",X],["amount",q]]);S.recurrent_transfer=R(C.recurrent_transfer,[["from",b],["to",b],["amount",q],["memo",b],["recurrence",pe],["executions",pe],["extensions",V(le([["type",Pn],["value",le([["pair_id",Pn]])]]))]]);var rs=(e,t)=>{let r=S[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}},ns=le([["ref_block_num",pe],["ref_block_prefix",X],["expiration",Se],["operations",V(rs)],["extensions",V(b)]]),os=le([["from",ge],["to",ge],["nonce",On],["check",X],["encrypted",En()]]),de={Asset:q,Memo:os,Price:pr,PublicKey:ge,String:b,Transaction:ns,UInt16:pe,UInt32:X};var ot=e=>new Promise(t=>setTimeout(t,e));var In=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function gr(){return In?{"User-Agent":x.userAgent}:{}}var Ce={served:0,fallback:0,skipped:0,fallbackByReason:{status:0,rpcerror:0,timeout:0,transport:0,validate:0,parse:0}},Re=class extends Error{constructor(r,n){super(n);this.reason=r;}reason},kn=e=>e instanceof Error?e.message:typeof e=="string"?e:String(e),kt=0,Cn=0;async function is(e,t,r,n,o,i){let s=t.indexOf(".");if(s<=0||s===t.length-1)throw new Re("transport",`method without an api prefix: ${t}`);let{signal:a,cleanup:c}=hr(Math.min(e.timeoutMs,n)),{signal:p,cleanup:l}=Ft(a,o);try{let d;try{d=await fetch(e.url,{method:"POST",body:JSON.stringify({api:t.slice(0,s),method:t.slice(s+1),params:r}),headers:{"Content-Type":"application/json",...gr(),...e.headers},signal:p});}catch(g){throw o?.aborted?g:new Re(a.aborted?"timeout":"transport",kn(g))}if(d.status!==200){try{await d.body?.cancel();}catch{}let g=d.status===502&&(d.headers.get("x-ssr-cache")??"").toUpperCase()==="RPCERROR";throw new Re(g?"rpcerror":"status",g?"proxy relayed a node error":`proxy answered ${d.status}`)}let m;try{m=await d.json();}catch(g){throw o?.aborted?g:new Re(a.aborted?"timeout":"parse",kn(g))}if(i&&!i(m))throw new Re("validate","proxy result rejected by validator");return m}finally{c(),l();}}var Z=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);}},qe=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 qn(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 ss=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],as=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function cs(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 us(e){if(!e)return false;if(e instanceof qe)return true;if(e instanceof Z)return false;let t=cs(e);return !!(ss.some(r=>t.includes(r))||as.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function lr(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function Dn(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var ps=1e4,ls=6e4,ds=12e4,Rn=2,Tn=6e4,Fn=12e4,fs=30,it=.3,dr=3,st=5*6e4,Kn=6e4,Bn=1e3,Mn=2e3,Rt=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,o){let i=this.getOrCreate(t);if(i.consecutiveFailures=0,i.rateLimitStreak=0,r){let s=i.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&i.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(i,n,o??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=dr&&o-i.updatedAt<=st?i.ewmaMs:void 0}return this.isLatencyUsable(n,o)?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 o=Date.now();if(t.latencyUpdatedAt>0&&o-t.latencyUpdatedAt>st&&(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=o,n!==void 0){let i=t.apiLatency.get(n);!i||o-i.updatedAt>st?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:o}):(i.ewmaMs=it*r+(1-it)*i.ewmaMs,i.sampleCount++,i.updatedAt=o);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(i.cooldownUntil>0&&i.cooldownUntil<=o||i.lastFailureTime>0&&o-i.lastFailureTime>3e4)&&(i.count=0,i.cooldownUntil=0),i.count++,i.lastFailureTime=o,i.count>=Rn&&(i.cooldownUntil=o+Tn),n.apiFailures.set(r,i);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};i.count=Math.max(i.count+1,Rn),i.lastFailureTime=o,i.cooldownUntil=o+Tn,i.defective=true,n.apiFailures.set(r,i);}recordRateLimit(t,r){let n=this.getOrCreate(t),o=Date.now();n.rateLimitStreak>0&&o-n.lastRateLimitAt>ds&&(n.rateLimitStreak=0);let i=typeof r=="number"&&Number.isFinite(r)&&r>0,s=i?r:Math.min(ps*2**n.rateLimitStreak,ls);i||n.rateLimitStreak++,n.lastRateLimitAt=o,n.rateLimitedUntil=i?o+s:Math.max(n.rateLimitedUntil,o+s),n.consecutiveFailures++,n.lastFailureTime=o;}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<=Fn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,o)=>n-o),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let o=Date.now();if(n.rateLimitedUntil>o||n.consecutiveFailures>=3&&o-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>o)return false}let i=this.consensusHeadBlock();return !(i>0&&n.headBlock>0&&o-n.headBlockUpdatedAt<=Fn&&i-n.headBlock>fs)}getOrderedNodes(t,r){let n=[],o=[];for(let c of t)this.isNodeHealthy(c,r)?n.push(c):o.push(c);if(n.length<=1)return [...n,...o];let i=Date.now(),s=n.map((c,p)=>({node:c,i:p,score:this.scoreNode(c,i)})).sort((c,p)=>c.score-p.score||c.i-p.i).map(c=>c.node),a=this.pickReprobeCandidate(n,i);return a&&s[0]!==a?[a,...s.filter(c=>c!==a),...o]:[...s,...o]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=dr&&r-t.latencyUpdatedAt<=st}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:Bn}pickReprobeCandidate(t,r){let n=r-Kn,o,i=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;}},mr=new fr;function Tt(e,t,r,n,o){let i=x.resilience;if(!i.adaptiveTimeout||o)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(i.adaptiveTimeoutFloorMs,i.adaptiveTimeoutFactor*s)))}function yr(e,t,r,n){r instanceof qe?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof Z?e.recordFailure(t,n):e.recordFailure(t);}function Nn(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let o=n.head_block_number;typeof o=="number"&&e.recordHeadBlock(t,o);}function ms(){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 hr(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(ms()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function Ft(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),o=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",o,{once:true});let i=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o);};return {signal:r.signal,cleanup:i}}var at=async(e,t,r,n=x.timeout,o=false,i)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:c,cleanup:p}=hr(n),{signal:l,cleanup:d}=Ft(c,i),m=()=>{p(),d();};try{let g=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...gr()},signal:l});if(g.status===429)throw new qe(e,"HTTP 429 Rate Limited",{rateLimitMs:qn(g.headers.get("Retry-After")),isRateLimit:!0});if(g.status>=500&&g.status<600)throw new qe(e,`HTTP ${g.status} from ${e}`);let h=await g.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 P=h.error;throw "message"in P&&"code"in P?new Z(P):h.error}throw h}catch(g){if(g instanceof Z||g instanceof qe||i?.aborted)throw g;if(o)return at(e,t,r,n,false,i);throw g}finally{m();}};function Ct(){return ot(50+Math.random()*50)}function gs(e){let{method:t,params:r,api:n,primary:o,hedgePool:i,callerTimeout:s,explicitTimeout:a,deadlineAt:c,externalSignal:p,onHedgeFired:l,validate:d}=e;return new Promise((m,g)=>{let h=false,P=0,O=false,T=false,F,ue,A=0,$=[],N=J=>{if(!h){h=true,ue!==void 0&&(clearTimeout(ue),ue=void 0);for(let I of $)I.signal.aborted||I.abort();J();}},H=(J,I)=>{P++;let me=new AbortController;$.push(me);let nt=Ft(me.signal,p),Li=Tt(j,J,t,s,a),tr=Date.now();I||(A=tr),at(J,t,r,Li,false,nt.signal).then(oe=>{if(nt.cleanup(),P--,I||(T=true),!h){if(d&&!d(oe)){if(j.recordDefectiveResponse(J,n),F=new Error(`[hive-tx] response validation failed for ${t} from ${J}`),!I&&!O){N(()=>g(F));return}P===0&&N(()=>g(F));return}j.recordSuccess(J,n,Date.now()-tr,t),Nn(j,J,t,oe),I?T||j.recordCensoredLatency(o,Date.now()-A,t):O||mr.refill(),N(()=>m(oe));}}).catch(oe=>{if(nt.cleanup(),P--,I||(T=true),!h){if(p?.aborted){N(()=>g(oe));return}if(oe instanceof Z&&!lr(oe.code,oe.message)){N(()=>g(oe));return}if(yr(j,J,oe,n),j.recordSlowFailure(J,Date.now()-tr,t),F=oe,!I&&!O){N(()=>g(oe));return}P===0&&N(()=>g(F));}});};H(o,false);let z=j.getUsableLatencyMs(o,t)??0,L=Tt(j,o,t,s,a),rt=Math.min(Math.max(x.resilience.hedgeDelayFloorMs,x.resilience.hedgeDelayFactor*z),.8*L);ue=setTimeout(()=>{if(ue=void 0,h||p?.aborted||Date.now()>=c)return;let J=i.filter(me=>j.isNodeHealthy(me,n));if(J.length===0)return;let I=J[Math.floor(Math.random()*J.length)];mr.trySpend()&&(O=true,l(I),H(I,true));},rt);})}var y=async(e,t=[],r,n=x.retry,o,i)=>{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=Dn(e),p=xt;if(p&&In&&p.methodSet.has(e))if(Date.now()=p.failureThreshold&&(Cn=Date.now()+p.cooldownMs,kt=0);}let l=Date.now()+x.resilience.totalBudgetFactor*a,d=new Set,m;for(let g=0;g<=n&&!(g>0&&Date.now()>=l);g++){let h=j.getOrderedNodes(x.nodes,c),P=h.find(F=>!d.has(F));P||(d.clear(),P=h[0]),d.add(P);let O=[];if(x.resilience.hedge&&j.getUsableLatencyMs(P,e)!==void 0&&(O=h.filter(F=>!d.has(F)&&j.isNodeHealthy(F,c)).slice(0,3)),O.length>0)try{return await gs({method:e,params:t,api:c,primary:P,hedgePool:O,callerTimeout:a,explicitTimeout:s,deadlineAt:l,externalSignal:o,onHedgeFired:F=>d.add(F),validate:i})}catch(F){if(F instanceof Z&&!lr(F.code,F.message)||o?.aborted)throw F;m=F,g{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 o=Dn(e),i=new Set,s;for(let a=0;a!i.has(l));if(!p)break;if(i.add(p),n?.aborted)throw new Error("Aborted");try{let l=await at(p,e,t,r,!1,n);return j.recordSuccess(p,o),l}catch(l){if(l instanceof Z||n?.aborted||(yr(j,p,l,o),s=l,!us(l)))throw l}}throw s},ys={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 te(e,t,r,n,o=x.retry,i){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,d=new Set,m,g=false;for(let h=0;h<=o&&!(h>0&&Date.now()>=c);h++){let P=ke.getOrderedNodes(l,e),O=P.find(I=>!d.has(I));O||(d.clear(),O=P[0]),d.add(O);let T=O+ys[e],F=t,ue=r||{},A=new Set;Object.entries(ue).forEach(([I,me])=>{F.includes(`{${I}}`)&&(F=F.replace(`{${I}}`,encodeURIComponent(String(me))),A.add(I));});let $=new URL(T+F);if(Object.entries(ue).forEach(([I,me])=>{A.has(I)||(Array.isArray(me)?me.forEach(nt=>$.searchParams.append(I,String(nt))):$.searchParams.set(I,String(me)));}),i?.aborted)throw new Error("Aborted");g=false;let{signal:N,cleanup:H}=hr(Tt(ke,O,p,a,s)),{signal:z,cleanup:L}=Ft(N,i),rt=()=>{H(),L();},J=Date.now();try{let I=await fetch($.toString(),{signal:z,headers:gr()});if(I.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(I.status===429)throw ke.recordRateLimit(O,qn(I.headers.get("Retry-After"))||void 0),g=!0,new Error(`HTTP 429 Rate Limited by ${O}`);if(I.status===503)throw ke.recordFailure(O,e),g=!0,new Error(`HTTP 503 Service Unavailable from ${O}`);if(!I.ok)throw ke.recordFailure(O,e),g=!0,new Error(`HTTP ${I.status} from ${O}`);return ke.recordSuccess(O,e,Date.now()-J,p),I.json()}catch(I){if(I?.message?.includes("HTTP 404")||i?.aborted)throw I;g||ke.recordFailure(O,e),ke.recordSlowFailure(O,Date.now()-J,p),m=I,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 i=(c=>{let p=[...c];for(let l=p.length-1;l>0;l--){let d=Math.floor(Math.random()*(l+1));[p[l],p[d]]=[p[d],p[l]];}return p})(x.nodes),s=Math.min(r,i.length),a=[];for(;s>0&&i.length>0;){let c=i.splice(0,s),p=[],l=[];for(let m=0;ml.push(g)).catch(()=>{}));await Promise.all(p),a.push(...l);let d=hs(a,r);if(d)return d;if(s=Math.min(r,i.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function hs(e,t){let r=new Map;for(let o of e){let i=JSON.stringify(o);r.has(i)||r.set(i,[]),r.get(i).push(o);}let n=Array.from(r.values()).find(o=>o.length>=t);return n?n[0]:null}var bs=utils_js.hexToBytes(x.chain_id),De=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 o of t){let i=o.sign(r);this.transaction.signatures.push(i.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 Le("condenser_api.broadcast_transaction",[this.transaction]);}catch(i){if(!(i instanceof Z&&i.message.includes("Duplicate transaction check failed")))throw i}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await ot(1e3);let n=await this.checkStatus(),o=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&o{let r=await y("condenser_api.get_dynamic_global_properties",[]),n=utils_js.hexToBytes(r.head_block_id),o=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),i=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:i,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:o,signatures:[]};}};var Ln=new Uint8Array([128]),U=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(As(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 o=0;o>6,128|i&63);else if(i>=55296&&i<=56319&&o+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else n.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(n);}return new e(sha2_js.sha256(t))}static fromLogin(t,r,n="active"){let o=t+n+r;return e.fromSeed(o)}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 Ee.from((n+31).toString(16)+utils_js.bytesToHex(r.subarray(1)))}createPublic(t){return new Y(secp256k1_js.secp256k1.getPublicKey(this.key),t)}toString(){return Ps(new Uint8Array([...Ln,...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)}},$n=e=>sha2_js.sha256(sha2_js.sha256(e)),Ps=e=>{let t=$n(e);return vn__default.default.encode(new Uint8Array([...e,...t.slice(0,4)]))},As=e=>{let t=vn__default.default.decode(e);if(!Vn(t.slice(0,1),Ln))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),o=$n(n).slice(0,4);if(!Vn(r,o))throw new Error("Private key checksum mismatch");return n},Vn=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;nJn(e,t,n,r),zn=(e,t,r,n,o)=>Jn(e,t,r,n,o).message,Jn=(e,t,r,n,o)=>{let i=r,s=e.getSharedSecret(t),a=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);a.writeUint64(i),a.append(s),a.flip();let c=sha2_js.sha512(new Uint8Array(a.toBuffer())),p=c.subarray(32,48),l=c.subarray(0,32),d=sha2_js.sha256(c).subarray(0,4),m=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);m.append(d),m.flip();let g=m.readUint32();if(o!==void 0){if(g!==o)throw new Error("Invalid key");n=Ss(n,l,p);}else n=ks(n,l,p);return {nonce:i,message:n,checksum:g}},Ss=(e,t,r)=>{let n=e;return n=aes_js.cbc(t,r).decrypt(n),n},ks=(e,t,r)=>{let n=e;return n=aes_js.cbc(t,r).encrypt(n),n},br=null,Cs=()=>{if(br===null){let r=secp256k1_js.secp256k1.utils.randomSecretKey();br=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++br%65536;return e=e<{let t=Ds(e,33);return new Y(t)},Ts=e=>e.readUint64(),Fs=e=>e.readUint32(),Is=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},qs=e=>t=>{let r={},n=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);n.append(t),n.flip();for(let[o,i]of e)try{r[o]=i(n);}catch(s){throw s.message=`${o}: ${s.message}`,s}return r};function Ds(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 Ks=qs([["from",Yn],["to",Yn],["nonce",Ts],["check",Fs],["encrypted",Is]]),Xn={Memo:Ks};var eo=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),ro(),e=no(e),t=Bs(t);let o=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);o.writeVString(r);let i=new Uint8Array(o.copy(0,o.offset).toBuffer()),{nonce:s,message:a,checksum:c}=Gn(e,t,i,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 "#"+vn__default.default.encode(l)},to=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),ro(),e=no(e);let r=Xn.Memo(vn__default.default.decode(t)),{from:n,to:o,nonce:i,check:s,encrypted:a}=r,p=e.createPublic().toString()===new Y(n.key).toString()?new Y(o.key):new Y(n.key);r=zn(e,p,i,a,s);let l=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},qt,ro=()=>{if(qt===void 0){let e;qt=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=eo(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=to(t,n);}finally{qt=e==="#memo\u7231";}}if(qt===false)throw new Error("This environment does not support encryption.")},no=e=>typeof e=="string"?U.fromString(e):e,Bs=e=>typeof e=="string"?Y.fromString(e):e,oo={decode:to,encode:eo};var ne={};vt(ne,{buildWitnessSetProperties:()=>Vs,makeBitMaskFilter:()=>Hs,operations:()=>Qs,validateUsername:()=>Ns});var Ns=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("."),o=n.length;for(let i=0;ie.reduce(Us,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),Us=([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 o;switch(n){case "key":case "new_signing_key":o=de.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":o=de.UInt32;break;case "hbd_interest_rate":o=de.UInt16;break;case "url":o=de.String;break;case "hbd_exchange_rate":o=de.Price;break;case "account_creation_fee":o=de.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,js(o,t[n])]);}return r.props.sort((n,o)=>n[0].localeCompare(o[0])),["witness_set_properties",r]},js=(e,t)=>{let r=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return e(r,t),r.flip(),utils_js.bytesToHex(new Uint8Array(r.toBuffer()))};function ug(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|o&63);else if(o>=55296&&o<=56319&&n+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else r.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(r);}else t=e;return sha2_js.sha256(t)}function io(e){try{return U.fromString(e),!0}catch{return false}}async function ee(e,t){let r=new De;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),Le("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function so(e,t){let r=new De;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var $s=432e3;function ao(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/$s,o=Math.round(n/e*1e4);return !isFinite(o)||o<0?o=0:o>1e4&&(o=1e4),{current_mana:n,max_mana:e,percentage:o}}function Ws(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),o=parseFloat(e.vesting_withdraw_rate),i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t-s-r+n}function wr(e){let t=Ws(e)*1e6;return ao(t,e.voting_manabar)}function Dt(e){return ao(Number(e.max_rc),e.rc_manabar)}var co=(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))(co||{});function $e(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",o=t||r||String(e||""),i=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||o&&a.test(o));if(i(/please wait to transact/i)||i(/insufficient rc/i)||i(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(i(/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(i(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(i(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(i(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(i(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(i(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(i(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(i(/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(i(/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(i(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(i(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(i(/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"||i(/token expired/i)||i(/invalid token/i)||i(/\bunauthorized\b/i)||i(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(i(/has already reblogged/i)||i(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(i(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(i(/econnrefused/i)||i(/connection refused/i)||i(/failed to fetch/i)||i(/\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(i(/timeout/i)||i(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(i(/account.*does not exist/i)||i(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(i(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(i(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(i(/\b(invalid|validation)\b/i))return {message:(e?.message||o).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}`:o&&o!=="[object Object]"?s=o.substring(0,150):s="Unknown error occurred":s=o.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function Gs(e){let t=$e(e);return [t.message,t.type]}function we(e){let{type:t}=$e(e);return t==="missing_authority"||t==="token_expired"}function zs(e){let{type:t}=$e(e);return t==="insufficient_resource_credits"}function Js(e){let{type:t}=$e(e);return t==="info"}function Ys(e){let{type:t}=$e(e);return t==="network"||t==="timeout"}async function ve(e,t,r,n,o="posting",i,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=i;if(p===void 0)switch(o){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 ${o} key available for ${t}`);let l=U.fromString(p);return a==="async"?await so(r,l):await ee(r,l)}case "hiveauth":{if(!c?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await c.broadcastWithHiveAuth(t,r,o)}case "hivesigner":{if(!c)throw new Error("No adapter provided for HiveSigner auth");if(o!=="posting"){if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);throw new Error(`HiveSigner access token cannot sign ${o} operations. No platform broadcast available.`)}let p=s!==void 0?s:await c.getAccessToken(t);if(p)try{return (await new uo__default.default.Client({accessToken:p}).broadcast(r)).result}catch(l){if(c.broadcastWithHiveSigner&&we(l))return await c.broadcastWithHiveSigner(t,r,o);throw l}if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);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,o)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,o)}default:throw new Error(`Unknown auth method: ${e}`)}}async function Zs(e,t,r,n="posting",o="async"){let i=r?.adapter;if(i?.getLoginType){let l=await i.getLoginType(e,n);if(l){let d=i.hasPostingAuthorization?await i.hasPostingAuthorization(e):false;if(n==="posting"&&d&&l==="key")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&d&&l==="keychain")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to keychain/snap:",m);}if(n==="posting"&&d&&l==="hiveauth")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await ve(l,e,t,r,n,void 0,void 0,o)}catch(m){if(we(m)&&i.showAuthUpgradeUI&&(n==="posting"||n==="active")){let g=t.length>0?t[0][0]:"unknown",h=await i.showAuthUpgradeUI(n,g);if(!h)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ve(h,e,t,r,n,void 0,void 0,o)}throw m}}if(n==="posting")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(d){if(we(d)&&i.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",g=await i.showAuthUpgradeUI(n,m);if(!g)throw new Error(`No login type available for ${e}. Please log in again.`);return await ve(g,e,t,r,n,void 0,void 0,o)}throw d}else if(n==="active"&&i.showAuthUpgradeUI){let d=t.length>0?t[0][0]:"unknown",m=await i.showAuthUpgradeUI(n,d);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ve(m,e,t,r,n,void 0,void 0,o)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let d=!1,m="",g,h;switch(l){case "key":if(!i)d=!0,m="No adapter provided";else {let P;switch(n){case "owner":i.getOwnerKey&&(P=await i.getOwnerKey(e));break;case "active":i.getActiveKey&&(P=await i.getActiveKey(e));break;case "memo":i.getMemoKey&&(P=await i.getMemoKey(e));break;default:P=await i.getPostingKey(e);break}P?g=P:(d=!0,m=`No ${n} key available`);}break;case "hiveauth":i?.broadcastWithHiveAuth||(d=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!i)d=!0,m="No adapter provided";else {let P=await i.getAccessToken(e);P&&(h=P);}break;case "keychain":i?.broadcastWithKeychain||(d=!0,m="Keychain not supported by adapter");break;case "custom":r?.broadcast||(d=!0,m="No custom broadcast function provided");break}if(d){a.set(l,new Error(`Skipped: ${m}`));continue}return await ve(l,e,t,r,n,g,h,o)}catch(d){if(a.set(l,d),!we(d))throw d}if(!Array.from(a.values()).some(l=>!l.message.startsWith("Skipped:"))){let l=Array.from(a.entries()).map(([d,m])=>`${d}: ${m.message}`).join(", ");throw new Error(`[SDK][Broadcast] No auth methods attempted for ${e}. ${l}`)}let p=Array.from(a.entries()).map(([l,d])=>`${l}: ${d.message}`).join(", ");throw new Error(`[SDK][Broadcast] All auth methods failed for ${e}. Errors: ${p}`)}function v(e=[],t,r,n=()=>{},o,i="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(o?.enableFallback!==!1&&o?.adapter)return await Zs(t,p,o,i,a);if(o?.broadcast)return await o.broadcast(p,i);let l=o?.postingKey;if(l){if(i!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${i}' was requested. Use AuthContextV2 with an adapter for ${i} operations.`);let m=U.fromString(l);return await ee(p,m)}let d=o?.accessToken;if(d)return (await new uo__default.default.Client({accessToken:d}).broadcast(p)).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}catch(l){throw l instanceof Z?new Error(l.message):l}}})}async function po(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let o={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",o]],"posting");let i=n?.postingKey;if(i){let c=U.fromString(i);return ee([["custom_json",o]],c)}let s=n?.accessToken;if(s)return (await new uo__default.default.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let c=[["custom_json",o]];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 xg=4e3;function E(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function Pe(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,o=()=>{let i=t.aborted?t.reason:r.reason;n.abort(i),t.removeEventListener("abort",o),r.removeEventListener("abort",o);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",o,{once:true}),r.addEventListener("abort",o,{once:true})),n.signal}var Ke=(()=>{try{return process.env?.NODE_ENV==="development"}catch{return false}})(),ra=()=>{try{return process.env?.VITE_HELIUS_API_KEY}catch{return}},Ae=1e4,lo=120*1e3,Kt,na;function oa(){return Kt?Kt():na??=new reactQuery.QueryClient}var f={privateApiHost:"https://ecency.com",defaultObserver:"ecency",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return x.nodes},heliusApiKey:ra(),get queryClient(){return oa()},set queryClient(e){Kt=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false};exports.ConfigManager=void 0;(ue=>{function e(A){f.queryClient=A;}ue.setQueryClient=e;function t(A){Kt=A;}ue.setQueryClientResolver=t;function r(A){f.privateApiHost=A;}ue.setPrivateApiHost=r;function n(A){f.clientId=A;}ue.setClientId=n;function o(A){if(typeof A!="string"||A.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.");f.defaultObserver=A;}ue.setDefaultObserver=o;function i(){return f.privateApiHost?f.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}ue.getValidatedBaseUrl=i;function s(A){f.pollsApiHost=A;}ue.setPollsApiHost=s;function a(A){f.imageHost=A;}ue.setImageHost=a;function c(A){or(A);}ue.setHiveNodes=c;function p(A){ir(A);}ue.setRestNodes=p;function l(A){sr(A);}ue.setRestNodesByApi=l;function d(A){ar(A);}ue.setUserAgent=d;function m(A){cr(A);}ue.setResilience=m;function g(A){rr(A);}ue.setServerRpcProxy=g;function h(){return Ce}ue.getServerRpcProxyStats=h;function P(A){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(A))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(A))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(A))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(A)||/\.\+\.\+/.test(A))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let $=/\.?\{(\d+),(\d+)\}/g,N;for(;(N=$.exec(A))!==null;){let[,H,z]=N;if(parseInt(z,10)-parseInt(H,10)>1e3)return {safe:false,reason:`excessive range: {${H},${z}}`}}return {safe:true}}function O(A){let $=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],N=5;for(let H of $){let z=Date.now();try{A.test(H);let L=Date.now()-z;if(L>N)return {safe:!1,reason:`runtime test exceeded ${N}ms (took ${L}ms on input length ${H.length})`}}catch(L){return {safe:false,reason:`runtime test threw error: ${L}`}}}return {safe:true}}function T(A,$=200){try{if(!A)return Ke&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(A.length>$)return Ke&&console.warn(`[SDK] DMCA pattern rejected: length ${A.length} exceeds max ${$} - pattern: ${A.substring(0,50)}...`),null;let N=P(A);if(!N.safe)return Ke&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${N.reason}) - pattern: ${A.substring(0,50)}...`),null;let H;try{H=new RegExp(A);}catch(L){return Ke&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${A.substring(0,50)}...`,L),null}let z=O(H);return z.safe?H:(Ke&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${z.reason}) - pattern: ${A.substring(0,50)}...`),null)}catch(N){return Ke&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${A.substring(0,50)}...`,N),null}}function F(A={}){let $=L=>Array.isArray(L)?L.filter(rt=>typeof rt=="string"):[],N=A||{},H={accounts:$(N.accounts),tags:$(N.tags),patterns:$(N.posts)};f.dmcaAccounts=H.accounts,f.dmcaTags=H.tags,f.dmcaPatterns=H.patterns,f.dmcaTagRegexes=H.tags.map(L=>T(L)).filter(L=>L!==null),f.dmcaPatternRegexes=[];let z=H.tags.length-f.dmcaTagRegexes.length;!f._dmcaInitialized&&Ke&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${H.accounts.length}`),console.log(` - Tag patterns: ${f.dmcaTagRegexes.length}/${H.tags.length} compiled (${z} rejected)`),console.log(` - Post patterns: ${H.patterns.length} (using exact string matching)`),z>0&&console.warn(`[SDK] ${z} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),f._dmcaInitialized=true;}ue.setDmcaLists=F;})(exports.ConfigManager||={});function Bg(){return new reactQuery.QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var w=()=>f.queryClient;exports.EcencyQueriesManager=void 0;(s=>{function e(a){return w().getQueryData(a)}s.getQueryData=e;function t(a){return w().getQueryData(a)}s.getInfiniteQueryData=t;async function r(a){return await w().prefetchQuery(a),e(a.queryKey)}s.prefetchQuery=r;async function n(a){return await w().prefetchInfiniteQuery(a),t(a.queryKey)}s.prefetchInfiniteQuery=n;function o(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>reactQuery.useQuery(a),fetchAndGet:()=>w().fetchQuery(a)}}s.generateClientServerQuery=o;function i(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>reactQuery.useInfiniteQuery(a),fetchAndGet:()=>w().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=i;})(exports.EcencyQueriesManager||={});function Ng(e){return btoa(JSON.stringify(e))}function Qg(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var fo=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(fo||{}),Bt=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(Bt||{});function k(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:fo[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:Bt[e.nai]}}var vr;function _(){if(!vr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");vr=globalThis.fetch.bind(globalThis);}return vr}function mo(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function ua(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function se(e,t){return ua(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function We(e,t){return e/1e6*t}function go(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var yo=60*1e3;function Oe(){return reactQuery.queryOptions({queryKey:u.core.dynamicProps(),refetchInterval:yo,staleTime:yo,queryFn:async({signal:e})=>{let[t,r,n,o,i]=await Promise.all([y("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),y("condenser_api.get_feed_history",[],void 0,void 0,e),y("condenser_api.get_chain_properties",[],void 0,void 0,e),y("condenser_api.get_reward_fund",["post"],void 0,void 0,e),y("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=k(t.total_vesting_shares).amount,a=k(t.total_vesting_fund_hive).amount,c=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(c=a/s*1e6);let p=k(r.current_median_history.base).amount,l=k(r.current_median_history.quote).amount,d=parseFloat(o.recent_claims),m=k(o.reward_balance).amount,g=Number(t.vote_power_reserve_rate??0),h=o.author_reward_curve??"linear",P=Number(o.content_constant??0),O=String(i.current_hardfork_version??"0.0.0"),T=Number(i.last_hardfork??0),F=t.hbd_print_rate,ue=t.hbd_interest_rate,A=t.head_block_number,$=a,N=s,H=k(t.virtual_supply).amount,z=t.vesting_reward_percent||0,L=n.account_creation_fee;return {hivePerMVests:c,base:p,quote:l,fundRecentClaims:d,fundRewardBalance:m,votePowerReserveRate:g,authorRewardCurve:h,contentConstant:P,currentHardforkVersion:O,lastHardfork:T,hbdPrintRate:F,hbdInterestRate:ue,headBlock:A,totalVestingFund:$,totalVestingShares:N,virtualSupply:H,vestingRewardPercent:z,accountCreationFee:L,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:o,hardforkProps:i}}}})}function ry(e="post"){return reactQuery.queryOptions({queryKey:u.core.rewardFund(e),queryFn:()=>y("condenser_api.get_reward_fund",[e])})}function Be(...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,o,i)=>["posts","account-posts-page",e,t,r,n,o,i],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)=>Be("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>Be("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>Be("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>Be("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,o,i)=>["posts","posts-ranked-page",e,t,r,n,o,i],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)=>Be("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)=>Be("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,o,i)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,o,i],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,o,i)=>Be("search","api",e,t,r,n,o,i)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,o)=>["witnesses","voters",e,t,r,n,o],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 ut(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 cy(e){return reactQuery.queryOptions({queryKey:u.ai.prices(),queryFn:async()=>{let r=await _()(f.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 dy(e,t){return reactQuery.queryOptions({queryKey:u.ai.assistPrices(e),queryFn:async()=>{let n=await _()(f.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 yy(e,t){return reactQuery.queryOptions({queryKey:u.ai.transcribePrice(e),queryFn:async()=>{let n=await _()(f.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 ya(){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 wy(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 o=await _()(f.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??ya()})});if(!o.ok){let s=await o.text(),a={};try{a=JSON.parse(s);}catch{}let c=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${o.status}${s?`: ${s}`:""}`);throw c.status=o.status,c.data=a,c}if(o.status===202){let s={};try{s=await o.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await o.json()},onSuccess:()=>{e&&w().invalidateQueries({queryKey:u.points._prefix(e)});}})}function _a(){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 Oy(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 o=await _()(f.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:_a()})});if(!o.ok){let i=await o.text(),s={};try{s=JSON.parse(i);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${o.status}${i?`: ${i}`:""}`);throw a.status=o.status,a.data=s,a}return await o.json()},onSuccess:r=>{e&&(r.cost>0&&w().invalidateQueries({queryKey:u.points._prefix(e)}),w().invalidateQueries({queryKey:u.ai.assistPrices(e)}));}})}function wa(){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 ky(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 o=new FormData;o.append("code",n),o.append("duration_ms",String(Math.round(r.durationMs))),o.append("idempotency_key",r.idempotency_key??wa()),o.append("audio",r.audio,r.fileName??"clip.webm");let s=await _()(f.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:o});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&&w().invalidateQueries({queryKey:u.points._prefix(e)}),w().invalidateQueries({queryKey:u.ai.transcribePrice(e)}));}})}function Pr(e){return !e.posting_json_metadata&&!e.json_metadata}function Pa(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([y("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),y("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 o=r[0];if(Pr(o)&&Pa(n?.metadata?.profile)){let p=await y("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]))o=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let i=Me(o.posting_json_metadata),s=n?.stats,a=s?{account:o.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,c=n?.reputation??0;return {name:o.name,owner:o.owner,active:o.active,posting:o.posting,memo_key:o.memo_key,post_count:o.post_count,created:o.created,posting_json_metadata:o.posting_json_metadata,last_vote_time:o.last_vote_time,last_post:o.last_post,json_metadata:o.json_metadata,reward_hive_balance:o.reward_hive_balance,reward_hbd_balance:o.reward_hbd_balance,reward_vesting_hive:o.reward_vesting_hive,reward_vesting_balance:o.reward_vesting_balance,balance:o.balance,hbd_balance:o.hbd_balance,savings_balance:o.savings_balance,savings_hbd_balance:o.savings_hbd_balance,savings_hbd_last_interest_payment:o.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:o.savings_hbd_seconds_last_update,savings_hbd_seconds:o.savings_hbd_seconds,next_vesting_withdrawal:o.next_vesting_withdrawal,pending_claimed_accounts:o.pending_claimed_accounts,vesting_shares:o.vesting_shares,delegated_vesting_shares:o.delegated_vesting_shares,received_vesting_shares:o.received_vesting_shares,vesting_withdraw_rate:o.vesting_withdraw_rate,to_withdraw:o.to_withdraw,withdrawn:o.withdrawn,witness_votes:o.witness_votes,proxy:o.proxy,recovery_account:o.recovery_account,proxied_vsf_votes:o.proxied_vsf_votes,voting_manabar:o.voting_manabar,voting_power:o.voting_power,downvote_manabar:o.downvote_manabar,follow_stats:a,reputation:c,profile:i}},enabled:!!e,staleTime:6e4})}var Aa=new Set(["__proto__","constructor","prototype"]);function Mt(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ho(e,t){let r={...e};for(let n of Object.keys(t)){if(Aa.has(n))continue;let o=t[n],i=r[n];Mt(o)&&Mt(i)?r[n]=ho(i,o):r[n]=o;}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:o,...i}=t;return {...r,meta:i}})}function Me(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 _o(e){return Me(e?.posting_json_metadata)}function bo(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(Me(e.posting_json_metadata)).length;return Object.keys(Me(t.posting_json_metadata)).length>r?t:e}function xa(e){if(!e)return {};try{let t=JSON.parse(e);if(Mt(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function wo({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=xa(e),o=Mt(n.profile)?n.profile:{},i=Ar({existingProfile:o,profile:t,tokens:r});return JSON.stringify({...n,profile:i})}function Ar({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:o,...i}=t??{},s=ho(e??{},i);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 Nt(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=Me(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let o=JSON.parse(t.json_metadata||"{}");o.profile&&(n=o.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function Ea(e){return new TextEncoder().encode(e).length}function Ge(e){return e?Ea(e)<=16:false}function jy(e){return reactQuery.queryOptions({queryKey:u.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(Ge);if(t.length===0)return [];let r=await y("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return Nt(r??[])}})}function zy(e){return reactQuery.queryOptions({queryKey:u.accounts.followCount(e),queryFn:()=>y("condenser_api.get_follow_count",[e])})}function eh(e,t,r="blog",n=100){return reactQuery.queryOptions({queryKey:u.accounts.followers(e,t,r,n),queryFn:()=>y("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function ih(e,t,r="blog",n=100){return reactQuery.queryOptions({queryKey:u.accounts.following(e,t,r,n),queryFn:()=>y("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var vo=1e3,Fa=20;function ph(e){return reactQuery.queryOptions({queryKey:u.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(i[0]===r&&(i=i.slice(1)),!i.length||(t.push(...i),o.lengthGe(e)?y("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function vh(e,t=5,r=[]){return reactQuery.queryOptions({queryKey:u.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await y("condenser_api.lookup_accounts",[e,t])).filter(o=>r.length>0?!r.includes(o):true)})}var Ka=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function xh(e,t){return reactQuery.queryOptions({queryKey:u.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await _()(f.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 o=await n.json(),i=Array.isArray(o)?o.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={},d=typeof a.address=="string"&&a.address?a.address:void 0,g=(typeof a.status=="number"?a.status===3:void 0)??false;d&&(l.address=d),l.show=g;let h={symbol:c,currency:c,address:d,show:g,type:"CHAIN",meta:l},P=[];for(let[O,T]of Object.entries(p))typeof O=="string"&&(Ka.has(O)||typeof T!="string"||!T||/^[A-Z0-9]{2,10}$/.test(O)&&P.push({symbol:O,currency:O,address:T,show:g,type:"CHAIN",meta:{address:T,show:g}}));return [h,...P]}):[];return {exist:i.length>0,tokens:i.length?i:void 0,wallets:i.length?i:void 0}},refetchOnMount:true})}function Po(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 y("bridge.get_relationship_between_accounts",[e,t])??r}})}function qh(e){return reactQuery.queryOptions({queryKey:u.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await y("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function Mh(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 _()(f.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Nh(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 i=await _()(`${f.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch bookmarks: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Vh(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 _()(f.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function jh(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 i=await _()(`${f.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch favorites: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Gh(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 o=await _()(f.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!o.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${o.status}: ${o.statusText}`);let i=await o.json();if(typeof i!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof i}`);return i}})}function Xh(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 _()(f.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function n_(e){return reactQuery.queryOptions({enabled:!!e,queryKey:u.accounts.pendingRecovery(e),queryFn:()=>y("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function u_(e,t=50){return reactQuery.queryOptions({queryKey:u.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!Ge(e)?[]:y("condenser_api.get_account_reputations",[e,t])})}var K=ne.operations,Ao={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]},Ga=Array.from(new Set(Object.values(Ao).flat()));function za(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function Ja(e){return e.replace(/_operation$/,"")}function Ya(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function Xa(e){if(!Ya(e))return e;let t=k(e),r=Bt[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function Za(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Xa(n);return t}function h_(e,t=20,r=""){let n=r?Ao[r]:Ga;return reactQuery.infiniteQueryOptions({queryKey:u.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:o,signal:i})=>{if(!e)return {entries:[],currentPage:0};let s=async d=>{let m={"account-name":e,"operation-types":n.join(","),"page-size":t};return d!==null&&(m.page=d),await te("hafah","/accounts/{account-name}/operations",m,void 0,void 0,i)},a=d=>d.operations_result.map(m=>{let g=Ja(m.op.type);return {...Za(m.op.value),num:za(m),type:g,timestamp:m.timestamp,trx_id:m.trx_id}}),c=await s(o),p=a(c),l=o??c.total_pages;if(o===null&&p.length1)try{let d=await s(c.total_pages-1);p=[...p,...a(d)],l=c.total_pages-1;}catch(d){if(i?.aborted)throw d}return {entries:p,currentPage:l}},getNextPageParam:o=>{let i=o.currentPage-1;return i>=1?i:void 0}})}function v_(){return reactQuery.queryOptions({queryKey:u.accounts.bots(),queryFn:async()=>{let e=await fetch(f.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 x_(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(),o=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&o.searchParams.set("max_id",r.toString());let i=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch referrals: ${i.status}`);return i.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function C_(e){return reactQuery.queryOptions({queryKey:u.accounts.referralsStats(e),queryFn:async()=>{let t=await fetch(f.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 D_(e,t,r){let{followType:n="blog",limit:o=100,enabled:i=true}=r??{};return reactQuery.infiniteQueryOptions({queryKey:u.accounts.friends(e,t,n,o),initialPageParam:{startFollowing:""},enabled:i,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await y(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,o])).map(g=>t==="following"?g.following:g.follower);return (await y("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(g=>({name:g.name,reputation:g.reputation,active:g.active}))},getNextPageParam:s=>s&&s.length===o?{startFollowing:s[s.length-1].name}:void 0})}var ic=30;function Q_(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 y(`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,ic);return (await y("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 L_(e=20){return reactQuery.infiniteQueryOptions({queryKey:u.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>y("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 Y_(e=250){return reactQuery.infiniteQueryOptions({queryKey:u.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>y("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!mo(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function ze(e,t){return reactQuery.queryOptions({queryKey:u.posts.fragments(e),queryFn:async()=>t?(await _()(f.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function tb(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 i=await _()(`${f.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch fragments: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function ib(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 _()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function pb(e){return reactQuery.queryOptions({queryKey:u.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>y("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function gb(e,t,r){return reactQuery.queryOptions({queryKey:u.posts.userPostVote(e,t,r),queryFn:async()=>(await y("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function wb(e,t){return reactQuery.queryOptions({queryKey:u.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content",[e,t])})}function xb(e,t){return reactQuery.queryOptions({queryKey:u.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content_replies",{author:e,permlink:t})})}function Rb(e,t){return reactQuery.queryOptions({queryKey:u.posts.postHeader(e,t),queryFn:async()=>y("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function re(e){return Array.isArray(e)?e.map(t=>Oo(t)):Oo(e)}function Oo(e){if(!e)return e;let t=`@${e.author}/${e.permlink}`;return f.dmcaPatterns.includes(t)||f.dmcaPatternRegexes.some(n=>n.test(t))?{...e,body:"This post is not available due to a copyright/fraudulent claim.",title:""}:e}async function xo(e,t,r){try{let n=await It("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 Eo(e,t,r="",n){let o=t?.trim(),i=`/@${e}/${o??""}`;return reactQuery.queryOptions({queryKey:u.posts.entry(i),queryFn:async()=>{if(!o||o==="undefined")return null;let s=await y("bridge.get_post",{author:e,permlink:o,observer:r});if(!s){let c=await xo(e,o,r);if(!c)return null;let p=n!==void 0?{...c,num:n}:c;return re(p)}let a=n!==void 0?{...s,num:n}:s;return re(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function ae(e,t,r){return y(`bridge.${e}`,t,void 0,void 0,r)}async function So(e,t,r,n){let{json_metadata:o}=e;if(o?.original_author&&o?.original_permlink&&o.tags?.[0]==="cross-post")try{let i=await hc(o.original_author,o.original_permlink,t,r,n);return i?{...e,original_entry:i,num:r}:e}catch{return e}return {...e,num:r}}async function ko(e,t,r){let n=e.map(pt),o=await Promise.all(n.map(i=>So(i,t,void 0,r)));return re(o)}async function Co(e,t="",r="",n=20,o="",i="",s){let a=await ae("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:o,observer:i},s);return Array.isArray(a)?ko(a,i,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 Or(e,t,r="",n="",o=20,i="",s){if(f.dmcaAccounts.includes(t))return [];let a=await ae("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:o,observer:i},s);return Array.isArray(a)?ko(a,i,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 pt(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 hc(e="",t="",r="",n,o){let i=await ae("get_post",{author:e,permlink:t,observer:r},o);if(i){let s=pt(i),a=await So(s,r,n,o);return re(a)}}async function Lb(e="",t=""){let r=await ae("get_post_header",{author:e,permlink:t});return r&&pt(r)}async function Ro(e,t,r){let n=await ae("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let o={};for(let[i,s]of Object.entries(n))o[i]=pt(s);return o}return n}async function To(e,t=""){return ae("get_community",{name:e,observer:t})}async function $b(e="",t=100,r,n="rank",o=""){return ae("list_communities",{last:e,limit:t,query:r,sort:n,observer:o})}async function Fo(e){let t=await ae("normalize_post",{post:e});return t&&pt(t)}async function Wb(e){return ae("list_all_subscriptions",{account:e})}async function Gb(e){return ae("list_subscribers",{community:e})}async function zb(e,t){return ae("get_relationship_between_accounts",[e,t])}async function Qt(e,t){return ae("get_profiles",{accounts:e,observer:t})}var qo=(o=>(o.trending="trending",o.author_reputation="author_reputation",o.votes="votes",o.created="created",o))(qo||{});function xr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function _c(e,t,r){let n=l=>xr(l.pending_payout_value).amount+xr(l.author_payout_value).amount+xr(l.curator_payout_value).amount,o=l=>l.net_rshares<0,i=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,d)=>{if(o(l))return 1;if(o(d))return -1;let m=n(l),g=n(d);return m!==g?g-m:0},author_reputation:(l,d)=>{let m=l.author_reputation,g=d.author_reputation;return m>g?-1:m{let m=l.children,g=d.children;return m>g?-1:m{if(o(l))return 1;if(o(d))return -1;let m=Date.parse(l.created),g=Date.parse(d.created);return m>g?-1:mi(l)),p=a[c];return c>=0&&(a.splice(c,1),a.unshift(p)),a}function Do(e,t="created",r=true,n){let o=n||f.defaultObserver;return reactQuery.queryOptions({queryKey:u.posts.discussions(e?.author,e?.permlink,t,o),queryFn:async()=>{if(!e)return [];let i=await y("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:o}),s=i?Array.from(Object.values(i)):[];return re(s)},enabled:r&&!!e,select:i=>_c(e,i,t),structuralSharing:(i,s)=>{if(!i||!s)return s;let a=i.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 rw(e,t,r,n=true){let o=r||f.defaultObserver;return reactQuery.queryOptions({queryKey:u.posts.discussion(e,t,o),enabled:n&&!!e&&!!t,queryFn:async()=>Ro(e,t,o)})}function uw(e,t="posts",r=20,n="",o=true){return reactQuery.infiniteQueryOptions({queryKey:u.posts.accountPosts(e??"",t,r,n),enabled:!!e&&o,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:i,signal:s})=>{if(!i?.hasNextPage||!e)return [];let a=await Or(t,e,i.author??"",i.permlink??"",r,n,s);return re(a??[])},getNextPageParam:i=>{let s=i?.[i.length-1],a=(i?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function pw(e,t="posts",r="",n="",o=20,i="",s=true){return reactQuery.queryOptions({queryKey:u.posts.accountPostsPage(e??"",t,r,n,o,i),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let c=await Or(t,e,r,n,o,i,a);return re(c??[])}})}var Ko=new Map;function Ac(e){let t=Ko.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>Oc(n,e))}),Ko.set(e,t)),t}function Oc(e,t){let r=e.filter(i=>i.stats?.is_pinned),n=e.filter(i=>!i.stats?.is_pinned);if(t==="hot")return [...r,...n];let o=[...n].sort((i,s)=>new Date(s.created).getTime()-new Date(i.created).getTime());return [...r,...o]}function _w(e,t,r=20,n="",o=true,i={}){return reactQuery.infiniteQueryOptions({queryKey:u.posts.postsRanked(e,t,r,n),queryFn:async({pageParam:s,signal:a})=>{let c=t;f.dmcaTagRegexes.some(l=>l.test(t))&&(c="");let p=await y("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 re(p)},select:Ac(e),enabled:o,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 bw(e,t="",r="",n=20,o="",i="",s=true){return reactQuery.queryOptions({queryKey:u.posts.postsRankedPage(e,t,r,n,o,i),enabled:s,queryFn:async({signal:a}={})=>{let c=o;f.dmcaTagRegexes.some(l=>l.test(o))&&(c="");let p=await Co(e,t,r,n,c,i,a);return re(p??[])}})}function Ow(e,t,r=200){return reactQuery.queryOptions({queryKey:u.posts.reblogs(e??"",r),queryFn:async()=>(await y("condenser_api.get_blog_entries",[e??t,0,r])).filter(o=>o.author!==t&&!o.reblogged_on.startsWith("1970-")).map(o=>({author:o.author,permlink:o.permlink})),enabled:!!e})}function Cw(e,t){return reactQuery.queryOptions({queryKey:u.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await y("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function Iw(e,t){return reactQuery.queryOptions({queryKey:u.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(f.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 qw(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 i=await _()(`${f.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch schedules: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Mw(e,t){return reactQuery.queryOptions({queryKey:u.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(f.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 Nw(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 i=await _()(`${f.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch drafts: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function Mo(e){let r=await _()(f.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 Vw(e,t){return reactQuery.queryOptions({queryKey:u.posts.images(e),queryFn:async()=>!e||!t?[]:Mo(t),enabled:!!e&&!!t})}function jw(e,t){return reactQuery.queryOptions({queryKey:u.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:Mo(t),enabled:!!e&&!!t})}function Lw(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 i=await _()(`${f.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch images: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function zw(e,t,r=false){return reactQuery.queryOptions({queryKey:u.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let o=await fetch(f.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(!o.ok)throw new Error(`Failed to fetch comment history: ${o.status}`);return o.json()},enabled:!!e&&!!t})}function qc(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let o=r.replace(/^@+/,""),i=n.replace(/^\/+/,"");if(!o||!i)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${o}/${i}`}function Zw(e,t){let r=t?.trim(),n=e?.trim(),o=!!n&&!!r&&r!=="undefined",i=o?qc(n,r):"";return reactQuery.queryOptions({queryKey:u.posts.deletedEntry(i),queryFn:async({signal:s})=>{let a=await fetch(f.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:o})}function nv(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)}`,o=await fetch(f.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch post tips: ${o.status}`);return o.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function Kc(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function Bc(e){return {...e,id:e.id??e.post_id}}function he(e,t){if(!e)return null;let r=e.container??e,n=Kc(r,t),o=e.parent?Bc(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:o}}function Mc(e){return Array.isArray(e)?e:[]}async function No(e){let t=Do(e,"created",true),r=await f.queryClient.fetchQuery(t),n=Mc(r);if(n.length<=1)return [];let o=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return o.length===0?[]:o.filter(s=>!s.stats?.gray)}function Qo(e,t,r){return e.length===0?[]:e.map(n=>{let o=e.find(i=>i.author===n.parent_author&&i.permlink===n.parent_permlink&&i.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:o}}).filter(n=>n.container.post_id!==n.post_id).sort((n,o)=>new Date(o.created).getTime()-new Date(n.created).getTime())}var Hc=20;function Ho(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??Hc}}async function Uo({containers:e,tag:t,following:r,author:n,observer:o,limit:i},s,a){let c=exports.ConfigManager.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",c);p.searchParams.set("limit",String(i)),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),o&&p.searchParams.set("observer",o);let l=await fetch(p.toString(),{method:"GET",signal:a});if(!l.ok)throw new Error(`Failed to fetch waves feed: ${l.status}`);let d=await l.json();return !Array.isArray(d)||d.length===0?[]:d.map(m=>{let g=he(m,m.host??"");return g?{...g,_cursor:m._cursor}:null}).filter(m=>!!m)}function lv(e={}){let t=Ho(e),{containers:r,tag:n,following:o,author:i,observer:s,limit:a}=t;return reactQuery.infiniteQueryOptions({queryKey:u.posts.wavesFeed({containers:r,tag:n,following:o,author:i,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:c,signal:p})=>Uo(t,c,p),getNextPageParam:c=>{if(!(c.lengthUo(t,void 0,c)})}var Vc=20;function jc(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??Vc}}async function Lc({containers:e,tag:t,author:r,observer:n,limit:o},i,s){let a=exports.ConfigManager.getValidatedBaseUrl(),c=new URL("/private-api/waves/shorts",a);c.searchParams.set("limit",String(o)),i&&c.searchParams.set("cursor",i),e.forEach(d=>c.searchParams.append("container",d)),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(d=>{let m=he(d,d.host??"");return m?{...m,active_votes:m.active_votes??[],video:d.video,_cursor:d._cursor}:null}).filter(d=>!!d)}function hv(e={}){let t=jc(e),{containers:r,tag:n,author:o,observer:i,limit:s}=t;return reactQuery.infiniteQueryOptions({queryKey:u.posts.shortsFeed({containers:r,tag:n,author:o,observer:i,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:c})=>Lc(t,a,c),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of c){if(i&&l.post_id===i){i=void 0;continue}if(o+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let d;try{d=await No(l);}catch(m){console.error("[SDK] getThreads get_discussion error:",m),r=l.author,n=l.permlink;continue}if(d.length===0){r=l.author,n=l.permlink;continue}return {entries:Qo(d,l,e)}}let p=c[c.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function Ov(e){return reactQuery.infiniteQueryOptions({queryKey:u.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await zc(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var Yc=40;function Cv(e,t,r=Yc){return reactQuery.infiniteQueryOptions({queryKey:u.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let o=exports.ConfigManager.getValidatedBaseUrl(),i=new URL("/private-api/waves/tags",o);i.searchParams.set("container",e),i.searchParams.set("tag",t);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves by tag",o),[]}},getNextPageParam:()=>{}})}function qv(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 o=exports.ConfigManager.getValidatedBaseUrl(),i=new URL("/private-api/waves/following",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves following feed",o),[]}},getNextPageParam:()=>{}})}function Mv(e,t=24){let r=e?.trim()||void 0;return reactQuery.queryOptions({queryKey:u.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let o=exports.ConfigManager.getValidatedBaseUrl(),i=new URL("/private-api/waves/trending/tags",o);r&&i.searchParams.set("container",r),i.searchParams.set("hours",t.toString());let s=await fetch(i.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(o){return console.error("[SDK] Failed to fetch waves trending tags",o),[]}}})}function Vv(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 o=exports.ConfigManager.getValidatedBaseUrl(),i=new URL("/private-api/waves/account",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){throw console.error("[SDK] Failed to fetch waves for account",o),o}},getNextPageParam:()=>{}})}function Wv(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 o=await fetch(n.toString(),{method:"GET",signal:t});if(!o.ok)throw new Error(`Failed to fetch waves trending authors: ${o.status}`);return (await o.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 Xv(e,t=true){return reactQuery.queryOptions({queryKey:u.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>Fo(e)})}function ou(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Vo(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function s0(e,t){let{limit:r=20,filters:n=[],dayLimit:o=7}=t??{};return reactQuery.infiniteQueryOptions({queryKey:u.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:i})=>{let{start:s}=i,a=await y("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,g])=>({...g.op[1],num:m,timestamp:g.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Vo(m.timestamp)<=o),l=[];for(let m of p){let g=await f.queryClient.fetchQuery(Eo(m.author,m.permlink));ou(g)&&l.push(g);}let[d]=a;return {lastDate:d?Vo(d[1].timestamp):0,lastItemFetched:d?d[0]:s,entries:l}},getNextPageParam:i=>({start:i.lastItemFetched})})}function l0(e,t,r=true){return reactQuery.queryOptions({queryKey:u.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Qt(e,t)})}function h0(e,t="HIVE",r=200){return reactQuery.infiniteQueryOptions({queryKey:u.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:o})=>{if(!e)return {entries:[],currentPage:0};let i={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(i.page=n);let s=await te("balance","/accounts/{account-name}/balance-history",i,void 0,void 0,o);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let o=n.currentPage-1;return o>=1?o:void 0},enabled:!!e})}function P0(e,t="HIVE",r="yearly"){return reactQuery.queryOptions({queryKey:u.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await te("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function E0(){return reactQuery.queryOptions({queryKey:u.accounts.proMembers(),queryFn:async()=>{let e=await fetch(f.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 S0(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function I0(e,t,r){let n=reactQuery.useQueryClient(),{data:o}=reactQuery.useQuery(M(e));return v(["accounts","update"],e,i=>{let s=bo(n.getQueryData(M(e).queryKey),o);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:wo({existingPostingJsonMetadata:s.posting_json_metadata,profile:i.profile,tokens:i.tokens})}]]},async(i,s)=>{n.setQueryData(M(e).queryKey,a=>{if(!a)return a;let c=JSON.parse(JSON.stringify(a));return c.profile=Ar({existingProfile:_o(a),profile:s.profile,tokens:s.tokens}),c}),await E(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 M0(e,t,r,n,o){return reactQuery.useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async i=>{let s=Po(e,t);await w().prefetchQuery(s);let a=w().getQueryData(s.queryKey);return await po(e,"follow",["follow",{follower:e,following:t,what:[...i==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...i==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:i==="toggle-ignore"?!a?.ignores:a?.ignores,follows:i==="toggle-follow"?!a?.follows:a?.follows}},onError:o,onSuccess(i){n(i),w().setQueryData(u.accounts.relations(e,t),i),t&&w().invalidateQueries(M(t));}})}function Er(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,o,i,s){if(!e||!t||n===void 0||!i)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:o,body:i,json_metadata:JSON.stringify(s)}]}function Qe(e,t,r,n,o,i,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:o,allow_curation_rewards:i,extensions:s}]}function Sr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function kr(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let o={account:e,author:t,permlink:r};return n&&(o.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",o]),required_auths:[],required_posting_auths:[e]}]}function He(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 du(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(i=>He(e,i.trim(),r,n))}function fu(e,t,r,n,o,i){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(o<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:o,executions:i,extensions:[]}]}function Je(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 Ue(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:o}]}function jo(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 lt(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [Ue(e,t,r,n,o),jo(e,o)]}function dt(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 ft(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function mt(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 gt(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 yt(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 Cr(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 Ve(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 Rr(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function Tr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(o=>o.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 Fr(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 Ht(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 mu(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 Ht(e,t)}function Ir(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]}],o=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,o]}function qr(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 Dr(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 Br(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 yu(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 hu(e,t,r,n,o){if(e==null||typeof e!="number"||!t||!r||!n||!o)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:o,extensions:[]}]}function Mr(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 Nr(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 Qr(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 Hr(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 Ur(e,t,r,n,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function Vr(e,t,r,n,o,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:o}]),required_auths:[],required_posting_auths:[e]}]}function _u(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function bu(e,t,r,n,o){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:o}]),required_auths:[],required_posting_auths:[e]}]}var Lo=(r=>(r.Buy="buy",r.Sell="sell",r))(Lo||{}),$o=(r=>(r.EMPTY="",r.SWAP="9",r))($o||{});function Vt(e,t,r,n,o,i){if(!e||!t||!r||!o||i===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:i,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:o}]}function Ut(e,t=3){return e.toFixed(t)}function wu(e,t,r,n,o=""){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 i=new Date(Date.now());i.setDate(i.getDate()+27);let s=i.toISOString().split(".")[0],a=+`${o}${Math.floor(Date.now()/1e3).toString().slice(2)}`,c=n==="buy"?`${Ut(t,3)} HBD`:`${Ut(t,3)} HIVE`,p=n==="buy"?`${Ut(r,3)} HIVE`:`${Ut(r,3)} HBD`;return Vt(e,c,p,false,s,a)}function jr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function Lr(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 vu(e,t,r,n,o,i){if(!e||!o)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:o,json_metadata:i}]}function Pu(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 $r(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let o={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={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:o,active:i,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Wr(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]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},i={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:o,posting:i,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Gr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function zr(e,t,r,n,o,i){if(!e||!t||!r||!o)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:o,json_metadata:i}]}function Au(e,t,r,n,o){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let i={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:i,memo_key:n,json_metadata:o}]}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 xu(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 Eu(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 Yr(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 Xr(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 Ye(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let o=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:o,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function Su(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let o=t.trim().split(/[\s,]+/).filter(Boolean);if(o.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return o.map(i=>Ye(e,i.trim(),r,n))}function Zr(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 ku(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 Cu(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 iP(e,t,r){return v(["accounts","follow"],e,({following:n})=>[Fr(e,n)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function uP(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[Ht(e,n)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function fP(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:o,permlink:i})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(f.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:o,permlink:i,code:t})})).json()},onSuccess:()=>{r(),w().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function hP(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(f.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:o,code:t})})).json()},onSuccess:()=>{r(),w().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function vP(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await _()(f.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})})).json()},onSuccess:(o,i)=>{r();let s=w();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,i)});},onError:n})}function EP(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await _()(f.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async o=>{if(!e)return;let i=w(),s=u.accounts.favorites(e),a=u.accounts.favoritesInfinite(e),c=u.accounts.checkFavorite(e,o);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a}),i.cancelQueries({queryKey:c})]);let p=i.getQueryData(s);p&&i.setQueryData(s,p.filter(g=>g.account!==o));let l=i.getQueryData(c);i.setQueryData(c,false);let d=i.getQueriesData({queryKey:a}),m=new Map(d);for(let[g,h]of d)h&&i.setQueryData(g,{...h,pages:h.pages.map(P=>({...P,data:P.data.filter(O=>O.account!==o)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(o,i)=>{r();let s=w();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,i)});},onError:(o,i,s)=>{let a=w();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,i),s.previousCheck),n(o);}})}function Ku(e,t){let r=new Map;return e.forEach(([n,o])=>{r.set(n.toString(),o);}),t.forEach(([n,o])=>{r.set(n.toString(),o);}),Array.from(r.entries()).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>[n,o])}function Wo(e,t){let{data:r}=reactQuery.useQuery(M(e));return reactQuery.useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:o=false,currentKey:i,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:[]],g=o?l.key_auths.filter(([h])=>!m.includes(h.toString())):[];return l.key_auths=Ku(g,n.map((h,P)=>[h[p].createPublic().toString(),P+1])),l};return ee([["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()}]],i)},...t})}function KP(e,t){let{data:r}=reactQuery.useQuery(M(e)),{mutateAsync:n}=Wo(e);return reactQuery.useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:o,currentPassword:i,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=U.fromLogin(e,i,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:U.fromLogin(e,o,"owner"),active:U.fromLogin(e,o,"active"),posting:U.fromLogin(e,o,"posting"),memo_key:U.fromLogin(e,o,"memo")}]})},...t})}function UP(e,t,r){let n=reactQuery.useQueryClient(),{data:o}=reactQuery.useQuery(M(e));return reactQuery.useMutation({mutationKey:["accounts","revoke-posting",o?.name],mutationFn:async({accountName:i,type:s,key:a})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let c=JSON.parse(JSON.stringify(o.posting));c.account_auths=c.account_auths.filter(([l])=>l!==i);let p={account:o.name,posting:c,memo_key:o.memo_key,json_metadata:o.json_metadata};if(s==="key"&&a)return ee([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(o.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."),uo__default.default.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(i,s,a)=>{t.onSuccess?.(i,s,a),n.setQueryData(M(e).queryKey,c=>({...c,posting:{...c?.posting,account_auths:c?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function zP(e,t,r,n){let{data:o}=reactQuery.useQuery(M(e));return reactQuery.useMutation({mutationKey:["accounts","recovery",o?.name],mutationFn:async({accountName:i,type:s,key:a,email:c})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:o.name,new_recovery_account:i,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let d=await _()(f.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:c,publicKeys:[...o.owner.key_auths,...o.active.key_auths,...o.posting.key_auths,o.memo_key]})});if(!d.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${d.status}`);return d}else {if(s==="key"&&a)return ee([["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(o.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."),uo__default.default.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function YP(e,t){let r=e.key_auths.filter(([o])=>!t.has(String(o))).reduce((o,[,i])=>o+i,0),n=(e.account_auths??[]).reduce((o,[,i])=>o+i,0);return r+n>=e.weight_threshold}function Go(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),o=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([c])=>!r.has(c.toString())),a},i=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:i?o(e.owner):void 0,active:o(e.active),posting:o(e.posting),memo_key:e.memo_key}}function nA(e,t){let{data:r}=reactQuery.useQuery(M(e));return reactQuery.useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:o})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let i=Array.isArray(o)?o:[o],s=Go(r,i);return ee([["account_update",s]],n)},...t})}function aA(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:o="0.000 HIVE"})=>[Gr(n,o)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(o.creator)]);},t,"active",{broadcastMode:r})}function lA(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[zr(e,n.currentPosting,n.grantedAccount,n.weightThreshold,n.memoKey,n.jsonMetadata)],async()=>{await E(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}function gA(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?Wr(e,n.newAccountName,n.keys):$r(e,n.newAccountName,n.keys,n.fee)],async()=>{await E(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}var en=300*60*24,Gu=1e4,zu=5e7;function zo(e){let t=k(e.vesting_shares).amount,r=k(e.received_vesting_shares).amount,n=k(e.delegated_vesting_shares).amount,o=k(e.vesting_withdraw_rate).amount,i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t+r-n-s}function Ju(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function Yu(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 Xu(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 o=zo(e);if(!Number.isFinite(o)||o<=0)return 0;let i=o*1e6,s=Math.ceil(i*r*60*60*24/Gu/(n*en)),a=wr(e),c=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(c)||s>c?0:Math.max(s-zu,0)}function Zu(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(Yu(t))return Xu(e,t,n);let o=0;try{if(o=zo(e),!Number.isFinite(o))return 0}catch{return 0}return Ju(o,r,n)}function bA(e){return wr(e).percentage/100}function wA(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*en/1e4}function vA(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 o=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/en;o>n&&(o=n);let i=o*100/n;return isNaN(i)?0:i>100?100:i}function PA(e){return Dt(e).percentage/100}function AA(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:o,fundRewardBalance:i,base:s,quote:a}=t;if(!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(a)||o===0||a===0)return 0;let c=Zu(e,t,r,n);return Number.isFinite(c)?c/o*i*(s/a):0}var ep={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 tp(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 rp(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function np(e){let t=e[0];return t==="custom_json"?tp(e):t==="create_proposal"||t==="update_proposal"?rp(e):ep[t]??"posting"}function xA(e){let t="posting";for(let r of e){let n=np(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function RA(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=U.fromLogin(e,r,"active"):io(r)?n=U.fromString(r):n=U.from(r),ee([t],n)}})}function IA(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 BA(e="/"){return reactQuery.useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>uo__default.default.sendOperation(t,{callback:e},()=>{})})}function HA(){return reactQuery.queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await y("condenser_api.get_chain_properties",[])})}function Jo(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function Yo(e,t){return {...e??{},title:t.title,body:t.body}}function zA(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 i=await _()(f.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${i.status}`);return i.json()},onSuccess(r,n){let o=w(),i=Yo(r,n);o.setQueryData(ze(e,t).queryKey,s=>[i,...s??[]]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,c)=>c===0?{...a,data:[i,...a.data]}:a)});}})}function rO(e,t){return reactQuery.useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:o})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await _()(f.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:o}),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 o=w(),i=s=>Jo(s,r,n);o.setQueryData(ze(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?i(a):a)??[]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(c=>c.id===n.fragmentId?i(c):c)}))});}})}function cO(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 o=await _()(f.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${o.status}`);return o},onSuccess(r,n){let o=w();o.setQueryData(ze(e,t).queryKey,i=>[...i??[]].filter(({id:s})=>s!==n.fragmentId)),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},i=>i&&{...i,pages:i.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 lO(e,t,r,n){let i=await _()(f.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(i);return {status:i.status,data:s}}async function dO(e){let r=await _()(f.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 fO(e,t,r="",n=""){let o={code:e,ty:t};r&&(o.bl=r),n&&(o.tx=n);let s=await _()(f.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});await G(s);}async function mO(e,t,r=null,n=null){let o={code:e};t&&(o.filter=t),r&&(o.since=r),n&&(o.user=n);let s=await _()(f.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return G(s)}async function gO(e,t,r,n,o,i){let s={code:e,username:t,token:i,system:r,allows_notify:n,notify_types:o},c=await _()(f.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function yO(e,t,r){let n={code:e,username:t,token:r},i=await _()(f.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}async function Xo(e,t){let r={code:e};t&&(r.id=t);let o=await _()(f.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function Zo(e,t){let r={code:e,url:t},o=await _()(f.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}var dp="https://i.ecency.com";async function ei(e,t,r){let n=_(),o=new FormData;o.append("file",e);let i=await n(`${dp}/hs/${t}`,{method:"POST",body:o,signal:r});return G(i)}async function hO(e,t,r,n){let o=_(),i=new FormData;i.append("file",e);let s=await o(`${f.imageHost}/${t}/${r}`,{method:"POST",body:i,signal:n});return G(s)}async function ti(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function ri(e,t,r,n,o){let i={code:e,title:t,body:r,tags:n,meta:o},a=await _()(f.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return G(a)}async function ni(e,t,r,n,o,i){let s={code:e,id:t,title:r,body:n,tags:o,meta:i},c=await _()(f.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function oi(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function ii(e,t,r,n,o,i,s,a){let c={code:e,permlink:t,title:r,body:n,meta:o,schedule:s,reblog:a};i&&(c.options=i);let l=await _()(f.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});return G(l)}async function si(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function ai(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function _O(e,t,r){let n={code:e,author:t,permlink:r},i=await _()(f.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}async function bO(e,t,r){let n={username:e,email:t,friend:r},i=await _()(f.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}function OO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:o,body:i,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return ri(t,o,i,s,a)},onSuccess:o=>{r?.();let i=w();o?.drafts?i.setQueryData(u.posts.drafts(e),o.drafts):i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function CO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:o,title:i,body:s,tags:a,meta:c})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return ni(t,o,i,s,a,c)},onSuccess:()=>{r?.();let o=w();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function DO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return oi(t,o)},onMutate:async({draftId:o})=>{if(!e)return;let i=w(),s=u.posts.drafts(e),a=u.posts.draftsInfinite(e);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a})]);let c=i.getQueryData(s);c&&i.setQueryData(s,c.filter(d=>d._id!==o));let p=i.getQueriesData({queryKey:a}),l=new Map(p);for(let[d,m]of p)m&&i.setQueryData(d,{...m,pages:m.pages.map(g=>({...g,data:g.data.filter(h=>h._id!==o)}))});return {previousList:c,previousInfinite:l}},onSuccess:()=>{r?.();let o=w();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:(o,i,s)=>{let a=w();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?.(o);}})}function QO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:o,title:i,body:s,meta:a,options:c,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return ii(t,o,i,s,a,c,p,l)},onSuccess:()=>{r?.(),w().invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function LO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return si(t,o)},onSuccess:o=>{r?.();let i=w();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function JO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return ai(t,o)},onSuccess:o=>{r?.();let i=w();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)}),i.invalidateQueries({queryKey:u.posts.drafts(e)});},onError:n})}function tx(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:o,code:i})=>{let s=i??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return Zo(s,o)},onSuccess:()=>{r?.(),w().invalidateQueries({queryKey:u.posts.images(e)});},onError:n})}function sx(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return ti(t,o)},onSuccess:(o,i)=>{r?.();let s=w(),{imageId:a}=i;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 px(e,t){return reactQuery.useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:o})=>ei(r,n,o),onSuccess:e,onError:t})}function Lt(e,t){return `/@${e}/${t}`}function Pp(e,t,r){return (r??w()).getQueryData(u.posts.entry(Lt(e,t)))}function Ap(e,t){(t??w()).setQueryData(u.posts.entry(Lt(e.author,e.permlink)),e);}function jt(e,t,r,n){let o=n??w(),i=Lt(e,t),s=o.getQueryData(u.posts.entry(i));if(!s)return;let a=r(s);return o.setQueryData(u.posts.entry(i),a),s}exports.EntriesCacheManagement=void 0;(a=>{function e(c,p,l,d,m){jt(c,p,g=>({...g,active_votes:l,stats:{...g.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:g.stats?.flag_weight||0},total_votes:l.length,payout:d,pending_payout_value:String(d)}),m);}a.updateVotes=e;function t(c,p,l,d){jt(c,p,m=>({...m,reblogs:l}),d);}a.updateReblogsCount=t;function r(c,p,l,d){jt(c,p,m=>({...m,children:l}),d);}a.updateRepliesCount=r;function n(c,p,l,d){jt(p,l,m=>({...m,children:m.children+1,replies:[c,...m.replies]}),d);}a.addReply=n;function o(c,p){c.forEach(l=>Ap(l,p));}a.updateEntries=o;function i(c,p,l){(l??w()).invalidateQueries({queryKey:u.posts.entry(Lt(c,p))});}a.invalidateEntry=i;function s(c,p,l){return Pp(c,p,l)}a.getEntry=s;})(exports.EntriesCacheManagement||={});function Op(e,t,r){let n=e.some(o=>o.voter===t);return r!==0?n:!n}function xp(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 o=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],i=n.payout+(t.estimated??0);exports.EntriesCacheManagement.updateVotes(t.author,t.permlink,o,i,r);}function hx(e,t,r){return v(["posts","vote"],e,({author:n,permlink:o,weight:i})=>[Er(e,n,o,i)],async(n,o)=>{xp(e,o);let i=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(120,i,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([u.posts.entry(`/@${o.author}/${o.permlink}`),u.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function Px(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:o,deleteReblog:i})=>[kr(e,n,o,i??false)],async(n,o)=>{let i=exports.EntriesCacheManagement.getEntry(o.author,o.permlink);if(i){let p=Math.max(0,(i.reblogs??0)+(o.deleteReblog?-1:1));exports.EntriesCacheManagement.updateReblogsCount(o.author,o.permlink,p);}let s=n?.id??n?.tx_id;t?.adapter?.recordActivity&&s&&t.adapter.recordActivity(130,s,n?.block_num).catch(()=>{});let a=()=>{w().invalidateQueries({queryKey:u.posts.accountPostsBlogPrefix(e)}),t?.adapter?.invalidateQueries&&t.adapter.invalidateQueries([u.posts.entry(`/@${o.author}/${o.permlink}`),u.posts.rebloggedBy(o.author,o.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function Ep(e){return e.isUpdate?null:e.parentAuthor?110:100}function Ex(e,t,r){return v(["posts","comment"],e,n=>{let o=[];if(o.push(Ne(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let d=[...p].sort((m,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:d.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(Qe(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{let i=!o.parentAuthor,s=Ep(o),a=n?.id??n?.tx_id;if(s!==null&&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(!i){c.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let p=o.rootAuthor||o.parentAuthor,l=o.rootPermlink||o.parentPermlink;c.push({predicate:d=>{let m=d.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 Cx(e,t,r,n){let o=n??w(),i=o.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 i)a&&o.setQueryData(s,[e,...a]);}function ci(e,t,r,n,o){let i=o??w(),s=new Map,a=i.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),i.setQueryData(c,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function ui(e,t){let r=t??w();for(let[n,o]of e)r.setQueryData(n,o);}function Rx(e,t,r,n){let o=n??w(),i=`/@${e}/${t}`,s=o.getQueryData(u.posts.entry(i));return s&&o.setQueryData(u.posts.entry(i),{...s,...r}),s}function Tx(e,t,r,n){let o=n??w(),i=`/@${e}/${t}`;o.setQueryData(u.posts.entry(i),r);}function Kx(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:o})=>[Sr(n,o)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e)];if(o.parentAuthor&&o.parentPermlink){i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let o=n.rootAuthor||n.parentAuthor,i=n.rootPermlink||n.parentPermlink;return o&&i?{snapshots:ci(n.author,n.permlink,o,i)}:{}},onError:(n,o,i)=>{let{snapshots:s}=i??{};s&&ui(s);}})}function Qx(e,t,r){return v(["posts","cross-post"],e,n=>{let o=[];if(o.push(Ne(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true}=n.options;o.push(Qe(n.author,n.permlink,i,s,a,c,[]));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.parentPermlink}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"async"})}function jx(e,t,r){return v(["posts","update-reply"],e,n=>{let o=[];if(o.push(Ne(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let d=[...p].sort((m,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:d.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(Qe(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.resourceCredits.account(e)];i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r})}function Gx(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:o,duration:i})=>[Xr(e,n,o,i)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.posts._promotedPrefix],[...u.points._prefix(e)],u.posts.entry(`/@${o.author}/${o.permlink}`)]);},t,"active",{broadcastMode:r})}var Sp=[3e3,3e3,3e3],kp=e=>new Promise(t=>setTimeout(t,e));async function Cp(e,t){return y("condenser_api.get_content",[e,t])}async function Rp(e,t,r=0,n){let o=n?.delays??Sp,i;try{i=await Cp(e,t);}catch{i=void 0;}if(i||r>=o.length)return;let s=o[r];return s>0&&await kp(s),Rp(e,t,r+1,n)}var Xe={};vt(Xe,{useRecordActivity:()=>tn});function Fp(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function tn(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=_(),o=Fp(),i=r?.url??o.url,s=r?.domain??o.domain;try{await n(f.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:i,domain:s,props:{username:e}})});}catch{}}})}function oE(e){return reactQuery.queryOptions({queryKey:["analytics","discover-leaderboard",e],queryFn:async({signal:t})=>{let r=await fetch(f.privateApiHost+`/private-api/leaderboard/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch leaderboard: ${r.status}`);return r.json()}})}function uE(e){return reactQuery.queryOptions({queryKey:["analytics","discover-curation",e],queryFn:async({signal:t})=>{let r=await fetch(f.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(),o=n.map(s=>s.account),i=await y("condenser_api.get_accounts",[o]);for(let s=0;sa.efficiency-s.efficiency),n}})}function fE(e,t=[],r=["visitors","pageviews","visit_duration"],n){let o=[...t].sort(),i=[...r].sort();return reactQuery.queryOptions({queryKey:["analytics","page-stats",e,o,i,n],queryFn:async({signal:s})=>{let a=await fetch(f.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 $t="threespeakfund",bE=1100;function Kp(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function wE(e,t){if(!Kp(t))return e;let r=e.find(n=>n.account===$t);return r&&r.weight===1100?e:r?e.map(n=>n.account===$t?{...n,weight:1100}:n):[...e,{account:$t,weight:1100}]}function vE(e){return e===$t}var on={};vt(on,{getAccountTokenQueryOptions:()=>nn,getAccountVideosQueryOptions:()=>Up});var rn={};vt(rn,{getDecodeMemoQueryOptions:()=>Np});function Np(e,t,r){return reactQuery.queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new uo__default.default.Client({accessToken:r}).decode(t)}})}var pi={queries:rn};function nn(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"}}),o=pi.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await w().prefetchQuery(o);let{memoDecoded:i}=w().getQueryData(o.queryKey);return i.replace("#","")}})}function Up(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=nn(e,t);await w().prefetchQuery(r);let n=w().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 ME={queries:on};function jE(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 GE({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:o,enabled:i=true}){return reactQuery.queryOptions({queryKey:["integrations","plausible",e,t,r,n,o],queryFn:async()=>{let a=await _()(`${f.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...o?{date_range:o}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&i,retry:1})}function XE(){return reactQuery.queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await y("rc_api.get_rc_stats",{})).rc_stats})}function rS(e){return reactQuery.queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await y("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}function aS(){return reactQuery.queryOptions({queryKey:u.resourceCredits.resourceParams(),staleTime:1440*60*1e3,gcTime:1/0,queryFn:async()=>await y("rc_api.get_resource_params",{})})}var Wt=["resource_history_bytes","resource_new_accounts","resource_market_bytes","resource_state_bytes","resource_execution_time"];var Gp=11,zp=65,Jp=16,Ze=e=>BigInt(typeof e=="string"?e:Math.trunc(e));function sn(e,t,r,n){if(r<=0||n<=0)return 0;let o=Ze(e.coeff_a),i=Ze(e.coeff_b),s=Ze(e.shift),a=Ze(n)*o>>s;a+=1n,a*=Ze(r);let c=i+(t>0?Ze(t):0n);return c===0n?0:Number(a/c+1n)}function an({transactionBytes:e,permlinkLength:t,signatures:r=1,beneficiaries:n=0,hasCommentOptions:o=false},i){let s=i.resource_state_bytes,a=i.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+(o?a.comment_options_time:0)}}var _e=e=>{let t=ut(e);return ye(t)+t},Yp=e=>1+_e(e.parent_author)+_e(e.parent_permlink)+_e(e.author)+_e(e.permlink)+_e(e.title)+_e(e.body)+_e(e.json_metadata),Xp=(e,t)=>{let r=t.beneficiaries??[],n=1+_e(e.author)+_e(e.permlink)+Jp+2+2;return n+=ye(r.length>0?1:0),r.length>0&&(n+=1+ye(r.length),r.forEach(o=>{n+=_e(o.account)+2;})),n};function cn({op:e,options:t,signatures:r=1}){let n=[Yp(e)];return t&&n.push(Xp(e,t)),Gp+ye(n.length)+n.reduce((o,i)=>o+i,0)+ye(r)+zp*r}var Zp={ready:false,cost:0,transactionBytes:0,breakdown:[]};function dS({op:e,options:t,rcParams:r,rcStats:n,signatures:o=1}){if(!r?.resource_params||!r.size_info||!n?.pool||!n.share)return Zp;let i=cn({op:e,options:t,signatures:o}),s=an({transactionBytes:i,permlinkLength:ut(e.permlink),signatures:o,beneficiaries:t?.beneficiaries?.length??0,hasCommentOptions:!!t},r.size_info),a=Number(n.regen),c=0,p=[];return Wt.forEach((l,d)=>{let m=r.resource_params[l],g=Number(n.pool[d]??0),h=Number(n.share[d]??0);if(!m||h<=0)return;let P=s[l]*Number(m.resource_dynamics_params.resource_unit??1),O=Number(BigInt(a)*BigInt(h)/10000n),T=sn(m.price_curve_params,g,P,O);c+=T,p.push({resource:l,usage:P,cost:T});}),{ready:true,cost:c,transactionBytes:i,breakdown:p}}function un(e,t,r){let n=Number(r.regen),o=0,i=[];return Wt.forEach((s,a)=>{let c=t.resource_params[s],p=Number(r.pool[a]??0),l=Number(r.share[a]??0);if(!c||l<=0)return;let d=e[s]*Number(c.resource_dynamics_params.resource_unit??1),m=Number(BigInt(n)*BigInt(l)/10000n),g=sn(c.price_curve_params,p,d,m);o+=g,i.push({resource:s,usage:d,cost:g});}),{cost:o,breakdown:i}}var el=11,tl=65,pn=e=>{let t=ut(e);return ye(t)+t},rl=()=>({resource_history_bytes:0,resource_new_accounts:0,resource_market_bytes:0,resource_state_bytes:0,resource_execution_time:0});function li(e,t=1){let r=1+pn(e.voter)+pn(e.author)+pn(e.permlink)+2;return el+ye(1)+r+ye(t)+tl*t}function di({transactionBytes:e,signatures:t=1},r){let n=r.resource_state_bytes,o=r.resource_execution_time;return {...rl(),resource_history_bytes:e,resource_state_bytes:n.vote_size+n.transaction_base_size,resource_execution_time:o.vote_time+o.transaction_time+o.verify_authority_time*t}}var fi={ready:false,currentMana:0,maxMana:0,avgCost:0,cost:0,transactionBytes:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function AS({rcAccount:e,rcStats:t,rcParams:r,operation:n,payload:o,fallback:i="minimal",buffer:s=1.2}){if(!e||!t?.ops)return fi;let{current_mana:a,max_mana:c}=Dt(e),p=nl(n,o,i,r,t);if(!p)return {...fi,currentMana:a,maxMana:c};let{cost:l,transactionBytes:d}=p,m=Number.isFinite(s)&&s>0?s:1.2,g=l*m,h=a0?{cost:r,transactionBytes:0}:null}var il={author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa",parent_author:"",parent_permlink:"hive-100000",title:"",body:"",json_metadata:"{}"},sl={voter:"aaaaaaaaaa",author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa"};function SS(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 _()(f.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}async function ul(e,t,r){let o=await _()(f.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:t,code:e,key:r}),headers:{"Content-Type":"application/json"}}),i=(o.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),s=await o.text();if(!o.ok){let a=s&&i.includes("json")?`: ${s.slice(0,200)}`:"";throw new Error(`[SDK][Games] \u2013 failed with status ${o.status}${a}`)}if(!i.includes("json"))throw new Error(`[SDK][Games] \u2013 expected JSON but received "${i||"empty"}" response (status ${o.status})`);try{return JSON.parse(s)}catch{throw new Error(`[SDK][Games] \u2013 malformed JSON response (status ${o.status})`)}}function FS(e,t,r,n){let{mutateAsync:o}=tn(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 ul(t,r,n)},onSuccess(){o();}})}function KS(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 _()(f.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 ll=[{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 MS(e,t){return ll.find(r=>r.tier===e&&r.id===t)}var dl=25;function fl(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function NS(e){return fl(e)>dl}var QS=300,HS=2;function yl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function hl(e){let r=await _()(f.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:yl()})});if(!r.ok){let n;try{n=await r.json();}catch{}let o=n?.message??`Failed to buy streak freeze: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function LS(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 hl(t)},onSuccess(){n&&r.invalidateQueries({queryKey:u.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:u.quests.status(n)});}})}function zS(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[Mr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"async"})}function ZS(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[Nr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"sync"})}function nk(e,t,r){return v(["communities","mutePost"],e,({community:n,author:o,permlink:i,notes:s,mute:a})=>[Vr(e,n,o,i,s,a)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.posts.entry(`/@${o.author}/${o.permlink}`),["community","single",o.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.community}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"sync"})}function ak(e,t,r,n){return v(["communities","set-role",e],t,({account:o,role:i})=>[Qr(t,e,o,i)],async(o,i)=>{w().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>{if(!a)return a;let c=[...a.team??[]],p=c.findIndex(([l])=>l===i.account);return p>=0?c[p]=[c[p][0],i.role,c[p][2]??""]:c.push([i.account,i.role,""]),{...a,team:c}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)],u.communities.context(i.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function lk(e,t,r,n){return v(["communities","update",e],t,o=>[Hr(t,e,o)],async(o,i)=>{w().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>a&&{...a,...i}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function gk(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[Zr(n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.communities.singlePrefix(o.name)],[...u.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function bk(e,t,r){return v(["communities","pin-post"],e,({community:n,account:o,permlink:i,pin:s})=>[Ur(e,n,o,i,s)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.posts.entry(`/@${o.account}/${o.permlink}`),[...u.communities.singlePrefix(o.community)]]);},t,"posting",{broadcastMode:r??"async"})}function Ok(e,t,r=100,n=void 0,o=true){return reactQuery.queryOptions({queryKey:u.communities.list(e,t??"",r),enabled:o,queryFn:async()=>{let i=await y("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return i?e==="hot"?i.sort(()=>Math.random()-.5):i:[]}})}function Ck(e,t){return reactQuery.queryOptions({queryKey:u.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await y("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function qk(e,t="",r=true){return reactQuery.queryOptions({queryKey:u.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>To(e??"",t)})}var mi=100;async function gi(e,t){return await y("bridge.list_subscribers",{community:e,limit:mi,...t?{last:t}:{}})??[]}function Qk(e){return reactQuery.queryOptions({queryKey:u.communities.subscribers(e),queryFn:async()=>gi(e,null),staleTime:6e4})}function Hk(e){return reactQuery.infiniteQueryOptions({queryKey:u.communities.subscribersInfinite(e),initialPageParam:null,queryFn:async({pageParam:t})=>gi(e,t),getNextPageParam:t=>t?.length>=mi?t[t.length-1]?.[0]??null:null,staleTime:6e4})}function Wk(e,t){return reactQuery.infiniteQueryOptions({queryKey:u.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await y("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function Yk(){return reactQuery.queryOptions({queryKey:u.communities.rewarded(),queryFn:async()=>{let e=await fetch(f.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 xl=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(xl||{}),Zk={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function tC(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function rC({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),o=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),i=["owner","admin","mod"].includes(t);return {canPost:n,canComment:o,isModerator:i}}function sC(e,t){return reactQuery.queryOptions({queryKey:u.notifications.unreadCount(e),queryFn:async()=>t?(await(await fetch(`${f.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 pC(e,t,r=void 0){return reactQuery.infiniteQueryOptions({queryKey:u.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let o={code:t,filter:r,since:n,user:void 0},i=await fetch(f.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)return [];try{return await i.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var kl=(g=>(g.VOTES="rvotes",g.MENTIONS="mentions",g.FAVORITES="nfavorites",g.BOOKMARKS="nbookmarks",g.FOLLOWS="follows",g.REPLIES="replies",g.REBLOGS="reblogs",g.TRANSFERS="transfers",g.DELEGATIONS="delegations",g.PAYOUTS="payouts",g.SCHEDULED_PUBLISHED="scheduled_published",g.ACCOUNT_UPDATES="account_updates",g.WEEKLY_EARNINGS="weekly_earnings",g))(kl||{});var Cl=(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))(Cl||{}),yi=[1,2,3,4,5,6,10,13,15,19,20,21,22],Rl=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(Rl||{});function hC(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 o=await fetch(f.privateApiHost+"/private-api/detail-device",{body:JSON.stringify({code:t,username:e,token:n}),method:"POST",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch notification settings: ${o.status}`);return o.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...yi]})})}function vC(){return reactQuery.queryOptions({queryKey:u.notifications.announcements(),queryFn:async()=>{let e=await fetch(f.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 xC(e){return reactQuery.queryOptions({queryKey:u.notifications.spotlights(),queryFn:async()=>{let t=await fetch(f.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 Dl(e,t){return {...e,read:!t||t===e.id?1:e.read}}function hi(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function FC(e,t,r,n){let o=w();return reactQuery.useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:i})=>{if(!e||!t){process.env.NODE_ENV!=="production"&&console.warn("[SDK][Notifications] \u2013 missing auth for markNotifications");return}return Xo(t,i)},onMutate:async({id:i})=>{if(!e||!t)return {previousData:[]};await o.cancelQueries({queryKey:u.notifications._prefix});let s=[],a=o.getQueriesData({queryKey:u.notifications._prefix,predicate:l=>{let d=l.state.data;return hi(d)}});a.forEach(([l,d])=>{if(d&&hi(d)){s.push([l,d]);let m={...d,pages:d.pages.map(g=>g.map(h=>Dl(h,i)))};o.setQueryData(l,m);}});let c=u.notifications.unreadCount(e),p=o.getQueryData(c);return typeof p=="number"&&p>0&&(s.push([c,p]),i?a.some(([,d])=>d?.pages.some(m=>m.some(g=>g.id===i&&g.read===0)))&&o.setQueryData(c,p-1):o.setQueryData(c,0)),{previousData:s}},onSuccess:i=>{let s=typeof i=="object"&&i!==null?i.unread:void 0;typeof s=="number"&&o.setQueryData(u.notifications.unreadCount(e),s),r?.(s);},onError:(i,s,a)=>{a?.previousData&&a.previousData.forEach(([c,p])=>{o.setQueryData(c,p);}),n?.(i);},onSettled:()=>{o.invalidateQueries({queryKey:u.notifications._prefix});}})}function KC(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>Ir(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function QC(e){return reactQuery.queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await y("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 y("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(o=>o.status==="expired");return [...t.filter(o=>o.status!=="expired"),...r]}})}function JC(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 y("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 y("condenser_api.get_accounts",[s.map(l=>l.voter)]),c=Nt(a);return s.map(l=>({...l,voterAccount:c.find(d=>l.voter===d.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function eR(e){return reactQuery.queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await y("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 oR(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:o})=>[Br(e,n,o)],async n=>{try{let o=n?.id??n?.tx_id;t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(150,o,n?.block_num).catch(i=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:o,error:i});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.proposals.list(),u.proposals.votesByUser(e)]);}catch(o){console.warn("[useProposalVote] Post-broadcast side-effect failed:",o);}},t,"active",{broadcastMode:r})}function cR(e,t,r){return v(["proposals","create"],e,n=>[Kr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.proposals.list()]);},t,"active",{broadcastMode:r})}function dR(e,t=50){return reactQuery.infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,o=await y("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&o.length>0&&o[0]?.delegatee===r?o.slice(1,t+1):o},getNextPageParam:r=>!r||r.lengthte("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function wR(e){return reactQuery.queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await y("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function OR(e){return reactQuery.queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>y("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function kR(e){return reactQuery.queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>y("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function FR(e){return reactQuery.queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>y("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function KR(e){return reactQuery.queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function QR(e){return reactQuery.queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>y("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function LR(e,t=100){return reactQuery.infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let o=(await y("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(i=>i)).rc_direct_delegations||[];return r&&(o=o.filter(i=>i.to!==r)),o},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function zR(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 _()(`${f.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function ZR(e){return reactQuery.queryOptions({queryKey:["wallet","received-vesting-shares",e],queryFn:async()=>{let t=await fetch(f.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 nT(e){return reactQuery.queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>y("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 o=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(o){let i=Number.parseFloat(o[0]);if(Number.isFinite(i))return i}}}function Zl(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 ed(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 o of ["wallets","tokens","assets","items","portfolio","balances"]){let i=n[o];if(Array.isArray(i))return i}}return []}function td(e){if(!e||typeof e!="object")return;let t=e;return fe(t.username)??fe(t.name)??fe(t.account)}function _i(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`,o=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!o.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${o.status})`);let i=await o.json(),s=ed(i).map(a=>Zl(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:td(i)??e,currency:fe(i?.fiatCurrency??i?.currency)?.toUpperCase(),wallets:s}}})}function Gt(e){return reactQuery.queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await w().prefetchQuery(Oe()),await w().prefetchQuery(M(e));let t=w().getQueryData(Oe().queryKey),r=w().getQueryData(M(e).queryKey),n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:0};let i=k(r.balance).amount,s=k(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:i+s,parts:[{name:"current",balance:i},{name:"savings",balance:s}]}}})}function bi(e){return reactQuery.queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await w().prefetchQuery(Oe()),await w().prefetchQuery(M(e));let t=w().getQueryData(M(e).queryKey),r=w().getQueryData(Oe().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:k(t.hbd_balance).amount+k(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:k(t.hbd_balance).amount},{name:"savings",balance:k(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function id(e){let c=9.5-(e.headBlock-7e6)/25e4*.01;c<.95&&(c=.95);let p=e.vestingRewardPercent/1e4,l=e.virtualSupply,d=e.totalVestingFund;return (l*c*p/d).toFixed(3)}function wi(e){return reactQuery.queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await w().prefetchQuery(Oe()),await w().prefetchQuery(M(e));let t=w().getQueryData(Oe().queryKey),r=w().getQueryData(M(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??""),i=Number.isFinite(o)?o:t.base/t.quote,s=k(r.vesting_shares).amount,a=k(r.delegated_vesting_shares).amount,c=k(r.received_vesting_shares).amount,p=k(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),d=go(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+We(s,t.hivePerMVests).toFixed(3),g=+We(a,t.hivePerMVests).toFixed(3),h=+We(c,t.hivePerMVests).toFixed(3),P=+We(l,t.hivePerMVests).toFixed(3),O=+We(d,t.hivePerMVests).toFixed(3),T=Math.max(m-P,0),F=Math.max(m-g,0);return {name:"HP",title:"Hive Power",price:i,accountBalance:+T.toFixed(3),apr:id(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+F.toFixed(3)},{name:"outgoing_delegations",balance:g},{name:"incoming_delegations",balance:h},...P>0?[{name:"pending_power_down",balance:+P.toFixed(3)}]:[],...O>0&&O!==P?[{name:"next_power_down",balance:+O.toFixed(3)}]:[]]}}})}var B=ne.operations,ln={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 kT=Object.keys(ne.operations);var vi=ne.operations,TT=vi,FT=Object.entries(vi).reduce((e,[t,r])=>(e[r]=t,e),{});var Pi=ne.operations;function ad(e){return Object.prototype.hasOwnProperty.call(Pi,e)}function ht(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),o=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),i=new Set;r||n.forEach(a=>{if(a in ln){ln[a].forEach(c=>i.add(c));return}ad(a)&&i.add(Pi[a]);});let s=pd(Array.from(i));return {filterKey:o,filterArgs:s}}function dn(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function cd(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function ud(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function pd(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await y("condenser_api.get_account_history",[e,s,ud(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 k(p.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(p.amount).symbol==="HIVE";case "transfer_from_savings":case "fill_transfer_from_savings":return k(p.amount).symbol==="HIVE";case "fill_recurrent_transfer":let d=k(p.amount);return ["HIVE"].includes(d.symbol);case "claim_reward_balance":return k(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 i.has(p.type)}}))})})}function VT(e,t=20,r=[]){let{filterKey:n}=ht(r),o=dn(r);return reactQuery.infiniteQueryOptions({...zt(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:i,pageParams:s})=>({pageParams:s,pages:i.map(a=>a.filter(c=>{switch(c.type){case "author_reward":case "comment_benefactor_reward":return k(c.hbd_payout).amount>0;case "claim_reward_balance":return k(c.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(c.amount).symbol==="HBD";case "transfer_from_savings":case "fill_transfer_from_savings":return k(c.amount).symbol==="HBD";case "fill_recurrent_transfer":let d=k(c.amount);return ["HBD"].includes(d.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 o.has(c.type)}}))})})}function GT(e,t=20,r=[]){let{filterKey:n}=ht(r),o=new Set(Array.isArray(r)?r:[r]),i=o.has("")||o.size===0;return reactQuery.infiniteQueryOptions({...zt(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 k(p.vesting_payout).amount>0;case "claim_reward_balance":return k(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(k(p.amount).symbol);case "fill_recurrent_transfer":let m=k(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 i||o.has(p.type)}}))})})}function Ai(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 fn(e,t){return new Date(e.getTime()-t*1e3)}function XT(e=86400){return reactQuery.infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await y("condenser_api.get_market_history",[e,Ai(t),Ai(r)])).map(({hive:o,non_hive:i,open:s})=>({close:i.close/o.close,open:i.open/o.open,low:i.low/o.low,high:i.high/o.high,volume:o.volume,time:new Date(s)})),initialPageParam:[fn(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[fn(n,Math.max(100*e,28800)),fn(n,e)]})}function rF(e){return reactQuery.queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function sF(e,t=50){return reactQuery.queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>y("condenser_api.get_vesting_delegations",[e,"",t])})}function lF(e){return reactQuery.queryOptions({queryKey:["assets","hive-power","delegatings",e],queryFn:async()=>(await(await fetch(f.privateApiHost+`/private-api/received-vesting/${e}`,{headers:{"Content-Type":"application/json"}})).json()).list,select:t=>t.sort((r,n)=>k(n.vesting_shares).amount-k(r.vesting_shares).amount)})}function gF(e=500){return reactQuery.queryOptions({queryKey:["market","order-book",e],queryFn:()=>y("condenser_api.get_order_book",[e])})}function bF(){return reactQuery.queryOptions({queryKey:["market","statistics"],queryFn:()=>y("condenser_api.get_ticker",[])})}function AF(e,t,r){let n=o=>o.toISOString().replace(/\.\d{3}Z$/,"");return reactQuery.queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>y("condenser_api.get_market_history",[e,n(t),n(r)])})}function SF(){return reactQuery.queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await y("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),o=await y("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:o[0]?o[0].non_hive.open/o[0].hive.open:0,high:o[0]?o[0].non_hive.high/o[0].hive.high:0,low:o[0]?o[0].non_hive.low/o[0].hive.low:0,percent:o[0]?100-o[0].non_hive.open/o[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function TF(e,t,r,n){return reactQuery.queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:o})=>{let i=_(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await i(s,{signal:o});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function Oi(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function DF(e=1e3,t,r){let n=r??new Date,o=t??new Date(n.getTime()-600*60*1e3);return reactQuery.queryOptions({queryKey:["market","trade-history",e,o.getTime(),n.getTime()],queryFn:()=>y("condenser_api.get_trade_history",[Oi(o),Oi(n),e])})}function NF(){return reactQuery.queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await y("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function VF(){return reactQuery.queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await y("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function WF(e,t,r){return v(["market","limit-order-create"],e,n=>[Vt(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 YF(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[jr(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 _t(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 eI(e,t,r,n){let o=_(),i=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await o(i);return _t(s)}async function xi(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 _t(n)).hive_dollar[e]}async function tI(e,t){let n=await _()(f.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return _t(n)}async function rI(){let t=await _()(f.privateApiHost+"/private-api/market-data/latest");return _t(t)}async function nI(){let t=await _()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return _t(t)}var xd={"Content-type":"application/json"};async function Ed(e){let t=_(),r=exports.ConfigManager.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:xd});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function Te(e,t){try{return await Ed(e)}catch{return t}}async function sI(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,o]=await Promise.all([Te({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),Te({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),i=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),d=Number(p.price??0);return l-d});return {buy:i(n),sell:s(o)}}async function aI(e,t=50){return Te({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 cI(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},[o,i]=await Promise.all([Te({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),Te({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=o.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=i.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 Sd(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return Te({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function et(e,t){return Sd(t,e)}async function Jt(e){return Te({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function Yt(e){return Te({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function Ei(e,t,r,n){let o=_(),i=exports.ConfigManager.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",i);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 o(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 Si(e,t="daily"){let r=_(),n=exports.ConfigManager.getValidatedBaseUrl(),o=new URL("/private-api/engine-chart-api",n);o.searchParams.set("symbol",e),o.searchParams.set("interval",t);let i=await r(o.toString(),{headers:{"Content-type":"application/json"}});if(!i.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${i.status}`);return await i.json()}async function ki(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 Xt(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Jt(e)})}function gI(){return reactQuery.queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>et()})}function Ci(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Yt(e)})}function PI(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 Ei(e,t,r,n)},getNextPageParam:(n,o,i)=>(n?.length??0)===r?i+r:void 0,getPreviousPageParam:(n,o,i)=>i>0?i-r:void 0})}function EI(e,t="daily"){return reactQuery.queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Si(e,t)})}function RI(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await ki(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function Ri(e,t){return reactQuery.queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>et(e,t)})}function tt(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:o,suffix:i}=r,s="";o&&(s+=o+" ");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}),i&&(s+=" "+i),s}var Zt=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()?`(${tt(this.stake,{fractionDigits:this.precision})} + ${tt(this.delegationsIn,{fractionDigits:this.precision})} - ${tt(this.delegationsOut,{fractionDigits:this.precision})})`:"";staked=()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():tt(this.stakedBalance,{fractionDigits:this.precision}):"-";balanced=()=>this.balance<1e-4?this.balance.toString():tt(this.balance,{fractionDigits:this.precision})};function HI(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 Jt(e),o=await Yt(n.map(p=>p.symbol)),i=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 et(void 0,a):[]];return n.map(p=>{let l=o.find(O=>O.symbol===p.symbol),d;if(l?.metadata)try{d=JSON.parse(l.metadata);}catch{d=void 0;}let m=c.find(O=>O.symbol===p.symbol),g=Number(m?.lastPrice??"0"),h=Number(p.balance),P=p.symbol==="SWAP.HIVE"?i*h:g===0?0:Number((g*i*h).toFixed(10));return new Zt({symbol:p.symbol,name:l?.name??p.symbol,icon:d?.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:P})})},enabled:!!e})}function Ti(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=w(),n=Gt(e);await r.prefetchQuery(n);let o=r.getQueryData(n.queryKey),i=await r.ensureQueryData(Ci([t])),s=await r.ensureQueryData(Xt(e)),a=await r.ensureQueryData(Ri(void 0,t)),c=i?.find(O=>O.symbol===t),p=s?.find(O=>O.symbol===t),d=+(a?.find(O=>O.symbol===t)?.lastPrice??"0"),m=parseFloat(p?.balance??"0"),g=parseFloat(p?.stake??"0"),h=parseFloat(p?.pendingUnstake??"0"),P=[{name:"liquid",balance:m},{name:"staked",balance:g}];return h>0&&P.push({name:"unstaking",balance:h}),{name:t,title:c?.name??"",price:d===0?0:Number(d*(o?.price??0)),accountBalance:m+g,layer:"ENGINE",parts:P}}})}function bt(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(f.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 o=await n.json(),i=await fetch(f.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!i.ok)throw new Error(`Failed to fetch point transactions: ${i.status}`);let s=await i.json();return {points:o.points,uPoints:o.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function Fi(e){return reactQuery.queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await w().prefetchQuery(bt(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(w().getQueryData(bt(e).queryKey)?.points??0)})})}function iq(e,t){return reactQuery.queryOptions({queryKey:["assets","points","transactions",e,t],queryFn:async()=>(await(await fetch(`${f.privateApiHost}/private-api/point-list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,type:t??0})})).json()).map(({created:o,type:i,amount:s,id:a,sender:c,receiver:p,memo:l})=>({created:new Date(o),type:i,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:c??void 0,to:p??void 0,memo:l??void 0}))})}function hq(e,t,r={refetch:false}){let n=w(),o=r.currency??"usd",i=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||o==="usd")return p;try{let l=await xi(o);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${o}:`,l),p}},a=_i(e,o,true),c=async()=>{try{let l=(await n.fetchQuery(a)).wallets.find(m=>m.symbol.toUpperCase()===t.toUpperCase());if(!l)return;let d=[];if(l.liquid!==void 0&&l.liquid!==null&&d.push({name:"liquid",balance:l.liquid}),l.staked!==void 0&&l.staked!==null&&l.staked>0&&d.push({name:"staked",balance:l.staked}),l.savings!==void 0&&l.savings!==null&&l.savings>0&&d.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 g=m.dataKey,h=m.value;if(typeof h=="string"){let O=h.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(O){let T=Math.abs(Number.parseFloat(O[1]));g==="delegated_hive_power"?d.push({name:"outgoing_delegations",balance:T}):g==="received_hive_power"?d.push({name:"incoming_delegations",balance:T}):g==="powering_down_hive_power"&&d.push({name:"pending_power_down",balance:T});}}}return {name:l.symbol,title:l.name,price:l.fiatRate,accountBalance:l.balance,apr:l.apr?.toString(),layer:l.layer,pendingRewards:l.pendingRewards,parts:d}}catch{return}};return reactQuery.queryOptions({queryKey:["ecency-wallets","asset-info",e,t,o],queryFn:async()=>{let p=await c();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await i(Gt(e));else if(t==="HP")l=await i(wi(e));else if(t==="HBD")l=await i(bi(e));else if(t==="POINTS")l=await i(Fi(e));else if((await n.ensureQueryData(Xt(e))).some(m=>m.symbol===t))l=await i(Ti(e,t));else {if(p)return p;throw new Error(`[SDK][Wallet] \u2013 unrecognized asset "${t}"`)}if(p&&l&&l.price>0){let d=await s(l);return {...p,price:d.price}}return await s(l)}})}var Hd=(T=>(T.Transfer="transfer",T.TransferToSavings="transfer-saving",T.WithdrawFromSavings="withdraw-saving",T.Delegate="delegate",T.PowerUp="power-up",T.PowerDown="power-down",T.WithdrawRoutes="withdraw-routes",T.ClaimInterest="claim-interest",T.Swap="swap",T.Convert="convert",T.Gift="gift",T.Promote="promote",T.Claim="claim",T.Buy="buy",T.Stake="stake",T.Unstake="unstake",T.Undelegate="undelegate",T))(Hd||{});function Aq(e,t,r){return v(["wallet","transfer"],e,n=>[He(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function kq(e,t,r){return v(["wallet","transfer-point"],e,n=>[Ye(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Iq(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[mt(e,n.delegatee,n.vestingShares)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Mq(e,t,r){return v(["wallet","set-withdraw-vesting-route"],e,n=>[gt(e,n.toAccount,n.percent,n.autoVest)],async(n,o)=>{await E(t?.adapter,r,[u.wallet.withdrawRoutes(e),u.accounts.full(e),u.accounts.full(o.toAccount)]);},t,"active",{broadcastMode:r})}function Uq(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Wq(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[Je(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Xq(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[Ue(e,n.to,n.amount,n.memo,n.requestId)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function nD(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[dt(e,n.to,n.amount)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function cD(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[ft(e,n.vestingShares)],async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function fD(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?Cr(e,n.amount,n.requestId):yt(e,n.amount,n.requestId)],async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function _D(e,t,r){return v(["wallet","claim-interest"],e,n=>lt(e,n.to,n.amount,n.memo,n.requestId),async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}var Ud=5e3,er=new Map;function AD(e,t,r){return v(["wallet","claim-rewards"],e,n=>[Lr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",o=[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)],i=er.get(n);i&&(clearTimeout(i),er.delete(n));let s=setTimeout(async()=>{try{let a=w(),p=(await Promise.allSettled(o.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{er.delete(n);}},Ud);er.set(n,s);},t,"posting",{broadcastMode:r})}function SD(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function TD(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let o=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:o}]]},async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function DD(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.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 o=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:o}]]},async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function VD(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let o=JSON.stringify(n.tokens.map(i=>({symbol:i})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:o}]]},async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function WD(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let o,i;n.action==="cancel"?(i="cancel",o={type:n.orderType,id:n.orderId}):(i=n.action,o={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:i,contractPayload:o});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:s}]]},async()=>{await E(t?.adapter,r,[u.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:o="",amount:i="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [He(n,o,i,s)];case "transfer-saving":return [Je(n,o,i,s)];case "withdraw-saving":return [Ue(n,o,i,s,a)];case "power-up":return [dt(n,o,i)]}break;case "HBD":switch(t){case "transfer":return [He(n,o,i,s)];case "transfer-saving":return [Je(n,o,i,s)];case "withdraw-saving":return [Ue(n,o,i,s,a)];case "claim-interest":return lt(n,o,i,s,a);case "convert":return [yt(n,i,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [ft(n,i)];case "delegate":return [mt(n,o,i)];case "withdraw-routes":return [gt(r.from_account??n,r.to_account??o,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [Ye(n,o,i,s)];break}return null}function jd(e,t,r){let{from:n,to:o="",amount:i=""}=r,s=typeof i=="string"&&i.includes(" ")?i.split(" ")[0]:String(i);switch(t){case "transfer":return [Ve(n,"transfer",{symbol:e,to:o,quantity:s,memo:r.memo??""})];case "stake":return [Ve(n,"stake",{symbol:e,to:o,quantity:s})];case "unstake":return [Ve(n,"unstake",{symbol:e,to:o,quantity:s})];case "delegate":return [Ve(n,"delegate",{symbol:e,to:o,quantity:s})];case "undelegate":return [Ve(n,"undelegate",{symbol:e,from:o,quantity:s})];case "claim":return [Rr(n,[e])]}return null}function Ld(e){return e==="claim"?"posting":"active"}function ZD(e,t,r,n,o){let{mutateAsync:i}=Xe.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=Vd(t,r,s);if(a)return a;let c=jd(t,r,s);if(c)return c;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{i();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=>{w().invalidateQueries({queryKey:a});});},5e3);},n,Ld(r),{broadcastMode:o})}function nK(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:o})=>[Tr(e,n,o)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),u.resourceCredits.account(e),u.resourceCredits.account(o.to)]);},t,"active",{broadcastMode:r})}function aK(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:o})=>[qr(e,n,o)],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 lK(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[Dr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function Wd(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 hK(e){return reactQuery.infiniteQueryOptions({queryKey:u.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await te("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(Wd),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function _K(e,t,r,n="vests",o="desc"){return reactQuery.queryOptions({queryKey:u.witnesses.voters(e,t,r,n,o),queryFn:async({signal:i})=>await te("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:o},void 0,void 0,i),enabled:!!e,staleTime:6e4})}function bK(e){return reactQuery.queryOptions({queryKey:u.witnesses.voterCount(e),queryFn:async()=>await te("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var Gd=(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))(Gd||{});async function Jd(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 _()(f.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),o=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),i=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(i)}catch{return {message:i,code:n.status}}let s=i&&o.includes("json")?`: ${i.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!o.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${o||"empty"}" response (status ${n.status})`);try{return JSON.parse(i)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function EK(e,t,r,n){let{mutateAsync:o}=Xe.useRecordActivity(e,"points-claimed");return reactQuery.useMutation({mutationFn:()=>Jd(e,t),onError:n,onSuccess:()=>{o(),w().setQueryData(bt(e).queryKey,i=>i&&{...i,points:(parseFloat(i.points)+parseFloat(i.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var qi=/(^|\s)author:([^\s]+)/g,Di=/(^|\s)type:([^\s]+)/g,Ki=/(^|\s)category:([^\s]+)/g,Bi=/(^|\s)tag:([^\s]+)/g;var Ni=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(Ni||{}),kK=5,CK=100;function Qi(e){return e.trim().split(/\s+/)[0]??""}function Yd(e){return Qi(e).replace(/^@+/,"").toLowerCase()}function Xd(e){return Qi(e).replace(/^#+/,"").toLowerCase()}function Zd(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 RK({search:e="",author:t="",type:r="",category:n="",tags:o=[]}){let i=e.trim().replace(/\s+/g," "),s=Yd(t),a=Xd(n),c=Zd(Array.isArray(o)?o.join(","):o),p=[i];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:i,author:s,type:r,category:a,tags:c}}var Mi=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(qi);};grabType=()=>{let t=this.grab(Di);Object.values(Ni).includes(t)&&(this.type=t);};grabCategory=()=>{this.category=this.grab(Ki);};grabTags=()=>{let t=new Set;this.tags=[...this.query.matchAll(Bi)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));};grabSearch=()=>{for([qi,Di,Ki,Bi].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 xe(e,t){let n=await(async()=>{let o;try{o=await e.text();}catch{return}if(o!=="")try{return JSON.parse(o)}catch{return e.ok?void 0:o}})();if(!e.ok){let o=new Error(`Request failed with status ${e.status}`);throw o.status=e.status,o.data=n,o}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 Fe(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var tf=reactQuery.isServer?0:3;function wt(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),o&&(a.scroll_id=o),i&&(a.votes=i);let c=await fetch(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(a),signal:Pe(Ae,s)});return xe(c,Fe)},retry:wt})}function HK(e,t,r=true){return reactQuery.infiniteQueryOptions({queryKey:u.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:o})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let i,s=new Date;switch(t){case "today":i=new Date(s.getTime()-1440*60*1e3);break;case "week":i=new Date(s.getTime()-10080*60*1e3);break;case "month":i=new Date(s.getTime()-720*60*60*1e3);break;case "year":i=new Date(s.getTime()-365*24*60*60*1e3);break;default:i=void 0;}let a="* type:post",c=e==="rising"?"children":e,p=i?i.toISOString().split(".")[0]:void 0,l="0",d=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=d);let g=await fetch(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(m),signal:Pe(Ae,o)});return xe(g,Fe)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:wt})}async function LK(e,t,r,n,o,i,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),o&&(a.scroll_id=o),i&&(a.votes=i);let p=await _()(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(a),signal:Pe(Ae,s)});return xe(p,Fe)}async function Hi(e,t,r=Ae){let o=await _()(f.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(e),signal:Pe(r,t)});return xe(o,Fe)}async function $K(e,t){let n=await _()(f.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify({q:e}),signal:Pe(Ae,t)}),o=await xe(n,Array.isArray);return o?.length>0?o:[e]}var sf=4368*60*60*1e3,af=4,cf=3e3,uf=2e3,pf=4e3,YK=2;function lf(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function df(e){let t=5381;for(let r=0;r>>0).toString(36)}function XK(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),o=lf(e.body??"",cf),i=df(`${t}|${n.join(",")}|${o}`);return reactQuery.queryOptions({queryKey:u.search.similarEntries(e.author,e.permlink,i),queryFn:async({signal:s})=>{let a=new Date(Date.now()-sf).toISOString().slice(0,19),c=await Hi({author:e.author,permlink:e.permlink,title:t,body:o,tags:n,since:a},s,typeof window>"u"?uf:pf),p=[],l=new Set;for(let d of c.results){if(p.length>=af)break;d.permlink!==e.permlink&&(d.tags??[]).indexOf("nsfw")===-1&&(l.has(d.author)||(l.add(d.author),p.push(d)));}return p},staleTime:300*1e3,retry:false})}function oB(e,t=5){let r=e.trim();return reactQuery.queryOptions({queryKey:u.search.account(r,t),queryFn:async()=>{let n=await y("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Qt(n)},enabled:!!r})}function uB(e,t=10){let r=e.trim();return reactQuery.queryOptions({queryKey:u.search.topics(r,t),queryFn:async()=>(await y("condenser_api.get_trending_tags",[r,t+1])).map(o=>o.name).filter(o=>o!==""&&!o.startsWith("hive-")).slice(0,t),enabled:!!r})}function gB(e,t,r,n,o,i){return reactQuery.infiniteQueryOptions({queryKey:u.search.api(e,t,r,n,o,i),queryFn:async({pageParam:s,signal:a})=>{let c={q:e,sort:t,hide_low:r};n&&(c.since=n),s&&(c.scroll_id=s),o!==void 0&&(c.votes=o),i&&(c.include_nsfw=1);let p=await fetch(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(c),signal:Pe(Ae,a)});return xe(p,Fe)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:wt})}function bB(e){return reactQuery.queryOptions({queryKey:["search","path",e],queryFn:async()=>{let t=await fetch(f.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.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 _f(e){let r=await _()(f.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 o=n?.message??`Failed to fetch support settings: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function AB(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 _f(t)},enabled:!!r&&!!t})}async function vf(e,t){let n=await _()(f.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 o;try{o=await n.json();}catch{}let i=o?.message??`Failed to update support settings: ${n.status}`,s=new Error(i);throw s.status=n.status,s.data=o,s}return await n.json()}function Pf(e,t,r){return e.setQueryData(u.support.settings(t),r),e.invalidateQueries({queryKey:u.support.settings(t)})}function kB(e,t){let r=reactQuery.useQueryClient(),n=e?.replace("@","");return reactQuery.useMutation({mutationKey:["support","settings-update",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return vf(t,o)},onSuccess(o){n&&Pf(r,n,o);}})}function FB(e){return reactQuery.queryOptions({queryKey:["promotions","boost-plus-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(f.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 KB(e){return reactQuery.queryOptions({queryKey:["promotions","rc-delegation-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(f.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 QB(e,t){return reactQuery.queryOptions({queryKey:["promotions","rc-delegation-active",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(f.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 jB(e){return reactQuery.queryOptions({queryKey:["promotions","promote-price"],queryFn:async()=>{let t=await fetch(f.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 GB(e,t){return reactQuery.queryOptions({queryKey:["promotions","boost-plus-accounts",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(f.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 XB(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:o})=>[Jr(e,n,o)],async(n,{account:o})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.promotions.boostPlusAccounts(o)]);},t,"active",{broadcastMode:r})}function rM(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[Yr(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 iM(e){let r=await _()(f.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let o;try{o=await r.json();}catch{o=void 0;}let i=new Error(`Failed to refresh token: ${r.status}`);throw i.status=r.status,i.data=o,i}return await r.json()}var Cf="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function uM(){return reactQuery.queryOptions({queryKey:u.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(Cf,{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 lM=1.1,Rf=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(Rf||{});function dM(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 If(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,o=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}}),i=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:o,poll_voters:i,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 hM(e,t){return reactQuery.queryOptions({queryKey:u.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:reactQuery.isServer?lo:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=_(),n=`${f.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,o=await r(n);if(!o.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${o.status}`);let i=await o.json();if(!Array.isArray(i)||!i[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return If(i[0])}})}function wM(e,t,r){return v(u.polls.vote(),e??"",({pollTrxId:n,choices:o})=>{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:o})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}var qf=-1e10,Df=5,Kf=30;var Ui=e=>Math.abs(e)>0&&Math.abs(e)<=100;function Vi(e){if(typeof e=="number"&&Ui(e)||typeof e=="string"&&(e=Number(e),Ui(e)))return Math.floor(e);if(e===0)return 25;let t=false;e<0&&(t=true);let r=Math.log10(Math.abs(e));return r=Math.max(r-9,0),r<0&&(r=0),t&&(r*=-1),r=r*9+25,Math.floor(r)}var Bf=["ecency.com","ecency.app","hive.blog","hive.io","hiveblocks.com","peakd.com","snapie.io","hivesuite.app","leofinance.io","inleo.io","3speak.tv","d.buzz","waivio.com"],Mf=["imgur.com","images.hive.blog","files.peakd.com","i.ecency.com","images.ecency.com","steemitimages.com","cdn.steemitimages.com","media.giphy.com"],Nf=/\.(jpe?g|png|gif|webp|svg|bmp|avif)(\?|#|$)/i,Qf=/(?:https?:)?\/\/[^\s)<>"'\]]+/gi,Hf=/[.,;:!?'"]+$/;function Uf(e){let t=/^(?:https?:)?\/\/([^/?#]+)/i.exec(e);return t?t[1].toLowerCase().replace(/^www\./,""):""}function Vf(e){let t=e.replace(Hf,"");if(Nf.test(t))return false;let r=Uf(t);if(!r.includes("."))return false;let n=o=>r===o||r.endsWith("."+o);return !(Bf.some(n)||Mf.some(n))}function ji(e){if(!e)return false;let t=e.match(Qf);return t?t.some(Vf):false}var jf=(n=>(n.MOD_MUTED="mod_muted",n.DOWNVOTED="downvoted",n.LOW_TRUST="low_trust",n))(jf||{});function Lf(e){return e?.stats?.total_votes??e?.active_votes?.length??0}function $f(e,t){return (e??0)<-1e10&&t>=5}function Wf(e){let t=e?.author_reputation;return t==null?false:Vi(t)<30&&ji(e?.body)}function SM(e,t){return !!e&&!!t?.includes(e)}function kM(e){return e?e.stats?.gray||e.stats?.hide?"mod_muted":$f(e.net_rshares,Lf(e))?"downvoted":Wf(e)?"low_trust":null:null}/** +'use strict';var reactQuery=require('@tanstack/react-query'),utils_js=require('@noble/hashes/utils.js'),legacy_js=require('@noble/hashes/legacy.js'),xn=require('bs58'),secp256k1_js=require('@noble/curves/secp256k1.js'),sha2_js=require('@noble/hashes/sha2.js'),aes_js=require('@noble/ciphers/aes.js'),mo=require('hivesigner');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var xn__default=/*#__PURE__*/_interopDefault(xn);var mo__default=/*#__PURE__*/_interopDefault(mo);var as=Object.defineProperty;var Ot=(e,t)=>{for(var r in t)as(e,r,{get:t[r],enumerable:true});};var xt=new ArrayBuffer(0),St=null,Et=null;function us(){return St||(typeof TextEncoder<"u"?St=new TextEncoder:St={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)}}),St}function _n(){return Et||(typeof TextDecoder<"u"?Et=new TextDecoder:Et={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+(i&1023)));}return r}}),Et}var D=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?xt:new ArrayBuffer(t),this.view=t===0?new DataView(xt):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(xt));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 o;return t instanceof e?(o=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=o.length):t instanceof Uint8Array?o=t:t instanceof ArrayBuffer?o=new Uint8Array(t):o=new Uint8Array(t),o.length<=0?this:(r+o.length>this.buffer.byteLength&&this.resize(r+o.length),new Uint8Array(this.buffer).set(o,r),n&&(this.offset+=o.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,o=new e(n,this.littleEndian);return o.offset=0,o.limit=n,new Uint8Array(o.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),o}copyTo(t,r,n,o){let i=typeof r>"u",s=typeof n>"u";r=i?t.offset:r,n=s?this.offset:n,o=o===void 0?this.limit:o;let a=o-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,o),r),s&&(this.offset+=a),i&&(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?xt: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 o=this.calculateVarint32(t);for(r+o>this.buffer.byteLength&&this.resize(r+o),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):o}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,o=0,i;do i=this.view.getUint8(t++),n<5&&(o|=(i&127)<<7*n),++n;while((i&128)!==0);return o|=0,r?(this.offset=t,o):{value:o,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",o=n?this.offset:r,i=us().encode(t),s=i.length,a=this.calculateVarint32(s);return o+a+s>this.buffer.byteLength&&this.resize(o+a+s),this.writeVarint32(s,o),o+=a,new Uint8Array(this.buffer).set(i,o),o+=s,n?(this.offset=o,this):o-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,o=this.readVarint32(t),i=o.value,s=o.length;t+=s;let a=_n().decode(new Uint8Array(this.buffer,t,i));return t+=i,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 o=_n().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,o):{string:o,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}},wn=["bridge.get_ranked_posts","bridge.get_account_posts","bridge.get_post","bridge.get_discussion","bridge.get_profile","bridge.get_profiles","bridge.get_community","bridge.list_communities","condenser_api.get_accounts","condenser_api.get_content","condenser_api.get_dynamic_global_properties","condenser_api.get_trending_tags"],kt=null,sr=e=>{if(e===null){kt=null;return}if(!e||typeof e!="object")return;let t=typeof e.url=="string"?e.url.trim():"";if(!/^https?:\/\//i.test(t))return;let r={};if(e.headers&&typeof e.headers=="object")for(let[s,a]of Object.entries(e.headers))typeof a=="string"&&a&&!/[\u0000-\u001f\u007f]/.test(a)&&!/[\u0000-\u001f\u007f]/.test(s)&&(r[s]=a);let n=typeof e.timeoutMs=="number"&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:2e3,o=e.methods===void 0?[...wn]:Array.isArray(e.methods)?e.methods.filter(s=>typeof s=="string"&&s.includes(".")):[];if(o.length===0)return;let i=(s,a)=>typeof s=="number"&&Number.isFinite(s)&&s>0?s:a;kt={url:t,headers:r,timeoutMs:n,methods:o,failureThreshold:Math.floor(i(e.failureThreshold,3)),cooldownMs:i(e.cooldownMs,1e4),methodSet:new Set(o)};},ar=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)))]:[],ur=e=>{let t=ar(e);t.length&&(x.nodes=t);},cr=e=>{let t=ar(e);t.length&&(x.restNodes=t);},pr=e=>{if(!e||typeof e!="object")return;let t={...x.restNodesByApi};for(let[r,n]of Object.entries(e)){let o=ar(n);o.length?t[r]=o:delete t[r];}x.restNodesByApi=t;},lr=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(x.userAgent=t);},dr=e=>{if(!e||typeof e!="object")return;let t=x.resilience,r=o=>typeof o=="boolean",n=o=>typeof o=="number"&&Number.isFinite(o)&&o>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 Se=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,o=true;n<0&&(o=false,n=n+4);let i=r.subarray(1);return new e(i,n,o)}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 Y(n.recoverPublicKey(t).toBytes())}};var Y=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 o;try{o=xn__default.default.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(o.length!==37)throw new Error("Invalid public key length");let i=o.subarray(0,33),s=o.subarray(33,37),a=legacy_js.ripemd160(i).subarray(0,4);if(!ps(s,a))throw new Error("Public key checksum mismatch");try{secp256k1_js.secp256k1.Point.fromBytes(i);}catch{throw new Error("Invalid public key")}return new e(i,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=Se.from(r)),secp256k1_js.secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return cs(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},cs=(e,t)=>{let r=legacy_js.ripemd160(e);return t+xn__default.default.encode(new Uint8Array([...e,...r.subarray(0,4)]))},ps=(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);},fs=(e,t)=>{e.writeInt16(t);},En=(e,t)=>{e.writeInt64(t);},Sn=(e,t)=>{e.writeUint8(t);},pe=(e,t)=>{e.writeUint16(t);},X=(e,t)=>{e.writeUint32(t);},kn=(e,t)=>{e.writeUint64(t);},we=(e,t)=>{e.writeByte(t?1:0);},Cn=e=>(t,r)=>{let[n,o]=r;t.writeVarint32(n),e[n](t,o);},I=(e,t)=>{let r=Ct.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let o=0;o<7;o++)e.writeUint8(r.symbol.charCodeAt(o)||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(Y.from(t).key);},Rn=(e=null)=>(t,r)=>{r=Rt.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);},Tn=Rn(),fr=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[o,i]of n)e(r,o),t(r,i);},V=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},le=e=>(t,r)=>{for(let[n,o]of e)try{o(t,r[n]);}catch(i){throw i.message=`${n}: ${i.message}`,i}},Ie=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},W=le([["weight_threshold",X],["account_auths",fr(w,pe)],["key_auths",fr(ge,pe)]]),ms=le([["account",w],["weight",pe]]),mr=le([["base",I],["quote",I]]),gs=le([["account_creation_fee",I],["maximum_block_size",X],["hbd_interest_rate",pe]]),R=(e,t)=>{let r=le(t);return (n,o)=>{n.writeVarint32(e),r(n,o);}},E={};E.account_create=R(C.account_create,[["fee",I],["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",w]]);E.account_create_with_delegation=R(C.account_create_with_delegation,[["fee",I],["delegation",I],["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",w],["extensions",V(ie)]]);E.account_update=R(C.account_update,[["account",w],["owner",Ie(W)],["active",Ie(W)],["posting",Ie(W)],["memo_key",ge],["json_metadata",w]]);E.account_witness_proxy=R(C.account_witness_proxy,[["account",w],["proxy",w]]);E.account_witness_vote=R(C.account_witness_vote,[["account",w],["witness",w],["approve",we]]);E.cancel_transfer_from_savings=R(C.cancel_transfer_from_savings,[["from",w],["request_id",X]]);E.change_recovery_account=R(C.change_recovery_account,[["account_to_recover",w],["new_recovery_account",w],["extensions",V(ie)]]);E.claim_account=R(C.claim_account,[["creator",w],["fee",I],["extensions",V(ie)]]);E.claim_reward_balance=R(C.claim_reward_balance,[["account",w],["reward_hive",I],["reward_hbd",I],["reward_vests",I]]);E.comment=R(C.comment,[["parent_author",w],["parent_permlink",w],["author",w],["permlink",w],["title",w],["body",w],["json_metadata",w]]);E.comment_options=R(C.comment_options,[["author",w],["permlink",w],["max_accepted_payout",I],["percent_hbd",pe],["allow_votes",we],["allow_curation_rewards",we],["extensions",V(Cn([le([["beneficiaries",V(ms)]])]))]]);E.convert=R(C.convert,[["owner",w],["requestid",X],["amount",I]]);E.create_claimed_account=R(C.create_claimed_account,[["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",w],["extensions",V(ie)]]);E.custom=R(C.custom,[["required_auths",V(w)],["id",pe],["data",Tn]]);E.custom_json=R(C.custom_json,[["required_auths",V(w)],["required_posting_auths",V(w)],["id",w],["json",w]]);E.decline_voting_rights=R(C.decline_voting_rights,[["account",w],["decline",we]]);E.delegate_vesting_shares=R(C.delegate_vesting_shares,[["delegator",w],["delegatee",w],["vesting_shares",I]]);E.delete_comment=R(C.delete_comment,[["author",w],["permlink",w]]);E.escrow_approve=R(C.escrow_approve,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",X],["approve",we]]);E.escrow_dispute=R(C.escrow_dispute,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",X]]);E.escrow_release=R(C.escrow_release,[["from",w],["to",w],["agent",w],["who",w],["receiver",w],["escrow_id",X],["hbd_amount",I],["hive_amount",I]]);E.escrow_transfer=R(C.escrow_transfer,[["from",w],["to",w],["hbd_amount",I],["hive_amount",I],["escrow_id",X],["agent",w],["fee",I],["json_meta",w],["ratification_deadline",Ee],["escrow_expiration",Ee]]);E.feed_publish=R(C.feed_publish,[["publisher",w],["exchange_rate",mr]]);E.limit_order_cancel=R(C.limit_order_cancel,[["owner",w],["orderid",X]]);E.limit_order_create=R(C.limit_order_create,[["owner",w],["orderid",X],["amount_to_sell",I],["min_to_receive",I],["fill_or_kill",we],["expiration",Ee]]);E.limit_order_create2=R(C.limit_order_create2,[["owner",w],["orderid",X],["amount_to_sell",I],["exchange_rate",mr],["fill_or_kill",we],["expiration",Ee]]);E.recover_account=R(C.recover_account,[["account_to_recover",w],["new_owner_authority",W],["recent_owner_authority",W],["extensions",V(ie)]]);E.request_account_recovery=R(C.request_account_recovery,[["recovery_account",w],["account_to_recover",w],["new_owner_authority",W],["extensions",V(ie)]]);E.reset_account=R(C.reset_account,[["reset_account",w],["account_to_reset",w],["new_owner_authority",W]]);E.set_reset_account=R(C.set_reset_account,[["account",w],["current_reset_account",w],["reset_account",w]]);E.set_withdraw_vesting_route=R(C.set_withdraw_vesting_route,[["from_account",w],["to_account",w],["percent",pe],["auto_vest",we]]);E.transfer=R(C.transfer,[["from",w],["to",w],["amount",I],["memo",w]]);E.transfer_from_savings=R(C.transfer_from_savings,[["from",w],["request_id",X],["to",w],["amount",I],["memo",w]]);E.transfer_to_savings=R(C.transfer_to_savings,[["from",w],["to",w],["amount",I],["memo",w]]);E.transfer_to_vesting=R(C.transfer_to_vesting,[["from",w],["to",w],["amount",I]]);E.vote=R(C.vote,[["voter",w],["author",w],["permlink",w],["weight",fs]]);E.withdraw_vesting=R(C.withdraw_vesting,[["account",w],["vesting_shares",I]]);E.witness_update=R(C.witness_update,[["owner",w],["url",w],["block_signing_key",ge],["props",gs],["fee",I]]);E.witness_set_properties=R(C.witness_set_properties,[["owner",w],["props",fr(w,Tn)],["extensions",V(ie)]]);E.account_update2=R(C.account_update2,[["account",w],["owner",Ie(W)],["active",Ie(W)],["posting",Ie(W)],["memo_key",Ie(ge)],["json_metadata",w],["posting_json_metadata",w],["extensions",V(ie)]]);E.create_proposal=R(C.create_proposal,[["creator",w],["receiver",w],["start_date",Ee],["end_date",Ee],["daily_pay",I],["subject",w],["permlink",w],["extensions",V(ie)]]);E.update_proposal_votes=R(C.update_proposal_votes,[["voter",w],["proposal_ids",V(En)],["approve",we],["extensions",V(ie)]]);E.remove_proposal=R(C.remove_proposal,[["proposal_owner",w],["proposal_ids",V(En)],["extensions",V(ie)]]);var ys=le([["end_date",Ee]]);E.update_proposal=R(C.update_proposal,[["proposal_id",kn],["creator",w],["daily_pay",I],["subject",w],["permlink",w],["extensions",V(Cn([ie,ys]))]]);E.collateralized_convert=R(C.collateralized_convert,[["owner",w],["requestid",X],["amount",I]]);E.recurrent_transfer=R(C.recurrent_transfer,[["from",w],["to",w],["amount",I],["memo",w],["recurrence",pe],["executions",pe],["extensions",V(le([["type",Sn],["value",le([["pair_id",Sn]])]]))]]);var hs=(e,t)=>{let r=E[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}},_s=le([["ref_block_num",pe],["ref_block_prefix",X],["expiration",Ee],["operations",V(hs)],["extensions",V(w)]]),ws=le([["from",ge],["to",ge],["nonce",kn],["check",X],["encrypted",Rn()]]),de={Asset:I,Memo:ws,Price:mr,PublicKey:ge,String:w,Transaction:_s,UInt16:pe,UInt32:X};var st=e=>new Promise(t=>setTimeout(t,e));var Nn=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function wr(){return Nn?{"User-Agent":x.userAgent}:{}}var Ce={served:0,fallback:0,skipped:0,fallbackByReason:{status:0,rpcerror:0,timeout:0,transport:0,validate:0,parse:0}},Re=class extends Error{constructor(r,n){super(n);this.reason=r;}reason},qn=e=>e instanceof Error?e.message:typeof e=="string"?e:String(e),Tt=0,Fn=0;async function bs(e,t,r,n,o,i){let s=t.indexOf(".");if(s<=0||s===t.length-1)throw new Re("transport",`method without an api prefix: ${t}`);let{signal:a,cleanup:c}=vr(Math.min(e.timeoutMs,n)),{signal:p,cleanup:l}=Dt(a,o);try{let f;try{f=await fetch(e.url,{method:"POST",body:JSON.stringify({api:t.slice(0,s),method:t.slice(s+1),params:r}),headers:{"Content-Type":"application/json",...wr(),...e.headers},signal:p});}catch(g){throw o?.aborted?g:new Re(a.aborted?"timeout":"transport",qn(g))}if(f.status!==200){try{await f.body?.cancel();}catch{}let g=f.status===502&&(f.headers.get("x-ssr-cache")??"").toUpperCase()==="RPCERROR";throw new Re(g?"rpcerror":"status",g?"proxy relayed a node error":`proxy answered ${f.status}`)}let m;try{m=await f.json();}catch(g){throw o?.aborted?g:new Re(a.aborted?"timeout":"parse",qn(g))}if(i&&!i(m))throw new Re("validate","proxy result rejected by validator");return m}finally{c(),l();}}var Z=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);}},De=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 Bn(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 vs=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],Ps=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function As(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 Os(e){if(!e)return false;if(e instanceof De)return true;if(e instanceof Z)return false;let t=As(e);return !!(vs.some(r=>t.includes(r))||Ps.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function gr(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function Mn(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var xs=1e4,Ss=6e4,Es=12e4,In=2,Dn=6e4,Kn=12e4,ks=30,at=.3,yr=3,ut=5*6e4,Qn=6e4,Hn=1e3,Un=2e3,Ft=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,o){let i=this.getOrCreate(t);if(i.consecutiveFailures=0,i.rateLimitStreak=0,r){let s=i.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&i.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(i,n,o??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=yr&&o-i.updatedAt<=ut?i.ewmaMs:void 0}return this.isLatencyUsable(n,o)?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 o=Date.now();if(t.latencyUpdatedAt>0&&o-t.latencyUpdatedAt>ut&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:at*r+(1-at)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=o,n!==void 0){let i=t.apiLatency.get(n);!i||o-i.updatedAt>ut?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:o}):(i.ewmaMs=at*r+(1-at)*i.ewmaMs,i.sampleCount++,i.updatedAt=o);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(i.cooldownUntil>0&&i.cooldownUntil<=o||i.lastFailureTime>0&&o-i.lastFailureTime>3e4)&&(i.count=0,i.cooldownUntil=0),i.count++,i.lastFailureTime=o,i.count>=In&&(i.cooldownUntil=o+Dn),n.apiFailures.set(r,i);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};i.count=Math.max(i.count+1,In),i.lastFailureTime=o,i.cooldownUntil=o+Dn,i.defective=true,n.apiFailures.set(r,i);}recordRateLimit(t,r){let n=this.getOrCreate(t),o=Date.now();n.rateLimitStreak>0&&o-n.lastRateLimitAt>Es&&(n.rateLimitStreak=0);let i=typeof r=="number"&&Number.isFinite(r)&&r>0,s=i?r:Math.min(xs*2**n.rateLimitStreak,Ss);i||n.rateLimitStreak++,n.lastRateLimitAt=o,n.rateLimitedUntil=i?o+s:Math.max(n.rateLimitedUntil,o+s),n.consecutiveFailures++,n.lastFailureTime=o;}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<=Kn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,o)=>n-o),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let o=Date.now();if(n.rateLimitedUntil>o||n.consecutiveFailures>=3&&o-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>o)return false}let i=this.consensusHeadBlock();return !(i>0&&n.headBlock>0&&o-n.headBlockUpdatedAt<=Kn&&i-n.headBlock>ks)}getOrderedNodes(t,r){let n=[],o=[];for(let c of t)this.isNodeHealthy(c,r)?n.push(c):o.push(c);if(n.length<=1)return [...n,...o];let i=Date.now(),s=n.map((c,p)=>({node:c,i:p,score:this.scoreNode(c,i)})).sort((c,p)=>c.score-p.score||c.i-p.i).map(c=>c.node),a=this.pickReprobeCandidate(n,i);return a&&s[0]!==a?[a,...s.filter(c=>c!==a),...o]:[...s,...o]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=yr&&r-t.latencyUpdatedAt<=ut}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:Hn}pickReprobeCandidate(t,r){let n=r-Qn,o,i=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;}},_r=new hr;function It(e,t,r,n,o){let i=x.resilience;if(!i.adaptiveTimeout||o)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(i.adaptiveTimeoutFloorMs,i.adaptiveTimeoutFactor*s)))}function br(e,t,r,n){r instanceof De?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof Z?e.recordFailure(t,n):e.recordFailure(t);}function Vn(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let o=n.head_block_number;typeof o=="number"&&e.recordHeadBlock(t,o);}function Cs(){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 vr(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(Cs()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function Dt(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),o=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",o,{once:true});let i=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o);};return {signal:r.signal,cleanup:i}}var ct=async(e,t,r,n=x.timeout,o=false,i)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:c,cleanup:p}=vr(n),{signal:l,cleanup:f}=Dt(c,i),m=()=>{p(),f();};try{let g=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...wr()},signal:l});if(g.status===429)throw new De(e,"HTTP 429 Rate Limited",{rateLimitMs:Bn(g.headers.get("Retry-After")),isRateLimit:!0});if(g.status>=500&&g.status<600)throw new De(e,`HTTP ${g.status} from ${e}`);let _=await g.json();if(!_||typeof _.id>"u"||_.id!==s||_.jsonrpc!=="2.0")throw new Error("JSONRPC id mismatch");if("result"in _)return _.result;if("error"in _){let P=_.error;throw "message"in P&&"code"in P?new Z(P):_.error}throw _}catch(g){if(g instanceof Z||g instanceof De||i?.aborted)throw g;if(o)return ct(e,t,r,n,false,i);throw g}finally{m();}};function qt(){return st(50+Math.random()*50)}function Rs(e){let{method:t,params:r,api:n,primary:o,hedgePool:i,callerTimeout:s,explicitTimeout:a,deadlineAt:c,externalSignal:p,onHedgeFired:l,validate:f}=e;return new Promise((m,g)=>{let _=false,P=0,O=false,T=false,q,ce,A=0,$=[],M=J=>{if(!_){_=true,ce!==void 0&&(clearTimeout(ce),ce=void 0);for(let F of $)F.signal.aborted||F.abort();J();}},H=(J,F)=>{P++;let me=new AbortController;$.push(me);let it=Dt(me.signal,p),ss=It(j,J,t,s,a),ir=Date.now();F||(A=ir),ct(J,t,r,ss,false,it.signal).then(oe=>{if(it.cleanup(),P--,F||(T=true),!_){if(f&&!f(oe)){if(j.recordDefectiveResponse(J,n),q=new Error(`[hive-tx] response validation failed for ${t} from ${J}`),!F&&!O){M(()=>g(q));return}P===0&&M(()=>g(q));return}j.recordSuccess(J,n,Date.now()-ir,t),Vn(j,J,t,oe),F?T||j.recordCensoredLatency(o,Date.now()-A,t):O||_r.refill(),M(()=>m(oe));}}).catch(oe=>{if(it.cleanup(),P--,F||(T=true),!_){if(p?.aborted){M(()=>g(oe));return}if(oe instanceof Z&&!gr(oe.code,oe.message)){M(()=>g(oe));return}if(br(j,J,oe,n),j.recordSlowFailure(J,Date.now()-ir,t),q=oe,!F&&!O){M(()=>g(oe));return}P===0&&M(()=>g(q));}});};H(o,false);let z=j.getUsableLatencyMs(o,t)??0,L=It(j,o,t,s,a),ot=Math.min(Math.max(x.resilience.hedgeDelayFloorMs,x.resilience.hedgeDelayFactor*z),.8*L);ce=setTimeout(()=>{if(ce=void 0,_||p?.aborted||Date.now()>=c)return;let J=i.filter(me=>j.isNodeHealthy(me,n));if(J.length===0)return;let F=J[Math.floor(Math.random()*J.length)];_r.trySpend()&&(O=true,l(F),H(F,true));},ot);})}var y=async(e,t=[],r,n=x.retry,o,i)=>{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=Mn(e),p=kt;if(p&&Nn&&p.methodSet.has(e))if(Date.now()=p.failureThreshold&&(Fn=Date.now()+p.cooldownMs,Tt=0);}let l=Date.now()+x.resilience.totalBudgetFactor*a,f=new Set,m;for(let g=0;g<=n&&!(g>0&&Date.now()>=l);g++){let _=j.getOrderedNodes(x.nodes,c),P=_.find(q=>!f.has(q));P||(f.clear(),P=_[0]),f.add(P);let O=[];if(x.resilience.hedge&&j.getUsableLatencyMs(P,e)!==void 0&&(O=_.filter(q=>!f.has(q)&&j.isNodeHealthy(q,c)).slice(0,3)),O.length>0)try{return await Rs({method:e,params:t,api:c,primary:P,hedgePool:O,callerTimeout:a,explicitTimeout:s,deadlineAt:l,externalSignal:o,onHedgeFired:q=>f.add(q),validate:i})}catch(q){if(q instanceof Z&&!gr(q.code,q.message)||o?.aborted)throw q;m=q,g{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 o=Mn(e),i=new Set,s;for(let a=0;a!i.has(l));if(!p)break;if(i.add(p),n?.aborted)throw new Error("Aborted");try{let l=await ct(p,e,t,r,!1,n);return j.recordSuccess(p,o),l}catch(l){if(l instanceof Z||n?.aborted||(br(j,p,l,o),s=l,!Os(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 te(e,t,r,n,o=x.retry,i){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,g=false;for(let _=0;_<=o&&!(_>0&&Date.now()>=c);_++){let P=ke.getOrderedNodes(l,e),O=P.find(F=>!f.has(F));O||(f.clear(),O=P[0]),f.add(O);let T=O+Ts[e],q=t,ce=r||{},A=new Set;Object.entries(ce).forEach(([F,me])=>{q.includes(`{${F}}`)&&(q=q.replace(`{${F}}`,encodeURIComponent(String(me))),A.add(F));});let $=new URL(T+q);if(Object.entries(ce).forEach(([F,me])=>{A.has(F)||(Array.isArray(me)?me.forEach(it=>$.searchParams.append(F,String(it))):$.searchParams.set(F,String(me)));}),i?.aborted)throw new Error("Aborted");g=false;let{signal:M,cleanup:H}=vr(It(ke,O,p,a,s)),{signal:z,cleanup:L}=Dt(M,i),ot=()=>{H(),L();},J=Date.now();try{let F=await fetch($.toString(),{signal:z,headers:wr()});if(F.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(F.status===429)throw ke.recordRateLimit(O,Bn(F.headers.get("Retry-After"))||void 0),g=!0,new Error(`HTTP 429 Rate Limited by ${O}`);if(F.status===503)throw ke.recordFailure(O,e),g=!0,new Error(`HTTP 503 Service Unavailable from ${O}`);if(!F.ok)throw ke.recordFailure(O,e),g=!0,new Error(`HTTP ${F.status} from ${O}`);return ke.recordSuccess(O,e,Date.now()-J,p),F.json()}catch(F){if(F?.message?.includes("HTTP 404")||i?.aborted)throw F;g||ke.recordFailure(O,e),ke.recordSlowFailure(O,Date.now()-J,p),m=F,_{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 i=(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,i.length),a=[];for(;s>0&&i.length>0;){let c=i.splice(0,s),p=[],l=[];for(let m=0;ml.push(g)).catch(()=>{}));await Promise.all(p),a.push(...l);let f=qs(a,r);if(f)return f;if(s=Math.min(r,i.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function qs(e,t){let r=new Map;for(let o of e){let i=JSON.stringify(o);r.has(i)||r.set(i,[]),r.get(i).push(o);}let n=Array.from(r.values()).find(o=>o.length>=t);return n?n[0]:null}var Is=utils_js.hexToBytes(x.chain_id),Ke=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 o of t){let i=o.sign(r);this.transaction.signatures.push(i.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 We("condenser_api.broadcast_transaction",[this.transaction]);}catch(i){if(!(i instanceof Z&&i.message.includes("Duplicate transaction check failed")))throw i}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await st(1e3);let n=await this.checkStatus(),o=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&o{let r=await y("condenser_api.get_dynamic_global_properties",[]),n=utils_js.hexToBytes(r.head_block_id),o=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),i=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:i,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:o,signatures:[]};}};var zn=new Uint8Array([128]),U=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(Bs(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 o=0;o>6,128|i&63);else if(i>=55296&&i<=56319&&o+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else n.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(n);}return new e(sha2_js.sha256(t))}static fromLogin(t,r,n="active"){let o=t+n+r;return e.fromSeed(o)}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 Se.from((n+31).toString(16)+utils_js.bytesToHex(r.subarray(1)))}createPublic(t){return new Y(secp256k1_js.secp256k1.getPublicKey(this.key),t)}toString(){return Ns(new Uint8Array([...zn,...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)}},Jn=e=>sha2_js.sha256(sha2_js.sha256(e)),Ns=e=>{let t=Jn(e);return xn__default.default.encode(new Uint8Array([...e,...t.slice(0,4)]))},Bs=e=>{let t=xn__default.default.decode(e);if(!Wn(t.slice(0,1),zn))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),o=Jn(n).slice(0,4);if(!Wn(r,o))throw new Error("Private key checksum mismatch");return n},Wn=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;neo(e,t,n,r),Zn=(e,t,r,n,o)=>eo(e,t,r,n,o).message,eo=(e,t,r,n,o)=>{let i=r,s=e.getSharedSecret(t),a=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);a.writeUint64(i),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 D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);m.append(f),m.flip();let g=m.readUint32();if(o!==void 0){if(g!==o)throw new Error("Invalid key");n=Us(n,l,p);}else n=Vs(n,l,p);return {nonce:i,message:n,checksum:g}},Us=(e,t,r)=>{let n=e;return n=aes_js.cbc(t,r).decrypt(n),n},Vs=(e,t,r)=>{let n=e;return n=aes_js.cbc(t,r).encrypt(n),n},Ar=null,js=()=>{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=Js(e,33);return new Y(t)},$s=e=>e.readUint64(),Ws=e=>e.readUint32(),Gs=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},zs=e=>t=>{let r={},n=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);n.append(t),n.flip();for(let[o,i]of e)try{r[o]=i(n);}catch(s){throw s.message=`${o}: ${s.message}`,s}return r};function Js(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=zs([["from",to],["to",to],["nonce",$s],["check",Ws],["encrypted",Gs]]),ro={Memo:Ys};var oo=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),so(),e=ao(e),t=Xs(t);let o=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);o.writeVString(r);let i=new Uint8Array(o.copy(0,o.offset).toBuffer()),{nonce:s,message:a,checksum:c}=Xn(e,t,i,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 "#"+xn__default.default.encode(l)},io=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),so(),e=ao(e);let r=ro.Memo(xn__default.default.decode(t)),{from:n,to:o,nonce:i,check:s,encrypted:a}=r,p=e.createPublic().toString()===new Y(n.key).toString()?new Y(o.key):new Y(n.key);r=Zn(e,p,i,a,s);let l=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},Nt,so=()=>{if(Nt===void 0){let e;Nt=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=oo(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=io(t,n);}finally{Nt=e==="#memo\u7231";}}if(Nt===false)throw new Error("This environment does not support encryption.")},ao=e=>typeof e=="string"?U.fromString(e):e,Xs=e=>typeof e=="string"?Y.fromString(e):e,uo={decode:io,encode:oo};var ne={};Ot(ne,{buildWitnessSetProperties:()=>oa,makeBitMaskFilter:()=>ra,operations:()=>ta,validateUsername:()=>ea});var ea=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("."),o=n.length;for(let i=0;ie.reduce(na,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),na=([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 o;switch(n){case "key":case "new_signing_key":o=de.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":o=de.UInt32;break;case "hbd_interest_rate":o=de.UInt16;break;case "url":o=de.String;break;case "hbd_exchange_rate":o=de.Price;break;case "account_creation_fee":o=de.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,ia(o,t[n])]);}return r.props.sort((n,o)=>n[0].localeCompare(o[0])),["witness_set_properties",r]},ia=(e,t)=>{let r=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return e(r,t),r.flip(),utils_js.bytesToHex(new Uint8Array(r.toBuffer()))};function Dg(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|o&63);else if(o>=55296&&o<=56319&&n+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else r.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(r);}else t=e;return sha2_js.sha256(t)}function co(e){try{return U.fromString(e),!0}catch{return false}}async function ee(e,t){let r=new Ke;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),We("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function po(e,t){let r=new Ke;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var aa=432e3;function lo(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/aa,o=Math.round(n/e*1e4);return !isFinite(o)||o<0?o=0:o>1e4&&(o=1e4),{current_mana:n,max_mana:e,percentage:o}}function ua(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),o=parseFloat(e.vesting_withdraw_rate),i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t-s-r+n}function Or(e){let t=ua(e)*1e6;return lo(t,e.voting_manabar)}function Bt(e){return lo(Number(e.max_rc),e.rc_manabar)}var fo=(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))(fo||{});function Ge(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",o=t||r||String(e||""),i=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||o&&a.test(o));if(i(/please wait to transact/i)||i(/insufficient rc/i)||i(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(i(/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(i(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(i(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(i(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(i(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(i(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(i(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(i(/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(i(/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(i(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(i(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(i(/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"||i(/token expired/i)||i(/invalid token/i)||i(/\bunauthorized\b/i)||i(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(i(/has already reblogged/i)||i(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(i(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(i(/econnrefused/i)||i(/connection refused/i)||i(/failed to fetch/i)||i(/\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(i(/timeout/i)||i(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(i(/account.*does not exist/i)||i(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(i(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(i(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(i(/\b(invalid|validation)\b/i))return {message:(e?.message||o).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}`:o&&o!=="[object Object]"?s=o.substring(0,150):s="Unknown error occurred":s=o.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function ca(e){let t=Ge(e);return [t.message,t.type]}function be(e){let{type:t}=Ge(e);return t==="missing_authority"||t==="token_expired"}function pa(e){let{type:t}=Ge(e);return t==="insufficient_resource_credits"}function la(e){let{type:t}=Ge(e);return t==="info"}function da(e){let{type:t}=Ge(e);return t==="network"||t==="timeout"}async function ve(e,t,r,n,o="posting",i,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=i;if(p===void 0)switch(o){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 ${o} key available for ${t}`);let l=U.fromString(p);return a==="async"?await po(r,l):await ee(r,l)}case "hiveauth":{if(!c?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await c.broadcastWithHiveAuth(t,r,o)}case "hivesigner":{if(!c)throw new Error("No adapter provided for HiveSigner auth");if(o!=="posting"){if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);throw new Error(`HiveSigner access token cannot sign ${o} operations. No platform broadcast available.`)}let p=s!==void 0?s:await c.getAccessToken(t);if(p)try{return (await new mo__default.default.Client({accessToken:p}).broadcast(r)).result}catch(l){if(c.broadcastWithHiveSigner&&be(l))return await c.broadcastWithHiveSigner(t,r,o);throw l}if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);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,o)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,o)}default:throw new Error(`Unknown auth method: ${e}`)}}async function ma(e,t,r,n="posting",o="async"){let i=r?.adapter;if(i?.getLoginType){let l=await i.getLoginType(e,n);if(l){let f=i.hasPostingAuthorization?await i.hasPostingAuthorization(e):false;if(n==="posting"&&f&&l==="key")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!be(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&f&&l==="keychain")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!be(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 ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!be(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await ve(l,e,t,r,n,void 0,void 0,o)}catch(m){if(be(m)&&i.showAuthUpgradeUI&&(n==="posting"||n==="active")){let g=t.length>0?t[0][0]:"unknown",_=await i.showAuthUpgradeUI(n,g);if(!_)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ve(_,e,t,r,n,void 0,void 0,o)}throw m}}if(n==="posting")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(f){if(be(f)&&i.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",g=await i.showAuthUpgradeUI(n,m);if(!g)throw new Error(`No login type available for ${e}. Please log in again.`);return await ve(g,e,t,r,n,void 0,void 0,o)}throw f}else if(n==="active"&&i.showAuthUpgradeUI){let f=t.length>0?t[0][0]:"unknown",m=await i.showAuthUpgradeUI(n,f);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ve(m,e,t,r,n,void 0,void 0,o)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let f=!1,m="",g,_;switch(l){case "key":if(!i)f=!0,m="No adapter provided";else {let P;switch(n){case "owner":i.getOwnerKey&&(P=await i.getOwnerKey(e));break;case "active":i.getActiveKey&&(P=await i.getActiveKey(e));break;case "memo":i.getMemoKey&&(P=await i.getMemoKey(e));break;default:P=await i.getPostingKey(e);break}P?g=P:(f=!0,m=`No ${n} key available`);}break;case "hiveauth":i?.broadcastWithHiveAuth||(f=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!i)f=!0,m="No adapter provided";else {let P=await i.getAccessToken(e);P&&(_=P);}break;case "keychain":i?.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 ve(l,e,t,r,n,g,_,o)}catch(f){if(a.set(l,f),!be(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=()=>{},o,i="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(o?.enableFallback!==!1&&o?.adapter)return await ma(t,p,o,i,a);if(o?.broadcast)return await o.broadcast(p,i);let l=o?.postingKey;if(l){if(i!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${i}' was requested. Use AuthContextV2 with an adapter for ${i} operations.`);let m=U.fromString(l);return await ee(p,m)}let f=o?.accessToken;if(f)return (await new mo__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 Z?new Error(l.message):l}}})}async function go(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let o={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",o]],"posting");let i=n?.postingKey;if(i){let c=U.fromString(i);return ee([["custom_json",o]],c)}let s=n?.accessToken;if(s)return (await new mo__default.default.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let c=[["custom_json",o]];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 Yg=4e3;function S(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function Pe(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,o=()=>{let i=t.aborted?t.reason:r.reason;n.abort(i),t.removeEventListener("abort",o),r.removeEventListener("abort",o);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",o,{once:true}),r.addEventListener("abort",o,{once:true})),n.signal}var Ne=(()=>{try{return process.env?.NODE_ENV==="development"}catch{return false}})(),ha=()=>{try{return process.env?.VITE_HELIUS_API_KEY}catch{return}},Ae=1e4,yo=120*1e3,Mt,_a;function wa(){return Mt?Mt():_a??=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:ha(),get queryClient(){return wa()},set queryClient(e){Mt=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false};exports.ConfigManager=void 0;(ce=>{function e(A){d.queryClient=A;}ce.setQueryClient=e;function t(A){Mt=A;}ce.setQueryClientResolver=t;function r(A){d.privateApiHost=A;}ce.setPrivateApiHost=r;function n(A){d.clientId=A;}ce.setClientId=n;function o(A){if(typeof A!="string"||A.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=A;}ce.setDefaultObserver=o;function i(){return d.privateApiHost?d.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}ce.getValidatedBaseUrl=i;function s(A){d.pollsApiHost=A;}ce.setPollsApiHost=s;function a(A){d.imageHost=A;}ce.setImageHost=a;function c(A){ur(A);}ce.setHiveNodes=c;function p(A){cr(A);}ce.setRestNodes=p;function l(A){pr(A);}ce.setRestNodesByApi=l;function f(A){lr(A);}ce.setUserAgent=f;function m(A){dr(A);}ce.setResilience=m;function g(A){sr(A);}ce.setServerRpcProxy=g;function _(){return Ce}ce.getServerRpcProxyStats=_;function P(A){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(A))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(A))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(A))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(A)||/\.\+\.\+/.test(A))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let $=/\.?\{(\d+),(\d+)\}/g,M;for(;(M=$.exec(A))!==null;){let[,H,z]=M;if(parseInt(z,10)-parseInt(H,10)>1e3)return {safe:false,reason:`excessive range: {${H},${z}}`}}return {safe:true}}function O(A){let $=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],M=5;for(let H of $){let z=Date.now();try{A.test(H);let L=Date.now()-z;if(L>M)return {safe:!1,reason:`runtime test exceeded ${M}ms (took ${L}ms on input length ${H.length})`}}catch(L){return {safe:false,reason:`runtime test threw error: ${L}`}}}return {safe:true}}function T(A,$=200){try{if(!A)return Ne&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(A.length>$)return Ne&&console.warn(`[SDK] DMCA pattern rejected: length ${A.length} exceeds max ${$} - pattern: ${A.substring(0,50)}...`),null;let M=P(A);if(!M.safe)return Ne&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${M.reason}) - pattern: ${A.substring(0,50)}...`),null;let H;try{H=new RegExp(A);}catch(L){return Ne&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${A.substring(0,50)}...`,L),null}let z=O(H);return z.safe?H:(Ne&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${z.reason}) - pattern: ${A.substring(0,50)}...`),null)}catch(M){return Ne&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${A.substring(0,50)}...`,M),null}}function q(A={}){let $=L=>Array.isArray(L)?L.filter(ot=>typeof ot=="string"):[],M=A||{},H={accounts:$(M.accounts),tags:$(M.tags),patterns:$(M.posts)};d.dmcaAccounts=H.accounts,d.dmcaTags=H.tags,d.dmcaPatterns=H.patterns,d.dmcaTagRegexes=H.tags.map(L=>T(L)).filter(L=>L!==null),d.dmcaPatternRegexes=[];let z=H.tags.length-d.dmcaTagRegexes.length;!d._dmcaInitialized&&Ne&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${H.accounts.length}`),console.log(` - Tag patterns: ${d.dmcaTagRegexes.length}/${H.tags.length} compiled (${z} rejected)`),console.log(` - Post patterns: ${H.patterns.length} (using exact string matching)`),z>0&&console.warn(`[SDK] ${z} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),d._dmcaInitialized=true;}ce.setDmcaLists=q;})(exports.ConfigManager||={});function cy(){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 o(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>reactQuery.useQuery(a),fetchAndGet:()=>b().fetchQuery(a)}}s.generateClientServerQuery=o;function i(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>reactQuery.useInfiniteQuery(a),fetchAndGet:()=>b().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=i;})(exports.EcencyQueriesManager||={});function ly(e){return btoa(JSON.stringify(e))}function dy(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var ho=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(ho||{}),Qt=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(Qt||{});function k(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:ho[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:Qt[e.nai]}}var xr;function h(){if(!xr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");xr=globalThis.fetch.bind(globalThis);}return xr}function _o(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function Oa(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function se(e,t){return Oa(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function ze(e,t){return e/1e6*t}function wo(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var bo=60*1e3;function Oe(){return reactQuery.queryOptions({queryKey:u.core.dynamicProps(),refetchInterval:bo,staleTime:bo,queryFn:async({signal:e})=>{let[t,r,n,o,i]=await Promise.all([y("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),y("condenser_api.get_feed_history",[],void 0,void 0,e),y("condenser_api.get_chain_properties",[],void 0,void 0,e),y("condenser_api.get_reward_fund",["post"],void 0,void 0,e),y("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=k(t.total_vesting_shares).amount,a=k(t.total_vesting_fund_hive).amount,c=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(c=a/s*1e6);let p=k(r.current_median_history.base).amount,l=k(r.current_median_history.quote).amount,f=parseFloat(o.recent_claims),m=k(o.reward_balance).amount,g=Number(t.vote_power_reserve_rate??0),_=o.author_reward_curve??"linear",P=Number(o.content_constant??0),O=String(i.current_hardfork_version??"0.0.0"),T=Number(i.last_hardfork??0),q=t.hbd_print_rate,ce=t.hbd_interest_rate,A=t.head_block_number,$=a,M=s,H=k(t.virtual_supply).amount,z=t.vesting_reward_percent||0,L=n.account_creation_fee;return {hivePerMVests:c,base:p,quote:l,fundRecentClaims:f,fundRewardBalance:m,votePowerReserveRate:g,authorRewardCurve:_,contentConstant:P,currentHardforkVersion:O,lastHardfork:T,hbdPrintRate:q,hbdInterestRate:ce,headBlock:A,totalVestingFund:$,totalVestingShares:M,virtualSupply:H,vestingRewardPercent:z,accountCreationFee:L,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:o,hardforkProps:i}}}})}function ky(e="post"){return reactQuery.queryOptions({queryKey:u.core.rewardFund(e),queryFn:()=>y("condenser_api.get_reward_fund",[e])})}function Be(...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,o,i)=>["posts","account-posts-page",e,t,r,n,o,i],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)=>Be("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>Be("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>Be("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>Be("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,o,i)=>["posts","posts-ranked-page",e,t,r,n,o,i],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)=>Be("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)=>Be("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,o,i)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,o,i],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,o,i)=>Be("search","api",e,t,r,n,o,i)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,o)=>["witnesses","voters",e,t,r,n,o],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]},newsletter:{subscriptions:e=>["newsletter","subscriptions",e],sender:(e,t,r)=>["newsletter","sender",e,t,r],issues:(e,t,r)=>["newsletter","issues",e,t,r],posts:(e,t,r,n)=>["newsletter","posts",e,t,r,n],_prefix:["newsletter"]},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 lt(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 Iy(e){return reactQuery.queryOptions({queryKey:u.ai.prices(),queryFn:async()=>{let r=await h()(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 By(e,t){return reactQuery.queryOptions({queryKey:u.ai.assistPrices(e),queryFn:async()=>{let n=await h()(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 Uy(e,t){return reactQuery.queryOptions({queryKey:u.ai.transcribePrice(e),queryFn:async()=>{let n=await h()(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 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 $y(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 o=await h()(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??Ta()})});if(!o.ok){let s=await o.text(),a={};try{a=JSON.parse(s);}catch{}let c=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${o.status}${s?`: ${s}`:""}`);throw c.status=o.status,c.data=a,c}if(o.status===202){let s={};try{s=await o.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await o.json()},onSuccess:()=>{e&&b().invalidateQueries({queryKey:u.points._prefix(e)});}})}function Fa(){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 Jy(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 o=await h()(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:Fa()})});if(!o.ok){let i=await o.text(),s={};try{s=JSON.parse(i);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${o.status}${i?`: ${i}`:""}`);throw a.status=o.status,a.data=s,a}return await o.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:u.points._prefix(e)}),b().invalidateQueries({queryKey:u.ai.assistPrices(e)}));}})}function Da(){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 eh(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 o=new FormData;o.append("code",n),o.append("duration_ms",String(Math.round(r.durationMs))),o.append("idempotency_key",r.idempotency_key??Da()),o.append("audio",r.audio,r.fileName??"clip.webm");let s=await h()(d.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:o});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 Sr(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 B(e){return reactQuery.queryOptions({queryKey:u.accounts.full(e),queryFn:async({signal:t})=>{if(!e)return null;let[r,n]=await Promise.all([y("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),y("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 o=r[0];if(Sr(o)&&Na(n?.metadata?.profile)){let p=await y("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!Sr(l[0])));if(p[0]&&!Sr(p[0]))o=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let i=Me(o.posting_json_metadata),s=n?.stats,a=s?{account:o.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,c=n?.reputation??0;return {name:o.name,owner:o.owner,active:o.active,posting:o.posting,memo_key:o.memo_key,post_count:o.post_count,created:o.created,posting_json_metadata:o.posting_json_metadata,last_vote_time:o.last_vote_time,last_post:o.last_post,json_metadata:o.json_metadata,reward_hive_balance:o.reward_hive_balance,reward_hbd_balance:o.reward_hbd_balance,reward_vesting_hive:o.reward_vesting_hive,reward_vesting_balance:o.reward_vesting_balance,balance:o.balance,hbd_balance:o.hbd_balance,savings_balance:o.savings_balance,savings_hbd_balance:o.savings_hbd_balance,savings_hbd_last_interest_payment:o.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:o.savings_hbd_seconds_last_update,savings_hbd_seconds:o.savings_hbd_seconds,next_vesting_withdrawal:o.next_vesting_withdrawal,pending_claimed_accounts:o.pending_claimed_accounts,vesting_shares:o.vesting_shares,delegated_vesting_shares:o.delegated_vesting_shares,received_vesting_shares:o.received_vesting_shares,vesting_withdraw_rate:o.vesting_withdraw_rate,to_withdraw:o.to_withdraw,withdrawn:o.withdrawn,witness_votes:o.witness_votes,proxy:o.proxy,recovery_account:o.recovery_account,proxied_vsf_votes:o.proxied_vsf_votes,voting_manabar:o.voting_manabar,voting_power:o.voting_power,downvote_manabar:o.downvote_manabar,follow_stats:a,reputation:c,profile:i}},enabled:!!e,staleTime:6e4})}var Ba=new Set(["__proto__","constructor","prototype"]);function Ht(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function vo(e,t){let r={...e};for(let n of Object.keys(t)){if(Ba.has(n))continue;let o=t[n],i=r[n];Ht(o)&&Ht(i)?r[n]=vo(i,o):r[n]=o;}return r}function Ma(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:o,...i}=t;return {...r,meta:i}})}function Me(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 Po(e){return Me(e?.posting_json_metadata)}function Ao(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(Me(e.posting_json_metadata)).length;return Object.keys(Me(t.posting_json_metadata)).length>r?t:e}function Qa(e){if(!e)return {};try{let t=JSON.parse(e);if(Ht(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function Oo({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=Qa(e),o=Ht(n.profile)?n.profile:{},i=Er({existingProfile:o,profile:t,tokens:r});return JSON.stringify({...n,profile:i})}function Er({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:o,...i}=t??{},s=vo(e??{},i);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=Ma(s.tokens),s.version=2,s}function Ut(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=Me(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let o=JSON.parse(t.json_metadata||"{}");o.profile&&(n=o.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function Ha(e){return new TextEncoder().encode(e).length}function Je(e){return e?Ha(e)<=16:false}function yh(e){return reactQuery.queryOptions({queryKey:u.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(Je);if(t.length===0)return [];let r=await y("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return Ut(r??[])}})}function vh(e){return reactQuery.queryOptions({queryKey:u.accounts.followCount(e),queryFn:()=>y("condenser_api.get_follow_count",[e])})}function Sh(e,t,r="blog",n=100){return reactQuery.queryOptions({queryKey:u.accounts.followers(e,t,r,n),queryFn:()=>y("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function Th(e,t,r="blog",n=100){return reactQuery.queryOptions({queryKey:u.accounts.following(e,t,r,n),queryFn:()=>y("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var xo=1e3,Wa=20;function Kh(e){return reactQuery.queryOptions({queryKey:u.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(i[0]===r&&(i=i.slice(1)),!i.length||(t.push(...i),o.lengthJe(e)?y("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function Wh(e,t=5,r=[]){return reactQuery.queryOptions({queryKey:u.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await y("condenser_api.lookup_accounts",[e,t])).filter(o=>r.length>0?!r.includes(o):true)})}var Ya=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function Yh(e,t){return reactQuery.queryOptions({queryKey:u.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await h()(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 o=await n.json(),i=Array.isArray(o)?o.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,g=(typeof a.status=="number"?a.status===3:void 0)??false;f&&(l.address=f),l.show=g;let _={symbol:c,currency:c,address:f,show:g,type:"CHAIN",meta:l},P=[];for(let[O,T]of Object.entries(p))typeof O=="string"&&(Ya.has(O)||typeof T!="string"||!T||/^[A-Z0-9]{2,10}$/.test(O)&&P.push({symbol:O,currency:O,address:T,show:g,type:"CHAIN",meta:{address:T,show:g}}));return [_,...P]}):[];return {exist:i.length>0,tokens:i.length?i:void 0,wallets:i.length?i:void 0}},refetchOnMount:true})}function So(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 y("bridge.get_relationship_between_accounts",[e,t])??r}})}function s_(e){return reactQuery.queryOptions({queryKey:u.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await y("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function p_(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 h()(d.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function l_(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 i=await h()(`${d.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch bookmarks: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function g_(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 h()(d.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function y_(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 i=await h()(`${d.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch favorites: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function b_(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 o=await h()(d.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!o.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${o.status}: ${o.statusText}`);let i=await o.json();if(typeof i!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof i}`);return i}})}function O_(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 h()(d.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function C_(e){return reactQuery.queryOptions({enabled:!!e,queryKey:u.accounts.pendingRecovery(e),queryFn:()=>y("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function D_(e,t=50){return reactQuery.queryOptions({queryKey:u.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!Je(e)?[]:y("condenser_api.get_account_reputations",[e,t])})}var K=ne.operations,Eo={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]},cu=Array.from(new Set(Object.values(Eo).flat()));function pu(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function lu(e){return e.replace(/_operation$/,"")}function du(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function fu(e){if(!du(e))return e;let t=k(e),r=Qt[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function mu(e){let t={};for(let[r,n]of Object.entries(e))t[r]=fu(n);return t}function V_(e,t=20,r=""){let n=r?Eo[r]:cu;return reactQuery.infiniteQueryOptions({queryKey:u.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:o,signal:i})=>{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 te("hafah","/accounts/{account-name}/operations",m,void 0,void 0,i)},a=f=>f.operations_result.map(m=>{let g=lu(m.op.type);return {...mu(m.op.value),num:pu(m),type:g,timestamp:m.timestamp,trx_id:m.trx_id}}),c=await s(o),p=a(c),l=o??c.total_pages;if(o===null&&p.length1)try{let f=await s(c.total_pages-1);p=[...p,...a(f)],l=c.total_pages-1;}catch(f){if(i?.aborted)throw f}return {entries:p,currentPage:l}},getNextPageParam:o=>{let i=o.currentPage-1;return i>=1?i:void 0}})}function W_(){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 Y_(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(),o=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&o.searchParams.set("max_id",r.toString());let i=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch referrals: ${i.status}`);return i.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function tw(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 aw(e,t,r){let{followType:n="blog",limit:o=100,enabled:i=true}=r??{};return reactQuery.infiniteQueryOptions({queryKey:u.accounts.friends(e,t,n,o),initialPageParam:{startFollowing:""},enabled:i,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await y(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,o])).map(g=>t==="following"?g.following:g.follower);return (await y("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(g=>({name:g.name,reputation:g.reputation,active:g.active}))},getNextPageParam:s=>s&&s.length===o?{startFollowing:s[s.length-1].name}:void 0})}var bu=30;function dw(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 y(`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,bu);return (await y("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 hw(e=20){return reactQuery.infiniteQueryOptions({queryKey:u.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>y("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 Aw(e=250){return reactQuery.infiniteQueryOptions({queryKey:u.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>y("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!_o(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function Ye(e,t){return reactQuery.queryOptions({queryKey:u.posts.fragments(e),queryFn:async()=>t?(await h()(d.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function Ew(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 i=await h()(`${d.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch fragments: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Tw(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 h()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function Kw(e){return reactQuery.queryOptions({queryKey:u.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>y("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function Hw(e,t,r){return reactQuery.queryOptions({queryKey:u.posts.userPostVote(e,t,r),queryFn:async()=>(await y("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function $w(e,t){return reactQuery.queryOptions({queryKey:u.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content",[e,t])})}function Yw(e,t){return reactQuery.queryOptions({queryKey:u.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content_replies",{author:e,permlink:t})})}function rb(e,t){return reactQuery.queryOptions({queryKey:u.posts.postHeader(e,t),queryFn:async()=>y("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function re(e){return Array.isArray(e)?e.map(t=>ko(t)):ko(e)}function ko(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 Co(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 Ro(e,t,r="",n){let o=t?.trim(),i=`/@${e}/${o??""}`;return reactQuery.queryOptions({queryKey:u.posts.entry(i),queryFn:async()=>{if(!o||o==="undefined")return null;let s=await y("bridge.get_post",{author:e,permlink:o,observer:r});if(!s){let c=await Co(e,o,r);if(!c)return null;let p=n!==void 0?{...c,num:n}:c;return re(p)}let a=n!==void 0?{...s,num:n}:s;return re(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function ae(e,t,r){return y(`bridge.${e}`,t,void 0,void 0,r)}async function To(e,t,r,n){let{json_metadata:o}=e;if(o?.original_author&&o?.original_permlink&&o.tags?.[0]==="cross-post")try{let i=await qu(o.original_author,o.original_permlink,t,r,n);return i?{...e,original_entry:i,num:r}:e}catch{return e}return {...e,num:r}}async function qo(e,t,r){let n=e.map(dt),o=await Promise.all(n.map(i=>To(i,t,void 0,r)));return re(o)}async function Fo(e,t="",r="",n=20,o="",i="",s){let a=await ae("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:o,observer:i},s);return Array.isArray(a)?qo(a,i,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 kr(e,t,r="",n="",o=20,i="",s){if(d.dmcaAccounts.includes(t))return [];let a=await ae("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:o,observer:i},s);return Array.isArray(a)?qo(a,i,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 dt(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 qu(e="",t="",r="",n,o){let i=await ae("get_post",{author:e,permlink:t,observer:r},o);if(i){let s=dt(i),a=await To(s,r,n,o);return re(a)}}async function hb(e="",t=""){let r=await ae("get_post_header",{author:e,permlink:t});return r&&dt(r)}async function Io(e,t,r){let n=await ae("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let o={};for(let[i,s]of Object.entries(n))o[i]=dt(s);return o}return n}async function Do(e,t=""){return ae("get_community",{name:e,observer:t})}async function _b(e="",t=100,r,n="rank",o=""){return ae("list_communities",{last:e,limit:t,query:r,sort:n,observer:o})}async function Ko(e){let t=await ae("normalize_post",{post:e});return t&&dt(t)}async function wb(e){return ae("list_all_subscriptions",{account:e})}async function bb(e){return ae("list_subscribers",{community:e})}async function vb(e,t){return ae("get_relationship_between_accounts",[e,t])}async function Vt(e,t){return ae("get_profiles",{accounts:e,observer:t})}var Bo=(o=>(o.trending="trending",o.author_reputation="author_reputation",o.votes="votes",o.created="created",o))(Bo||{});function Cr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function Fu(e,t,r){let n=l=>Cr(l.pending_payout_value).amount+Cr(l.author_payout_value).amount+Cr(l.curator_payout_value).amount,o=l=>l.net_rshares<0,i=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,f)=>{if(o(l))return 1;if(o(f))return -1;let m=n(l),g=n(f);return m!==g?g-m:0},author_reputation:(l,f)=>{let m=l.author_reputation,g=f.author_reputation;return m>g?-1:m{let m=l.children,g=f.children;return m>g?-1:m{if(o(l))return 1;if(o(f))return -1;let m=Date.parse(l.created),g=Date.parse(f.created);return m>g?-1:mi(l)),p=a[c];return c>=0&&(a.splice(c,1),a.unshift(p)),a}function Mo(e,t="created",r=true,n){let o=n||d.defaultObserver;return reactQuery.queryOptions({queryKey:u.posts.discussions(e?.author,e?.permlink,t,o),queryFn:async()=>{if(!e)return [];let i=await y("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:o}),s=i?Array.from(Object.values(i)):[];return re(s)},enabled:r&&!!e,select:i=>Fu(e,i,t),structuralSharing:(i,s)=>{if(!i||!s)return s;let a=i.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 kb(e,t,r,n=true){let o=r||d.defaultObserver;return reactQuery.queryOptions({queryKey:u.posts.discussion(e,t,o),enabled:n&&!!e&&!!t,queryFn:async()=>Io(e,t,o)})}function Db(e,t="posts",r=20,n="",o=true){return reactQuery.infiniteQueryOptions({queryKey:u.posts.accountPosts(e??"",t,r,n),enabled:!!e&&o,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:i,signal:s})=>{if(!i?.hasNextPage||!e)return [];let a=await kr(t,e,i.author??"",i.permlink??"",r,n,s);return re(a??[])},getNextPageParam:i=>{let s=i?.[i.length-1],a=(i?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function Kb(e,t="posts",r="",n="",o=20,i="",s=true){return reactQuery.queryOptions({queryKey:u.posts.accountPostsPage(e??"",t,r,n,o,i),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let c=await kr(t,e,r,n,o,i,a);return re(c??[])}})}var Qo=new Map;function Bu(e){let t=Qo.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>Mu(n,e))}),Qo.set(e,t)),t}function Mu(e,t){let r=e.filter(i=>i.stats?.is_pinned),n=e.filter(i=>!i.stats?.is_pinned);if(t==="hot")return [...r,...n];let o=[...n].sort((i,s)=>new Date(s.created).getTime()-new Date(i.created).getTime());return [...r,...o]}function jb(e,t,r=20,n="",o=true,i={}){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 y("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 re(p)},select:Bu(e),enabled:o,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 Lb(e,t="",r="",n=20,o="",i="",s=true){return reactQuery.queryOptions({queryKey:u.posts.postsRankedPage(e,t,r,n,o,i),enabled:s,queryFn:async({signal:a}={})=>{let c=o;d.dmcaTagRegexes.some(l=>l.test(o))&&(c="");let p=await Fo(e,t,r,n,c,i,a);return re(p??[])}})}function Jb(e,t,r=200){return reactQuery.queryOptions({queryKey:u.posts.reblogs(e??"",r),queryFn:async()=>(await y("condenser_api.get_blog_entries",[e??t,0,r])).filter(o=>o.author!==t&&!o.reblogged_on.startsWith("1970-")).map(o=>({author:o.author,permlink:o.permlink})),enabled:!!e})}function tv(e,t){return reactQuery.queryOptions({queryKey:u.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await y("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function iv(e,t){return reactQuery.queryOptions({queryKey:u.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await h()(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 sv(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 i=await h()(`${d.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch schedules: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function pv(e,t){return reactQuery.queryOptions({queryKey:u.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await h()(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 lv(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 i=await h()(`${d.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch drafts: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function Uo(e){let r=await h()(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 gv(e,t){return reactQuery.queryOptions({queryKey:u.posts.images(e),queryFn:async()=>!e||!t?[]:Uo(t),enabled:!!e&&!!t})}function yv(e,t){return reactQuery.queryOptions({queryKey:u.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:Uo(t),enabled:!!e&&!!t})}function hv(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 i=await h()(`${d.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch images: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function vv(e,t,r=false){return reactQuery.queryOptions({queryKey:u.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let o=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(!o.ok)throw new Error(`Failed to fetch comment history: ${o.status}`);return o.json()},enabled:!!e&&!!t})}function zu(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let o=r.replace(/^@+/,""),i=n.replace(/^\/+/,"");if(!o||!i)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${o}/${i}`}function xv(e,t){let r=t?.trim(),n=e?.trim(),o=!!n&&!!r&&r!=="undefined",i=o?zu(n,r):"";return reactQuery.queryOptions({queryKey:u.posts.deletedEntry(i),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:o})}function Cv(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)}`,o=await fetch(d.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch post tips: ${o.status}`);return o.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function Yu(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function Xu(e){return {...e,id:e.id??e.post_id}}function he(e,t){if(!e)return null;let r=e.container??e,n=Yu(r,t),o=e.parent?Xu(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:o}}function Zu(e){return Array.isArray(e)?e:[]}async function Vo(e){let t=Mo(e,"created",true),r=await d.queryClient.fetchQuery(t),n=Zu(r);if(n.length<=1)return [];let o=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return o.length===0?[]:o.filter(s=>!s.stats?.gray)}function jo(e,t,r){return e.length===0?[]:e.map(n=>{let o=e.find(i=>i.author===n.parent_author&&i.permlink===n.parent_permlink&&i.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:o}}).filter(n=>n.container.post_id!==n.post_id).sort((n,o)=>new Date(o.created).getTime()-new Date(n.created).getTime())}var rc=20;function Lo(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??rc}}async function $o({containers:e,tag:t,following:r,author:n,observer:o,limit:i},s,a){let c=exports.ConfigManager.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",c);p.searchParams.set("limit",String(i)),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),o&&p.searchParams.set("observer",o);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 g=he(m,m.host??"");return g?{...g,_cursor:m._cursor}:null}).filter(m=>!!m)}function Nv(e={}){let t=Lo(e),{containers:r,tag:n,following:o,author:i,observer:s,limit:a}=t;return reactQuery.infiniteQueryOptions({queryKey:u.posts.wavesFeed({containers:r,tag:n,following:o,author:i,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:c,signal:p})=>$o(t,c,p),getNextPageParam:c=>{if(!(c.length$o(t,void 0,c)})}var oc=20;function ic(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 sc({containers:e,tag:t,author:r,observer:n,limit:o},i,s){let a=exports.ConfigManager.getValidatedBaseUrl(),c=new URL("/private-api/waves/shorts",a);c.searchParams.set("limit",String(o)),i&&c.searchParams.set("cursor",i),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=he(f,f.host??"");return m?{...m,active_votes:m.active_votes??[],video:f.video,_cursor:f._cursor}:null}).filter(f=>!!f)}function Vv(e={}){let t=ic(e),{containers:r,tag:n,author:o,observer:i,limit:s}=t;return reactQuery.infiniteQueryOptions({queryKey:u.posts.shortsFeed({containers:r,tag:n,author:o,observer:i,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:c})=>sc(t,a,c),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of c){if(i&&l.post_id===i){i=void 0;continue}if(o+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let f;try{f=await Vo(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:jo(f,l,e)}}let p=c[c.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function Jv(e){return reactQuery.infiniteQueryOptions({queryKey:u.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await pc(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var dc=40;function t0(e,t,r=dc){return reactQuery.infiniteQueryOptions({queryKey:u.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let o=exports.ConfigManager.getValidatedBaseUrl(),i=new URL("/private-api/waves/tags",o);i.searchParams.set("container",e),i.searchParams.set("tag",t);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves by tag",o),[]}},getNextPageParam:()=>{}})}function s0(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 o=exports.ConfigManager.getValidatedBaseUrl(),i=new URL("/private-api/waves/following",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves following feed",o),[]}},getNextPageParam:()=>{}})}function p0(e,t=24){let r=e?.trim()||void 0;return reactQuery.queryOptions({queryKey:u.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let o=exports.ConfigManager.getValidatedBaseUrl(),i=new URL("/private-api/waves/trending/tags",o);r&&i.searchParams.set("container",r),i.searchParams.set("hours",t.toString());let s=await fetch(i.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(o){return console.error("[SDK] Failed to fetch waves trending tags",o),[]}}})}function g0(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 o=exports.ConfigManager.getValidatedBaseUrl(),i=new URL("/private-api/waves/account",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){throw console.error("[SDK] Failed to fetch waves for account",o),o}},getNextPageParam:()=>{}})}function w0(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 o=await fetch(n.toString(),{method:"GET",signal:t});if(!o.ok)throw new Error(`Failed to fetch waves trending authors: ${o.status}`);return (await o.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 O0(e,t=true){return reactQuery.queryOptions({queryKey:u.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>Ko(e)})}function wc(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Wo(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function q0(e,t){let{limit:r=20,filters:n=[],dayLimit:o=7}=t??{};return reactQuery.infiniteQueryOptions({queryKey:u.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:i})=>{let{start:s}=i,a=await y("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,g])=>({...g.op[1],num:m,timestamp:g.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Wo(m.timestamp)<=o),l=[];for(let m of p){let g=await d.queryClient.fetchQuery(Ro(m.author,m.permlink));wc(g)&&l.push(g);}let[f]=a;return {lastDate:f?Wo(f[1].timestamp):0,lastItemFetched:f?f[0]:s,entries:l}},getNextPageParam:i=>({start:i.lastItemFetched})})}function N0(e,t,r=true){return reactQuery.queryOptions({queryKey:u.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Vt(e,t)})}function V0(e,t="HIVE",r=200){return reactQuery.infiniteQueryOptions({queryKey:u.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:o})=>{if(!e)return {entries:[],currentPage:0};let i={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(i.page=n);let s=await te("balance","/accounts/{account-name}/balance-history",i,void 0,void 0,o);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let o=n.currentPage-1;return o>=1?o:void 0},enabled:!!e})}function G0(e,t="HIVE",r="yearly"){return reactQuery.queryOptions({queryKey:u.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await te("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function X0(){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 Z0(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function iP(e,t,r){let n=reactQuery.useQueryClient(),{data:o}=reactQuery.useQuery(B(e));return v(["accounts","update"],e,i=>{let s=Ao(n.getQueryData(B(e).queryKey),o);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:Oo({existingPostingJsonMetadata:s.posting_json_metadata,profile:i.profile,tokens:i.tokens})}]]},async(i,s)=>{n.setQueryData(B(e).queryKey,a=>{if(!a)return a;let c=JSON.parse(JSON.stringify(a));return c.profile=Er({existingProfile:Po(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({...B(e),staleTime:0});}catch{}}})}function pP(e,t,r,n,o){return reactQuery.useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async i=>{let s=So(e,t);await b().prefetchQuery(s);let a=b().getQueryData(s.queryKey);return await go(e,"follow",["follow",{follower:e,following:t,what:[...i==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...i==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:i==="toggle-ignore"?!a?.ignores:a?.ignores,follows:i==="toggle-follow"?!a?.follows:a?.follows}},onError:o,onSuccess(i){n(i),b().setQueryData(u.accounts.relations(e,t),i),t&&b().invalidateQueries(B(t));}})}function Rr(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 Qe(e,t,r,n,o,i,s){if(!e||!t||n===void 0||!i)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:o,body:i,json_metadata:JSON.stringify(s)}]}function He(e,t,r,n,o,i,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:o,allow_curation_rewards:i,extensions:s}]}function Tr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function qr(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let o={account:e,author:t,permlink:r};return n&&(o.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",o]),required_auths:[],required_posting_auths:[e]}]}function Ue(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 Ec(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(i=>Ue(e,i.trim(),r,n))}function kc(e,t,r,n,o,i){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(o<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:o,executions:i,extensions:[]}]}function Xe(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 Ve(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:o}]}function Go(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 ft(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [Ve(e,t,r,n,o),Go(e,o)]}function mt(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 gt(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function yt(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 ht(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 _t(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 Fr(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 je(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 Ir(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function Dr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(o=>o.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 Kr(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 jt(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 Cc(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 Rc(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return jt(e,t)}function Nr(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]}],o=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,o]}function Br(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 Mr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function Qr(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 Hr(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 Tc(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 qc(e,t,r,n,o){if(e==null||typeof e!="number"||!t||!r||!n||!o)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:o,extensions:[]}]}function Ur(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 Vr(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 jr(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 Lr(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 $r(e,t,r,n,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function Wr(e,t,r,n,o,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:o}]),required_auths:[],required_posting_auths:[e]}]}function Fc(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function Ic(e,t,r,n,o){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:o}]),required_auths:[],required_posting_auths:[e]}]}var zo=(r=>(r.Buy="buy",r.Sell="sell",r))(zo||{}),Jo=(r=>(r.EMPTY="",r.SWAP="9",r))(Jo||{});function $t(e,t,r,n,o,i){if(!e||!t||!r||!o||i===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:i,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:o}]}function Lt(e,t=3){return e.toFixed(t)}function Dc(e,t,r,n,o=""){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 i=new Date(Date.now());i.setDate(i.getDate()+27);let s=i.toISOString().split(".")[0],a=+`${o}${Math.floor(Date.now()/1e3).toString().slice(2)}`,c=n==="buy"?`${Lt(t,3)} HBD`:`${Lt(t,3)} HIVE`,p=n==="buy"?`${Lt(r,3)} HIVE`:`${Lt(r,3)} HBD`;return $t(e,c,p,false,s,a)}function Gr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function zr(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 Kc(e,t,r,n,o,i){if(!e||!o)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:o,json_metadata:i}]}function Nc(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 Jr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let o={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={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:o,active:i,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Yr(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]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},i={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:o,posting:i,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Xr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function Zr(e,t,r,n,o,i){if(!e||!t||!r||!o)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:o,json_metadata:i}]}function Bc(e,t,r,n,o){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let i={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:i,memo_key:n,json_metadata:o}]}function Mc(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 Qc(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 Hc(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 en(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 tn(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 rn(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 Ze(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let o=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:o,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function Uc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let o=t.trim().split(/[\s,]+/).filter(Boolean);if(o.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return o.map(i=>Ze(e,i.trim(),r,n))}function nn(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 Vc(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 jc(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 TP(e,t,r){return v(["accounts","follow"],e,({following:n})=>[Kr(e,n)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function DP(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[jt(e,n)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function MP(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:o,permlink:i})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:o,permlink:i,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function VP(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:o,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function WP(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})})).json()},onSuccess:(o,i)=>{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,i)});},onError:n})}function XP(e,t,r,n){return reactQuery.useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await h()(d.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async o=>{if(!e)return;let i=b(),s=u.accounts.favorites(e),a=u.accounts.favoritesInfinite(e),c=u.accounts.checkFavorite(e,o);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a}),i.cancelQueries({queryKey:c})]);let p=i.getQueryData(s);p&&i.setQueryData(s,p.filter(g=>g.account!==o));let l=i.getQueryData(c);i.setQueryData(c,false);let f=i.getQueriesData({queryKey:a}),m=new Map(f);for(let[g,_]of f)_&&i.setQueryData(g,{..._,pages:_.pages.map(P=>({...P,data:P.data.filter(O=>O.account!==o)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(o,i)=>{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,i)});},onError:(o,i,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,i),s.previousCheck),n(o);}})}function Yc(e,t){let r=new Map;return e.forEach(([n,o])=>{r.set(n.toString(),o);}),t.forEach(([n,o])=>{r.set(n.toString(),o);}),Array.from(r.entries()).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>[n,o])}function Yo(e,t){let{data:r}=reactQuery.useQuery(B(e));return reactQuery.useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:o=false,currentKey:i,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:[]],g=o?l.key_auths.filter(([_])=>!m.includes(_.toString())):[];return l.key_auths=Yc(g,n.map((_,P)=>[_[p].createPublic().toString(),P+1])),l};return ee([["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()}]],i)},...t})}function uA(e,t){let{data:r}=reactQuery.useQuery(B(e)),{mutateAsync:n}=Yo(e);return reactQuery.useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:o,currentPassword:i,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=U.fromLogin(e,i,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:U.fromLogin(e,o,"owner"),active:U.fromLogin(e,o,"active"),posting:U.fromLogin(e,o,"posting"),memo_key:U.fromLogin(e,o,"memo")}]})},...t})}function mA(e,t,r){let n=reactQuery.useQueryClient(),{data:o}=reactQuery.useQuery(B(e));return reactQuery.useMutation({mutationKey:["accounts","revoke-posting",o?.name],mutationFn:async({accountName:i,type:s,key:a})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let c=JSON.parse(JSON.stringify(o.posting));c.account_auths=c.account_auths.filter(([l])=>l!==i);let p={account:o.name,posting:c,memo_key:o.memo_key,json_metadata:o.json_metadata};if(s==="key"&&a)return ee([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(o.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."),mo__default.default.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(i,s,a)=>{t.onSuccess?.(i,s,a),n.setQueryData(B(e).queryKey,c=>({...c,posting:{...c?.posting,account_auths:c?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function vA(e,t,r,n){let{data:o}=reactQuery.useQuery(B(e));return reactQuery.useMutation({mutationKey:["accounts","recovery",o?.name],mutationFn:async({accountName:i,type:s,key:a,email:c})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:o.name,new_recovery_account:i,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let f=await h()(d.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:c,publicKeys:[...o.owner.key_auths,...o.active.key_auths,...o.posting.key_auths,o.memo_key]})});if(!f.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${f.status}`);return f}else {if(s==="key"&&a)return ee([["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(o.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."),mo__default.default.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function AA(e,t){let r=e.key_auths.filter(([o])=>!t.has(String(o))).reduce((o,[,i])=>o+i,0),n=(e.account_auths??[]).reduce((o,[,i])=>o+i,0);return r+n>=e.weight_threshold}function Xo(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),o=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([c])=>!r.has(c.toString())),a},i=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:i?o(e.owner):void 0,active:o(e.active),posting:o(e.posting),memo_key:e.memo_key}}function CA(e,t){let{data:r}=reactQuery.useQuery(B(e));return reactQuery.useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:o})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let i=Array.isArray(o)?o:[o],s=Xo(r,i);return ee([["account_update",s]],n)},...t})}function FA(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:o="0.000 HIVE"})=>[Xr(n,o)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(o.creator)]);},t,"active",{broadcastMode:r})}function NA(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[Zr(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 HA(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?Yr(e,n.newAccountName,n.keys):Jr(e,n.newAccountName,n.keys,n.fee)],async()=>{await S(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}var on=300*60*24,cp=1e4,pp=5e7;function Zo(e){let t=k(e.vesting_shares).amount,r=k(e.received_vesting_shares).amount,n=k(e.delegated_vesting_shares).amount,o=k(e.vesting_withdraw_rate).amount,i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t+r-n-s}function lp(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function dp(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 fp(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 o=Zo(e);if(!Number.isFinite(o)||o<=0)return 0;let i=o*1e6,s=Math.ceil(i*r*60*60*24/cp/(n*on)),a=Or(e),c=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(c)||s>c?0:Math.max(s-pp,0)}function mp(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(dp(t))return fp(e,t,n);let o=0;try{if(o=Zo(e),!Number.isFinite(o))return 0}catch{return 0}return lp(o,r,n)}function LA(e){return Or(e).percentage/100}function $A(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*on/1e4}function WA(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 o=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/on;o>n&&(o=n);let i=o*100/n;return isNaN(i)?0:i>100?100:i}function GA(e){return Bt(e).percentage/100}function zA(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:o,fundRewardBalance:i,base:s,quote:a}=t;if(!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(a)||o===0||a===0)return 0;let c=mp(e,t,r,n);return Number.isFinite(c)?c/o*i*(s/a):0}var gp={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 yp(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 hp(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function _p(e){let t=e[0];return t==="custom_json"?yp(e):t==="create_proposal"||t==="update_proposal"?hp(e):gp[t]??"posting"}function YA(e){let t="posting";for(let r of e){let n=_p(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function rO(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=U.fromLogin(e,r,"active"):co(r)?n=U.fromString(r):n=U.from(r),ee([t],n)}})}function iO(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 cO(e="/"){return reactQuery.useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>mo__default.default.sendOperation(t,{callback:e},()=>{})})}function fO(){return reactQuery.queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await y("condenser_api.get_chain_properties",[])})}function ei(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function ti(e,t){return {...e??{},title:t.title,body:t.body}}function vO(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 i=await h()(d.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${i.status}`);return i.json()},onSuccess(r,n){let o=b(),i=ti(r,n);o.setQueryData(Ye(e,t).queryKey,s=>[i,...s??[]]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,c)=>c===0?{...a,data:[i,...a.data]}:a)});}})}function kO(e,t){return reactQuery.useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:o})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await h()(d.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:o}),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 o=b(),i=s=>ei(s,r,n);o.setQueryData(Ye(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?i(a):a)??[]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(c=>c.id===n.fragmentId?i(c):c)}))});}})}function IO(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 o=await h()(d.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${o.status}`);return o},onSuccess(r,n){let o=b();o.setQueryData(Ye(e,t).queryKey,i=>[...i??[]].filter(({id:s})=>s!==n.fragmentId)),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},i=>i&&{...i,pages:i.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 NO(e,t,r,n){let i=await h()(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(i);return {status:i.status,data:s}}async function BO(e){let r=await h()(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 MO(e,t,r="",n=""){let o={code:e,ty:t};r&&(o.bl=r),n&&(o.tx=n);let s=await h()(d.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});await G(s);}async function QO(e,t,r=null,n=null){let o={code:e};t&&(o.filter=t),r&&(o.since=r),n&&(o.user=n);let s=await h()(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return G(s)}async function HO(e,t,r,n,o,i){let s={code:e,username:t,token:i,system:r,allows_notify:n,notify_types:o},c=await h()(d.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function UO(e,t,r){let n={code:e,username:t,token:r},i=await h()(d.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}async function ri(e,t){let r={code:e};t&&(r.id=t);let o=await h()(d.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function ni(e,t){let r={code:e,url:t},o=await h()(d.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}var Ep="https://i.ecency.com";async function oi(e,t,r){let n=h(),o=new FormData;o.append("file",e);let i=await n(`${Ep}/hs/${t}`,{method:"POST",body:o,signal:r});return G(i)}async function VO(e,t,r,n){let o=h(),i=new FormData;i.append("file",e);let s=await o(`${d.imageHost}/${t}/${r}`,{method:"POST",body:i,signal:n});return G(s)}async function ii(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function si(e,t,r,n,o){let i={code:e,title:t,body:r,tags:n,meta:o},a=await h()(d.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return G(a)}async function ai(e,t,r,n,o,i){let s={code:e,id:t,title:r,body:n,tags:o,meta:i},c=await h()(d.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function ui(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function ci(e,t,r,n,o,i,s,a){let c={code:e,permlink:t,title:r,body:n,meta:o,schedule:s,reblog:a};i&&(c.options=i);let l=await h()(d.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});return G(l)}async function pi(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function li(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function jO(e,t,r){let n={code:e,author:t,permlink:r},i=await h()(d.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}async function LO(e,t,r){let n={username:e,email:t,friend:r},i=await h()(d.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}function JO(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:o,body:i,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return si(t,o,i,s,a)},onSuccess:o=>{r?.();let i=b();o?.drafts?i.setQueryData(u.posts.drafts(e),o.drafts):i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function tx(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:o,title:i,body:s,tags:a,meta:c})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return ai(t,o,i,s,a,c)},onSuccess:()=>{r?.();let o=b();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function ax(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return ui(t,o)},onMutate:async({draftId:o})=>{if(!e)return;let i=b(),s=u.posts.drafts(e),a=u.posts.draftsInfinite(e);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a})]);let c=i.getQueryData(s);c&&i.setQueryData(s,c.filter(f=>f._id!==o));let p=i.getQueriesData({queryKey:a}),l=new Map(p);for(let[f,m]of p)m&&i.setQueryData(f,{...m,pages:m.pages.map(g=>({...g,data:g.data.filter(_=>_._id!==o)}))});return {previousList:c,previousInfinite:l}},onSuccess:()=>{r?.();let o=b();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:(o,i,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?.(o);}})}function dx(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:o,title:i,body:s,meta:a,options:c,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return ci(t,o,i,s,a,c,p,l)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function hx(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return pi(t,o)},onSuccess:o=>{r?.();let i=b();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function Px(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return li(t,o)},onSuccess:o=>{r?.();let i=b();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)}),i.invalidateQueries({queryKey:u.posts.drafts(e)});},onError:n})}function Ex(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:o,code:i})=>{let s=i??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return ni(s,o)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.images(e)});},onError:n})}function qx(e,t,r,n){return reactQuery.useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return ii(t,o)},onSuccess:(o,i)=>{r?.();let s=b(),{imageId:a}=i;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 Kx(e,t){return reactQuery.useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:o})=>oi(r,n,o),onSuccess:e,onError:t})}function Gt(e,t){return `/@${e}/${t}`}function Np(e,t,r){return (r??b()).getQueryData(u.posts.entry(Gt(e,t)))}function Bp(e,t){(t??b()).setQueryData(u.posts.entry(Gt(e.author,e.permlink)),e);}function Wt(e,t,r,n){let o=n??b(),i=Gt(e,t),s=o.getQueryData(u.posts.entry(i));if(!s)return;let a=r(s);return o.setQueryData(u.posts.entry(i),a),s}exports.EntriesCacheManagement=void 0;(a=>{function e(c,p,l,f,m){Wt(c,p,g=>({...g,active_votes:l,stats:{...g.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:g.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){Wt(c,p,m=>({...m,reblogs:l}),f);}a.updateReblogsCount=t;function r(c,p,l,f){Wt(c,p,m=>({...m,children:l}),f);}a.updateRepliesCount=r;function n(c,p,l,f){Wt(p,l,m=>({...m,children:m.children+1,replies:[c,...m.replies]}),f);}a.addReply=n;function o(c,p){c.forEach(l=>Bp(l,p));}a.updateEntries=o;function i(c,p,l){(l??b()).invalidateQueries({queryKey:u.posts.entry(Gt(c,p))});}a.invalidateEntry=i;function s(c,p,l){return Np(c,p,l)}a.getEntry=s;})(exports.EntriesCacheManagement||={});function Mp(e,t,r){let n=e.some(o=>o.voter===t);return r!==0?n:!n}function Qp(e,t,r){let n=exports.EntriesCacheManagement.getEntry(t.author,t.permlink,r);if(!n?.active_votes||Mp(n.active_votes,e,t.weight))return;let o=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],i=n.payout+(t.estimated??0);exports.EntriesCacheManagement.updateVotes(t.author,t.permlink,o,i,r);}function Vx(e,t,r){return v(["posts","vote"],e,({author:n,permlink:o,weight:i})=>[Rr(e,n,o,i)],async(n,o)=>{Qp(e,o);let i=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(120,i,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([u.posts.entry(`/@${o.author}/${o.permlink}`),u.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function Gx(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:o,deleteReblog:i})=>[qr(e,n,o,i??false)],async(n,o)=>{let i=exports.EntriesCacheManagement.getEntry(o.author,o.permlink);if(i){let p=Math.max(0,(i.reblogs??0)+(o.deleteReblog?-1:1));exports.EntriesCacheManagement.updateReblogsCount(o.author,o.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(`/@${o.author}/${o.permlink}`),u.posts.rebloggedBy(o.author,o.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function Hp(e){return e.isUpdate?null:e.parentAuthor?110:100}function Xx(e,t,r){return v(["posts","comment"],e,n=>{let o=[];if(o.push(Qe(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="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,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(He(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{let i=!o.parentAuthor,s=Hp(o),a=n?.id??n?.tx_id;if(s!==null&&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(!i){c.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let p=o.rootAuthor||o.parentAuthor,l=o.rootPermlink||o.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 tS(e,t,r,n){let o=n??b(),i=o.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 i)a&&o.setQueryData(s,[e,...a]);}function di(e,t,r,n,o){let i=o??b(),s=new Map,a=i.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),i.setQueryData(c,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function fi(e,t){let r=t??b();for(let[n,o]of e)r.setQueryData(n,o);}function rS(e,t,r,n){let o=n??b(),i=`/@${e}/${t}`,s=o.getQueryData(u.posts.entry(i));return s&&o.setQueryData(u.posts.entry(i),{...s,...r}),s}function nS(e,t,r,n){let o=n??b(),i=`/@${e}/${t}`;o.setQueryData(u.posts.entry(i),r);}function uS(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:o})=>[Tr(n,o)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e)];if(o.parentAuthor&&o.parentPermlink){i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let o=n.rootAuthor||n.parentAuthor,i=n.rootPermlink||n.parentPermlink;return o&&i?{snapshots:di(n.author,n.permlink,o,i)}:{}},onError:(n,o,i)=>{let{snapshots:s}=i??{};s&&fi(s);}})}function dS(e,t,r){return v(["posts","cross-post"],e,n=>{let o=[];if(o.push(Qe(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true}=n.options;o.push(He(n.author,n.permlink,i,s,a,c,[]));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.parentPermlink}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"async"})}function yS(e,t,r){return v(["posts","update-reply"],e,n=>{let o=[];if(o.push(Qe(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="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,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(He(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.resourceCredits.account(e)];i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r})}function bS(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:o,duration:i})=>[rn(e,n,o,i)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.posts._promotedPrefix],[...u.points._prefix(e)],u.posts.entry(`/@${o.author}/${o.permlink}`)]);},t,"active",{broadcastMode:r})}var Up=[3e3,3e3,3e3],Vp=e=>new Promise(t=>setTimeout(t,e));async function jp(e,t){return y("condenser_api.get_content",[e,t])}async function Lp(e,t,r=0,n){let o=n?.delays??Up,i;try{i=await jp(e,t);}catch{i=void 0;}if(i||r>=o.length)return;let s=o[r];return s>0&&await Vp(s),Lp(e,t,r+1,n)}var et={};Ot(et,{useRecordActivity:()=>sn});function Wp(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function sn(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=h(),o=Wp(),i=r?.url??o.url,s=r?.domain??o.domain;try{await n(d.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:i,domain:s,props:{username:e}})});}catch{}}})}function RS(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 DS(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(),o=n.map(s=>s.account),i=await y("condenser_api.get_accounts",[o]);for(let s=0;sa.efficiency-s.efficiency),n}})}function MS(e,t=[],r=["visitors","pageviews","visit_duration"],n){let o=[...t].sort(),i=[...r].sort();return reactQuery.queryOptions({queryKey:["analytics","page-stats",e,o,i,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 zt="threespeakfund",LS=1100;function Yp(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function $S(e,t){if(!Yp(t))return e;let r=e.find(n=>n.account===zt);return r&&r.weight===1100?e:r?e.map(n=>n.account===zt?{...n,weight:1100}:n):[...e,{account:zt,weight:1100}]}function WS(e){return e===zt}var cn={};Ot(cn,{getAccountTokenQueryOptions:()=>un,getAccountVideosQueryOptions:()=>nl});var an={};Ot(an,{getDecodeMemoQueryOptions:()=>el});function el(e,t,r){return reactQuery.queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new mo__default.default.Client({accessToken:r}).decode(t)}})}var mi={queries:an};function un(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 h()(`https://studio.3speak.tv/mobile/login?username=${e}&hivesigner=true`,{headers:{"Content-Type":"application/json"}}),o=mi.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await b().prefetchQuery(o);let{memoDecoded:i}=b().getQueryData(o.queryKey);return i.replace("#","")}})}function nl(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=un(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 h()("https://studio.3speak.tv/mobile/api/my-videos",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})).json()}})}var pE={queries:cn};function yE(e){return reactQuery.queryOptions({queryKey:["integrations","hiveposh","links",e],retry:false,queryFn:async()=>{try{let r=await h()(`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 bE({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:o,enabled:i=true}){return reactQuery.queryOptions({queryKey:["integrations","plausible",e,t,r,n,o],queryFn:async()=>{let a=await h()(`${d.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...o?{date_range:o}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&i,retry:1})}function OE(){return reactQuery.queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await y("rc_api.get_rc_stats",{})).rc_stats})}function kE(e){return reactQuery.queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await y("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}function FE(){return reactQuery.queryOptions({queryKey:u.resourceCredits.resourceParams(),staleTime:1440*60*1e3,gcTime:1/0,queryFn:async()=>await y("rc_api.get_resource_params",{})})}var Jt=["resource_history_bytes","resource_new_accounts","resource_market_bytes","resource_state_bytes","resource_execution_time"];var cl=11,pl=65,ll=16,tt=e=>BigInt(typeof e=="string"?e:Math.trunc(e));function pn(e,t,r,n){if(r<=0||n<=0)return 0;let o=tt(e.coeff_a),i=tt(e.coeff_b),s=tt(e.shift),a=tt(n)*o>>s;a+=1n,a*=tt(r);let c=i+(t>0?tt(t):0n);return c===0n?0:Number(a/c+1n)}function ln({transactionBytes:e,permlinkLength:t,signatures:r=1,beneficiaries:n=0,hasCommentOptions:o=false},i){let s=i.resource_state_bytes,a=i.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+(o?a.comment_options_time:0)}}var _e=e=>{let t=lt(e);return ye(t)+t},dl=e=>1+_e(e.parent_author)+_e(e.parent_permlink)+_e(e.author)+_e(e.permlink)+_e(e.title)+_e(e.body)+_e(e.json_metadata),fl=(e,t)=>{let r=t.beneficiaries??[],n=1+_e(e.author)+_e(e.permlink)+ll+2+2;return n+=ye(r.length>0?1:0),r.length>0&&(n+=1+ye(r.length),r.forEach(o=>{n+=_e(o.account)+2;})),n};function dn({op:e,options:t,signatures:r=1}){let n=[dl(e)];return t&&n.push(fl(e,t)),cl+ye(n.length)+n.reduce((o,i)=>o+i,0)+ye(r)+pl*r}var ml={ready:false,cost:0,transactionBytes:0,breakdown:[]};function BE({op:e,options:t,rcParams:r,rcStats:n,signatures:o=1}){if(!r?.resource_params||!r.size_info||!n?.pool||!n.share)return ml;let i=dn({op:e,options:t,signatures:o}),s=ln({transactionBytes:i,permlinkLength:lt(e.permlink),signatures:o,beneficiaries:t?.beneficiaries?.length??0,hasCommentOptions:!!t},r.size_info),a=Number(n.regen),c=0,p=[];return Jt.forEach((l,f)=>{let m=r.resource_params[l],g=Number(n.pool[f]??0),_=Number(n.share[f]??0);if(!m||_<=0)return;let P=s[l]*Number(m.resource_dynamics_params.resource_unit??1),O=Number(BigInt(a)*BigInt(_)/10000n),T=pn(m.price_curve_params,g,P,O);c+=T,p.push({resource:l,usage:P,cost:T});}),{ready:true,cost:c,transactionBytes:i,breakdown:p}}function fn(e,t,r){let n=Number(r.regen),o=0,i=[];return Jt.forEach((s,a)=>{let c=t.resource_params[s],p=Number(r.pool[a]??0),l=Number(r.share[a]??0);if(!c||l<=0)return;let f=e[s]*Number(c.resource_dynamics_params.resource_unit??1),m=Number(BigInt(n)*BigInt(l)/10000n),g=pn(c.price_curve_params,p,f,m);o+=g,i.push({resource:s,usage:f,cost:g});}),{cost:o,breakdown:i}}var gl=11,yl=65,mn=e=>{let t=lt(e);return ye(t)+t},hl=()=>({resource_history_bytes:0,resource_new_accounts:0,resource_market_bytes:0,resource_state_bytes:0,resource_execution_time:0});function gi(e,t=1){let r=1+mn(e.voter)+mn(e.author)+mn(e.permlink)+2;return gl+ye(1)+r+ye(t)+yl*t}function yi({transactionBytes:e,signatures:t=1},r){let n=r.resource_state_bytes,o=r.resource_execution_time;return {...hl(),resource_history_bytes:e,resource_state_bytes:n.vote_size+n.transaction_base_size,resource_execution_time:o.vote_time+o.transaction_time+o.verify_authority_time*t}}var hi={ready:false,currentMana:0,maxMana:0,avgCost:0,cost:0,transactionBytes:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function zE({rcAccount:e,rcStats:t,rcParams:r,operation:n,payload:o,fallback:i="minimal",buffer:s=1.2}){if(!e||!t?.ops)return hi;let{current_mana:a,max_mana:c}=Bt(e),p=_l(n,o,i,r,t);if(!p)return {...hi,currentMana:a,maxMana:c};let{cost:l,transactionBytes:f}=p,m=Number.isFinite(s)&&s>0?s:1.2,g=l*m,_=a0?{cost:r,transactionBytes:0}:null}var bl={author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa",parent_author:"",parent_permlink:"hive-100000",title:"",body:"",json_metadata:"{}"},vl={voter:"aaaaaaaaaa",author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa"};function ZE(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 h()(d.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}async function Ol(e,t,r){let o=await h()(d.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:t,code:e,key:r}),headers:{"Content-Type":"application/json"}}),i=(o.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),s=await o.text();if(!o.ok){let a=s&&i.includes("json")?`: ${s.slice(0,200)}`:"";throw new Error(`[SDK][Games] \u2013 failed with status ${o.status}${a}`)}if(!i.includes("json"))throw new Error(`[SDK][Games] \u2013 expected JSON but received "${i||"empty"}" response (status ${o.status})`);try{return JSON.parse(s)}catch{throw new Error(`[SDK][Games] \u2013 malformed JSON response (status ${o.status})`)}}function ok(e,t,r,n){let{mutateAsync:o}=sn(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 Ol(t,r,n)},onSuccess(){o();}})}function uk(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 h()(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 Sl=[{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 pk(e,t){return Sl.find(r=>r.tier===e&&r.id===t)}var El=25;function kl(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function lk(e){return kl(e)>El}var dk=300,fk=2;function Tl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function ql(e){let r=await h()(d.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:Tl()})});if(!r.ok){let n;try{n=await r.json();}catch{}let o=n?.message??`Failed to buy streak freeze: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function hk(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 ql(t)},onSuccess(){n&&r.invalidateQueries({queryKey:u.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:u.quests.status(n)});}})}function vk(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[Ur(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"async"})}function xk(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[Vr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"sync"})}function Ck(e,t,r){return v(["communities","mutePost"],e,({community:n,author:o,permlink:i,notes:s,mute:a})=>[Wr(e,n,o,i,s,a)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.posts.entry(`/@${o.author}/${o.permlink}`),["community","single",o.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.community}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"sync"})}function Fk(e,t,r,n){return v(["communities","set-role",e],t,({account:o,role:i})=>[jr(t,e,o,i)],async(o,i)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>{if(!a)return a;let c=[...a.team??[]],p=c.findIndex(([l])=>l===i.account);return p>=0?c[p]=[c[p][0],i.role,c[p][2]??""]:c.push([i.account,i.role,""]),{...a,team:c}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)],u.communities.context(i.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function Nk(e,t,r,n){return v(["communities","update",e],t,o=>[Lr(t,e,o)],async(o,i)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>a&&{...a,...i}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function Hk(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[nn(n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.communities.singlePrefix(o.name)],[...u.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function Lk(e,t,r){return v(["communities","pin-post"],e,({community:n,account:o,permlink:i,pin:s})=>[$r(e,n,o,i,s)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.posts.entry(`/@${o.account}/${o.permlink}`),[...u.communities.singlePrefix(o.community)]]);},t,"posting",{broadcastMode:r??"async"})}function Jk(e,t,r=100,n=void 0,o=true){return reactQuery.queryOptions({queryKey:u.communities.list(e,t??"",r),enabled:o,queryFn:async()=>{let i=await y("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return i?e==="hot"?i.sort(()=>Math.random()-.5):i:[]}})}function tC(e,t){return reactQuery.queryOptions({queryKey:u.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await y("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function sC(e,t="",r=true){return reactQuery.queryOptions({queryKey:u.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>Do(e??"",t)})}var _i=100;async function wi(e,t){return await y("bridge.list_subscribers",{community:e,limit:_i,...t?{last:t}:{}})??[]}function dC(e){return reactQuery.queryOptions({queryKey:u.communities.subscribers(e),queryFn:async()=>wi(e,null),staleTime:6e4})}function fC(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 wC(e,t){return reactQuery.infiniteQueryOptions({queryKey:u.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await y("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function AC(){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 Ql=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(Ql||{}),xC={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function EC(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function kC({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),o=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),i=["owner","admin","mod"].includes(t);return {canPost:n,canComment:o,isModerator:i}}function qC(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 KC(e,t,r=void 0){return reactQuery.infiniteQueryOptions({queryKey:u.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let o={code:t,filter:r,since:n,user:void 0},i=await fetch(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)return [];try{return await i.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var Vl=(g=>(g.VOTES="rvotes",g.MENTIONS="mentions",g.FAVORITES="nfavorites",g.BOOKMARKS="nbookmarks",g.FOLLOWS="follows",g.REPLIES="replies",g.REBLOGS="reblogs",g.TRANSFERS="transfers",g.DELEGATIONS="delegations",g.PAYOUTS="payouts",g.SCHEDULED_PUBLISHED="scheduled_published",g.ACCOUNT_UPDATES="account_updates",g.WEEKLY_EARNINGS="weekly_earnings",g))(Vl||{});var jl=(_=>(_[_.VOTE=1]="VOTE",_[_.MENTION=2]="MENTION",_[_.FOLLOW=3]="FOLLOW",_[_.COMMENT=4]="COMMENT",_[_.RE_BLOG=5]="RE_BLOG",_[_.TRANSFERS=6]="TRANSFERS",_[_.DELEGATIONS=10]="DELEGATIONS",_[_.FAVORITES=13]="FAVORITES",_[_.BOOKMARKS=15]="BOOKMARKS",_[_.PAYOUTS=19]="PAYOUTS",_[_.ACCOUNT_UPDATE=20]="ACCOUNT_UPDATE",_[_.WEEKLY_EARNINGS=21]="WEEKLY_EARNINGS",_[_.SCHEDULED_PUBLISHED=22]="SCHEDULED_PUBLISHED",_.ALLOW_NOTIFY="ALLOW_NOTIFY",_))(jl||{}),bi=[1,2,3,4,5,6,10,13,15,19,20,21,22],Ll=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(Ll||{});function VC(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 o=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(!o.ok)throw new Error(`Failed to fetch notification settings: ${o.status}`);return o.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...bi]})})}function WC(){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 YC(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 Jl(e,t){return {...e,read:!t||t===e.id?1:e.read}}function vi(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function oR(e,t,r,n){let o=b();return reactQuery.useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:i})=>{if(!e||!t){process.env.NODE_ENV!=="production"&&console.warn("[SDK][Notifications] \u2013 missing auth for markNotifications");return}return ri(t,i)},onMutate:async({id:i})=>{if(!e||!t)return {previousData:[]};await o.cancelQueries({queryKey:u.notifications._prefix});let s=[],a=o.getQueriesData({queryKey:u.notifications._prefix,predicate:l=>{let f=l.state.data;return vi(f)}});a.forEach(([l,f])=>{if(f&&vi(f)){s.push([l,f]);let m={...f,pages:f.pages.map(g=>g.map(_=>Jl(_,i)))};o.setQueryData(l,m);}});let c=u.notifications.unreadCount(e),p=o.getQueryData(c);return typeof p=="number"&&p>0&&(s.push([c,p]),i?a.some(([,f])=>f?.pages.some(m=>m.some(g=>g.id===i&&g.read===0)))&&o.setQueryData(c,p-1):o.setQueryData(c,0)),{previousData:s}},onSuccess:i=>{let s=typeof i=="object"&&i!==null?i.unread:void 0;typeof s=="number"&&o.setQueryData(u.notifications.unreadCount(e),s),r?.(s);},onError:(i,s,a)=>{a?.previousData&&a.previousData.forEach(([c,p])=>{o.setQueryData(c,p);}),n?.(i);},onSettled:()=>{o.invalidateQueries({queryKey:u.notifications._prefix});}})}function uR(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>Nr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function dR(e){return reactQuery.queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await y("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 y("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(o=>o.status==="expired");return [...t.filter(o=>o.status!=="expired"),...r]}})}function PR(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 y("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 y("condenser_api.get_accounts",[s.map(l=>l.voter)]),c=Ut(a);return s.map(l=>({...l,voterAccount:c.find(f=>l.voter===f.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function SR(e){return reactQuery.queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await y("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 RR(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:o})=>[Hr(e,n,o)],async n=>{try{let o=n?.id??n?.tx_id;t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(150,o,n?.block_num).catch(i=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:o,error:i});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.proposals.list(),u.proposals.votesByUser(e)]);}catch(o){console.warn("[useProposalVote] Post-broadcast side-effect failed:",o);}},t,"active",{broadcastMode:r})}function IR(e,t,r){return v(["proposals","create"],e,n=>[Qr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.proposals.list()]);},t,"active",{broadcastMode:r})}function BR(e,t=50){return reactQuery.infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,o=await y("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&o.length>0&&o[0]?.delegatee===r?o.slice(1,t+1):o},getNextPageParam:r=>!r||r.lengthte("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function $R(e){return reactQuery.queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await y("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function JR(e){return reactQuery.queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>y("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function eT(e){return reactQuery.queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>y("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function oT(e){return reactQuery.queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>y("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function uT(e){return reactQuery.queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function dT(e){return reactQuery.queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>y("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function hT(e,t=100){return reactQuery.infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let o=(await y("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(i=>i)).rc_direct_delegations||[];return r&&(o=o.filter(i=>i.to!==r)),o},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function vT(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 h()(`${d.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function xT(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 CT(e){return reactQuery.queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>y("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 o=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(o){let i=Number.parseFloat(o[0]);if(Number.isFinite(i))return i}}}function md(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 gd(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 o of ["wallets","tokens","assets","items","portfolio","balances"]){let i=n[o];if(Array.isArray(i))return i}}return []}function yd(e){if(!e||typeof e!="object")return;let t=e;return fe(t.username)??fe(t.name)??fe(t.account)}function Pi(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`,o=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!o.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${o.status})`);let i=await o.json(),s=gd(i).map(a=>md(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:yd(i)??e,currency:fe(i?.fiatCurrency??i?.currency)?.toUpperCase(),wallets:s}}})}function Yt(e){return reactQuery.queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Oe()),await b().prefetchQuery(B(e));let t=b().getQueryData(Oe().queryKey),r=b().getQueryData(B(e).queryKey),n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:0};let i=k(r.balance).amount,s=k(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:i+s,parts:[{name:"current",balance:i},{name:"savings",balance:s}]}}})}function Ai(e){return reactQuery.queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Oe()),await b().prefetchQuery(B(e));let t=b().getQueryData(B(e).queryKey),r=b().getQueryData(Oe().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:k(t.hbd_balance).amount+k(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:k(t.hbd_balance).amount},{name:"savings",balance:k(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function bd(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 Oi(e){return reactQuery.queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Oe()),await b().prefetchQuery(B(e));let t=b().getQueryData(Oe().queryKey),r=b().getQueryData(B(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??""),i=Number.isFinite(o)?o:t.base/t.quote,s=k(r.vesting_shares).amount,a=k(r.delegated_vesting_shares).amount,c=k(r.received_vesting_shares).amount,p=k(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),f=wo(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+ze(s,t.hivePerMVests).toFixed(3),g=+ze(a,t.hivePerMVests).toFixed(3),_=+ze(c,t.hivePerMVests).toFixed(3),P=+ze(l,t.hivePerMVests).toFixed(3),O=+ze(f,t.hivePerMVests).toFixed(3),T=Math.max(m-P,0),q=Math.max(m-g,0);return {name:"HP",title:"Hive Power",price:i,accountBalance:+T.toFixed(3),apr:bd(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+q.toFixed(3)},{name:"outgoing_delegations",balance:g},{name:"incoming_delegations",balance:_},...P>0?[{name:"pending_power_down",balance:+P.toFixed(3)}]:[],...O>0&&O!==P?[{name:"next_power_down",balance:+O.toFixed(3)}]:[]]}}})}var N=ne.operations,gn={transfers:[N.transfer,N.transfer_to_savings,N.transfer_from_savings,N.cancel_transfer_from_savings,N.recurrent_transfer,N.fill_recurrent_transfer,N.escrow_transfer,N.fill_recurrent_transfer],"market-orders":[N.fill_convert_request,N.fill_order,N.fill_collateralized_convert_request,N.limit_order_create2,N.limit_order_create,N.limit_order_cancel],interests:[N.interest],"stake-operations":[N.return_vesting_delegation,N.withdraw_vesting,N.transfer_to_vesting,N.set_withdraw_vesting_route,N.update_proposal_votes,N.fill_vesting_withdraw,N.account_witness_proxy,N.delegate_vesting_shares],rewards:[N.author_reward,N.curation_reward,N.producer_reward,N.claim_reward_balance,N.comment_benefactor_reward,N.liquidity_reward,N.proposal_pay],"":[]};var eq=Object.keys(ne.operations);var xi=ne.operations,nq=xi,oq=Object.entries(xi).reduce((e,[t,r])=>(e[r]=t,e),{});var Si=ne.operations;function Pd(e){return Object.prototype.hasOwnProperty.call(Si,e)}function wt(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),o=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),i=new Set;r||n.forEach(a=>{if(a in gn){gn[a].forEach(c=>i.add(c));return}Pd(a)&&i.add(Si[a]);});let s=xd(Array.from(i));return {filterKey:o,filterArgs:s}}function yn(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function Ad(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function Od(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function xd(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await y("condenser_api.get_account_history",[e,s,Od(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 k(p.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(p.amount).symbol==="HIVE";case "transfer_from_savings":case "fill_transfer_from_savings":return k(p.amount).symbol==="HIVE";case "fill_recurrent_transfer":let f=k(p.amount);return ["HIVE"].includes(f.symbol);case "claim_reward_balance":return k(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 i.has(p.type)}}))})})}function gq(e,t=20,r=[]){let{filterKey:n}=wt(r),o=yn(r);return reactQuery.infiniteQueryOptions({...Xt(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:i,pageParams:s})=>({pageParams:s,pages:i.map(a=>a.filter(c=>{switch(c.type){case "author_reward":case "comment_benefactor_reward":return k(c.hbd_payout).amount>0;case "claim_reward_balance":return k(c.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(c.amount).symbol==="HBD";case "transfer_from_savings":case "fill_transfer_from_savings":return k(c.amount).symbol==="HBD";case "fill_recurrent_transfer":let f=k(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 o.has(c.type)}}))})})}function bq(e,t=20,r=[]){let{filterKey:n}=wt(r),o=new Set(Array.isArray(r)?r:[r]),i=o.has("")||o.size===0;return reactQuery.infiniteQueryOptions({...Xt(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 k(p.vesting_payout).amount>0;case "claim_reward_balance":return k(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(k(p.amount).symbol);case "fill_recurrent_transfer":let m=k(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 i||o.has(p.type)}}))})})}function Ei(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 hn(e,t){return new Date(e.getTime()-t*1e3)}function Oq(e=86400){return reactQuery.infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await y("condenser_api.get_market_history",[e,Ei(t),Ei(r)])).map(({hive:o,non_hive:i,open:s})=>({close:i.close/o.close,open:i.open/o.open,low:i.low/o.low,high:i.high/o.high,volume:o.volume,time:new Date(s)})),initialPageParam:[hn(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[hn(n,Math.max(100*e,28800)),hn(n,e)]})}function kq(e){return reactQuery.queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function qq(e,t=50){return reactQuery.queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>y("condenser_api.get_vesting_delegations",[e,"",t])})}function Nq(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)=>k(n.vesting_shares).amount-k(r.vesting_shares).amount)})}function Hq(e=500){return reactQuery.queryOptions({queryKey:["market","order-book",e],queryFn:()=>y("condenser_api.get_order_book",[e])})}function Lq(){return reactQuery.queryOptions({queryKey:["market","statistics"],queryFn:()=>y("condenser_api.get_ticker",[])})}function zq(e,t,r){let n=o=>o.toISOString().replace(/\.\d{3}Z$/,"");return reactQuery.queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>y("condenser_api.get_market_history",[e,n(t),n(r)])})}function Zq(){return reactQuery.queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await y("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),o=await y("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:o[0]?o[0].non_hive.open/o[0].hive.open:0,high:o[0]?o[0].non_hive.high/o[0].hive.high:0,low:o[0]?o[0].non_hive.low/o[0].hive.low:0,percent:o[0]?100-o[0].non_hive.open/o[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function nF(e,t,r,n){return reactQuery.queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:o})=>{let i=h(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await i(s,{signal:o});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function ki(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function aF(e=1e3,t,r){let n=r??new Date,o=t??new Date(n.getTime()-600*60*1e3);return reactQuery.queryOptions({queryKey:["market","trade-history",e,o.getTime(),n.getTime()],queryFn:()=>y("condenser_api.get_trade_history",[ki(o),ki(n),e])})}function lF(){return reactQuery.queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await y("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function gF(){return reactQuery.queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await y("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function wF(e,t,r){return v(["market","limit-order-create"],e,n=>[$t(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 AF(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[Gr(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 bt(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 o=h(),i=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await o(i);return bt(s)}async function Ci(e){if(e==="hbd")return 1;let t=h(),r=`https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${e}`,n=await t(r);return (await bt(n)).hive_dollar[e]}async function EF(e,t){let n=await h()(d.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return bt(n)}async function kF(){let t=await h()(d.privateApiHost+"/private-api/market-data/latest");return bt(t)}async function CF(){let t=await h()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return bt(t)}var Qd={"Content-type":"application/json"};async function Hd(e){let t=h(),r=exports.ConfigManager.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:Qd});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function Te(e,t){try{return await Hd(e)}catch{return t}}async function qF(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,o]=await Promise.all([Te({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),Te({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),i=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:i(n),sell:s(o)}}async function FF(e,t=50){return Te({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 IF(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},[o,i]=await Promise.all([Te({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),Te({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=o.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=i.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 Ud(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return Te({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function rt(e,t){return Ud(t,e)}async function Zt(e){return Te({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function er(e){return Te({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function Ri(e,t,r,n){let o=h(),i=exports.ConfigManager.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",i);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 o(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 Ti(e,t="daily"){let r=h(),n=exports.ConfigManager.getValidatedBaseUrl(),o=new URL("/private-api/engine-chart-api",n);o.searchParams.set("symbol",e),o.searchParams.set("interval",t);let i=await r(o.toString(),{headers:{"Content-type":"application/json"}});if(!i.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${i.status}`);return await i.json()}async function qi(e){let t=h(),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 tr(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Zt(e)})}function HF(){return reactQuery.queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>rt()})}function Fi(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>er(e)})}function GF(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 Ri(e,t,r,n)},getNextPageParam:(n,o,i)=>(n?.length??0)===r?i+r:void 0,getPreviousPageParam:(n,o,i)=>i>0?i-r:void 0})}function XF(e,t="daily"){return reactQuery.queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ti(e,t)})}function rI(e){return reactQuery.queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await qi(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function Ii(e,t){return reactQuery.queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>rt(e,t)})}function nt(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:o,suffix:i}=r,s="";o&&(s+=o+" ");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}),i&&(s+=" "+i),s}var rr=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()?`(${nt(this.stake,{fractionDigits:this.precision})} + ${nt(this.delegationsIn,{fractionDigits:this.precision})} - ${nt(this.delegationsOut,{fractionDigits:this.precision})})`:"";staked=()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():nt(this.stakedBalance,{fractionDigits:this.precision}):"-";balanced=()=>this.balance<1e-4?this.balance.toString():nt(this.balance,{fractionDigits:this.precision})};function fI(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 Zt(e),o=await er(n.map(p=>p.symbol)),i=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 rt(void 0,a):[]];return n.map(p=>{let l=o.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),g=Number(m?.lastPrice??"0"),_=Number(p.balance),P=p.symbol==="SWAP.HIVE"?i*_:g===0?0:Number((g*i*_).toFixed(10));return new rr({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:P})})},enabled:!!e})}function Di(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=Yt(e);await r.prefetchQuery(n);let o=r.getQueryData(n.queryKey),i=await r.ensureQueryData(Fi([t])),s=await r.ensureQueryData(tr(e)),a=await r.ensureQueryData(Ii(void 0,t)),c=i?.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"),g=parseFloat(p?.stake??"0"),_=parseFloat(p?.pendingUnstake??"0"),P=[{name:"liquid",balance:m},{name:"staked",balance:g}];return _>0&&P.push({name:"unstaking",balance:_}),{name:t,title:c?.name??"",price:f===0?0:Number(f*(o?.price??0)),accountBalance:m+g,layer:"ENGINE",parts:P}}})}function vt(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 o=await n.json(),i=await fetch(d.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!i.ok)throw new Error(`Failed to fetch point transactions: ${i.status}`);let s=await i.json();return {points:o.points,uPoints:o.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function Ki(e){return reactQuery.queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await b().prefetchQuery(vt(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(b().getQueryData(vt(e).queryKey)?.points??0)})})}function TI(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:o,type:i,amount:s,id:a,sender:c,receiver:p,memo:l})=>({created:new Date(o),type:i,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:c??void 0,to:p??void 0,memo:l??void 0}))})}function VI(e,t,r={refetch:false}){let n=b(),o=r.currency??"usd",i=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||o==="usd")return p;try{let l=await Ci(o);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${o}:`,l),p}},a=Pi(e,o,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 g=m.dataKey,_=m.value;if(typeof _=="string"){let O=_.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(O){let T=Math.abs(Number.parseFloat(O[1]));g==="delegated_hive_power"?f.push({name:"outgoing_delegations",balance:T}):g==="received_hive_power"?f.push({name:"incoming_delegations",balance:T}):g==="powering_down_hive_power"&&f.push({name:"pending_power_down",balance:T});}}}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,o],queryFn:async()=>{let p=await c();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await i(Yt(e));else if(t==="HP")l=await i(Oi(e));else if(t==="HBD")l=await i(Ai(e));else if(t==="POINTS")l=await i(Ki(e));else if((await n.ensureQueryData(tr(e))).some(m=>m.symbol===t))l=await i(Di(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 rf=(T=>(T.Transfer="transfer",T.TransferToSavings="transfer-saving",T.WithdrawFromSavings="withdraw-saving",T.Delegate="delegate",T.PowerUp="power-up",T.PowerDown="power-down",T.WithdrawRoutes="withdraw-routes",T.ClaimInterest="claim-interest",T.Swap="swap",T.Convert="convert",T.Gift="gift",T.Promote="promote",T.Claim="claim",T.Buy="buy",T.Stake="stake",T.Unstake="unstake",T.Undelegate="undelegate",T))(rf||{});function zI(e,t,r){return v(["wallet","transfer"],e,n=>[Ue(e,n.to,n.amount,n.memo)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function eD(e,t,r){return v(["wallet","transfer-point"],e,n=>[Ze(e,n.to,n.amount,n.memo)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function iD(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[yt(e,n.delegatee,n.vestingShares)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function pD(e,t,r){return v(["wallet","set-withdraw-vesting-route"],e,n=>[ht(e,n.toAccount,n.percent,n.autoVest)],async(n,o)=>{await S(t?.adapter,r,[u.wallet.withdrawRoutes(e),u.accounts.full(e),u.accounts.full(o.toAccount)]);},t,"active",{broadcastMode:r})}function mD(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function wD(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[Xe(e,n.to,n.amount,n.memo)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function OD(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[Ve(e,n.to,n.amount,n.memo,n.requestId)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function CD(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[mt(e,n.to,n.amount)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function ID(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[gt(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 MD(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?Fr(e,n.amount,n.requestId):_t(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 jD(e,t,r){return v(["wallet","claim-interest"],e,n=>ft(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 nf=5e3,nr=new Map;function zD(e,t,r){return v(["wallet","claim-rewards"],e,n=>[zr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",o=[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)],i=nr.get(n);i&&(clearTimeout(i),nr.delete(n));let s=setTimeout(async()=>{try{let a=b(),p=(await Promise.allSettled(o.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{nr.delete(n);}},nf);nr.set(n,s);},t,"posting",{broadcastMode:r})}function ZD(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function nK(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let o=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:o}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function aK(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function lK(e,t,r){return v(["wallet","unstake-engine-token"],e,n=>{let o=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:o}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function gK(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let o=JSON.stringify(n.tokens.map(i=>({symbol:i})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:o}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function wK(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let o,i;n.action==="cancel"?(i="cancel",o={type:n.orderType,id:n.orderId}):(i=n.action,o={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:i,contractPayload:o});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 of(e,t,r){let{from:n,to:o="",amount:i="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [Ue(n,o,i,s)];case "transfer-saving":return [Xe(n,o,i,s)];case "withdraw-saving":return [Ve(n,o,i,s,a)];case "power-up":return [mt(n,o,i)]}break;case "HBD":switch(t){case "transfer":return [Ue(n,o,i,s)];case "transfer-saving":return [Xe(n,o,i,s)];case "withdraw-saving":return [Ve(n,o,i,s,a)];case "claim-interest":return ft(n,o,i,s,a);case "convert":return [_t(n,i,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [gt(n,i)];case "delegate":return [yt(n,o,i)];case "withdraw-routes":return [ht(r.from_account??n,r.to_account??o,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [Ze(n,o,i,s)];break}return null}function sf(e,t,r){let{from:n,to:o="",amount:i=""}=r,s=typeof i=="string"&&i.includes(" ")?i.split(" ")[0]:String(i);switch(t){case "transfer":return [je(n,"transfer",{symbol:e,to:o,quantity:s,memo:r.memo??""})];case "stake":return [je(n,"stake",{symbol:e,to:o,quantity:s})];case "unstake":return [je(n,"unstake",{symbol:e,to:o,quantity:s})];case "delegate":return [je(n,"delegate",{symbol:e,to:o,quantity:s})];case "undelegate":return [je(n,"undelegate",{symbol:e,from:o,quantity:s})];case "claim":return [Ir(n,[e])]}return null}function af(e){return e==="claim"?"posting":"active"}function xK(e,t,r,n,o){let{mutateAsync:i}=et.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=of(t,r,s);if(a)return a;let c=sf(t,r,s);if(c)return c;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{i();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,af(r),{broadcastMode:o})}function CK(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:o})=>[Dr(e,n,o)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),u.resourceCredits.account(e),u.resourceCredits.account(o.to)]);},t,"active",{broadcastMode:r})}function FK(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:o})=>[Br(e,n,o)],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 NK(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[Mr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function cf(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 VK(e){return reactQuery.infiniteQueryOptions({queryKey:u.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await te("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(cf),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function jK(e,t,r,n="vests",o="desc"){return reactQuery.queryOptions({queryKey:u.witnesses.voters(e,t,r,n,o),queryFn:async({signal:i})=>await te("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:o},void 0,void 0,i),enabled:!!e,staleTime:6e4})}function LK(e){return reactQuery.queryOptions({queryKey:u.witnesses.voterCount(e),queryFn:async()=>await te("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var pf=(_=>(_[_.CHECKIN=10]="CHECKIN",_[_.LOGIN=20]="LOGIN",_[_.CHECKIN_EXTRA=30]="CHECKIN_EXTRA",_[_.POST=100]="POST",_[_.COMMENT=110]="COMMENT",_[_.VOTE=120]="VOTE",_[_.REBLOG=130]="REBLOG",_[_.DELEGATION=150]="DELEGATION",_[_.REFERRAL=160]="REFERRAL",_[_.COMMUNITY=170]="COMMUNITY",_[_.TRANSFER_SENT=998]="TRANSFER_SENT",_[_.TRANSFER_INCOMING=999]="TRANSFER_INCOMING",_[_.MINTED=991]="MINTED",_[_.BURNED=997]="BURNED",_))(pf||{});async function df(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 h()(d.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),o=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),i=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(i)}catch{return {message:i,code:n.status}}let s=i&&o.includes("json")?`: ${i.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!o.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${o||"empty"}" response (status ${n.status})`);try{return JSON.parse(i)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function XK(e,t,r,n){let{mutateAsync:o}=et.useRecordActivity(e,"points-claimed");return reactQuery.useMutation({mutationFn:()=>df(e,t),onError:n,onSuccess:()=>{o(),b().setQueryData(vt(e).queryKey,i=>i&&{...i,points:(parseFloat(i.points)+parseFloat(i.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var Bi=/(^|\s)author:([^\s]+)/g,Mi=/(^|\s)type:([^\s]+)/g,Qi=/(^|\s)category:([^\s]+)/g,Hi=/(^|\s)tag:([^\s]+)/g;var Vi=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(Vi||{}),eN=5,tN=100;function ji(e){return e.trim().split(/\s+/)[0]??""}function ff(e){return ji(e).replace(/^@+/,"").toLowerCase()}function mf(e){return ji(e).replace(/^#+/,"").toLowerCase()}function gf(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 rN({search:e="",author:t="",type:r="",category:n="",tags:o=[]}){let i=e.trim().replace(/\s+/g," "),s=ff(t),a=mf(n),c=gf(Array.isArray(o)?o.join(","):o),p=[i];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:i,author:s,type:r,category:a,tags:c}}var Ui=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(Bi);};grabType=()=>{let t=this.grab(Mi);Object.values(Vi).includes(t)&&(this.type=t);};grabCategory=()=>{this.category=this.grab(Qi);};grabTags=()=>{let t=new Set;this.tags=[...this.query.matchAll(Hi)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));};grabSearch=()=>{for([Bi,Mi,Qi,Hi].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 xe(e,t){let n=await(async()=>{let o;try{o=await e.text();}catch{return}if(o!=="")try{return JSON.parse(o)}catch{return e.ok?void 0:o}})();if(!e.ok){let o=new Error(`Request failed with status ${e.status}`);throw o.status=e.status,o.data=n,o}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 qe(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var hf=reactQuery.isServer?0:3;function Pt(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),o&&(a.scroll_id=o),i&&(a.votes=i);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:Pe(Ae,s)});return xe(c,qe)},retry:Pt})}function fN(e,t,r=true){return reactQuery.infiniteQueryOptions({queryKey:u.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:o})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let i,s=new Date;switch(t){case "today":i=new Date(s.getTime()-1440*60*1e3);break;case "week":i=new Date(s.getTime()-10080*60*1e3);break;case "month":i=new Date(s.getTime()-720*60*60*1e3);break;case "year":i=new Date(s.getTime()-365*24*60*60*1e3);break;default:i=void 0;}let a="* type:post",c=e==="rising"?"children":e,p=i?i.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 g=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(m),signal:Pe(Ae,o)});return xe(g,qe)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:Pt})}async function hN(e,t,r,n,o,i,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),o&&(a.scroll_id=o),i&&(a.votes=i);let p=await h()(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:Pe(Ae,s)});return xe(p,qe)}async function Li(e,t,r=Ae){let o=await h()(d.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(e),signal:Pe(r,t)});return xe(o,qe)}async function _N(e,t){let n=await h()(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e}),signal:Pe(Ae,t)}),o=await xe(n,Array.isArray);return o?.length>0?o:[e]}var vf=4368*60*60*1e3,Pf=4,Af=3e3,Of=2e3,xf=4e3,AN=2;function Sf(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function Ef(e){let t=5381;for(let r=0;r>>0).toString(36)}function ON(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),o=Sf(e.body??"",Af),i=Ef(`${t}|${n.join(",")}|${o}`);return reactQuery.queryOptions({queryKey:u.search.similarEntries(e.author,e.permlink,i),queryFn:async({signal:s})=>{let a=new Date(Date.now()-vf).toISOString().slice(0,19),c=await Li({author:e.author,permlink:e.permlink,title:t,body:o,tags:n,since:a},s,typeof window>"u"?Of:xf),p=[],l=new Set;for(let f of c.results){if(p.length>=Pf)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 RN(e,t=5){let r=e.trim();return reactQuery.queryOptions({queryKey:u.search.account(r,t),queryFn:async()=>{let n=await y("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Vt(n)},enabled:!!r})}function DN(e,t=10){let r=e.trim();return reactQuery.queryOptions({queryKey:u.search.topics(r,t),queryFn:async()=>(await y("condenser_api.get_trending_tags",[r,t+1])).map(o=>o.name).filter(o=>o!==""&&!o.startsWith("hive-")).slice(0,t),enabled:!!r})}function HN(e,t,r,n,o,i){return reactQuery.infiniteQueryOptions({queryKey:u.search.api(e,t,r,n,o,i),queryFn:async({pageParam:s,signal:a})=>{let c={q:e,sort:t,hide_low:r};n&&(c.since=n),s&&(c.scroll_id=s),o!==void 0&&(c.votes=o),i&&(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:Pe(Ae,a)});return xe(p,qe)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:Pt})}function LN(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 Ff(e){let r=await h()(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 o=n?.message??`Failed to fetch support settings: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function zN(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 Ff(t)},enabled:!!r&&!!t})}async function Kf(e,t){let n=await h()(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 o;try{o=await n.json();}catch{}let i=o?.message??`Failed to update support settings: ${n.status}`,s=new Error(i);throw s.status=n.status,s.data=o,s}return await n.json()}function Nf(e,t,r){return e.setQueryData(u.support.settings(t),r),e.invalidateQueries({queryKey:u.support.settings(t)})}function eB(e,t){let r=reactQuery.useQueryClient(),n=e?.replace("@","");return reactQuery.useMutation({mutationKey:["support","settings-update",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return Kf(t,o)},onSuccess(o){n&&Nf(r,n,o);}})}function oB(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 uB(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 dB(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 yB(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 bB(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 OB(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:o})=>[en(e,n,o)],async(n,{account:o})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.promotions.boostPlusAccounts(o)]);},t,"active",{broadcastMode:r})}function kB(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[tn(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 TB(e){let r=await h()(d.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let o;try{o=await r.json();}catch{o=void 0;}let i=new Error(`Failed to refresh token: ${r.status}`);throw i.status=r.status,i.data=o,i}return await r.json()}var jf="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function DB(){return reactQuery.queryOptions({queryKey:u.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(jf,{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 NB=1.1,Lf=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(Lf||{});function BB(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 Gf(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,o=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}}),i=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:o,poll_voters:i,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 VB(e,t){return reactQuery.queryOptions({queryKey:u.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:reactQuery.isServer?yo:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=h(),n=`${d.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,o=await r(n);if(!o.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${o.status}`);let i=await o.json();if(!Array.isArray(i)||!i[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return Gf(i[0])}})}function $B(e,t,r){return v(u.polls.vote(),e??"",({pollTrxId:n,choices:o})=>{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:o})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}var zf=-1e10,Jf=5,Yf=30;var $i=e=>Math.abs(e)>0&&Math.abs(e)<=100;function Wi(e){if(typeof e=="number"&&$i(e)||typeof e=="string"&&(e=Number(e),$i(e)))return Math.floor(e);if(e===0)return 25;let t=false;e<0&&(t=true);let r=Math.log10(Math.abs(e));return r=Math.max(r-9,0),r<0&&(r=0),t&&(r*=-1),r=r*9+25,Math.floor(r)}var Xf=["ecency.com","ecency.app","hive.blog","hive.io","hiveblocks.com","peakd.com","snapie.io","hivesuite.app","leofinance.io","inleo.io","3speak.tv","d.buzz","waivio.com"],Zf=["imgur.com","images.hive.blog","files.peakd.com","i.ecency.com","images.ecency.com","steemitimages.com","cdn.steemitimages.com","media.giphy.com"],em=/\.(jpe?g|png|gif|webp|svg|bmp|avif)(\?|#|$)/i,tm=/(?:https?:)?\/\/[^\s)<>"'\]]+/gi,rm=/[.,;:!?'"]+$/;function nm(e){let t=/^(?:https?:)?\/\/([^/?#]+)/i.exec(e);return t?t[1].toLowerCase().replace(/^www\./,""):""}function om(e){let t=e.replace(rm,"");if(em.test(t))return false;let r=nm(t);if(!r.includes("."))return false;let n=o=>r===o||r.endsWith("."+o);return !(Xf.some(n)||Zf.some(n))}function Gi(e){if(!e)return false;let t=e.match(tm);return t?t.some(om):false}var im=(n=>(n.MOD_MUTED="mod_muted",n.DOWNVOTED="downvoted",n.LOW_TRUST="low_trust",n))(im||{});function sm(e){return e?.stats?.total_votes??e?.active_votes?.length??0}function am(e,t){return (e??0)<-1e10&&t>=5}function um(e){let t=e?.author_reputation;return t==null?false:Wi(t)<30&&Gi(e?.body)}function ZB(e,t){return !!e&&!!t?.includes(e)}function eM(e){return e?e.stats?.gray||e.stats?.hide?"mod_muted":am(e.net_rshares,sm(e))?"downvoted":um(e)?"low_trust":null:null}var At=class extends Error{constructor(r,n,o){super(r);this.status=n;this.data=o;}status;data},or=class extends At{constructor(r,n,o,i,s){super(r,n,s);this.code=o;this.taken=i;}code;taken};function Fe(e){return `${d.privateApiHost}/api/newsletter${e}`}async function $e(e){let t=await e.json().catch(()=>{});if(!e.ok)throw new At(t?.error||`Request failed (${e.status})`,e.status,t);if(!t||typeof t!="object")throw new At(`Unexpected response (${e.status})`,e.status);return t}async function zi(e,t){let n=await h()(Fe("/subscribe"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,...t?{code:t}:{}})});return $e(n)}async function Ji(e){let r=await h()(Fe("/subscriptions"),{headers:{"X-HS-Token":e}});return (await $e(r)).subscriptions??[]}async function Yi(e,t){let n=await h()(Fe(`/subscriptions/${encodeURIComponent(e)}`),{method:"DELETE",headers:{"X-HS-Token":t}});await $e(n);}async function Xi(e,t){let n=await h()(Fe("/unsubscribe-all"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,code:t})});await $e(n);}async function Zi(e,t,r){let o=await h()(Fe(`/sender?type=${e}&target=${encodeURIComponent(t)}`),{headers:{"X-HS-Token":r}});return $e(o)}async function es(e,t,r){let o=await h()(Fe(`/issues?type=${e}&target=${encodeURIComponent(t)}`),{headers:{"X-HS-Token":r}});return (await $e(o)).issues??[]}async function ts(e,t,r,n=20){let i=await h()(Fe(`/posts?type=${e}&target=${encodeURIComponent(t)}&limit=${n}`),{headers:{"X-HS-Token":r}});return (await $e(i)).posts??[]}async function rs(e,t,r){let o=await h()(Fe(e),{method:"POST",headers:{"Content-Type":"application/json","X-HS-Token":r},body:JSON.stringify(t)}),i=await o.json().catch(()=>{});if(!o.ok)throw new or(i?.error||`Request failed (${o.status})`,o.status,i?.code,i?.taken,i);if(!i||typeof i!="object")throw new or(`Unexpected response (${o.status})`,o.status);return i}function ns(e,t){return rs("/send/preview",e,t)}function os(e,t){return rs("/send",e,t)}function aM(e,t){let r=e?.replace("@","");return reactQuery.queryOptions({queryKey:u.newsletter.subscriptions(r),enabled:!!r&&!!t,queryFn:async()=>{if(!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return Ji(t)},staleTime:6e4,retry:false})}function dM(e,t,r,n){let o=r?.replace("@","");return reactQuery.queryOptions({queryKey:u.newsletter.sender(e,t,o),enabled:!!o&&!!n&&!!t,queryFn:async()=>{if(!n)throw new Error("[SDK][Newsletter] \u2013 missing auth");return Zi(e,t,n)},staleTime:5*6e4})}function hM(e,t,r,n){let o=r?.replace("@","");return reactQuery.queryOptions({queryKey:u.newsletter.issues(e,t,o),enabled:!!o&&!!n&&!!t,queryFn:async()=>{if(!n)throw new Error("[SDK][Newsletter] \u2013 missing auth");return es(e,t,n)},staleTime:6e4})}function PM(e,t,r,n,o=20){let i=r?.replace("@","");return reactQuery.queryOptions({queryKey:u.newsletter.posts(e,t,i,o),enabled:!!i&&!!n&&!!t,queryFn:async()=>{if(!n)throw new Error("[SDK][Newsletter] \u2013 missing auth");return ts(e,t,n,o)},staleTime:6e4})}function EM(e,t){let r=reactQuery.useQueryClient(),n=e?.replace("@","");return reactQuery.useMutation({mutationKey:["newsletter","subscribe",n],mutationFn:o=>zi(o,t),onSuccess(){n&&r.invalidateQueries({queryKey:u.newsletter.subscriptions(n)});}})}function qM(e,t){let r=reactQuery.useQueryClient(),n=e?.replace("@","");return reactQuery.useMutation({mutationKey:["newsletter","leave",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return Yi(o,t)},onSuccess(o,i){r.setQueryData(u.newsletter.subscriptions(n),s=>(s??[]).filter(a=>a.id!==i));}})}function NM(e,t){let r=reactQuery.useQueryClient(),n=e?.replace("@","");return reactQuery.useMutation({mutationKey:["newsletter","unsubscribe-all",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return Xi(o,t)},onSuccess(o,i){r.setQueryData(u.newsletter.subscriptions(n),s=>(s??[]).filter(a=>a.email.toLowerCase()!==i.toLowerCase()));}})}function UM(e,t){let r=e?.replace("@","");return reactQuery.useMutation({mutationKey:["newsletter","send-preview",r],mutationFn:async n=>{if(!r||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return ns(n,t)}})}function VM(e,t){let r=reactQuery.useQueryClient(),n=e?.replace("@","");return reactQuery.useMutation({mutationKey:["newsletter","send",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return os(o,t)},onSuccess(o,i){r.invalidateQueries({queryKey:u.newsletter.issues(i.type,i.target,n)}),r.invalidateQueries({queryKey:u.newsletter.sender(i.type,i.target,n)});}})}/** * @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=Ao;exports.ALL_ACCOUNT_OPERATIONS=Ga;exports.ALL_NOTIFY_TYPES=yi;exports.AssetOperation=Hd;exports.BROADCAST_INCLUSION_DELAY_MS=xg;exports.BuySellTransactionType=Lo;exports.CONFIG=f;exports.ContentModerationReason=jf;exports.EcencyAnalytics=Xe;exports.ErrorType=co;exports.HIDDEN_POST_MIN_VOTES=Df;exports.HIDDEN_POST_RSHARES_THRESHOLD=qf;exports.HIVE_ACCOUNT_OPERATION_GROUPS=ln;exports.HIVE_OPERATION_LIST=kT;exports.HIVE_OPERATION_NAME_BY_ID=FT;exports.HIVE_OPERATION_ORDERS=TT;exports.HiveEngineToken=Zt;exports.HiveSignerIntegration=pi;exports.HiveTxTransaction=De;exports.INTERNAL_API_TIMEOUT_MS=Ae;exports.LOW_TRUST_REPUTATION_THRESHOLD=Kf;exports.MAX_SEARCH_QUERY_LENGTH=CK;exports.MAX_SEARCH_TAGS=kK;exports.Memo=oo;exports.NaiMap=Bt;exports.NotificationFilter=kl;exports.NotificationViewType=Rl;exports.NotifyTypes=Cl;exports.OPERATION_AUTHORITY_MAP=ep;exports.OrderIdPrefix=$o;exports.POLLS_PROTOCOL_VERSION=lM;exports.PointTransactionType=Gd;exports.PollPreferredInterpretation=Rf;exports.PrivateKey=U;exports.PublicKey=Y;exports.QUEST_CATALOG=ll;exports.QUEST_MIN_CONTENT_LENGTH=dl;exports.QueryKeys=u;exports.RC_RESOURCE_NAMES=Wt;exports.ROLES=xl;exports.SERVER_GC_TIME_MS=lo;exports.SIGNATURE_BYTES=tl;exports.SIMILAR_ENTRIES_MIN_RENDER=YK;exports.STREAK_FREEZE_MAX_OWNED=HS;exports.STREAK_FREEZE_PRICE=QS;exports.SUBSCRIBERS_PAGE_SIZE=mi;exports.SearchQuery=Mi;exports.SearchType=Ni;exports.Signature=Ee;exports.SortOrder=qo;exports.Symbol=fo;exports.THREESPEAK_BENEFICIARY_ACCOUNT=$t;exports.THREESPEAK_BENEFICIARY_WEIGHT=bE;exports.TRANSACTION_HEADER_BYTES=el;exports.ThreeSpeakIntegration=ME;exports.accountNameByteLength=Ea;exports.addDraft=ri;exports.addImage=Zo;exports.addOptimisticDiscussionEntry=Cx;exports.addSchedule=ii;exports.applySupportSettingsUpdate=Pf;exports.applyVoteCacheUpdate=xp;exports.bridgeApiCall=ae;exports.broadcastJson=po;exports.broadcastOperations=ee;exports.broadcastOperationsAsync=so;exports.buildAccountCreateOp=$r;exports.buildAccountUpdate2Op=Pu;exports.buildAccountUpdateOp=vu;exports.buildActiveCustomJsonOp=ku;exports.buildBoostPlusOp=Jr;exports.buildCancelTransferFromSavingsOp=jo;exports.buildChangeRecoveryAccountOp=Ou;exports.buildClaimAccountOp=Gr;exports.buildClaimInterestOps=lt;exports.buildClaimRewardBalanceOp=Lr;exports.buildCollateralizedConvertOp=Cr;exports.buildCommentOp=Ne;exports.buildCommentOptionsOp=Qe;exports.buildCommunityRegistrationOp=Zr;exports.buildConvertOp=yt;exports.buildCreateClaimedAccountOp=Wr;exports.buildDelegateRcOp=Tr;exports.buildDelegateVestingSharesOp=mt;exports.buildDeleteCommentOp=Sr;exports.buildEngineClaimOp=Rr;exports.buildEngineOp=Ve;exports.buildFlagPostOp=bu;exports.buildFollowOp=Fr;exports.buildGrantPostingPermissionOp=zr;exports.buildIgnoreOp=mu;exports.buildLimitOrderCancelOp=jr;exports.buildLimitOrderCreateOp=Vt;exports.buildLimitOrderCreateOpWithType=wu;exports.buildMultiPointTransferOps=Su;exports.buildMultiTransferOps=du;exports.buildMutePostOp=Vr;exports.buildMuteUserOp=_u;exports.buildPinPostOp=Ur;exports.buildPointTransferOp=Ye;exports.buildPostingCustomJsonOp=Cu;exports.buildPostingJsonMetadata=wo;exports.buildProfileMetadata=Ar;exports.buildPromoteOp=Xr;exports.buildProposalCreateOp=Kr;exports.buildProposalVoteOp=Br;exports.buildRcDelegationOp=Yr;exports.buildReblogOp=kr;exports.buildRecoverAccountOp=Eu;exports.buildRecurrentTransferOp=fu;exports.buildRemoveProposalOp=yu;exports.buildRequestAccountRecoveryOp=xu;exports.buildRevokeKeysOp=Go;exports.buildRevokePostingPermissionOp=Au;exports.buildSearchQuery=RK;exports.buildSetLastReadOps=Ir;exports.buildSetRoleOp=Qr;exports.buildSetWithdrawVestingRouteOp=gt;exports.buildSubscribeOp=Mr;exports.buildTransferFromSavingsOp=Ue;exports.buildTransferOp=He;exports.buildTransferToSavingsOp=Je;exports.buildTransferToVestingOp=dt;exports.buildUnfollowOp=Ht;exports.buildUnignoreOp=gu;exports.buildUnsubscribeOp=Nr;exports.buildUpdateCommunityOp=Hr;exports.buildUpdateProposalOp=hu;exports.buildVoteOp=Er;exports.buildWithdrawVestingOp=ft;exports.buildWitnessProxyOp=Dr;exports.buildWitnessVoteOp=qr;exports.buyStreakFreezeRequest=hl;exports.calculateRCMana=Dt;exports.calculateVPMana=wr;exports.callREST=te;exports.callRPC=y;exports.callRPCBroadcast=Le;exports.callWithQuorum=It;exports.canRevokeFromAuthority=YP;exports.checkFavoriteQueryOptions=Gh;exports.checkUsernameWalletsPendingQueryOptions=xh;exports.claimPointsRequest=Jd;exports.collectRequestedOperations=dn;exports.computeResourceCost=sn;exports.countCommentResourceUsage=an;exports.countVoteResourceUsage=di;exports.decodeObj=Qg;exports.dedupeAndSortKeyAuths=Ku;exports.deleteDraft=oi;exports.deleteImage=ti;exports.deleteSchedule=si;exports.downVotingPower=vA;exports.earnsQuestContentCredit=NS;exports.encodeObj=Ng;exports.enforceThreeSpeakBeneficiary=wE;exports.estimateCommentRcCost=dS;exports.estimateCommentTransactionBytes=cn;exports.estimateRcPrecheck=AS;exports.estimateVoteTransactionBytes=li;exports.extractAccountProfile=_o;exports.formatError=Gs;exports.formattedNumber=tt;exports.gameClaimRequest=ul;exports.getAccountDelegationsQueryOptions=yR;exports.getAccountFullQueryOptions=M;exports.getAccountNotificationsInfiniteQueryOptions=Wk;exports.getAccountPendingRecoveryQueryOptions=n_;exports.getAccountPosts=Or;exports.getAccountPostsInfiniteQueryOptions=uw;exports.getAccountPostsQueryOptions=pw;exports.getAccountRcQueryOptions=rS;exports.getAccountRecoveriesQueryOptions=Xh;exports.getAccountReputationsQueryOptions=u_;exports.getAccountSubscriptionsQueryOptions=qh;exports.getAccountVoteHistoryInfiniteQueryOptions=s0;exports.getAccountWalletAssetInfoQueryOptions=hq;exports.getAccountsQueryOptions=jy;exports.getAggregatedBalanceQueryOptions=P0;exports.getAiAssistPriceQueryOptions=dy;exports.getAiGeneratePriceQueryOptions=cy;exports.getAiTranscribePriceQueryOptions=yy;exports.getAllHiveEngineTokensQueryOptions=Ri;exports.getAnnouncementsQueryOptions=vC;exports.getBadActorsQueryOptions=uM;exports.getBalanceHistoryInfiniteQueryOptions=h0;exports.getBookmarksInfiniteQueryOptions=Nh;exports.getBookmarksQueryOptions=Mh;exports.getBoostPlusAccountPricesQueryOptions=GB;exports.getBoostPlusPricesQueryOptions=FB;exports.getBotsQueryOptions=v_;exports.getBoundFetch=_;exports.getChainPropertiesQueryOptions=HA;exports.getCollateralizedConversionRequestsQueryOptions=kR;exports.getCommentHistoryQueryOptions=zw;exports.getCommunities=$b;exports.getCommunitiesQueryOptions=Ok;exports.getCommunity=To;exports.getCommunityContextQueryOptions=Ck;exports.getCommunityPermissions=rC;exports.getCommunityQueryOptions=qk;exports.getCommunitySubscribersInfiniteQueryOptions=Hk;exports.getCommunitySubscribersQueryOptions=Qk;exports.getCommunityType=tC;exports.getContentModerationReason=kM;exports.getContentQueryOptions=wb;exports.getContentRepliesQueryOptions=xb;exports.getControversialRisingInfiniteQueryOptions=HK;exports.getConversionRequestsQueryOptions=OR;exports.getCurrencyRate=xi;exports.getCurrencyRates=rI;exports.getCurrencyTokenRate=tI;exports.getCurrentMedianHistoryPriceQueryOptions=VF;exports.getCustomJsonAuthority=tp;exports.getDeletedEntryQueryOptions=Zw;exports.getDiscoverCurationQueryOptions=uE;exports.getDiscoverLeaderboardQueryOptions=oE;exports.getDiscussion=Ro;exports.getDiscussionQueryOptions=rw;exports.getDiscussionsQueryOptions=Do;exports.getDraftsInfiniteQueryOptions=Nw;exports.getDraftsQueryOptions=Mw;exports.getDynamicPropsQueryOptions=Oe;exports.getEntryActiveVotesQueryOptions=pb;exports.getFavoritesInfiniteQueryOptions=jh;exports.getFavoritesQueryOptions=Vh;exports.getFeedHistoryQueryOptions=NF;exports.getFollowCountQueryOptions=zy;exports.getFollowersQueryOptions=eh;exports.getFollowingQueryOptions=ih;exports.getFragmentsInfiniteQueryOptions=tb;exports.getFragmentsQueryOptions=ze;exports.getFriendsInfiniteQueryOptions=D_;exports.getGalleryImagesQueryOptions=jw;exports.getGameStatusCheckQueryOptions=SS;exports.getHbdAssetGeneralInfoQueryOptions=bi;exports.getHbdAssetTransactionsQueryOptions=VT;exports.getHiveAssetGeneralInfoQueryOptions=Gt;exports.getHiveAssetMetricQueryOptions=XT;exports.getHiveAssetTransactionsQueryOptions=zt;exports.getHiveAssetWithdrawalRoutesQueryOptions=rF;exports.getHiveEngineBalancesWithUsdQueryOptions=HI;exports.getHiveEngineMetrics=Sd;exports.getHiveEngineOpenOrders=cI;exports.getHiveEngineOrderBook=sI;exports.getHiveEngineTokenGeneralInfoQueryOptions=Ti;exports.getHiveEngineTokenMetrics=Si;exports.getHiveEngineTokenTransactions=Ei;exports.getHiveEngineTokenTransactionsQueryOptions=PI;exports.getHiveEngineTokensBalances=Jt;exports.getHiveEngineTokensBalancesQueryOptions=Xt;exports.getHiveEngineTokensMarket=et;exports.getHiveEngineTokensMarketQueryOptions=gI;exports.getHiveEngineTokensMetadata=Yt;exports.getHiveEngineTokensMetadataQueryOptions=Ci;exports.getHiveEngineTokensMetricsQueryOptions=EI;exports.getHiveEngineTradeHistory=aI;exports.getHiveEngineUnclaimedRewards=ki;exports.getHiveEngineUnclaimedRewardsQueryOptions=RI;exports.getHiveHbdStatsQueryOptions=SF;exports.getHivePoshLinksQueryOptions=jE;exports.getHivePowerAssetGeneralInfoQueryOptions=wi;exports.getHivePowerAssetTransactionsQueryOptions=GT;exports.getHivePowerDelegatesInfiniteQueryOptions=sF;exports.getHivePowerDelegatingsQueryOptions=lF;exports.getHivePrice=nI;exports.getImagesInfiniteQueryOptions=Lw;exports.getImagesQueryOptions=Vw;exports.getIncomingRcQueryOptions=zR;exports.getMarketData=eI;exports.getMarketDataQueryOptions=TF;exports.getMarketHistoryQueryOptions=AF;exports.getMarketStatisticsQueryOptions=bF;exports.getMutedUsersQueryOptions=ph;exports.getNextAccountHistoryPageParam=cd;exports.getNormalizePostQueryOptions=Xv;exports.getNotificationSetting=yO;exports.getNotifications=mO;exports.getNotificationsInfiniteQueryOptions=pC;exports.getNotificationsSettingsQueryOptions=hC;exports.getNotificationsUnreadCountQueryOptions=sC;exports.getOpenOrdersQueryOptions=QR;exports.getOperationAuthority=np;exports.getOrderBookQueryOptions=gF;exports.getOutgoingRcDelegationsInfiniteQueryOptions=LR;exports.getPageStatsQueryOptions=fE;exports.getPointsAssetGeneralInfoQueryOptions=Fi;exports.getPointsAssetTransactionsQueryOptions=iq;exports.getPointsQueryOptions=bt;exports.getPollQueryOptions=hM;exports.getPortfolioQueryOptions=_i;exports.getPost=hc;exports.getPostHeader=Lb;exports.getPostHeaderQueryOptions=Rb;exports.getPostQueryOptions=Eo;exports.getPostTipsQueryOptions=nv;exports.getPostsRanked=Co;exports.getPostsRankedInfiniteQueryOptions=_w;exports.getPostsRankedQueryOptions=bw;exports.getProMembersQueryOptions=E0;exports.getProfiles=Qt;exports.getProfilesQueryOptions=l0;exports.getPromotePriceQueryOptions=jB;exports.getPromotedPost=_O;exports.getPromotedPostsQuery=ib;exports.getProposalAuthority=rp;exports.getProposalQueryOptions=QC;exports.getProposalVotesInfiniteQueryOptions=JC;exports.getProposalsQueryOptions=jC;exports.getQueryClient=w;exports.getQuestCatalogEntry=MS;exports.getQuestsQueryOptions=KS;exports.getRcDelegationActiveQueryOptions=QB;exports.getRcDelegationPricesQueryOptions=KB;exports.getRcResourceParamsQueryOptions=aS;exports.getRcStatsQueryOptions=XE;exports.getRebloggedByQueryOptions=Cw;exports.getReblogsQueryOptions=Ow;exports.getReceivedVestingSharesQueryOptions=ZR;exports.getRecurrentTransfersQueryOptions=nT;exports.getReferralsInfiniteQueryOptions=x_;exports.getReferralsStatsQueryOptions=C_;exports.getRelationshipBetweenAccounts=zb;exports.getRelationshipBetweenAccountsQueryOptions=Po;exports.getRequiredAuthority=xA;exports.getRewardFundQueryOptions=ry;exports.getRewardedCommunitiesQueryOptions=Yk;exports.getSavingsWithdrawFromQueryOptions=FR;exports.getSchedulesInfiniteQueryOptions=qw;exports.getSchedulesQueryOptions=Iw;exports.getSearchAccountQueryOptions=oB;exports.getSearchAccountsByUsernameQueryOptions=vh;exports.getSearchApiInfiniteQueryOptions=gB;exports.getSearchFriendsQueryOptions=Q_;exports.getSearchPathQueryOptions=bB;exports.getSearchTopicsQueryOptions=uB;exports.getShortsFeedQueryOptions=hv;exports.getSimilarEntriesQueryOptions=XK;exports.getSpotlightsQueryOptions=xC;exports.getStatsQueryOptions=GE;exports.getSubscribers=Gb;exports.getSubscriptions=Wb;exports.getSupportSettingsQueryOptions=AB;exports.getSupportSettingsRequest=_f;exports.getTradeHistoryQueryOptions=DF;exports.getTransactionsInfiniteQueryOptions=h_;exports.getTrendingTagsQueryOptions=L_;exports.getTrendingTagsWithStatsQueryOptions=Y_;exports.getUserPostVoteQueryOptions=gb;exports.getUserProposalVotesQueryOptions=eR;exports.getVestingDelegationExpirationsQueryOptions=wR;exports.getVestingDelegationsQueryOptions=dR;exports.getVisibleFirstLevelThreadItems=No;exports.getWavesByAccountQueryOptions=Vv;exports.getWavesByHostQueryOptions=Ov;exports.getWavesByTagQueryOptions=Cv;exports.getWavesFeedQueryOptions=lv;exports.getWavesFollowingQueryOptions=qv;exports.getWavesLatestFeedQueryOptions=dv;exports.getWavesTrendingAuthorsQueryOptions=Wv;exports.getWavesTrendingTagsQueryOptions=Mv;exports.getWithdrawRoutesQueryOptions=KR;exports.getWitnessVoterCountQueryOptions=bK;exports.getWitnessVotersPageQueryOptions=_K;exports.getWitnessesInfiniteQueryOptions=hK;exports.hasExternalLink=ji;exports.hasThreeSpeakEmbed=Kp;exports.hiveTxConfig=x;exports.hiveTxUtils=ne;exports.hsTokenRenew=iM;exports.invalidateAfterBroadcast=E;exports.isAuthorMuted=SM;exports.isCommunity=mo;exports.isEmptyDate=go;exports.isHiddenPost=$f;exports.isInfoError=Js;exports.isLowTrustSeoPost=Wf;exports.isNetworkError=Ys;exports.isQueryableAccountName=Ge;exports.isResourceCreditsError=zs;exports.isThreeSpeakBeneficiary=vE;exports.isVoteAlreadyReflected=Op;exports.isWif=io;exports.isWrappedResponse=ua;exports.lookupAccountsQueryOptions=yh;exports.makeQueryClient=Bg;exports.mapMetaChoicesToPollChoices=dM;exports.mapThreadItemsToWaveEntries=Qo;exports.markNotifications=Xo;exports.measureQuestContentLength=fl;exports.moveSchedule=ai;exports.normalizePost=Fo;exports.normalizeSearchAuthor=Yd;exports.normalizeSearchCategory=Xd;exports.normalizeSearchTags=Zd;exports.normalizeToWrappedResponse=se;exports.normalizeWaveEntryFromApi=he;exports.onboardEmail=bO;exports.parseAccounts=Nt;exports.parseAsset=k;exports.parseChainError=$e;exports.parsePostingMetadataRoot=xa;exports.parseProfileMetadata=Me;exports.pickRicherMetadataSnapshot=bo;exports.powerRechargeTime=wA;exports.priceRcUsage=un;exports.proMembersSet=S0;exports.rcPower=PA;exports.removeOptimisticDiscussionEntry=ci;exports.resolveAccountHistoryLimit=ud;exports.resolveContentActivityType=Ep;exports.resolveHiveOperationFilters=ht;exports.resolvePost=So;exports.restoreDiscussionSnapshots=ui;exports.restoreEntryInCache=Tx;exports.roleMap=Zk;exports.saveNotificationSetting=gO;exports.search=LK;exports.searchPath=$K;exports.searchQueryOptions=QK;exports.sha256=ug;exports.shouldTriggerAuthFallback=we;exports.signUp=lO;exports.similar=Hi;exports.sortDiscussions=_c;exports.stringFieldBytes=pn;exports.subscribeEmail=dO;exports.toEntryArray=Mc;exports.updateDraft=ni;exports.updateEntryInCache=Rx;exports.updateSupportSettingsRequest=vf;exports.uploadImage=ei;exports.uploadImageWithSignature=hO;exports.useAccountFavoriteAdd=vP;exports.useAccountFavoriteDelete=EP;exports.useAccountRelationsUpdate=M0;exports.useAccountRevokeKey=nA;exports.useAccountRevokePosting=UP;exports.useAccountUpdate=I0;exports.useAccountUpdateKeyAuths=Wo;exports.useAccountUpdatePassword=KP;exports.useAccountUpdateRecovery=zP;exports.useAddDraft=OO;exports.useAddFragment=zA;exports.useAddImage=tx;exports.useAddSchedule=QO;exports.useAiAssist=Oy;exports.useAiTranscribe=ky;exports.useBookmarkAdd=fP;exports.useBookmarkDelete=hP;exports.useBoostPlus=XB;exports.useBroadcastMutation=v;exports.useBuyStreakFreeze=LS;exports.useClaimAccount=aA;exports.useClaimEngineRewards=VD;exports.useClaimInterest=_D;exports.useClaimPoints=EK;exports.useClaimRewards=AD;exports.useComment=Ex;exports.useConvert=fD;exports.useCreateAccount=gA;exports.useCrossPost=Qx;exports.useDelegateEngineToken=SD;exports.useDelegateRc=nK;exports.useDelegateVestingShares=Iq;exports.useDeleteComment=Kx;exports.useDeleteDraft=DO;exports.useDeleteImage=sx;exports.useDeleteSchedule=LO;exports.useEditFragment=rO;exports.useEngineMarketOrder=WD;exports.useFollow=iP;exports.useGameClaim=FS;exports.useGenerateImage=wy;exports.useGrantPostingPermission=lA;exports.useLimitOrderCancel=YF;exports.useLimitOrderCreate=WF;exports.useMarkNotificationsRead=FC;exports.useMoveSchedule=JO;exports.useMutePost=nk;exports.usePinPost=bk;exports.usePollVote=wM;exports.usePromote=Gx;exports.useProposalCreate=cR;exports.useProposalVote=oR;exports.useRcDelegation=rM;exports.useReblog=Px;exports.useRecordActivity=tn;exports.useRegisterCommunityRewards=gk;exports.useRemoveFragment=cO;exports.useSetCommunityRole=ak;exports.useSetLastRead=KC;exports.useSetWithdrawVestingRoute=Mq;exports.useSignOperationByHivesigner=BA;exports.useSignOperationByKey=RA;exports.useSignOperationByKeychain=IA;exports.useStakeEngineToken=DD;exports.useSubscribeCommunity=zS;exports.useTransfer=Aq;exports.useTransferEngineToken=Uq;exports.useTransferFromSavings=Xq;exports.useTransferPoint=kq;exports.useTransferToSavings=Wq;exports.useTransferToVesting=nD;exports.useUndelegateEngineToken=TD;exports.useUnfollow=uP;exports.useUnstakeEngineToken=ND;exports.useUnsubscribeCommunity=ZS;exports.useUpdateCommunity=lk;exports.useUpdateDraft=CO;exports.useUpdateReply=jx;exports.useUpdateSupportSettings=kB;exports.useUploadImage=px;exports.useVote=hx;exports.useWalletOperation=ZD;exports.useWithdrawVesting=cD;exports.useWitnessProxy=lK;exports.useWitnessVote=aK;exports.usrActivity=fO;exports.utf8ByteLength=ut;exports.validatePostCreating=Rp;exports.varintByteLength=ye;exports.verifyPostOnAlternateNode=xo;exports.vestsToHp=We;exports.votingPower=bA;exports.votingRshares=Zu;exports.votingValue=AA;exports.withTimeoutSignal=Pe;//# sourceMappingURL=index.cjs.map + */exports.ACCOUNT_OPERATION_GROUPS=Eo;exports.ALL_ACCOUNT_OPERATIONS=cu;exports.ALL_NOTIFY_TYPES=bi;exports.AssetOperation=rf;exports.BROADCAST_INCLUSION_DELAY_MS=Yg;exports.BuySellTransactionType=zo;exports.CONFIG=d;exports.ContentModerationReason=im;exports.EcencyAnalytics=et;exports.ErrorType=fo;exports.HIDDEN_POST_MIN_VOTES=Jf;exports.HIDDEN_POST_RSHARES_THRESHOLD=zf;exports.HIVE_ACCOUNT_OPERATION_GROUPS=gn;exports.HIVE_OPERATION_LIST=eq;exports.HIVE_OPERATION_NAME_BY_ID=oq;exports.HIVE_OPERATION_ORDERS=nq;exports.HiveEngineToken=rr;exports.HiveSignerIntegration=mi;exports.HiveTxTransaction=Ke;exports.INTERNAL_API_TIMEOUT_MS=Ae;exports.LOW_TRUST_REPUTATION_THRESHOLD=Yf;exports.MAX_SEARCH_QUERY_LENGTH=tN;exports.MAX_SEARCH_TAGS=eN;exports.Memo=uo;exports.NaiMap=Qt;exports.NewsletterApiError=At;exports.NewsletterSendRefusedError=or;exports.NotificationFilter=Vl;exports.NotificationViewType=Ll;exports.NotifyTypes=jl;exports.OPERATION_AUTHORITY_MAP=gp;exports.OrderIdPrefix=Jo;exports.POLLS_PROTOCOL_VERSION=NB;exports.PointTransactionType=pf;exports.PollPreferredInterpretation=Lf;exports.PrivateKey=U;exports.PublicKey=Y;exports.QUEST_CATALOG=Sl;exports.QUEST_MIN_CONTENT_LENGTH=El;exports.QueryKeys=u;exports.RC_RESOURCE_NAMES=Jt;exports.ROLES=Ql;exports.SERVER_GC_TIME_MS=yo;exports.SIGNATURE_BYTES=yl;exports.SIMILAR_ENTRIES_MIN_RENDER=AN;exports.STREAK_FREEZE_MAX_OWNED=fk;exports.STREAK_FREEZE_PRICE=dk;exports.SUBSCRIBERS_PAGE_SIZE=_i;exports.SearchQuery=Ui;exports.SearchType=Vi;exports.Signature=Se;exports.SortOrder=Bo;exports.Symbol=ho;exports.THREESPEAK_BENEFICIARY_ACCOUNT=zt;exports.THREESPEAK_BENEFICIARY_WEIGHT=LS;exports.TRANSACTION_HEADER_BYTES=gl;exports.ThreeSpeakIntegration=pE;exports.accountNameByteLength=Ha;exports.addDraft=si;exports.addImage=ni;exports.addOptimisticDiscussionEntry=tS;exports.addSchedule=ci;exports.applySupportSettingsUpdate=Nf;exports.applyVoteCacheUpdate=Qp;exports.bridgeApiCall=ae;exports.broadcastJson=go;exports.broadcastOperations=ee;exports.broadcastOperationsAsync=po;exports.buildAccountCreateOp=Jr;exports.buildAccountUpdate2Op=Nc;exports.buildAccountUpdateOp=Kc;exports.buildActiveCustomJsonOp=Vc;exports.buildBoostPlusOp=en;exports.buildCancelTransferFromSavingsOp=Go;exports.buildChangeRecoveryAccountOp=Mc;exports.buildClaimAccountOp=Xr;exports.buildClaimInterestOps=ft;exports.buildClaimRewardBalanceOp=zr;exports.buildCollateralizedConvertOp=Fr;exports.buildCommentOp=Qe;exports.buildCommentOptionsOp=He;exports.buildCommunityRegistrationOp=nn;exports.buildConvertOp=_t;exports.buildCreateClaimedAccountOp=Yr;exports.buildDelegateRcOp=Dr;exports.buildDelegateVestingSharesOp=yt;exports.buildDeleteCommentOp=Tr;exports.buildEngineClaimOp=Ir;exports.buildEngineOp=je;exports.buildFlagPostOp=Ic;exports.buildFollowOp=Kr;exports.buildGrantPostingPermissionOp=Zr;exports.buildIgnoreOp=Cc;exports.buildLimitOrderCancelOp=Gr;exports.buildLimitOrderCreateOp=$t;exports.buildLimitOrderCreateOpWithType=Dc;exports.buildMultiPointTransferOps=Uc;exports.buildMultiTransferOps=Ec;exports.buildMutePostOp=Wr;exports.buildMuteUserOp=Fc;exports.buildPinPostOp=$r;exports.buildPointTransferOp=Ze;exports.buildPostingCustomJsonOp=jc;exports.buildPostingJsonMetadata=Oo;exports.buildProfileMetadata=Er;exports.buildPromoteOp=rn;exports.buildProposalCreateOp=Qr;exports.buildProposalVoteOp=Hr;exports.buildRcDelegationOp=tn;exports.buildReblogOp=qr;exports.buildRecoverAccountOp=Hc;exports.buildRecurrentTransferOp=kc;exports.buildRemoveProposalOp=Tc;exports.buildRequestAccountRecoveryOp=Qc;exports.buildRevokeKeysOp=Xo;exports.buildRevokePostingPermissionOp=Bc;exports.buildSearchQuery=rN;exports.buildSetLastReadOps=Nr;exports.buildSetRoleOp=jr;exports.buildSetWithdrawVestingRouteOp=ht;exports.buildSubscribeOp=Ur;exports.buildTransferFromSavingsOp=Ve;exports.buildTransferOp=Ue;exports.buildTransferToSavingsOp=Xe;exports.buildTransferToVestingOp=mt;exports.buildUnfollowOp=jt;exports.buildUnignoreOp=Rc;exports.buildUnsubscribeOp=Vr;exports.buildUpdateCommunityOp=Lr;exports.buildUpdateProposalOp=qc;exports.buildVoteOp=Rr;exports.buildWithdrawVestingOp=gt;exports.buildWitnessProxyOp=Mr;exports.buildWitnessVoteOp=Br;exports.buyStreakFreezeRequest=ql;exports.calculateRCMana=Bt;exports.calculateVPMana=Or;exports.callREST=te;exports.callRPC=y;exports.callRPCBroadcast=We;exports.callWithQuorum=Kt;exports.canRevokeFromAuthority=AA;exports.checkFavoriteQueryOptions=b_;exports.checkUsernameWalletsPendingQueryOptions=Yh;exports.claimPointsRequest=df;exports.collectRequestedOperations=yn;exports.computeResourceCost=pn;exports.countCommentResourceUsage=ln;exports.countVoteResourceUsage=yi;exports.decodeObj=dy;exports.dedupeAndSortKeyAuths=Yc;exports.deleteDraft=ui;exports.deleteImage=ii;exports.deleteSchedule=pi;exports.downVotingPower=WA;exports.earnsQuestContentCredit=lk;exports.encodeObj=ly;exports.enforceThreeSpeakBeneficiary=$S;exports.estimateCommentRcCost=BE;exports.estimateCommentTransactionBytes=dn;exports.estimateRcPrecheck=zE;exports.estimateVoteTransactionBytes=gi;exports.extractAccountProfile=Po;exports.formatError=ca;exports.formattedNumber=nt;exports.gameClaimRequest=Ol;exports.getAccountDelegationsQueryOptions=UR;exports.getAccountFullQueryOptions=B;exports.getAccountNotificationsInfiniteQueryOptions=wC;exports.getAccountPendingRecoveryQueryOptions=C_;exports.getAccountPosts=kr;exports.getAccountPostsInfiniteQueryOptions=Db;exports.getAccountPostsQueryOptions=Kb;exports.getAccountRcQueryOptions=kE;exports.getAccountRecoveriesQueryOptions=O_;exports.getAccountReputationsQueryOptions=D_;exports.getAccountSubscriptionsQueryOptions=s_;exports.getAccountVoteHistoryInfiniteQueryOptions=q0;exports.getAccountWalletAssetInfoQueryOptions=VI;exports.getAccountsQueryOptions=yh;exports.getAggregatedBalanceQueryOptions=G0;exports.getAiAssistPriceQueryOptions=By;exports.getAiGeneratePriceQueryOptions=Iy;exports.getAiTranscribePriceQueryOptions=Uy;exports.getAllHiveEngineTokensQueryOptions=Ii;exports.getAnnouncementsQueryOptions=WC;exports.getBadActorsQueryOptions=DB;exports.getBalanceHistoryInfiniteQueryOptions=V0;exports.getBookmarksInfiniteQueryOptions=l_;exports.getBookmarksQueryOptions=p_;exports.getBoostPlusAccountPricesQueryOptions=bB;exports.getBoostPlusPricesQueryOptions=oB;exports.getBotsQueryOptions=W_;exports.getBoundFetch=h;exports.getChainPropertiesQueryOptions=fO;exports.getCollateralizedConversionRequestsQueryOptions=eT;exports.getCommentHistoryQueryOptions=vv;exports.getCommunities=_b;exports.getCommunitiesQueryOptions=Jk;exports.getCommunity=Do;exports.getCommunityContextQueryOptions=tC;exports.getCommunityPermissions=kC;exports.getCommunityQueryOptions=sC;exports.getCommunitySubscribersInfiniteQueryOptions=fC;exports.getCommunitySubscribersQueryOptions=dC;exports.getCommunityType=EC;exports.getContentModerationReason=eM;exports.getContentQueryOptions=$w;exports.getContentRepliesQueryOptions=Yw;exports.getControversialRisingInfiniteQueryOptions=fN;exports.getConversionRequestsQueryOptions=JR;exports.getCurrencyRate=Ci;exports.getCurrencyRates=kF;exports.getCurrencyTokenRate=EF;exports.getCurrentMedianHistoryPriceQueryOptions=gF;exports.getCustomJsonAuthority=yp;exports.getDeletedEntryQueryOptions=xv;exports.getDigestSubscriptionsQueryOptions=aM;exports.getDigestSubscriptionsRequest=Ji;exports.getDiscoverCurationQueryOptions=DS;exports.getDiscoverLeaderboardQueryOptions=RS;exports.getDiscussion=Io;exports.getDiscussionQueryOptions=kb;exports.getDiscussionsQueryOptions=Mo;exports.getDraftsInfiniteQueryOptions=lv;exports.getDraftsQueryOptions=pv;exports.getDynamicPropsQueryOptions=Oe;exports.getEntryActiveVotesQueryOptions=Kw;exports.getFavoritesInfiniteQueryOptions=y_;exports.getFavoritesQueryOptions=g_;exports.getFeedHistoryQueryOptions=lF;exports.getFollowCountQueryOptions=vh;exports.getFollowersQueryOptions=Sh;exports.getFollowingQueryOptions=Th;exports.getFragmentsInfiniteQueryOptions=Ew;exports.getFragmentsQueryOptions=Ye;exports.getFriendsInfiniteQueryOptions=aw;exports.getGalleryImagesQueryOptions=yv;exports.getGameStatusCheckQueryOptions=ZE;exports.getHbdAssetGeneralInfoQueryOptions=Ai;exports.getHbdAssetTransactionsQueryOptions=gq;exports.getHiveAssetGeneralInfoQueryOptions=Yt;exports.getHiveAssetMetricQueryOptions=Oq;exports.getHiveAssetTransactionsQueryOptions=Xt;exports.getHiveAssetWithdrawalRoutesQueryOptions=kq;exports.getHiveEngineBalancesWithUsdQueryOptions=fI;exports.getHiveEngineMetrics=Ud;exports.getHiveEngineOpenOrders=IF;exports.getHiveEngineOrderBook=qF;exports.getHiveEngineTokenGeneralInfoQueryOptions=Di;exports.getHiveEngineTokenMetrics=Ti;exports.getHiveEngineTokenTransactions=Ri;exports.getHiveEngineTokenTransactionsQueryOptions=GF;exports.getHiveEngineTokensBalances=Zt;exports.getHiveEngineTokensBalancesQueryOptions=tr;exports.getHiveEngineTokensMarket=rt;exports.getHiveEngineTokensMarketQueryOptions=HF;exports.getHiveEngineTokensMetadata=er;exports.getHiveEngineTokensMetadataQueryOptions=Fi;exports.getHiveEngineTokensMetricsQueryOptions=XF;exports.getHiveEngineTradeHistory=FF;exports.getHiveEngineUnclaimedRewards=qi;exports.getHiveEngineUnclaimedRewardsQueryOptions=rI;exports.getHiveHbdStatsQueryOptions=Zq;exports.getHivePoshLinksQueryOptions=yE;exports.getHivePowerAssetGeneralInfoQueryOptions=Oi;exports.getHivePowerAssetTransactionsQueryOptions=bq;exports.getHivePowerDelegatesInfiniteQueryOptions=qq;exports.getHivePowerDelegatingsQueryOptions=Nq;exports.getHivePrice=CF;exports.getImagesInfiniteQueryOptions=hv;exports.getImagesQueryOptions=gv;exports.getIncomingRcQueryOptions=vT;exports.getMarketData=SF;exports.getMarketDataQueryOptions=nF;exports.getMarketHistoryQueryOptions=zq;exports.getMarketStatisticsQueryOptions=Lq;exports.getMutedUsersQueryOptions=Kh;exports.getNewsletterIssuesQueryOptions=hM;exports.getNewsletterIssuesRequest=es;exports.getNewsletterPostsQueryOptions=PM;exports.getNewsletterPostsRequest=ts;exports.getNewsletterSenderQueryOptions=dM;exports.getNewsletterSenderRequest=Zi;exports.getNextAccountHistoryPageParam=Ad;exports.getNormalizePostQueryOptions=O0;exports.getNotificationSetting=UO;exports.getNotifications=QO;exports.getNotificationsInfiniteQueryOptions=KC;exports.getNotificationsSettingsQueryOptions=VC;exports.getNotificationsUnreadCountQueryOptions=qC;exports.getOpenOrdersQueryOptions=dT;exports.getOperationAuthority=_p;exports.getOrderBookQueryOptions=Hq;exports.getOutgoingRcDelegationsInfiniteQueryOptions=hT;exports.getPageStatsQueryOptions=MS;exports.getPointsAssetGeneralInfoQueryOptions=Ki;exports.getPointsAssetTransactionsQueryOptions=TI;exports.getPointsQueryOptions=vt;exports.getPollQueryOptions=VB;exports.getPortfolioQueryOptions=Pi;exports.getPost=qu;exports.getPostHeader=hb;exports.getPostHeaderQueryOptions=rb;exports.getPostQueryOptions=Ro;exports.getPostTipsQueryOptions=Cv;exports.getPostsRanked=Fo;exports.getPostsRankedInfiniteQueryOptions=jb;exports.getPostsRankedQueryOptions=Lb;exports.getProMembersQueryOptions=X0;exports.getProfiles=Vt;exports.getProfilesQueryOptions=N0;exports.getPromotePriceQueryOptions=yB;exports.getPromotedPost=jO;exports.getPromotedPostsQuery=Tw;exports.getProposalAuthority=hp;exports.getProposalQueryOptions=dR;exports.getProposalVotesInfiniteQueryOptions=PR;exports.getProposalsQueryOptions=yR;exports.getQueryClient=b;exports.getQuestCatalogEntry=pk;exports.getQuestsQueryOptions=uk;exports.getRcDelegationActiveQueryOptions=dB;exports.getRcDelegationPricesQueryOptions=uB;exports.getRcResourceParamsQueryOptions=FE;exports.getRcStatsQueryOptions=OE;exports.getRebloggedByQueryOptions=tv;exports.getReblogsQueryOptions=Jb;exports.getReceivedVestingSharesQueryOptions=xT;exports.getRecurrentTransfersQueryOptions=CT;exports.getReferralsInfiniteQueryOptions=Y_;exports.getReferralsStatsQueryOptions=tw;exports.getRelationshipBetweenAccounts=vb;exports.getRelationshipBetweenAccountsQueryOptions=So;exports.getRequiredAuthority=YA;exports.getRewardFundQueryOptions=ky;exports.getRewardedCommunitiesQueryOptions=AC;exports.getSavingsWithdrawFromQueryOptions=oT;exports.getSchedulesInfiniteQueryOptions=sv;exports.getSchedulesQueryOptions=iv;exports.getSearchAccountQueryOptions=RN;exports.getSearchAccountsByUsernameQueryOptions=Wh;exports.getSearchApiInfiniteQueryOptions=HN;exports.getSearchFriendsQueryOptions=dw;exports.getSearchPathQueryOptions=LN;exports.getSearchTopicsQueryOptions=DN;exports.getShortsFeedQueryOptions=Vv;exports.getSimilarEntriesQueryOptions=ON;exports.getSpotlightsQueryOptions=YC;exports.getStatsQueryOptions=bE;exports.getSubscribers=bb;exports.getSubscriptions=wb;exports.getSupportSettingsQueryOptions=zN;exports.getSupportSettingsRequest=Ff;exports.getTradeHistoryQueryOptions=aF;exports.getTransactionsInfiniteQueryOptions=V_;exports.getTrendingTagsQueryOptions=hw;exports.getTrendingTagsWithStatsQueryOptions=Aw;exports.getUserPostVoteQueryOptions=Hw;exports.getUserProposalVotesQueryOptions=SR;exports.getVestingDelegationExpirationsQueryOptions=$R;exports.getVestingDelegationsQueryOptions=BR;exports.getVisibleFirstLevelThreadItems=Vo;exports.getWavesByAccountQueryOptions=g0;exports.getWavesByHostQueryOptions=Jv;exports.getWavesByTagQueryOptions=t0;exports.getWavesFeedQueryOptions=Nv;exports.getWavesFollowingQueryOptions=s0;exports.getWavesLatestFeedQueryOptions=Bv;exports.getWavesTrendingAuthorsQueryOptions=w0;exports.getWavesTrendingTagsQueryOptions=p0;exports.getWithdrawRoutesQueryOptions=uT;exports.getWitnessVoterCountQueryOptions=LK;exports.getWitnessVotersPageQueryOptions=jK;exports.getWitnessesInfiniteQueryOptions=VK;exports.hasExternalLink=Gi;exports.hasThreeSpeakEmbed=Yp;exports.hiveTxConfig=x;exports.hiveTxUtils=ne;exports.hsTokenRenew=TB;exports.invalidateAfterBroadcast=S;exports.isAuthorMuted=ZB;exports.isCommunity=_o;exports.isEmptyDate=wo;exports.isHiddenPost=am;exports.isInfoError=la;exports.isLowTrustSeoPost=um;exports.isNetworkError=da;exports.isQueryableAccountName=Je;exports.isResourceCreditsError=pa;exports.isThreeSpeakBeneficiary=WS;exports.isVoteAlreadyReflected=Mp;exports.isWif=co;exports.isWrappedResponse=Oa;exports.leaveDigestRequest=Yi;exports.lookupAccountsQueryOptions=Uh;exports.makeQueryClient=cy;exports.mapMetaChoicesToPollChoices=BB;exports.mapThreadItemsToWaveEntries=jo;exports.markNotifications=ri;exports.measureQuestContentLength=kl;exports.moveSchedule=li;exports.normalizePost=Ko;exports.normalizeSearchAuthor=ff;exports.normalizeSearchCategory=mf;exports.normalizeSearchTags=gf;exports.normalizeToWrappedResponse=se;exports.normalizeWaveEntryFromApi=he;exports.onboardEmail=LO;exports.parseAccounts=Ut;exports.parseAsset=k;exports.parseChainError=Ge;exports.parsePostingMetadataRoot=Qa;exports.parseProfileMetadata=Me;exports.pickRicherMetadataSnapshot=Ao;exports.powerRechargeTime=$A;exports.previewNewsletterSendRequest=ns;exports.priceRcUsage=fn;exports.proMembersSet=Z0;exports.rcPower=GA;exports.removeOptimisticDiscussionEntry=di;exports.resolveAccountHistoryLimit=Od;exports.resolveContentActivityType=Hp;exports.resolveHiveOperationFilters=wt;exports.resolvePost=To;exports.restoreDiscussionSnapshots=fi;exports.restoreEntryInCache=nS;exports.roleMap=xC;exports.saveNotificationSetting=HO;exports.search=hN;exports.searchPath=_N;exports.searchQueryOptions=dN;exports.sendNewsletterIssueRequest=os;exports.sha256=Dg;exports.shouldTriggerAuthFallback=be;exports.signUp=NO;exports.similar=Li;exports.sortDiscussions=Fu;exports.stringFieldBytes=mn;exports.subscribeDigestRequest=zi;exports.subscribeEmail=BO;exports.toEntryArray=Zu;exports.unsubscribeAllDigestsRequest=Xi;exports.updateDraft=ai;exports.updateEntryInCache=rS;exports.updateSupportSettingsRequest=Kf;exports.uploadImage=oi;exports.uploadImageWithSignature=VO;exports.useAccountFavoriteAdd=WP;exports.useAccountFavoriteDelete=XP;exports.useAccountRelationsUpdate=pP;exports.useAccountRevokeKey=CA;exports.useAccountRevokePosting=mA;exports.useAccountUpdate=iP;exports.useAccountUpdateKeyAuths=Yo;exports.useAccountUpdatePassword=uA;exports.useAccountUpdateRecovery=vA;exports.useAddDraft=JO;exports.useAddFragment=vO;exports.useAddImage=Ex;exports.useAddSchedule=dx;exports.useAiAssist=Jy;exports.useAiTranscribe=eh;exports.useBookmarkAdd=MP;exports.useBookmarkDelete=VP;exports.useBoostPlus=OB;exports.useBroadcastMutation=v;exports.useBuyStreakFreeze=hk;exports.useClaimAccount=FA;exports.useClaimEngineRewards=gK;exports.useClaimInterest=jD;exports.useClaimPoints=XK;exports.useClaimRewards=zD;exports.useComment=Xx;exports.useConvert=MD;exports.useCreateAccount=HA;exports.useCrossPost=dS;exports.useDelegateEngineToken=ZD;exports.useDelegateRc=CK;exports.useDelegateVestingShares=iD;exports.useDeleteComment=uS;exports.useDeleteDraft=ax;exports.useDeleteImage=qx;exports.useDeleteSchedule=hx;exports.useEditFragment=kO;exports.useEngineMarketOrder=wK;exports.useFollow=TP;exports.useGameClaim=ok;exports.useGenerateImage=$y;exports.useGrantPostingPermission=NA;exports.useLeaveDigest=qM;exports.useLimitOrderCancel=AF;exports.useLimitOrderCreate=wF;exports.useMarkNotificationsRead=oR;exports.useMoveSchedule=Px;exports.useMutePost=Ck;exports.usePinPost=Lk;exports.usePollVote=$B;exports.usePreviewNewsletterIssue=UM;exports.usePromote=bS;exports.useProposalCreate=IR;exports.useProposalVote=RR;exports.useRcDelegation=kB;exports.useReblog=Gx;exports.useRecordActivity=sn;exports.useRegisterCommunityRewards=Hk;exports.useRemoveFragment=IO;exports.useSendNewsletterIssue=VM;exports.useSetCommunityRole=Fk;exports.useSetLastRead=uR;exports.useSetWithdrawVestingRoute=pD;exports.useSignOperationByHivesigner=cO;exports.useSignOperationByKey=rO;exports.useSignOperationByKeychain=iO;exports.useStakeEngineToken=aK;exports.useSubscribeCommunity=vk;exports.useSubscribeDigest=EM;exports.useTransfer=zI;exports.useTransferEngineToken=mD;exports.useTransferFromSavings=OD;exports.useTransferPoint=eD;exports.useTransferToSavings=wD;exports.useTransferToVesting=CD;exports.useUndelegateEngineToken=nK;exports.useUnfollow=DP;exports.useUnstakeEngineToken=lK;exports.useUnsubscribeAllDigests=NM;exports.useUnsubscribeCommunity=xk;exports.useUpdateCommunity=Nk;exports.useUpdateDraft=tx;exports.useUpdateReply=yS;exports.useUpdateSupportSettings=eB;exports.useUploadImage=Kx;exports.useVote=Vx;exports.useWalletOperation=xK;exports.useWithdrawVesting=ID;exports.useWitnessProxy=NK;exports.useWitnessVote=FK;exports.usrActivity=MO;exports.utf8ByteLength=lt;exports.validatePostCreating=Lp;exports.varintByteLength=ye;exports.verifyPostOnAlternateNode=Co;exports.vestsToHp=ze;exports.votingPower=LA;exports.votingRshares=mp;exports.votingValue=zA;exports.withTimeoutSignal=Pe;//# 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 ff081eb6cf..57ff79a6dd 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/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-comment-rc-cost.ts","../../src/modules/resource-credits/utils/price-rc-usage.ts","../../src/modules/resource-credits/utils/count-operation-usage.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","../../src/modules/moderation/constants.ts","../../src/modules/moderation/account-reputation.ts","../../src/modules/moderation/external-links.ts","../../src/modules/moderation/content-moderation.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","DEFAULT_SERVER_RPC_PROXY_METHODS","serverRpcProxy","setServerRpcProxy","opts","url","headers","k","v","timeoutMs","methods","m","pos","fallback","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","r","bool","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","rpcProxyStats","ProxyMiss","reason","errorMessage","proxyConsecutiveMisses","proxyOpenUntil","proxyRpcCall","proxy","method","params","callerTimeoutMs","externalSignal","validate","dot","tSignal","cleanupTimeout","createTimeoutSignal","signal","cleanupMerge","mergeSignals","res","e","relayed","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","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","tryRecordHeadBlock","block","createTimeoutReason","err","controller","timer","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","timeout","shouldRetry","body","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","served","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","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","timeoutSignal","ac","onAbort","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","getServerRpcProxyStats","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","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","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","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","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","resolveContentActivityType","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","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","EMPTY","estimateCommentRcCost","rcParams","rcStats","usage","regen","cost","breakdown","share","scaled","resourceCost","priceRcUsage","emptyUsage","estimateVoteTransactionBytes","operationBytes","countVoteResourceUsage","estimateRcPrecheck","priced","priceOperation","safeBuffer","estimatedCost","willLikelyFail","average","averageCost","MINIMAL_VOTE","MINIMAL_COMMENT","getGameStatusCheckQueryOptions","gameClaimRequest","contentType","detail","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","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","HIDDEN_POST_RSHARES_THRESHOLD","HIDDEN_POST_MIN_VOTES","LOW_TRUST_REPUTATION_THRESHOLD","isHumanReadable","accountReputation","neg","reputationLevel","INTERNAL_HOSTS","IMAGE_HOSTS","IMAGE_EXT_RE","URL_RE","TRAILING_PUNCT_RE","hostOf","isExternalPromoLink","rawUrl","hasExternalLink","ContentModerationReason","countVotes","isHiddenPost","netRshares","activeVotesLength","isLowTrustSeoPost","reputation","isAuthorMuted","mutedAuthors","getContentModerationReason"],"mappings":"wkBASA,IAAMA,GAAe,IAAI,WAAA,CAAY,CAAC,CAAA,CAIlCC,EAAAA,CAAqD,IAAA,CACrDC,EAAAA,CAAuD,IAAA,CAE3D,SAASC,IAAgD,CACvD,OAAKF,KACC,OAAO,WAAA,CAAgB,IACzBA,EAAAA,CAAW,IAAI,WAAA,CAEfA,EAAAA,CAAW,CACT,MAAA,CAAOG,EAAuB,CAE5B,IAAMC,EAAiB,EAAC,CACxB,QAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAE,MAAA,CAAQE,CAAAA,EAAAA,CAAK,CACjC,IAAIC,CAAAA,CAAIH,EAAE,UAAA,CAAWE,CAAC,EACtB,GAAIC,CAAAA,CAAI,GAAA,CACNF,CAAAA,CAAK,IAAA,CAAKE,CAAC,UACFA,CAAAA,CAAI,IAAA,CACbF,EAAK,IAAA,CAAK,GAAA,CAAQE,GAAK,CAAA,CAAI,GAAA,CAAQA,CAAAA,CAAI,EAAK,CAAA,CAAA,KAAA,GACnCA,CAAAA,EAAK,OAAUA,CAAAA,EAAK,KAAA,EAAUD,EAAI,CAAA,CAAIF,CAAAA,CAAE,OAAQ,CACzD,IAAMI,CAAAA,CAAOJ,CAAAA,C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AAM,CACpD,CAcO,SAASqsC,GACdrqC,CAAAA,CACgC,CAChC,OAAKA,CAAAA,CAGDA,CAAAA,CAAQ,OAAO,IAAA,EAAQA,CAAAA,CAAQ,OAAO,IAAA,CACjC,WAAA,CAEL8pC,GAAa9pC,CAAAA,CAAQ,WAAA,CAAa6pC,GAAW7pC,CAAO,CAAC,EAChD,WAAA,CAELiqC,EAAAA,CAAkBjqC,CAAO,CAAA,CACpB,WAAA,CAEF,KAXE,IAYX","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 * Server-side read-through proxy for RPC reads (see `setServerRpcProxy`).\n * `methods` is the allowlist the proxy serves; a read outside it goes straight\n * to the node pool as before.\n */\nexport interface ServerRpcProxyOptions {\n /** Absolute URL of the proxy endpoint (POST `{api, method, params}`). */\n url: string\n /** Headers sent with every proxy call (the shared internal secret). */\n headers: Record\n /** Per-call timeout in ms; on expiry the read falls back to the node pool. */\n timeoutMs: number\n /** Fully qualified method names (`bridge.get_post`) the proxy may answer;\n * omitted = DEFAULT_SERVER_RPC_PROXY_METHODS. An empty list is ignored. */\n methods?: string[]\n /**\n * After this many consecutive proxy misses the proxy is skipped for\n * `cooldownMs`, so a proxy that is down costs one failed call per cooldown\n * window rather than one per read. Default 3 / 10s. A served call resets it.\n */\n failureThreshold?: number\n cooldownMs?: number\n}\n\n/** Default allowlist: the reads a server render makes and the proxy caches. */\nexport const DEFAULT_SERVER_RPC_PROXY_METHODS: readonly string[] = [\n 'bridge.get_ranked_posts',\n 'bridge.get_account_posts',\n 'bridge.get_post',\n 'bridge.get_discussion',\n 'bridge.get_profile',\n 'bridge.get_profiles',\n 'bridge.get_community',\n 'bridge.list_communities',\n 'condenser_api.get_accounts',\n 'condenser_api.get_content',\n 'condenser_api.get_dynamic_global_properties',\n 'condenser_api.get_trending_tags'\n]\n\n/**\n * Active proxy configuration, or null (the default: every read goes to the node\n * pool). Lives outside `config` so the browser bundle never carries it; it is\n * only ever consulted under Node.\n */\nexport interface ServerRpcProxyState extends Required {\n methodSet: Set\n}\n\nexport let serverRpcProxy: ServerRpcProxyState | null = null\n\n/**\n * Route allowlisted server-side reads through a read-through cache in front\n * of the node pool. One cache per host answers the reads every renderer\n * process used to make on its own; a miss there is one upstream call shared by\n * every concurrent reader. The proxy is an optimization, never a dependency:\n * any failure (non-200, timeout, transport error, a response the caller's\n * validator rejects) falls straight through to the existing node loop, so the\n * worst case is the latency of a failed proxy call on top of what happens\n * today. Has no effect outside Node. Pass null to switch it off.\n */\nexport const setServerRpcProxy = (opts: ServerRpcProxyOptions | null): void => {\n if (opts === null) {\n serverRpcProxy = null\n return\n }\n if (!opts || typeof opts !== 'object') return\n const url = typeof opts.url === 'string' ? opts.url.trim() : ''\n if (!/^https?:\\/\\//i.test(url)) return\n const headers: Record = {}\n if (opts.headers && typeof opts.headers === 'object') {\n for (const [k, v] of Object.entries(opts.headers)) {\n if (typeof v === 'string' && v && !/[\\u0000-\\u001f\\u007f]/.test(v) && !/[\\u0000-\\u001f\\u007f]/.test(k)) {\n headers[k] = v\n }\n }\n }\n const timeoutMs =\n typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0\n ? opts.timeoutMs\n : 2_000\n const methods =\n opts.methods === undefined\n ? [...DEFAULT_SERVER_RPC_PROXY_METHODS]\n : Array.isArray(opts.methods)\n ? opts.methods.filter((m): m is string => typeof m === 'string' && m.includes('.'))\n : []\n // Nothing to route through the proxy: keep whatever was configured before.\n if (methods.length === 0) return\n const pos = (v: unknown, fallback: number): number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : fallback\n serverRpcProxy = {\n url,\n headers,\n timeoutMs,\n methods,\n failureThreshold: Math.floor(pos(opts.failureThreshold, 3)),\n cooldownMs: pos(opts.cooldownMs, 10_000),\n methodSet: new Set(methods)\n }\n}\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, serverRpcProxy, type ServerRpcProxyState } 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// ── Server-side read-through proxy ──────────────────────────────────────────\n\n/**\n * Counters for the proxy path, readable by a host's diagnostics (the web\n * tier's event-loop monitor prints them). `served` = answered by the proxy,\n * `fallback` = proxy configured and eligible but the read went to the node\n * pool, with the reason.\n */\nexport const rpcProxyStats = {\n served: 0,\n fallback: 0,\n /** Reads that went straight to the nodes because the breaker was open. */\n skipped: 0,\n fallbackByReason: { status: 0, rpcerror: 0, timeout: 0, transport: 0, validate: 0, parse: 0 } as Record\n}\n\n/**\n * `rpcerror` is a 502 tagged `X-Ssr-Cache: RPCERROR`: the proxy reached a node\n * and relayed the node's own error (a tag or post that does not exist, a bad\n * argument). The read still falls back so the caller sees the node's answer\n * unchanged, but the proxy was healthy, so it does not count toward the\n * breaker; the other reasons do.\n */\ntype ProxyMissReason = 'status' | 'rpcerror' | 'timeout' | 'transport' | 'validate' | 'parse'\n\nclass ProxyMiss extends Error {\n constructor(\n public reason: ProxyMissReason,\n message: string\n ) {\n super(message)\n }\n}\n\nconst errorMessage = (e: unknown): string =>\n e instanceof Error ? e.message : typeof e === 'string' ? e : String(e)\n\n// Breaker: consecutive misses open it for the configured cooldown, a served\n// call closes it. Module state, like the health tracker: one per process.\nlet proxyConsecutiveMisses = 0\nlet proxyOpenUntil = 0\n\n/** Test seam: forget breaker state. */\nexport function resetRpcProxyBreaker(): void {\n proxyConsecutiveMisses = 0\n proxyOpenUntil = 0\n}\n\n/**\n * One proxy call for an eligible read. Resolves with the upstream `result` the\n * proxy served, or throws ProxyMiss; the caller then continues with the node\n * loop exactly as if the proxy did not exist. Never throws anything else,\n * except the caller's own abort.\n */\nasync function proxyRpcCall(\n proxy: ServerRpcProxyState,\n method: string,\n params: unknown,\n callerTimeoutMs: number,\n externalSignal: AbortSignal | undefined,\n validate?: (result: unknown) => boolean\n): Promise {\n const dot = method.indexOf('.')\n if (dot <= 0 || dot === method.length - 1) {\n // Unreachable through setServerRpcProxy (it keeps only dotted names), kept\n // so a future allowlist change fails as a miss rather than a malformed call.\n throw new ProxyMiss('transport', `method without an api prefix: ${method}`)\n }\n // Never wait longer for the proxy than the caller would for one node.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n Math.min(proxy.timeoutMs, callerTimeoutMs)\n )\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n try {\n let res: Response\n try {\n res = await fetch(proxy.url, {\n method: 'POST',\n body: JSON.stringify({ api: method.slice(0, dot), method: method.slice(dot + 1), params }),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders(), ...proxy.headers },\n signal\n })\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'transport', errorMessage(e))\n }\n if (res.status !== 200) {\n // Release the connection: an unconsumed body pins a pooled socket.\n try {\n await res.body?.cancel()\n } catch {\n // nothing to release\n }\n const relayed = res.status === 502 && (res.headers.get('x-ssr-cache') ?? '').toUpperCase() === 'RPCERROR'\n throw new ProxyMiss(relayed ? 'rpcerror' : 'status', relayed ? 'proxy relayed a node error' : `proxy answered ${res.status}`)\n }\n let result: unknown\n try {\n result = await res.json()\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'parse', errorMessage(e))\n }\n if (validate && !validate(result)) {\n throw new ProxyMiss('validate', 'proxy result rejected by validator')\n }\n return result as T\n } finally {\n cleanupTimeout()\n cleanupMerge()\n }\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 // Server-side read-through proxy, when configured and the method is on its\n // allowlist: one call, and on any miss the node loop below runs unchanged.\n // It runs BEFORE the node deadline is taken, so a slow proxy costs its own\n // timeout and nothing of the failover budget the nodes get today.\n // Snapshot: the binding can be cleared by the host while this call awaits.\n const proxy = serverRpcProxy\n if (proxy && isNodeRuntime && proxy.methodSet.has(method)) {\n if (Date.now() < proxyOpenUntil) {\n rpcProxyStats.skipped++\n } else {\n try {\n const served = await proxyRpcCall(proxy, method, params, ceiling, signal, validate)\n rpcProxyStats.served++\n proxyConsecutiveMisses = 0\n return served\n } catch (e: unknown) {\n if (signal?.aborted) throw e\n rpcProxyStats.fallback++\n const reason: string = e instanceof ProxyMiss ? e.reason : 'transport'\n rpcProxyStats.fallbackByReason[reason] = (rpcProxyStats.fallbackByReason[reason] ?? 0) + 1\n if (reason === 'rpcerror') {\n // A relayed node error is a healthy proxy answer: it closes the\n // count like a served call. Crawler-made feed URLs produce these in\n // runs, and counting them opened the breaker on a working proxy.\n proxyConsecutiveMisses = 0\n } else if (++proxyConsecutiveMisses >= proxy.failureThreshold) {\n proxyOpenUntil = Date.now() + proxy.cooldownMs\n proxyConsecutiveMisses = 0\n }\n }\n }\n }\n\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n\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 setServerRpcProxy as setHiveTxServerRpcProxy,\n rpcProxyStats,\n type ResilienceOptions,\n type ServerRpcProxyOptions,\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 * Route allowlisted server-side RPC reads through a read-through cache in\n * front of the node pool (one cache per host, shared by every renderer\n * process). An optimization, never a dependency: any proxy failure falls\n * straight through to the node loop. No effect outside Node; null switches\n * it off. Delegates to the unified hive-tx `setServerRpcProxy`.\n * @param opts - `{ url, headers, timeoutMs, methods }` or null\n */\n export function setServerRpcProxy(opts: ServerRpcProxyOptions | null) {\n setHiveTxServerRpcProxy(opts);\n }\n\n /**\n * The live counters of that proxy path: `served` (answered by the proxy),\n * `fallback` with a per-reason breakdown (the read went to the node pool\n * after a proxy failure) and `skipped` (breaker open). The same object the\n * call path increments, exposed here because the root build carries its own\n * copy of the hive-tx internals; a consumer importing `rpcProxyStats` from\n * the `/hive` entry would read a different, never-incremented instance.\n * Read-only by contract: the web tier prints it, nothing resets it.\n */\n export function getServerRpcProxyStats(): Readonly {\n return rpcProxyStats;\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 /**\n * Optional: set when this operation edits existing content rather than creating it.\n *\n * A `comment` operation is byte-identical for a create and an update, so only the\n * caller knows which it is. When set, no content activity is recorded. Activity\n * rewards content creation. Without this, an edit of content published elsewhere\n * is credited as content created here. Never broadcast.\n */\n isUpdate?: boolean;\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\n * available, unless the payload sets `isUpdate`\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 */\n/**\n * Resolve which content activity a broadcast earns, or `null` for none.\n *\n * Content activity rewards publishing, so an update earns nothing: the `comment`\n * operation an edit broadcasts is indistinguishable from a create on chain, which\n * leaves the caller as the only party that can tell them apart. Without this, editing\n * a post first published on another frontend is credited here as a post.\n */\nexport function resolveContentActivityType(\n payload: Pick\n): 100 | 110 | null {\n if (payload.isUpdate) {\n return null;\n }\n\n return payload.parentAuthor ? 110 : 100;\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 = resolveContentActivityType(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 (activityType !== null && 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 // No activity is recorded here. Activity rewards creating content. Every\n // broadcast from this mutation edits content that already exists.\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 vote_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 vote_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 { 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 {\n RC_RESOURCE_NAMES,\n type RcCostBreakdown,\n type RcResourceName,\n type RcResourceParams\n} from \"../types/resource-params\";\nimport type { RcStats } from \"../types/stats\";\nimport { computeResourceCost } from \"./estimate-comment-rc-cost\";\n\nexport type RcResourceUsage = Record;\n\nexport interface RcPricedUsage {\n cost: number;\n breakdown: RcCostBreakdown[];\n}\n\n/**\n * Turns per-resource usage into an RC cost.\n *\n * This is the single pricing path. Every RC figure the app shows, the publish\n * warning, the comment warning, the vote warning and the credits tooltip, goes\n * through here, so they cannot disagree with each other or with the chain.\n */\nexport function priceRcUsage(\n usage: RcResourceUsage,\n rcParams: RcResourceParams,\n rcStats: Pick\n): RcPricedUsage {\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 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 leaves the safe-integer range.\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 { cost, breakdown };\n}\n","import { utf8ByteLength, varintByteLength } from \"@/modules/core/utf8\";\nimport type { RcResourceName, RcSizeInfo } from \"../types/resource-params\";\nimport type { RcResourceUsage } from \"./price-rc-usage\";\n\n/**\n * Ports of the per-operation arms of `count_resources`\n * (hive/libraries/chain/rc/resource_count.cpp).\n *\n * Every operation charges three things: the serialized transaction size as\n * history_bytes, a per-operation state footprint, and execution time. Only the\n * middle two differ per operation, which is why they live together here.\n */\n\n/** Fixed header: ref_block_num(2) + ref_block_prefix(4) + expiration(4) + extensions varint(1). */\nexport const TRANSACTION_HEADER_BYTES = 11;\nexport const SIGNATURE_BYTES = 65;\n\nexport const stringFieldBytes = (value: string): number => {\n const length = utf8ByteLength(value);\n return varintByteLength(length) + length;\n};\n\nconst emptyUsage = (): RcResourceUsage => ({\n resource_history_bytes: 0,\n resource_new_accounts: 0,\n resource_market_bytes: 0,\n resource_state_bytes: 0,\n resource_execution_time: 0\n});\n\nexport interface VoteLike {\n voter: string;\n author: string;\n permlink: string;\n}\n\n/** Serialized size of a transaction carrying a single vote. */\nexport function estimateVoteTransactionBytes(op: VoteLike, signatures = 1): number {\n const operationBytes =\n 1 + // operation variant id\n stringFieldBytes(op.voter) +\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n 2; // weight, int16\n\n return (\n TRANSACTION_HEADER_BYTES +\n varintByteLength(1) +\n operationBytes +\n varintByteLength(signatures) +\n SIGNATURE_BYTES * signatures\n );\n}\n\n/**\n * A vote's footprint is fixed: `vote_size` state bytes and `vote_time`\n * execution time, regardless of the post being voted on.\n */\nexport function countVoteResourceUsage(\n { transactionBytes, signatures = 1 }: { transactionBytes: number; signatures?: number },\n sizeInfo: RcSizeInfo\n): RcResourceUsage {\n const state = sizeInfo.resource_state_bytes;\n const exec = sizeInfo.resource_execution_time;\n\n return {\n ...emptyUsage(),\n resource_history_bytes: transactionBytes,\n resource_state_bytes: state.vote_size + state.transaction_base_size,\n resource_execution_time:\n exec.vote_time + exec.transaction_time + exec.verify_authority_time * signatures\n };\n}\n\n/** Resource names, re-exported so callers do not reach into the types module. */\nexport type { RcResourceName };\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\nimport type { RcResourceParams } from \"../types/resource-params\";\nimport { priceRcUsage } from \"./price-rc-usage\";\nimport {\n countVoteResourceUsage,\n estimateVoteTransactionBytes,\n type VoteLike\n} from \"./count-operation-usage\";\nimport {\n countCommentResourceUsage,\n estimateCommentTransactionBytes,\n type CommentLike,\n type CommentOptionsLike\n} from \"./estimate-comment-rc-cost\";\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\n/** The operation about to be broadcast, when the caller has it. */\nexport type RcPrecheckPayload =\n | { kind: \"comment\"; op: CommentLike; options?: CommentOptionsLike }\n | { kind: \"vote\"; op: VoteLike };\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 * From `getRcResourceParamsQueryOptions()`. Required for an exact estimate;\n * without it the result is not ready rather than silently approximate.\n */\n rcParams?: RcResourceParams | null;\n /**\n * The actual operation about to be broadcast. Supplying it is what makes the\n * estimate exact, because cost is dominated by the serialized transaction\n * size. Without it a minimal operation of that type is priced instead, which\n * is a lower bound: it can miss a marginal case but never invents one.\n */\n payload?: RcPrecheckPayload;\n /**\n * What to price when no payload is supplied.\n *\n * - `\"minimal\"` (default) prices the smallest operation of that type. It is\n * a lower bound, so a pre-submit warning is never invented for an\n * operation that would have succeeded.\n * - `\"average\"` prices the network average the chain publishes. Right for\n * \"how many of these can I afford\" displays, where there is no specific\n * operation in hand and the smallest conceivable one would flatter the\n * count.\n */\n fallback?: \"minimal\" | \"average\";\n /**\n * Safety multiplier applied to the 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 /**\n * RC cost of the operation itself.\n *\n * Named `avgCost` for backwards compatibility; it is no longer an average.\n * @deprecated prefer `cost`.\n */\n avgCost: number;\n /** RC cost of the operation, computed the way the chain computes it. */\n cost: number;\n /** Serialized transaction size, the dominant term for a comment. */\n transactionBytes: 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 cost: 0,\n transactionBytes: 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 * Costs are computed the way the chain computes them, from the actual\n * operation, not from the network-wide average. The average is dominated by\n * short replies and badly misleads on posts: it once told an account holding\n * 21.3B RC that it could afford 17 posts, and the next post it tried needed\n * 23.3B.\n *\n * Still a hint, never a hard gate: the buffer covers pool drift between the\n * estimate and the broadcast, and the publish/comment/vote action must stay\n * non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n rcParams,\n operation,\n payload,\n fallback = \"minimal\",\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\n const priced = priceOperation(operation, payload, fallback, rcParams, rcStats);\n if (!priced) {\n // Nothing to price against: reporting \"ready\" here would be a silent\n // all-clear, which is the one answer a pre-check must never invent.\n return { ...EMPTY, currentMana, maxMana };\n }\n\n const { cost, transactionBytes } = priced;\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = cost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost: cost,\n cost,\n transactionBytes,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / cost),\n };\n}\n\n/**\n * Prices whichever operation the caller is about to broadcast.\n *\n * Comments and votes are the two operations whose cost swings with what the\n * user wrote, so they are priced from the payload, and pricing them needs the\n * curve parameters. Every other operation the type advertises (transfer,\n * custom_json, ...) is fixed-shape and takes the network average the chain\n * publishes, which needs nothing else.\n *\n * When no payload is supplied a minimal operation is priced. That is\n * deliberately a lower bound: it can miss a marginal case, but it never warns\n * about one that would have succeeded.\n *\n * Returns null when the answer would have to be invented, so the caller\n * reports \"not ready\" rather than a zero-cost all-clear.\n */\nfunction priceOperation(\n operation: RcPrecheckOperation,\n payload: RcPrecheckPayload | undefined,\n fallback: \"minimal\" | \"average\",\n rcParams: RcResourceParams | null | undefined,\n rcStats: RcStats\n): { cost: number; transactionBytes: number } | null {\n const average = averageCost(rcStats, operation);\n const pricedFromPayload =\n operation === \"comment_operation\" || operation === \"vote_operation\";\n\n // The average is a number the node already returned. It needs no curve\n // parameters, so a caller pricing a transfer must not be blocked waiting on\n // them, which is how every operation outside these two is priced.\n if (!pricedFromPayload || (!payload && fallback === \"average\")) {\n return average;\n }\n\n // Asked to price a real comment or vote without the inputs to do it. The\n // honest answer is \"not ready\": falling back to the average here is exactly\n // what told an account holding 21.3B RC it could afford 17 more posts.\n if (!rcParams?.resource_params || !rcParams.size_info || !rcStats.pool || !rcStats.share) {\n return null;\n }\n\n const stats = { pool: rcStats.pool, regen: rcStats.regen, share: rcStats.share };\n\n if (operation === \"vote_operation\") {\n const op: VoteLike = payload?.kind === \"vote\" ? payload.op : MINIMAL_VOTE;\n const transactionBytes = estimateVoteTransactionBytes(op);\n const usage = countVoteResourceUsage({ transactionBytes }, rcParams.size_info);\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n }\n\n const op: CommentLike = payload?.kind === \"comment\" ? payload.op : MINIMAL_COMMENT;\n const options = payload?.kind === \"comment\" ? payload.options : undefined;\n const transactionBytes = estimateCommentTransactionBytes({ op, options });\n const usage = countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength: op.permlink.length,\n beneficiaries: options?.beneficiaries?.length ?? 0,\n hasCommentOptions: !!options\n },\n rcParams.size_info\n );\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n}\n\n/** The network average the chain publishes for an operation, when it has one. */\nfunction averageCost(\n rcStats: RcStats,\n operation: RcPrecheckOperation\n): { cost: number; transactionBytes: number } | null {\n const cost = rcStats.ops[operation]?.avg_cost;\n return typeof cost === \"number\" && cost > 0 ? { cost, transactionBytes: 0 } : null;\n}\n\n/** Smallest realistic operations, used only when the caller has no payload yet. */\nconst MINIMAL_COMMENT: CommentLike = {\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\",\n parent_author: \"\",\n parent_permlink: \"hive-100000\",\n title: \"\",\n body: \"\",\n json_metadata: \"{}\"\n};\n\nconst MINIMAL_VOTE: VoteLike = {\n voter: \"aaaaaaaaaa\",\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\"\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\n/**\n * POST a single game claim and return the parsed JSON body.\n *\n * A failed post-game comes back from the edge as an HTML gateway page (a 502 was\n * the trail on ECENCY-NEXT-1FCJ), and `response.json()` on that throws a bare\n * `SyntaxError` naming neither the endpoint nor the cause. Check the status and\n * the content type first, then fail with a STABLE, low-cardinality message\n * (content type + status, never the raw body) so these group as a single Sentry\n * issue instead of fragmenting on every distinct error page.\n *\n * Exported for unit testing; the hook below wraps it.\n */\nexport async function gameClaimRequest(\n code: string,\n gameType: \"spin\",\n key: string\n): Promise {\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 // 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 // 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 page.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Games] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Games] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body) as GameClaim;\n } catch {\n throw new Error(\n `[SDK][Games] – malformed JSON response (status ${response.status})`\n );\n }\n}\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 return gameClaimRequest(code, gameType, key);\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","/**\n * Thresholds behind the content moderation treatment. Single source of truth for\n * every client: web and mobile previously carried their own copies, which drifted\n * (mobile flagged downvoted content at -7B rshares and 4 voters where web used\n * -10B and 5), so the same post read differently depending on the app.\n */\n\n/** Sum of rshares below which a post counts as heavily downvoted. */\nexport const HIDDEN_POST_RSHARES_THRESHOLD = -10000000000;\n\n/** Downvoting is only conclusive once enough accounts have voted. */\nexport const HIDDEN_POST_MIN_VOTES = 5;\n\n/**\n * Reputation (human-readable 0-100 scale) below which an author counts as\n * low-trust. New Hive accounts start around 25.\n *\n * NOTE: reputation is the only input. Account age is NOT part of the check, so a\n * years-old account that never earned reputation trips it exactly like a fresh\n * one. User-facing copy must say \"low reputation\", never \"new account\".\n */\nexport const LOW_TRUST_REPUTATION_THRESHOLD = 30;\n","/**\n * Converts Hive's raw reputation to the human-readable 0-100 scale, passing\n * through values that are already on it (the bridge returns both shapes\n * depending on the endpoint).\n */\nconst isHumanReadable = (input: number): boolean =>\n Math.abs(input) > 0 && Math.abs(input) <= 100;\n\nexport function accountReputation(input: string | number): number {\n if (typeof input === \"number\" && isHumanReadable(input)) {\n return Math.floor(input);\n }\n\n if (typeof input === \"string\") {\n input = Number(input);\n\n if (isHumanReadable(input)) {\n return Math.floor(input);\n }\n }\n\n if (input === 0) {\n return 25;\n }\n\n let neg = false;\n\n if (input < 0) {\n neg = true;\n }\n\n let reputationLevel = Math.log10(Math.abs(input as number));\n reputationLevel = Math.max(reputationLevel - 9, 0);\n\n if (reputationLevel < 0) {\n reputationLevel = 0;\n }\n\n if (neg) {\n reputationLevel *= -1;\n }\n\n reputationLevel = reputationLevel * 9 + 25;\n\n return Math.floor(reputationLevel);\n}\n","/**\n * Outbound-link detection for the SEO/backlink-farm signal.\n *\n * A link only counts as outbound promotion when it leaves the Hive/Ecency\n * ecosystem and is not an embedded image, so ordinary on-platform references and\n * post illustrations never trip the check.\n */\n\n// Hosts that are part of the Hive/Ecency ecosystem.\nconst INTERNAL_HOSTS = [\n \"ecency.com\",\n \"ecency.app\",\n \"hive.blog\",\n \"hive.io\",\n \"hiveblocks.com\",\n \"peakd.com\",\n \"snapie.io\",\n \"hivesuite.app\",\n \"leofinance.io\",\n \"inleo.io\",\n \"3speak.tv\",\n \"d.buzz\",\n \"waivio.com\"\n];\n\n// Image/media hosts: an embedded image is content, not a backlink.\nconst IMAGE_HOSTS = [\n \"imgur.com\",\n \"images.hive.blog\",\n \"files.peakd.com\",\n \"i.ecency.com\",\n \"images.ecency.com\",\n \"steemitimages.com\",\n \"cdn.steemitimages.com\",\n \"media.giphy.com\"\n];\n\nconst IMAGE_EXT_RE = /\\.(jpe?g|png|gif|webp|svg|bmp|avif)(\\?|#|$)/i;\n// Match absolute AND protocol-relative URLs (\"//host/...\"), so the check can't be\n// evaded with `[promo](//shop.example)` (the renderer allows protocol-relative hrefs).\nconst URL_RE = /(?:https?:)?\\/\\/[^\\s)<>\"'\\]]+/gi;\n// URLs in prose are commonly followed by punctuation (\"https://ecency.com, and...\");\n// strip it so the host parses correctly and internal links do not false-positive.\nconst TRAILING_PUNCT_RE = /[.,;:!?'\"]+$/;\n\nfunction hostOf(url: string): string {\n const m = /^(?:https?:)?\\/\\/([^/?#]+)/i.exec(url);\n return m ? m[1].toLowerCase().replace(/^www\\./, \"\") : \"\";\n}\n\nfunction isExternalPromoLink(rawUrl: string): boolean {\n const url = rawUrl.replace(TRAILING_PUNCT_RE, \"\");\n if (IMAGE_EXT_RE.test(url)) {\n return false; // embedded image, not a backlink\n }\n const host = hostOf(url);\n if (!host.includes(\".\")) {\n return false; // not a real domain (e.g. a stray \"//something\")\n }\n const matches = (h: string) => host === h || host.endsWith(\".\" + h);\n if (INTERNAL_HOSTS.some(matches) || IMAGE_HOSTS.some(matches)) {\n return false; // Hive/Ecency or image host\n }\n return true;\n}\n\n/** True if the post body contains an outbound (non-Hive, non-image) link. */\nexport function hasExternalLink(body: string | undefined | null): boolean {\n if (!body) {\n return false;\n }\n const matches = body.match(URL_RE);\n if (!matches) {\n return false;\n }\n return matches.some(isExternalPromoLink);\n}\n","import { accountReputation } from \"./account-reputation\";\nimport {\n HIDDEN_POST_MIN_VOTES,\n HIDDEN_POST_RSHARES_THRESHOLD,\n LOW_TRUST_REPUTATION_THRESHOLD\n} from \"./constants\";\nimport { hasExternalLink } from \"./external-links\";\n\n/**\n * Why a piece of content gets the moderation treatment. Clients render their own\n * copy per reason; the rules that pick the reason live here so web and mobile\n * always agree on which one fired.\n */\nexport enum ContentModerationReason {\n /**\n * `stats.gray` / `stats.hide` from hivemind: community moderator mutes, mutes\n * applied by the observer account, and authors hivemind itself grays out.\n */\n MOD_MUTED = \"mod_muted\",\n /** Heavily downvoted by enough distinct accounts to be conclusive. */\n DOWNVOTED = \"downvoted\",\n /** Low-reputation author whose post carries an outbound promotional link. */\n LOW_TRUST = \"low_trust\"\n}\n\n/**\n * The fields of a post or comment the rules read. Deliberately structural: web\n * passes an `Entry`, mobile passes a raw bridge post, and neither has to convert.\n */\nexport interface ModerationCandidate {\n author?: string;\n author_reputation?: string | number;\n body?: string | null;\n net_rshares?: number;\n active_votes?: unknown[] | null;\n stats?: {\n gray?: boolean;\n hide?: boolean;\n total_votes?: number;\n } | null;\n}\n\n/**\n * hivemind's `total_votes` is the authoritative count when present; `active_votes`\n * is the fallback for the feeds that omit stats.\n */\nfunction countVotes(content: ModerationCandidate): number {\n return content?.stats?.total_votes ?? content?.active_votes?.length ?? 0;\n}\n\n/** Heavily downvoted: strongly negative rshares from more than a handful of voters. */\nexport function isHiddenPost(\n netRshares: number | undefined,\n activeVotesLength: number\n): boolean {\n return (\n (netRshares ?? 0) < HIDDEN_POST_RSHARES_THRESHOLD &&\n activeVotesLength >= HIDDEN_POST_MIN_VOTES\n );\n}\n\n/**\n * Content-moderation signal for SEO/backlink-farm abuse: low-reputation accounts\n * publishing an outbound link are the signature of free-faucet SEO spam.\n *\n * Such posts are not blocked, they are de-emphasized and their outbound link is\n * flagged as unverified, so the promotional payoff drops to zero. Low reputation\n * on its own is NOT a moderation signal: plenty of small accounts post ordinary\n * content, and dimming all of them punishes newcomers for existing.\n */\nexport function isLowTrustSeoPost(\n content: Pick\n): boolean {\n const reputation = content?.author_reputation;\n // Some feeds omit reputation entirely. An unknown value is not evidence of\n // anything, so it must not be read as \"brand new account\" (raw 0 scales to 25,\n // which is below the threshold and would flag every post carrying a link).\n if (reputation === undefined || reputation === null) {\n return false;\n }\n return (\n accountReputation(reputation) < LOW_TRUST_REPUTATION_THRESHOLD &&\n hasExternalLink(content?.body)\n );\n}\n\n/** True when the viewer has personally muted this author. */\nexport function isAuthorMuted(\n author: string | undefined,\n mutedAuthors: string[] | undefined | null\n): boolean {\n return !!author && !!mutedAuthors?.includes(author);\n}\n\n/**\n * The reason a post or comment should be de-emphasized, or null when it is fine.\n *\n * Precedence, most authoritative first: an explicit moderation action outranks\n * the vote heuristic, which outranks the spam heuristic. Order matters because a\n * heavily downvoted post usually also has a battered reputation, and labelling\n * that \"low trust\" would hide why the content was actually flagged.\n *\n * A viewer's personal mute list is NOT an input here. Muting an author removes\n * their content from the viewer's lists entirely (see `isAuthorMuted`), rather\n * than labelling it.\n */\nexport function getContentModerationReason(\n content: ModerationCandidate | undefined | null\n): ContentModerationReason | null {\n if (!content) {\n return null;\n }\n if (content.stats?.gray || content.stats?.hide) {\n return ContentModerationReason.MOD_MUTED;\n }\n if (isHiddenPost(content.net_rshares, countVotes(content))) {\n return ContentModerationReason.DOWNVOTED;\n }\n if (isLowTrustSeoPost(content)) {\n return ContentModerationReason.LOW_TRUST;\n }\n return null;\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-comment-rc-cost.ts","../../src/modules/resource-credits/utils/price-rc-usage.ts","../../src/modules/resource-credits/utils/count-operation-usage.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","../../src/modules/moderation/constants.ts","../../src/modules/moderation/account-reputation.ts","../../src/modules/moderation/external-links.ts","../../src/modules/moderation/content-moderation.ts","../../src/modules/newsletter/api.ts","../../src/modules/newsletter/queries/get-digest-subscriptions-query-options.ts","../../src/modules/newsletter/queries/get-newsletter-sender-query-options.ts","../../src/modules/newsletter/queries/get-newsletter-issues-query-options.ts","../../src/modules/newsletter/queries/get-newsletter-posts-query-options.ts","../../src/modules/newsletter/mutations/use-subscribe-digest.ts","../../src/modules/newsletter/mutations/use-leave-digest.ts","../../src/modules/newsletter/mutations/use-unsubscribe-all-digests.ts","../../src/modules/newsletter/mutations/use-send-newsletter-issue.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","DEFAULT_SERVER_RPC_PROXY_METHODS","serverRpcProxy","setServerRpcProxy","opts","url","headers","k","v","timeoutMs","methods","m","pos","fallback","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","r","bool","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","rpcProxyStats","ProxyMiss","reason","errorMessage","proxyConsecutiveMisses","proxyOpenUntil","proxyRpcCall","proxy","method","params","callerTimeoutMs","externalSignal","validate","dot","tSignal","cleanupTimeout","createTimeoutSignal","signal","cleanupMerge","mergeSignals","res","e","relayed","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","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","tryRecordHeadBlock","block","createTimeoutReason","err","controller","timer","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","timeout","shouldRetry","body","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","served","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","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","timeoutSignal","ac","onAbort","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","getServerRpcProxyStats","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","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","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","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","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","resolveContentActivityType","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","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","EMPTY","estimateCommentRcCost","rcParams","rcStats","usage","regen","cost","breakdown","share","scaled","resourceCost","priceRcUsage","emptyUsage","estimateVoteTransactionBytes","operationBytes","countVoteResourceUsage","estimateRcPrecheck","priced","priceOperation","safeBuffer","estimatedCost","willLikelyFail","average","averageCost","MINIMAL_VOTE","MINIMAL_COMMENT","getGameStatusCheckQueryOptions","gameClaimRequest","contentType","detail","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","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","HIDDEN_POST_RSHARES_THRESHOLD","HIDDEN_POST_MIN_VOTES","LOW_TRUST_REPUTATION_THRESHOLD","isHumanReadable","accountReputation","neg","reputationLevel","INTERNAL_HOSTS","IMAGE_HOSTS","IMAGE_EXT_RE","URL_RE","TRAILING_PUNCT_RE","hostOf","isExternalPromoLink","rawUrl","hasExternalLink","ContentModerationReason","countVotes","isHiddenPost","netRshares","activeVotesLength","isLowTrustSeoPost","reputation","isAuthorMuted","mutedAuthors","getContentModerationReason","NewsletterApiError","NewsletterSendRefusedError","taken","newsletterUrl","parse","subscribeDigestRequest","getDigestSubscriptionsRequest","leaveDigestRequest","unsubscribeAllDigestsRequest","getNewsletterSenderRequest","getNewsletterIssuesRequest","getNewsletterPostsRequest","postSend","request","previewNewsletterSendRequest","sendNewsletterIssueRequest","getDigestSubscriptionsQueryOptions","getNewsletterSenderQueryOptions","getNewsletterIssuesQueryOptions","getNewsletterPostsQueryOptions","useSubscribeDigest","useLeaveDigest","useUnsubscribeAllDigests","usePreviewNewsletterIssue","useSendNewsletterIssue"],"mappings":"wkBASA,IAAMA,GAAe,IAAI,WAAA,CAAY,CAAC,CAAA,CAIlCC,EAAAA,CAAqD,IAAA,CACrDC,EAAAA,CAAuD,IAAA,CAE3D,SAASC,IAAgD,CACvD,OAAKF,KACC,OAAO,WAAA,CAAgB,IACzBA,EAAAA,CAAW,IAAI,WAAA,CAEfA,EAAAA,CAAW,CACT,MAAA,CAAOG,EAAuB,CAE5B,IAAMC,EAAiB,EAAC,CACxB,QAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAE,MAAA,CAAQE,CAAAA,EAAAA,CAAK,CACjC,IAAIC,CAAAA,CAAIH,EAAE,UAAA,CAAWE,CAAC,EACtB,GAAIC,CAAAA,CAAI,GAAA,CACNF,CAAAA,CAAK,IAAA,CAAKE,CAAC,UACFA,CAAAA,CAAI,IAAA,CACbF,EAAK,IAAA,CAAK,GAAA,CAAQE,GAAK,CAAA,CAAI,GAAA,CAAQA,CAAAA,CAAI,EAAK,CAAA,CAAA,KAAA,GACnCA,CAAAA,EAAK,OAAUA,CAAAA,EAAK,KAAA,EAAUD,EAAI,CAAA,CAAIF,CAAAA,CAAE,OAAQ,CACzD,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B,QAAA,CAAUrX,EAAU,UAAA,CAAW,MAAA,CAAO+uC,CAAAA,CAAQ,IAAA,CAAMA,CAAAA,CAAQ,MAAA,CAAQ7rC,CAAI,CAC1E,CAAC,EACH,CACF,CAAC,CACH","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 * Server-side read-through proxy for RPC reads (see `setServerRpcProxy`).\n * `methods` is the allowlist the proxy serves; a read outside it goes straight\n * to the node pool as before.\n */\nexport interface ServerRpcProxyOptions {\n /** Absolute URL of the proxy endpoint (POST `{api, method, params}`). */\n url: string\n /** Headers sent with every proxy call (the shared internal secret). */\n headers: Record\n /** Per-call timeout in ms; on expiry the read falls back to the node pool. */\n timeoutMs: number\n /** Fully qualified method names (`bridge.get_post`) the proxy may answer;\n * omitted = DEFAULT_SERVER_RPC_PROXY_METHODS. An empty list is ignored. */\n methods?: string[]\n /**\n * After this many consecutive proxy misses the proxy is skipped for\n * `cooldownMs`, so a proxy that is down costs one failed call per cooldown\n * window rather than one per read. Default 3 / 10s. A served call resets it.\n */\n failureThreshold?: number\n cooldownMs?: number\n}\n\n/** Default allowlist: the reads a server render makes and the proxy caches. */\nexport const DEFAULT_SERVER_RPC_PROXY_METHODS: readonly string[] = [\n 'bridge.get_ranked_posts',\n 'bridge.get_account_posts',\n 'bridge.get_post',\n 'bridge.get_discussion',\n 'bridge.get_profile',\n 'bridge.get_profiles',\n 'bridge.get_community',\n 'bridge.list_communities',\n 'condenser_api.get_accounts',\n 'condenser_api.get_content',\n 'condenser_api.get_dynamic_global_properties',\n 'condenser_api.get_trending_tags'\n]\n\n/**\n * Active proxy configuration, or null (the default: every read goes to the node\n * pool). Lives outside `config` so the browser bundle never carries it; it is\n * only ever consulted under Node.\n */\nexport interface ServerRpcProxyState extends Required {\n methodSet: Set\n}\n\nexport let serverRpcProxy: ServerRpcProxyState | null = null\n\n/**\n * Route allowlisted server-side reads through a read-through cache in front\n * of the node pool. One cache per host answers the reads every renderer\n * process used to make on its own; a miss there is one upstream call shared by\n * every concurrent reader. The proxy is an optimization, never a dependency:\n * any failure (non-200, timeout, transport error, a response the caller's\n * validator rejects) falls straight through to the existing node loop, so the\n * worst case is the latency of a failed proxy call on top of what happens\n * today. Has no effect outside Node. Pass null to switch it off.\n */\nexport const setServerRpcProxy = (opts: ServerRpcProxyOptions | null): void => {\n if (opts === null) {\n serverRpcProxy = null\n return\n }\n if (!opts || typeof opts !== 'object') return\n const url = typeof opts.url === 'string' ? opts.url.trim() : ''\n if (!/^https?:\\/\\//i.test(url)) return\n const headers: Record = {}\n if (opts.headers && typeof opts.headers === 'object') {\n for (const [k, v] of Object.entries(opts.headers)) {\n if (typeof v === 'string' && v && !/[\\u0000-\\u001f\\u007f]/.test(v) && !/[\\u0000-\\u001f\\u007f]/.test(k)) {\n headers[k] = v\n }\n }\n }\n const timeoutMs =\n typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0\n ? opts.timeoutMs\n : 2_000\n const methods =\n opts.methods === undefined\n ? [...DEFAULT_SERVER_RPC_PROXY_METHODS]\n : Array.isArray(opts.methods)\n ? opts.methods.filter((m): m is string => typeof m === 'string' && m.includes('.'))\n : []\n // Nothing to route through the proxy: keep whatever was configured before.\n if (methods.length === 0) return\n const pos = (v: unknown, fallback: number): number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : fallback\n serverRpcProxy = {\n url,\n headers,\n timeoutMs,\n methods,\n failureThreshold: Math.floor(pos(opts.failureThreshold, 3)),\n cooldownMs: pos(opts.cooldownMs, 10_000),\n methodSet: new Set(methods)\n }\n}\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, serverRpcProxy, type ServerRpcProxyState } 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// ── Server-side read-through proxy ──────────────────────────────────────────\n\n/**\n * Counters for the proxy path, readable by a host's diagnostics (the web\n * tier's event-loop monitor prints them). `served` = answered by the proxy,\n * `fallback` = proxy configured and eligible but the read went to the node\n * pool, with the reason.\n */\nexport const rpcProxyStats = {\n served: 0,\n fallback: 0,\n /** Reads that went straight to the nodes because the breaker was open. */\n skipped: 0,\n fallbackByReason: { status: 0, rpcerror: 0, timeout: 0, transport: 0, validate: 0, parse: 0 } as Record\n}\n\n/**\n * `rpcerror` is a 502 tagged `X-Ssr-Cache: RPCERROR`: the proxy reached a node\n * and relayed the node's own error (a tag or post that does not exist, a bad\n * argument). The read still falls back so the caller sees the node's answer\n * unchanged, but the proxy was healthy, so it does not count toward the\n * breaker; the other reasons do.\n */\ntype ProxyMissReason = 'status' | 'rpcerror' | 'timeout' | 'transport' | 'validate' | 'parse'\n\nclass ProxyMiss extends Error {\n constructor(\n public reason: ProxyMissReason,\n message: string\n ) {\n super(message)\n }\n}\n\nconst errorMessage = (e: unknown): string =>\n e instanceof Error ? e.message : typeof e === 'string' ? e : String(e)\n\n// Breaker: consecutive misses open it for the configured cooldown, a served\n// call closes it. Module state, like the health tracker: one per process.\nlet proxyConsecutiveMisses = 0\nlet proxyOpenUntil = 0\n\n/** Test seam: forget breaker state. */\nexport function resetRpcProxyBreaker(): void {\n proxyConsecutiveMisses = 0\n proxyOpenUntil = 0\n}\n\n/**\n * One proxy call for an eligible read. Resolves with the upstream `result` the\n * proxy served, or throws ProxyMiss; the caller then continues with the node\n * loop exactly as if the proxy did not exist. Never throws anything else,\n * except the caller's own abort.\n */\nasync function proxyRpcCall(\n proxy: ServerRpcProxyState,\n method: string,\n params: unknown,\n callerTimeoutMs: number,\n externalSignal: AbortSignal | undefined,\n validate?: (result: unknown) => boolean\n): Promise {\n const dot = method.indexOf('.')\n if (dot <= 0 || dot === method.length - 1) {\n // Unreachable through setServerRpcProxy (it keeps only dotted names), kept\n // so a future allowlist change fails as a miss rather than a malformed call.\n throw new ProxyMiss('transport', `method without an api prefix: ${method}`)\n }\n // Never wait longer for the proxy than the caller would for one node.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n Math.min(proxy.timeoutMs, callerTimeoutMs)\n )\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n try {\n let res: Response\n try {\n res = await fetch(proxy.url, {\n method: 'POST',\n body: JSON.stringify({ api: method.slice(0, dot), method: method.slice(dot + 1), params }),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders(), ...proxy.headers },\n signal\n })\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'transport', errorMessage(e))\n }\n if (res.status !== 200) {\n // Release the connection: an unconsumed body pins a pooled socket.\n try {\n await res.body?.cancel()\n } catch {\n // nothing to release\n }\n const relayed = res.status === 502 && (res.headers.get('x-ssr-cache') ?? '').toUpperCase() === 'RPCERROR'\n throw new ProxyMiss(relayed ? 'rpcerror' : 'status', relayed ? 'proxy relayed a node error' : `proxy answered ${res.status}`)\n }\n let result: unknown\n try {\n result = await res.json()\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'parse', errorMessage(e))\n }\n if (validate && !validate(result)) {\n throw new ProxyMiss('validate', 'proxy result rejected by validator')\n }\n return result as T\n } finally {\n cleanupTimeout()\n cleanupMerge()\n }\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 // Server-side read-through proxy, when configured and the method is on its\n // allowlist: one call, and on any miss the node loop below runs unchanged.\n // It runs BEFORE the node deadline is taken, so a slow proxy costs its own\n // timeout and nothing of the failover budget the nodes get today.\n // Snapshot: the binding can be cleared by the host while this call awaits.\n const proxy = serverRpcProxy\n if (proxy && isNodeRuntime && proxy.methodSet.has(method)) {\n if (Date.now() < proxyOpenUntil) {\n rpcProxyStats.skipped++\n } else {\n try {\n const served = await proxyRpcCall(proxy, method, params, ceiling, signal, validate)\n rpcProxyStats.served++\n proxyConsecutiveMisses = 0\n return served\n } catch (e: unknown) {\n if (signal?.aborted) throw e\n rpcProxyStats.fallback++\n const reason: string = e instanceof ProxyMiss ? e.reason : 'transport'\n rpcProxyStats.fallbackByReason[reason] = (rpcProxyStats.fallbackByReason[reason] ?? 0) + 1\n if (reason === 'rpcerror') {\n // A relayed node error is a healthy proxy answer: it closes the\n // count like a served call. Crawler-made feed URLs produce these in\n // runs, and counting them opened the breaker on a working proxy.\n proxyConsecutiveMisses = 0\n } else if (++proxyConsecutiveMisses >= proxy.failureThreshold) {\n proxyOpenUntil = Date.now() + proxy.cooldownMs\n proxyConsecutiveMisses = 0\n }\n }\n }\n }\n\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n\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 setServerRpcProxy as setHiveTxServerRpcProxy,\n rpcProxyStats,\n type ResilienceOptions,\n type ServerRpcProxyOptions,\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 * Route allowlisted server-side RPC reads through a read-through cache in\n * front of the node pool (one cache per host, shared by every renderer\n * process). An optimization, never a dependency: any proxy failure falls\n * straight through to the node loop. No effect outside Node; null switches\n * it off. Delegates to the unified hive-tx `setServerRpcProxy`.\n * @param opts - `{ url, headers, timeoutMs, methods }` or null\n */\n export function setServerRpcProxy(opts: ServerRpcProxyOptions | null) {\n setHiveTxServerRpcProxy(opts);\n }\n\n /**\n * The live counters of that proxy path: `served` (answered by the proxy),\n * `fallback` with a per-reason breakdown (the read went to the node pool\n * after a proxy failure) and `skipped` (breaker open). The same object the\n * call path increments, exposed here because the root build carries its own\n * copy of the hive-tx internals; a consumer importing `rpcProxyStats` from\n * the `/hive` entry would read a different, never-incremented instance.\n * Read-only by contract: the web tier prints it, nothing resets it.\n */\n export function getServerRpcProxyStats(): Readonly {\n return rpcProxyStats;\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 // Newsletter (digest subscriptions + sender API)\n // ===========================================================================\n newsletter: {\n subscriptions: (username: string | undefined) => [\n \"newsletter\",\n \"subscriptions\",\n username,\n ],\n sender: (type: string, target: string, username: string | undefined) => [\n \"newsletter\",\n \"sender\",\n type,\n target,\n username,\n ],\n issues: (type: string, target: string, username: string | undefined) => [\n \"newsletter\",\n \"issues\",\n type,\n target,\n username,\n ],\n posts: (\n type: string,\n target: string,\n username: string | undefined,\n limit: number,\n ) => [\"newsletter\", \"posts\", type, target, username, limit],\n _prefix: [\"newsletter\"],\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 /**\n * The viewing user; exclude authors they currently mute. Ecency's own\n * moderation mutes are applied by esync regardless of this value, so leaving\n * it unset drops the viewer's personal mutes, not the platform ones.\n */\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 /**\n * The viewing user; exclude authors they currently mute. Ecency's own\n * moderation mutes are applied by esync regardless of this value.\n */\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 /**\n * Optional: set when this operation edits existing content rather than creating it.\n *\n * A `comment` operation is byte-identical for a create and an update, so only the\n * caller knows which it is. When set, no content activity is recorded. Activity\n * rewards content creation. Without this, an edit of content published elsewhere\n * is credited as content created here. Never broadcast.\n */\n isUpdate?: boolean;\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\n * available, unless the payload sets `isUpdate`\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 */\n/**\n * Resolve which content activity a broadcast earns, or `null` for none.\n *\n * Content activity rewards publishing, so an update earns nothing: the `comment`\n * operation an edit broadcasts is indistinguishable from a create on chain, which\n * leaves the caller as the only party that can tell them apart. Without this, editing\n * a post first published on another frontend is credited here as a post.\n */\nexport function resolveContentActivityType(\n payload: Pick\n): 100 | 110 | null {\n if (payload.isUpdate) {\n return null;\n }\n\n return payload.parentAuthor ? 110 : 100;\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 = resolveContentActivityType(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 (activityType !== null && 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 // No activity is recorded here. Activity rewards creating content. Every\n // broadcast from this mutation edits content that already exists.\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 vote_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 vote_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 { 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 {\n RC_RESOURCE_NAMES,\n type RcCostBreakdown,\n type RcResourceName,\n type RcResourceParams\n} from \"../types/resource-params\";\nimport type { RcStats } from \"../types/stats\";\nimport { computeResourceCost } from \"./estimate-comment-rc-cost\";\n\nexport type RcResourceUsage = Record;\n\nexport interface RcPricedUsage {\n cost: number;\n breakdown: RcCostBreakdown[];\n}\n\n/**\n * Turns per-resource usage into an RC cost.\n *\n * This is the single pricing path. Every RC figure the app shows, the publish\n * warning, the comment warning, the vote warning and the credits tooltip, goes\n * through here, so they cannot disagree with each other or with the chain.\n */\nexport function priceRcUsage(\n usage: RcResourceUsage,\n rcParams: RcResourceParams,\n rcStats: Pick\n): RcPricedUsage {\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 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 leaves the safe-integer range.\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 { cost, breakdown };\n}\n","import { utf8ByteLength, varintByteLength } from \"@/modules/core/utf8\";\nimport type { RcResourceName, RcSizeInfo } from \"../types/resource-params\";\nimport type { RcResourceUsage } from \"./price-rc-usage\";\n\n/**\n * Ports of the per-operation arms of `count_resources`\n * (hive/libraries/chain/rc/resource_count.cpp).\n *\n * Every operation charges three things: the serialized transaction size as\n * history_bytes, a per-operation state footprint, and execution time. Only the\n * middle two differ per operation, which is why they live together here.\n */\n\n/** Fixed header: ref_block_num(2) + ref_block_prefix(4) + expiration(4) + extensions varint(1). */\nexport const TRANSACTION_HEADER_BYTES = 11;\nexport const SIGNATURE_BYTES = 65;\n\nexport const stringFieldBytes = (value: string): number => {\n const length = utf8ByteLength(value);\n return varintByteLength(length) + length;\n};\n\nconst emptyUsage = (): RcResourceUsage => ({\n resource_history_bytes: 0,\n resource_new_accounts: 0,\n resource_market_bytes: 0,\n resource_state_bytes: 0,\n resource_execution_time: 0\n});\n\nexport interface VoteLike {\n voter: string;\n author: string;\n permlink: string;\n}\n\n/** Serialized size of a transaction carrying a single vote. */\nexport function estimateVoteTransactionBytes(op: VoteLike, signatures = 1): number {\n const operationBytes =\n 1 + // operation variant id\n stringFieldBytes(op.voter) +\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n 2; // weight, int16\n\n return (\n TRANSACTION_HEADER_BYTES +\n varintByteLength(1) +\n operationBytes +\n varintByteLength(signatures) +\n SIGNATURE_BYTES * signatures\n );\n}\n\n/**\n * A vote's footprint is fixed: `vote_size` state bytes and `vote_time`\n * execution time, regardless of the post being voted on.\n */\nexport function countVoteResourceUsage(\n { transactionBytes, signatures = 1 }: { transactionBytes: number; signatures?: number },\n sizeInfo: RcSizeInfo\n): RcResourceUsage {\n const state = sizeInfo.resource_state_bytes;\n const exec = sizeInfo.resource_execution_time;\n\n return {\n ...emptyUsage(),\n resource_history_bytes: transactionBytes,\n resource_state_bytes: state.vote_size + state.transaction_base_size,\n resource_execution_time:\n exec.vote_time + exec.transaction_time + exec.verify_authority_time * signatures\n };\n}\n\n/** Resource names, re-exported so callers do not reach into the types module. */\nexport type { RcResourceName };\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\nimport type { RcResourceParams } from \"../types/resource-params\";\nimport { priceRcUsage } from \"./price-rc-usage\";\nimport {\n countVoteResourceUsage,\n estimateVoteTransactionBytes,\n type VoteLike\n} from \"./count-operation-usage\";\nimport {\n countCommentResourceUsage,\n estimateCommentTransactionBytes,\n type CommentLike,\n type CommentOptionsLike\n} from \"./estimate-comment-rc-cost\";\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\n/** The operation about to be broadcast, when the caller has it. */\nexport type RcPrecheckPayload =\n | { kind: \"comment\"; op: CommentLike; options?: CommentOptionsLike }\n | { kind: \"vote\"; op: VoteLike };\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 * From `getRcResourceParamsQueryOptions()`. Required for an exact estimate;\n * without it the result is not ready rather than silently approximate.\n */\n rcParams?: RcResourceParams | null;\n /**\n * The actual operation about to be broadcast. Supplying it is what makes the\n * estimate exact, because cost is dominated by the serialized transaction\n * size. Without it a minimal operation of that type is priced instead, which\n * is a lower bound: it can miss a marginal case but never invents one.\n */\n payload?: RcPrecheckPayload;\n /**\n * What to price when no payload is supplied.\n *\n * - `\"minimal\"` (default) prices the smallest operation of that type. It is\n * a lower bound, so a pre-submit warning is never invented for an\n * operation that would have succeeded.\n * - `\"average\"` prices the network average the chain publishes. Right for\n * \"how many of these can I afford\" displays, where there is no specific\n * operation in hand and the smallest conceivable one would flatter the\n * count.\n */\n fallback?: \"minimal\" | \"average\";\n /**\n * Safety multiplier applied to the 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 /**\n * RC cost of the operation itself.\n *\n * Named `avgCost` for backwards compatibility; it is no longer an average.\n * @deprecated prefer `cost`.\n */\n avgCost: number;\n /** RC cost of the operation, computed the way the chain computes it. */\n cost: number;\n /** Serialized transaction size, the dominant term for a comment. */\n transactionBytes: 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 cost: 0,\n transactionBytes: 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 * Costs are computed the way the chain computes them, from the actual\n * operation, not from the network-wide average. The average is dominated by\n * short replies and badly misleads on posts: it once told an account holding\n * 21.3B RC that it could afford 17 posts, and the next post it tried needed\n * 23.3B.\n *\n * Still a hint, never a hard gate: the buffer covers pool drift between the\n * estimate and the broadcast, and the publish/comment/vote action must stay\n * non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n rcParams,\n operation,\n payload,\n fallback = \"minimal\",\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\n const priced = priceOperation(operation, payload, fallback, rcParams, rcStats);\n if (!priced) {\n // Nothing to price against: reporting \"ready\" here would be a silent\n // all-clear, which is the one answer a pre-check must never invent.\n return { ...EMPTY, currentMana, maxMana };\n }\n\n const { cost, transactionBytes } = priced;\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = cost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost: cost,\n cost,\n transactionBytes,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / cost),\n };\n}\n\n/**\n * Prices whichever operation the caller is about to broadcast.\n *\n * Comments and votes are the two operations whose cost swings with what the\n * user wrote, so they are priced from the payload, and pricing them needs the\n * curve parameters. Every other operation the type advertises (transfer,\n * custom_json, ...) is fixed-shape and takes the network average the chain\n * publishes, which needs nothing else.\n *\n * When no payload is supplied a minimal operation is priced. That is\n * deliberately a lower bound: it can miss a marginal case, but it never warns\n * about one that would have succeeded.\n *\n * Returns null when the answer would have to be invented, so the caller\n * reports \"not ready\" rather than a zero-cost all-clear.\n */\nfunction priceOperation(\n operation: RcPrecheckOperation,\n payload: RcPrecheckPayload | undefined,\n fallback: \"minimal\" | \"average\",\n rcParams: RcResourceParams | null | undefined,\n rcStats: RcStats\n): { cost: number; transactionBytes: number } | null {\n const average = averageCost(rcStats, operation);\n const pricedFromPayload =\n operation === \"comment_operation\" || operation === \"vote_operation\";\n\n // The average is a number the node already returned. It needs no curve\n // parameters, so a caller pricing a transfer must not be blocked waiting on\n // them, which is how every operation outside these two is priced.\n if (!pricedFromPayload || (!payload && fallback === \"average\")) {\n return average;\n }\n\n // Asked to price a real comment or vote without the inputs to do it. The\n // honest answer is \"not ready\": falling back to the average here is exactly\n // what told an account holding 21.3B RC it could afford 17 more posts.\n if (!rcParams?.resource_params || !rcParams.size_info || !rcStats.pool || !rcStats.share) {\n return null;\n }\n\n const stats = { pool: rcStats.pool, regen: rcStats.regen, share: rcStats.share };\n\n if (operation === \"vote_operation\") {\n const op: VoteLike = payload?.kind === \"vote\" ? payload.op : MINIMAL_VOTE;\n const transactionBytes = estimateVoteTransactionBytes(op);\n const usage = countVoteResourceUsage({ transactionBytes }, rcParams.size_info);\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n }\n\n const op: CommentLike = payload?.kind === \"comment\" ? payload.op : MINIMAL_COMMENT;\n const options = payload?.kind === \"comment\" ? payload.options : undefined;\n const transactionBytes = estimateCommentTransactionBytes({ op, options });\n const usage = countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength: op.permlink.length,\n beneficiaries: options?.beneficiaries?.length ?? 0,\n hasCommentOptions: !!options\n },\n rcParams.size_info\n );\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n}\n\n/** The network average the chain publishes for an operation, when it has one. */\nfunction averageCost(\n rcStats: RcStats,\n operation: RcPrecheckOperation\n): { cost: number; transactionBytes: number } | null {\n const cost = rcStats.ops[operation]?.avg_cost;\n return typeof cost === \"number\" && cost > 0 ? { cost, transactionBytes: 0 } : null;\n}\n\n/** Smallest realistic operations, used only when the caller has no payload yet. */\nconst MINIMAL_COMMENT: CommentLike = {\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\",\n parent_author: \"\",\n parent_permlink: \"hive-100000\",\n title: \"\",\n body: \"\",\n json_metadata: \"{}\"\n};\n\nconst MINIMAL_VOTE: VoteLike = {\n voter: \"aaaaaaaaaa\",\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\"\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\n/**\n * POST a single game claim and return the parsed JSON body.\n *\n * A failed post-game comes back from the edge as an HTML gateway page (a 502 was\n * the trail on ECENCY-NEXT-1FCJ), and `response.json()` on that throws a bare\n * `SyntaxError` naming neither the endpoint nor the cause. Check the status and\n * the content type first, then fail with a STABLE, low-cardinality message\n * (content type + status, never the raw body) so these group as a single Sentry\n * issue instead of fragmenting on every distinct error page.\n *\n * Exported for unit testing; the hook below wraps it.\n */\nexport async function gameClaimRequest(\n code: string,\n gameType: \"spin\",\n key: string\n): Promise {\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 // 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 // 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 page.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Games] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Games] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body) as GameClaim;\n } catch {\n throw new Error(\n `[SDK][Games] – malformed JSON response (status ${response.status})`\n );\n }\n}\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 return gameClaimRequest(code, gameType, key);\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","/**\n * Thresholds behind the content moderation treatment. Single source of truth for\n * every client: web and mobile previously carried their own copies, which drifted\n * (mobile flagged downvoted content at -7B rshares and 4 voters where web used\n * -10B and 5), so the same post read differently depending on the app.\n */\n\n/** Sum of rshares below which a post counts as heavily downvoted. */\nexport const HIDDEN_POST_RSHARES_THRESHOLD = -10000000000;\n\n/** Downvoting is only conclusive once enough accounts have voted. */\nexport const HIDDEN_POST_MIN_VOTES = 5;\n\n/**\n * Reputation (human-readable 0-100 scale) below which an author counts as\n * low-trust. New Hive accounts start around 25.\n *\n * NOTE: reputation is the only input. Account age is NOT part of the check, so a\n * years-old account that never earned reputation trips it exactly like a fresh\n * one. User-facing copy must say \"low reputation\", never \"new account\".\n */\nexport const LOW_TRUST_REPUTATION_THRESHOLD = 30;\n","/**\n * Converts Hive's raw reputation to the human-readable 0-100 scale, passing\n * through values that are already on it (the bridge returns both shapes\n * depending on the endpoint).\n */\nconst isHumanReadable = (input: number): boolean =>\n Math.abs(input) > 0 && Math.abs(input) <= 100;\n\nexport function accountReputation(input: string | number): number {\n if (typeof input === \"number\" && isHumanReadable(input)) {\n return Math.floor(input);\n }\n\n if (typeof input === \"string\") {\n input = Number(input);\n\n if (isHumanReadable(input)) {\n return Math.floor(input);\n }\n }\n\n if (input === 0) {\n return 25;\n }\n\n let neg = false;\n\n if (input < 0) {\n neg = true;\n }\n\n let reputationLevel = Math.log10(Math.abs(input as number));\n reputationLevel = Math.max(reputationLevel - 9, 0);\n\n if (reputationLevel < 0) {\n reputationLevel = 0;\n }\n\n if (neg) {\n reputationLevel *= -1;\n }\n\n reputationLevel = reputationLevel * 9 + 25;\n\n return Math.floor(reputationLevel);\n}\n","/**\n * Outbound-link detection for the SEO/backlink-farm signal.\n *\n * A link only counts as outbound promotion when it leaves the Hive/Ecency\n * ecosystem and is not an embedded image, so ordinary on-platform references and\n * post illustrations never trip the check.\n */\n\n// Hosts that are part of the Hive/Ecency ecosystem.\nconst INTERNAL_HOSTS = [\n \"ecency.com\",\n \"ecency.app\",\n \"hive.blog\",\n \"hive.io\",\n \"hiveblocks.com\",\n \"peakd.com\",\n \"snapie.io\",\n \"hivesuite.app\",\n \"leofinance.io\",\n \"inleo.io\",\n \"3speak.tv\",\n \"d.buzz\",\n \"waivio.com\"\n];\n\n// Image/media hosts: an embedded image is content, not a backlink.\nconst IMAGE_HOSTS = [\n \"imgur.com\",\n \"images.hive.blog\",\n \"files.peakd.com\",\n \"i.ecency.com\",\n \"images.ecency.com\",\n \"steemitimages.com\",\n \"cdn.steemitimages.com\",\n \"media.giphy.com\"\n];\n\nconst IMAGE_EXT_RE = /\\.(jpe?g|png|gif|webp|svg|bmp|avif)(\\?|#|$)/i;\n// Match absolute AND protocol-relative URLs (\"//host/...\"), so the check can't be\n// evaded with `[promo](//shop.example)` (the renderer allows protocol-relative hrefs).\nconst URL_RE = /(?:https?:)?\\/\\/[^\\s)<>\"'\\]]+/gi;\n// URLs in prose are commonly followed by punctuation (\"https://ecency.com, and...\");\n// strip it so the host parses correctly and internal links do not false-positive.\nconst TRAILING_PUNCT_RE = /[.,;:!?'\"]+$/;\n\nfunction hostOf(url: string): string {\n const m = /^(?:https?:)?\\/\\/([^/?#]+)/i.exec(url);\n return m ? m[1].toLowerCase().replace(/^www\\./, \"\") : \"\";\n}\n\nfunction isExternalPromoLink(rawUrl: string): boolean {\n const url = rawUrl.replace(TRAILING_PUNCT_RE, \"\");\n if (IMAGE_EXT_RE.test(url)) {\n return false; // embedded image, not a backlink\n }\n const host = hostOf(url);\n if (!host.includes(\".\")) {\n return false; // not a real domain (e.g. a stray \"//something\")\n }\n const matches = (h: string) => host === h || host.endsWith(\".\" + h);\n if (INTERNAL_HOSTS.some(matches) || IMAGE_HOSTS.some(matches)) {\n return false; // Hive/Ecency or image host\n }\n return true;\n}\n\n/** True if the post body contains an outbound (non-Hive, non-image) link. */\nexport function hasExternalLink(body: string | undefined | null): boolean {\n if (!body) {\n return false;\n }\n const matches = body.match(URL_RE);\n if (!matches) {\n return false;\n }\n return matches.some(isExternalPromoLink);\n}\n","import { accountReputation } from \"./account-reputation\";\nimport {\n HIDDEN_POST_MIN_VOTES,\n HIDDEN_POST_RSHARES_THRESHOLD,\n LOW_TRUST_REPUTATION_THRESHOLD\n} from \"./constants\";\nimport { hasExternalLink } from \"./external-links\";\n\n/**\n * Why a piece of content gets the moderation treatment. Clients render their own\n * copy per reason; the rules that pick the reason live here so web and mobile\n * always agree on which one fired.\n */\nexport enum ContentModerationReason {\n /**\n * `stats.gray` / `stats.hide` from hivemind: community moderator mutes, mutes\n * applied by the observer account, and authors hivemind itself grays out.\n */\n MOD_MUTED = \"mod_muted\",\n /** Heavily downvoted by enough distinct accounts to be conclusive. */\n DOWNVOTED = \"downvoted\",\n /** Low-reputation author whose post carries an outbound promotional link. */\n LOW_TRUST = \"low_trust\"\n}\n\n/**\n * The fields of a post or comment the rules read. Deliberately structural: web\n * passes an `Entry`, mobile passes a raw bridge post, and neither has to convert.\n */\nexport interface ModerationCandidate {\n author?: string;\n author_reputation?: string | number;\n body?: string | null;\n net_rshares?: number;\n active_votes?: unknown[] | null;\n stats?: {\n gray?: boolean;\n hide?: boolean;\n total_votes?: number;\n } | null;\n}\n\n/**\n * hivemind's `total_votes` is the authoritative count when present; `active_votes`\n * is the fallback for the feeds that omit stats.\n */\nfunction countVotes(content: ModerationCandidate): number {\n return content?.stats?.total_votes ?? content?.active_votes?.length ?? 0;\n}\n\n/** Heavily downvoted: strongly negative rshares from more than a handful of voters. */\nexport function isHiddenPost(\n netRshares: number | undefined,\n activeVotesLength: number\n): boolean {\n return (\n (netRshares ?? 0) < HIDDEN_POST_RSHARES_THRESHOLD &&\n activeVotesLength >= HIDDEN_POST_MIN_VOTES\n );\n}\n\n/**\n * Content-moderation signal for SEO/backlink-farm abuse: low-reputation accounts\n * publishing an outbound link are the signature of free-faucet SEO spam.\n *\n * Such posts are not blocked, they are de-emphasized and their outbound link is\n * flagged as unverified, so the promotional payoff drops to zero. Low reputation\n * on its own is NOT a moderation signal: plenty of small accounts post ordinary\n * content, and dimming all of them punishes newcomers for existing.\n */\nexport function isLowTrustSeoPost(\n content: Pick\n): boolean {\n const reputation = content?.author_reputation;\n // Some feeds omit reputation entirely. An unknown value is not evidence of\n // anything, so it must not be read as \"brand new account\" (raw 0 scales to 25,\n // which is below the threshold and would flag every post carrying a link).\n if (reputation === undefined || reputation === null) {\n return false;\n }\n return (\n accountReputation(reputation) < LOW_TRUST_REPUTATION_THRESHOLD &&\n hasExternalLink(content?.body)\n );\n}\n\n/** True when the viewer has personally muted this author. */\nexport function isAuthorMuted(\n author: string | undefined,\n mutedAuthors: string[] | undefined | null\n): boolean {\n return !!author && !!mutedAuthors?.includes(author);\n}\n\n/**\n * The reason a post or comment should be de-emphasized, or null when it is fine.\n *\n * Precedence, most authoritative first: an explicit moderation action outranks\n * the vote heuristic, which outranks the spam heuristic. Order matters because a\n * heavily downvoted post usually also has a battered reputation, and labelling\n * that \"low trust\" would hide why the content was actually flagged.\n *\n * A viewer's personal mute list is NOT an input here. Muting an author removes\n * their content from the viewer's lists entirely (see `isAuthorMuted`), rather\n * than labelling it.\n */\nexport function getContentModerationReason(\n content: ModerationCandidate | undefined | null\n): ContentModerationReason | null {\n if (!content) {\n return null;\n }\n if (content.stats?.gray || content.stats?.hide) {\n return ContentModerationReason.MOD_MUTED;\n }\n if (isHiddenPost(content.net_rshares, countVotes(content))) {\n return ContentModerationReason.DOWNVOTED;\n }\n if (isLowTrustSeoPost(content)) {\n return ContentModerationReason.LOW_TRUST;\n }\n return null;\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport type {\n DigestSubscribeInput,\n DigestSubscribeResult,\n DigestSubscription,\n NewsletterCandidatePost,\n NewsletterListType,\n NewsletterSendPreview,\n NewsletterSendRequest,\n NewsletterSendResult,\n NewsletterSenderStanding,\n NewsletterSentIssue,\n} from \"./types\";\n\n/**\n * Client for the newsletter relay at {privateApiHost}/api/newsletter/*\n * (Next.js route handlers on ecency.com, which alone hold the news-service\n * credentials — clients never talk to the service directly).\n *\n * Identity is the HiveSigner access token, passed here as the explicit `code`\n * argument. Transport mirrors the deployed web client per route: subscribe and\n * unsubscribe-all carry it in the POST body as `code` (the subscribe route\n * authenticates ONLY from the body — a header alone is treated as anonymous);\n * every other call, the send/preview POSTs included, uses the `X-HS-Token`\n * header. The relay verifies it upstream and derives the account from it, so\n * a stale token 401s — callers are responsible for supplying a fresh one\n * (web: ensureValidToken; mobile: the token-refresh wrapper).\n *\n * The email-token confirm/unsubscribe flows are deliberately absent: those\n * links land on web pages.\n */\nexport class NewsletterApiError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly data?: unknown,\n ) {\n super(message);\n }\n}\n\n/** A refused send, carrying the relay's routing `code` (already_sent, suspended, ...). */\nexport class NewsletterSendRefusedError extends NewsletterApiError {\n constructor(\n message: string,\n status: number,\n public readonly code?: string,\n public readonly taken?: Array<{ cadence: string; period: string; kind: string }>,\n data?: unknown,\n ) {\n super(message, status, data);\n }\n}\n\nfunction newsletterUrl(path: string): string {\n return `${CONFIG.privateApiHost}/api/newsletter${path}`;\n}\n\nasync function parse(response: Response): Promise {\n const data = (await response.json().catch(() => undefined)) as\n | (T & { error?: string })\n | undefined;\n if (!response.ok) {\n throw new NewsletterApiError(\n data?.error || `Request failed (${response.status})`,\n response.status,\n data,\n );\n }\n // A 2xx without a JSON body is not a result; saying so beats returning blanks.\n if (!data || typeof data !== \"object\") {\n throw new NewsletterApiError(\n `Unexpected response (${response.status})`,\n response.status,\n );\n }\n return data;\n}\n\n/**\n * Subscribe an address to a digest. Authenticated callers (code given) skip\n * the captcha; anonymous callers must supply `captchaToken` in the input and\n * get double opt-in. The `own` digest type is always authenticated.\n */\nexport async function subscribeDigestRequest(\n input: DigestSubscribeInput,\n code?: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(\"/subscribe\"), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ ...input, ...(code ? { code } : {}) }),\n });\n return parse(response);\n}\n\n/** Every live digest subscription attributed to the token's account. */\nexport async function getDigestSubscriptionsRequest(\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(\"/subscriptions\"), {\n headers: { \"X-HS-Token\": code },\n });\n const data = await parse<{ subscriptions?: DigestSubscription[] }>(response);\n return data.subscriptions ?? [];\n}\n\n/** Leave one digest by subscription id. */\nexport async function leaveDigestRequest(\n id: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(`/subscriptions/${encodeURIComponent(id)}`),\n { method: \"DELETE\", headers: { \"X-HS-Token\": code } },\n );\n await parse<{ left: boolean }>(response);\n}\n\n/**\n * Suppress ONE address entirely (no Ecency bulk mail to it again). Only that\n * address stops: an account can hold subscriptions under several addresses.\n */\nexport async function unsubscribeAllDigestsRequest(\n email: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(\"/unsubscribe-all\"), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email, code }),\n });\n await parse<{ suppressed: boolean }>(response);\n}\n\n/** Sender standing (status, complaint/bounce stats, subscriber counts) for a list. */\nexport async function getNewsletterSenderRequest(\n type: NewsletterListType,\n target: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(`/sender?type=${type}&target=${encodeURIComponent(target)}`),\n { headers: { \"X-HS-Token\": code } },\n );\n return parse(response);\n}\n\n/** Already-sent issues for a list, newest first. */\nexport async function getNewsletterIssuesRequest(\n type: NewsletterListType,\n target: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(`/issues?type=${type}&target=${encodeURIComponent(target)}`),\n { headers: { \"X-HS-Token\": code } },\n );\n const data = await parse<{ issues?: NewsletterSentIssue[] }>(response);\n return data.issues ?? [];\n}\n\n/** Candidate posts for composing a digest issue. */\nexport async function getNewsletterPostsRequest(\n type: NewsletterListType,\n target: string,\n code: string,\n limit = 20,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(\n `/posts?type=${type}&target=${encodeURIComponent(target)}&limit=${limit}`,\n ),\n { headers: { \"X-HS-Token\": code } },\n );\n const data = await parse<{ posts?: NewsletterCandidatePost[] }>(response);\n return data.posts ?? [];\n}\n\nasync function postSend(\n path: string,\n request: NewsletterSendRequest,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(path), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-HS-Token\": code },\n body: JSON.stringify(request),\n });\n const data = (await response.json().catch(() => undefined)) as\n | (T & {\n error?: string;\n code?: string;\n taken?: NewsletterSendRefusedError[\"taken\"];\n })\n | undefined;\n if (!response.ok) {\n throw new NewsletterSendRefusedError(\n data?.error || `Request failed (${response.status})`,\n response.status,\n data?.code,\n data?.taken,\n data,\n );\n }\n if (!data || typeof data !== \"object\") {\n throw new NewsletterSendRefusedError(\n `Unexpected response (${response.status})`,\n response.status,\n );\n }\n return data;\n}\n\n/** Render the would-be issue (subject/html/text, counts, taken periods) without sending. */\nexport function previewNewsletterSendRequest(\n request: NewsletterSendRequest,\n code: string,\n): Promise {\n return postSend(\"/send/preview\", request, code);\n}\n\n/** Send a post or composed digest to the list's subscribers. Pro/team gated by the relay. */\nexport function sendNewsletterIssueRequest(\n request: NewsletterSendRequest,\n code: string,\n): Promise {\n return postSend(\"/send\", request, code);\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getDigestSubscriptionsRequest } from \"../api\";\n\n/**\n * The signed-in account's live digest subscriptions. Disabled without a\n * username + token: callers render nothing then, and a request that\n * predictably 401s is noise. `retry: false` because the common failure is a\n * stale token, which a retry with the same token cannot fix.\n */\nexport function getDigestSubscriptionsQueryOptions(\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.subscriptions(name),\n enabled: !!name && !!code,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getDigestSubscriptionsRequest(code);\n },\n staleTime: 60_000,\n retry: false,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getNewsletterSenderRequest } from \"../api\";\nimport type { NewsletterListType } from \"../types\";\n\n/**\n * Sender standing for a creator/community list. View access is the list's\n * owner (creator) or the community team, decided by the relay — enable this\n * only for callers already known to be the sender.\n */\nexport function getNewsletterSenderQueryOptions(\n type: NewsletterListType,\n target: string,\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.sender(type, target, name),\n enabled: !!name && !!code && !!target,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getNewsletterSenderRequest(type, target, code);\n },\n staleTime: 5 * 60_000,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getNewsletterIssuesRequest } from \"../api\";\nimport type { NewsletterListType } from \"../types\";\n\n/** Already-sent issues for a creator/community list (sender-only view). */\nexport function getNewsletterIssuesQueryOptions(\n type: NewsletterListType,\n target: string,\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.issues(type, target, name),\n enabled: !!name && !!code && !!target,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getNewsletterIssuesRequest(type, target, code);\n },\n staleTime: 60_000,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getNewsletterPostsRequest } from \"../api\";\nimport type { NewsletterListType } from \"../types\";\n\n/** Candidate posts for composing a digest issue (send-gated by the relay). */\nexport function getNewsletterPostsQueryOptions(\n type: NewsletterListType,\n target: string,\n username: string | undefined,\n code: string | undefined,\n limit = 20,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.posts(type, target, name, limit),\n enabled: !!name && !!code && !!target,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getNewsletterPostsRequest(type, target, code, limit);\n },\n staleTime: 60_000,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { subscribeDigestRequest } from \"../api\";\nimport type { DigestSubscribeInput } from \"../types\";\n\n/**\n * Subscribe to a digest (also re-used to change cadence: same list + address\n * with a new cadence updates the row). Works signed-in (code) and anonymous\n * (input.captchaToken); the signed-in path refreshes the account's\n * subscriptions list on success.\n */\nexport function useSubscribeDigest(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"subscribe\", name],\n mutationFn: (input: DigestSubscribeInput) =>\n subscribeDigestRequest(input, code),\n onSuccess() {\n if (name) {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.newsletter.subscriptions(name),\n });\n }\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { leaveDigestRequest } from \"../api\";\nimport type { DigestSubscription } from \"../types\";\n\n/** Leave one digest by subscription id; drops the row from the cached list. */\nexport function useLeaveDigest(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"leave\", name],\n mutationFn: async (id: string) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return leaveDigestRequest(id, code);\n },\n onSuccess(_result, id) {\n queryClient.setQueryData(\n QueryKeys.newsletter.subscriptions(name),\n (prev) => (prev ?? []).filter((s) => s.id !== id),\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { unsubscribeAllDigestsRequest } from \"../api\";\nimport type { DigestSubscription } from \"../types\";\n\n/**\n * Stop all Ecency mail to ONE address. Only that address's rows leave the\n * cached list: an account can hold subscriptions under more than one address,\n * and those stay visible.\n */\nexport function useUnsubscribeAllDigests(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"unsubscribe-all\", name],\n mutationFn: async (email: string) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return unsubscribeAllDigestsRequest(email, code);\n },\n onSuccess(_result, email) {\n queryClient.setQueryData(\n QueryKeys.newsletter.subscriptions(name),\n (prev) =>\n (prev ?? []).filter(\n (s) => s.email.toLowerCase() !== email.toLowerCase(),\n ),\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport {\n previewNewsletterSendRequest,\n sendNewsletterIssueRequest,\n} from \"../api\";\nimport type { NewsletterSendRequest } from \"../types\";\n\n/**\n * Preview the would-be issue. No cache side effects: a preview changes\n * nothing server-side.\n */\nexport function usePreviewNewsletterIssue(\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return useMutation({\n mutationKey: [\"newsletter\", \"send-preview\", name],\n mutationFn: async (request: NewsletterSendRequest) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return previewNewsletterSendRequest(request, code);\n },\n });\n}\n\n/**\n * Send a post or composed digest to a list. Errors are\n * NewsletterSendRefusedError with the relay's routing `code`\n * (already_sent + taken periods, suspended, post_refused, ...). On success the\n * list's issues + sender standing refresh.\n */\nexport function useSendNewsletterIssue(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"send\", name],\n mutationFn: async (request: NewsletterSendRequest) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return sendNewsletterIssueRequest(request, code);\n },\n onSuccess(_result, request) {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.newsletter.issues(request.type, request.target, name),\n });\n queryClient.invalidateQueries({\n queryKey: QueryKeys.newsletter.sender(request.type, request.target, name),\n });\n },\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 d7cc816b1e..e798cc298c 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 vn 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 uo from'hivesigner';var $i=Object.defineProperty;var vt=(e,t)=>{for(var r in t)$i(e,r,{get:t[r],enumerable:true});};var Pt=new ArrayBuffer(0),At=null,Ot=null;function Wi(){return At||(typeof TextEncoder<"u"?At=new TextEncoder:At={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)}}),At}function mn(){return Ot||(typeof TextDecoder<"u"?Ot=new TextDecoder:Ot={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+(i&1023)));}return r}}),Ot}var D=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?Pt:new ArrayBuffer(t),this.view=t===0?new DataView(Pt):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(Pt));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 o;return t instanceof e?(o=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=o.length):t instanceof Uint8Array?o=t:t instanceof ArrayBuffer?o=new Uint8Array(t):o=new Uint8Array(t),o.length<=0?this:(r+o.length>this.buffer.byteLength&&this.resize(r+o.length),new Uint8Array(this.buffer).set(o,r),n&&(this.offset+=o.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,o=new e(n,this.littleEndian);return o.offset=0,o.limit=n,new Uint8Array(o.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),o}copyTo(t,r,n,o){let i=typeof r>"u",s=typeof n>"u";r=i?t.offset:r,n=s?this.offset:n,o=o===void 0?this.limit:o;let a=o-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,o),r),s&&(this.offset+=a),i&&(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?Pt: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 o=this.calculateVarint32(t);for(r+o>this.buffer.byteLength&&this.resize(r+o),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):o}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,o=0,i;do i=this.view.getUint8(t++),n<5&&(o|=(i&127)<<7*n),++n;while((i&128)!==0);return o|=0,r?(this.offset=t,o):{value:o,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",o=n?this.offset:r,i=Wi().encode(t),s=i.length,a=this.calculateVarint32(s);return o+a+s>this.buffer.byteLength&&this.resize(o+a+s),this.writeVarint32(s,o),o+=a,new Uint8Array(this.buffer).set(i,o),o+=s,n?(this.offset=o,this):o-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,o=this.readVarint32(t),i=o.value,s=o.length;t+=s;let a=mn().decode(new Uint8Array(this.buffer,t,i));return t+=i,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 o=mn().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,o):{string:o,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}},gn=["bridge.get_ranked_posts","bridge.get_account_posts","bridge.get_post","bridge.get_discussion","bridge.get_profile","bridge.get_profiles","bridge.get_community","bridge.list_communities","condenser_api.get_accounts","condenser_api.get_content","condenser_api.get_dynamic_global_properties","condenser_api.get_trending_tags"],xt=null,rr=e=>{if(e===null){xt=null;return}if(!e||typeof e!="object")return;let t=typeof e.url=="string"?e.url.trim():"";if(!/^https?:\/\//i.test(t))return;let r={};if(e.headers&&typeof e.headers=="object")for(let[s,a]of Object.entries(e.headers))typeof a=="string"&&a&&!/[\u0000-\u001f\u007f]/.test(a)&&!/[\u0000-\u001f\u007f]/.test(s)&&(r[s]=a);let n=typeof e.timeoutMs=="number"&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:2e3,o=e.methods===void 0?[...gn]:Array.isArray(e.methods)?e.methods.filter(s=>typeof s=="string"&&s.includes(".")):[];if(o.length===0)return;let i=(s,a)=>typeof s=="number"&&Number.isFinite(s)&&s>0?s:a;xt={url:t,headers:r,timeoutMs:n,methods:o,failureThreshold:Math.floor(i(e.failureThreshold,3)),cooldownMs:i(e.cooldownMs,1e4),methodSet:new Set(o)};},nr=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)))]:[],or=e=>{let t=nr(e);t.length&&(x.nodes=t);},ir=e=>{let t=nr(e);t.length&&(x.restNodes=t);},sr=e=>{if(!e||typeof e!="object")return;let t={...x.restNodesByApi};for(let[r,n]of Object.entries(e)){let o=nr(n);o.length?t[r]=o:delete t[r];}x.restNodesByApi=t;},ar=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(x.userAgent=t);},cr=e=>{if(!e||typeof e!="object")return;let t=x.resilience,r=o=>typeof o=="boolean",n=o=>typeof o=="number"&&Number.isFinite(o)&&o>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 Ee=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,o=true;n<0&&(o=false,n=n+4);let i=r.subarray(1);return new e(i,n,o)}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 Y(n.recoverPublicKey(t).toBytes())}};var Y=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 o;try{o=vn.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(o.length!==37)throw new Error("Invalid public key length");let i=o.subarray(0,33),s=o.subarray(33,37),a=ripemd160(i).subarray(0,4);if(!zi(s,a))throw new Error("Public key checksum mismatch");try{secp256k1.Point.fromBytes(i);}catch{throw new Error("Invalid public key")}return new e(i,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=Ee.from(r)),secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return Gi(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},Gi=(e,t)=>{let r=ripemd160(e);return t+vn.encode(new Uint8Array([...e,...r.subarray(0,4)]))},zi=(e,t)=>{if(e.byteLength!==t.byteLength)return false;for(let r=0;r{throw new Error("Void can not be serialized")},b=(e,t)=>{e.writeVString(t);},Xi=(e,t)=>{e.writeInt16(t);},An=(e,t)=>{e.writeInt64(t);},Pn=(e,t)=>{e.writeUint8(t);},pe=(e,t)=>{e.writeUint16(t);},X=(e,t)=>{e.writeUint32(t);},On=(e,t)=>{e.writeUint64(t);},be=(e,t)=>{e.writeByte(t?1:0);},xn=e=>(t,r)=>{let[n,o]=r;t.writeVarint32(n),e[n](t,o);},q=(e,t)=>{let r=Et.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let o=0;o<7;o++)e.writeUint8(r.symbol.charCodeAt(o)||0);},Se=(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(Y.from(t).key);},En=(e=null)=>(t,r)=>{r=St.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);},Sn=En(),ur=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[o,i]of n)e(r,o),t(r,i);},V=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},le=e=>(t,r)=>{for(let[n,o]of e)try{o(t,r[n]);}catch(i){throw i.message=`${n}: ${i.message}`,i}},Ie=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},W=le([["weight_threshold",X],["account_auths",ur(b,pe)],["key_auths",ur(ge,pe)]]),Zi=le([["account",b],["weight",pe]]),pr=le([["base",q],["quote",q]]),es=le([["account_creation_fee",q],["maximum_block_size",X],["hbd_interest_rate",pe]]),R=(e,t)=>{let r=le(t);return (n,o)=>{n.writeVarint32(e),r(n,o);}},S={};S.account_create=R(C.account_create,[["fee",q],["creator",b],["new_account_name",b],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",b]]);S.account_create_with_delegation=R(C.account_create_with_delegation,[["fee",q],["delegation",q],["creator",b],["new_account_name",b],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",b],["extensions",V(ie)]]);S.account_update=R(C.account_update,[["account",b],["owner",Ie(W)],["active",Ie(W)],["posting",Ie(W)],["memo_key",ge],["json_metadata",b]]);S.account_witness_proxy=R(C.account_witness_proxy,[["account",b],["proxy",b]]);S.account_witness_vote=R(C.account_witness_vote,[["account",b],["witness",b],["approve",be]]);S.cancel_transfer_from_savings=R(C.cancel_transfer_from_savings,[["from",b],["request_id",X]]);S.change_recovery_account=R(C.change_recovery_account,[["account_to_recover",b],["new_recovery_account",b],["extensions",V(ie)]]);S.claim_account=R(C.claim_account,[["creator",b],["fee",q],["extensions",V(ie)]]);S.claim_reward_balance=R(C.claim_reward_balance,[["account",b],["reward_hive",q],["reward_hbd",q],["reward_vests",q]]);S.comment=R(C.comment,[["parent_author",b],["parent_permlink",b],["author",b],["permlink",b],["title",b],["body",b],["json_metadata",b]]);S.comment_options=R(C.comment_options,[["author",b],["permlink",b],["max_accepted_payout",q],["percent_hbd",pe],["allow_votes",be],["allow_curation_rewards",be],["extensions",V(xn([le([["beneficiaries",V(Zi)]])]))]]);S.convert=R(C.convert,[["owner",b],["requestid",X],["amount",q]]);S.create_claimed_account=R(C.create_claimed_account,[["creator",b],["new_account_name",b],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",b],["extensions",V(ie)]]);S.custom=R(C.custom,[["required_auths",V(b)],["id",pe],["data",Sn]]);S.custom_json=R(C.custom_json,[["required_auths",V(b)],["required_posting_auths",V(b)],["id",b],["json",b]]);S.decline_voting_rights=R(C.decline_voting_rights,[["account",b],["decline",be]]);S.delegate_vesting_shares=R(C.delegate_vesting_shares,[["delegator",b],["delegatee",b],["vesting_shares",q]]);S.delete_comment=R(C.delete_comment,[["author",b],["permlink",b]]);S.escrow_approve=R(C.escrow_approve,[["from",b],["to",b],["agent",b],["who",b],["escrow_id",X],["approve",be]]);S.escrow_dispute=R(C.escrow_dispute,[["from",b],["to",b],["agent",b],["who",b],["escrow_id",X]]);S.escrow_release=R(C.escrow_release,[["from",b],["to",b],["agent",b],["who",b],["receiver",b],["escrow_id",X],["hbd_amount",q],["hive_amount",q]]);S.escrow_transfer=R(C.escrow_transfer,[["from",b],["to",b],["hbd_amount",q],["hive_amount",q],["escrow_id",X],["agent",b],["fee",q],["json_meta",b],["ratification_deadline",Se],["escrow_expiration",Se]]);S.feed_publish=R(C.feed_publish,[["publisher",b],["exchange_rate",pr]]);S.limit_order_cancel=R(C.limit_order_cancel,[["owner",b],["orderid",X]]);S.limit_order_create=R(C.limit_order_create,[["owner",b],["orderid",X],["amount_to_sell",q],["min_to_receive",q],["fill_or_kill",be],["expiration",Se]]);S.limit_order_create2=R(C.limit_order_create2,[["owner",b],["orderid",X],["amount_to_sell",q],["exchange_rate",pr],["fill_or_kill",be],["expiration",Se]]);S.recover_account=R(C.recover_account,[["account_to_recover",b],["new_owner_authority",W],["recent_owner_authority",W],["extensions",V(ie)]]);S.request_account_recovery=R(C.request_account_recovery,[["recovery_account",b],["account_to_recover",b],["new_owner_authority",W],["extensions",V(ie)]]);S.reset_account=R(C.reset_account,[["reset_account",b],["account_to_reset",b],["new_owner_authority",W]]);S.set_reset_account=R(C.set_reset_account,[["account",b],["current_reset_account",b],["reset_account",b]]);S.set_withdraw_vesting_route=R(C.set_withdraw_vesting_route,[["from_account",b],["to_account",b],["percent",pe],["auto_vest",be]]);S.transfer=R(C.transfer,[["from",b],["to",b],["amount",q],["memo",b]]);S.transfer_from_savings=R(C.transfer_from_savings,[["from",b],["request_id",X],["to",b],["amount",q],["memo",b]]);S.transfer_to_savings=R(C.transfer_to_savings,[["from",b],["to",b],["amount",q],["memo",b]]);S.transfer_to_vesting=R(C.transfer_to_vesting,[["from",b],["to",b],["amount",q]]);S.vote=R(C.vote,[["voter",b],["author",b],["permlink",b],["weight",Xi]]);S.withdraw_vesting=R(C.withdraw_vesting,[["account",b],["vesting_shares",q]]);S.witness_update=R(C.witness_update,[["owner",b],["url",b],["block_signing_key",ge],["props",es],["fee",q]]);S.witness_set_properties=R(C.witness_set_properties,[["owner",b],["props",ur(b,Sn)],["extensions",V(ie)]]);S.account_update2=R(C.account_update2,[["account",b],["owner",Ie(W)],["active",Ie(W)],["posting",Ie(W)],["memo_key",Ie(ge)],["json_metadata",b],["posting_json_metadata",b],["extensions",V(ie)]]);S.create_proposal=R(C.create_proposal,[["creator",b],["receiver",b],["start_date",Se],["end_date",Se],["daily_pay",q],["subject",b],["permlink",b],["extensions",V(ie)]]);S.update_proposal_votes=R(C.update_proposal_votes,[["voter",b],["proposal_ids",V(An)],["approve",be],["extensions",V(ie)]]);S.remove_proposal=R(C.remove_proposal,[["proposal_owner",b],["proposal_ids",V(An)],["extensions",V(ie)]]);var ts=le([["end_date",Se]]);S.update_proposal=R(C.update_proposal,[["proposal_id",On],["creator",b],["daily_pay",q],["subject",b],["permlink",b],["extensions",V(xn([ie,ts]))]]);S.collateralized_convert=R(C.collateralized_convert,[["owner",b],["requestid",X],["amount",q]]);S.recurrent_transfer=R(C.recurrent_transfer,[["from",b],["to",b],["amount",q],["memo",b],["recurrence",pe],["executions",pe],["extensions",V(le([["type",Pn],["value",le([["pair_id",Pn]])]]))]]);var rs=(e,t)=>{let r=S[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}},ns=le([["ref_block_num",pe],["ref_block_prefix",X],["expiration",Se],["operations",V(rs)],["extensions",V(b)]]),os=le([["from",ge],["to",ge],["nonce",On],["check",X],["encrypted",En()]]),de={Asset:q,Memo:os,Price:pr,PublicKey:ge,String:b,Transaction:ns,UInt16:pe,UInt32:X};var ot=e=>new Promise(t=>setTimeout(t,e));var In=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function gr(){return In?{"User-Agent":x.userAgent}:{}}var Ce={served:0,fallback:0,skipped:0,fallbackByReason:{status:0,rpcerror:0,timeout:0,transport:0,validate:0,parse:0}},Re=class extends Error{constructor(r,n){super(n);this.reason=r;}reason},kn=e=>e instanceof Error?e.message:typeof e=="string"?e:String(e),kt=0,Cn=0;async function is(e,t,r,n,o,i){let s=t.indexOf(".");if(s<=0||s===t.length-1)throw new Re("transport",`method without an api prefix: ${t}`);let{signal:a,cleanup:c}=hr(Math.min(e.timeoutMs,n)),{signal:p,cleanup:l}=Ft(a,o);try{let d;try{d=await fetch(e.url,{method:"POST",body:JSON.stringify({api:t.slice(0,s),method:t.slice(s+1),params:r}),headers:{"Content-Type":"application/json",...gr(),...e.headers},signal:p});}catch(g){throw o?.aborted?g:new Re(a.aborted?"timeout":"transport",kn(g))}if(d.status!==200){try{await d.body?.cancel();}catch{}let g=d.status===502&&(d.headers.get("x-ssr-cache")??"").toUpperCase()==="RPCERROR";throw new Re(g?"rpcerror":"status",g?"proxy relayed a node error":`proxy answered ${d.status}`)}let m;try{m=await d.json();}catch(g){throw o?.aborted?g:new Re(a.aborted?"timeout":"parse",kn(g))}if(i&&!i(m))throw new Re("validate","proxy result rejected by validator");return m}finally{c(),l();}}var Z=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);}},qe=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 qn(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 ss=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],as=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function cs(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 us(e){if(!e)return false;if(e instanceof qe)return true;if(e instanceof Z)return false;let t=cs(e);return !!(ss.some(r=>t.includes(r))||as.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function lr(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function Dn(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var ps=1e4,ls=6e4,ds=12e4,Rn=2,Tn=6e4,Fn=12e4,fs=30,it=.3,dr=3,st=5*6e4,Kn=6e4,Bn=1e3,Mn=2e3,Rt=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,o){let i=this.getOrCreate(t);if(i.consecutiveFailures=0,i.rateLimitStreak=0,r){let s=i.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&i.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(i,n,o??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=dr&&o-i.updatedAt<=st?i.ewmaMs:void 0}return this.isLatencyUsable(n,o)?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 o=Date.now();if(t.latencyUpdatedAt>0&&o-t.latencyUpdatedAt>st&&(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=o,n!==void 0){let i=t.apiLatency.get(n);!i||o-i.updatedAt>st?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:o}):(i.ewmaMs=it*r+(1-it)*i.ewmaMs,i.sampleCount++,i.updatedAt=o);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(i.cooldownUntil>0&&i.cooldownUntil<=o||i.lastFailureTime>0&&o-i.lastFailureTime>3e4)&&(i.count=0,i.cooldownUntil=0),i.count++,i.lastFailureTime=o,i.count>=Rn&&(i.cooldownUntil=o+Tn),n.apiFailures.set(r,i);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};i.count=Math.max(i.count+1,Rn),i.lastFailureTime=o,i.cooldownUntil=o+Tn,i.defective=true,n.apiFailures.set(r,i);}recordRateLimit(t,r){let n=this.getOrCreate(t),o=Date.now();n.rateLimitStreak>0&&o-n.lastRateLimitAt>ds&&(n.rateLimitStreak=0);let i=typeof r=="number"&&Number.isFinite(r)&&r>0,s=i?r:Math.min(ps*2**n.rateLimitStreak,ls);i||n.rateLimitStreak++,n.lastRateLimitAt=o,n.rateLimitedUntil=i?o+s:Math.max(n.rateLimitedUntil,o+s),n.consecutiveFailures++,n.lastFailureTime=o;}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<=Fn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,o)=>n-o),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let o=Date.now();if(n.rateLimitedUntil>o||n.consecutiveFailures>=3&&o-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>o)return false}let i=this.consensusHeadBlock();return !(i>0&&n.headBlock>0&&o-n.headBlockUpdatedAt<=Fn&&i-n.headBlock>fs)}getOrderedNodes(t,r){let n=[],o=[];for(let c of t)this.isNodeHealthy(c,r)?n.push(c):o.push(c);if(n.length<=1)return [...n,...o];let i=Date.now(),s=n.map((c,p)=>({node:c,i:p,score:this.scoreNode(c,i)})).sort((c,p)=>c.score-p.score||c.i-p.i).map(c=>c.node),a=this.pickReprobeCandidate(n,i);return a&&s[0]!==a?[a,...s.filter(c=>c!==a),...o]:[...s,...o]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=dr&&r-t.latencyUpdatedAt<=st}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:Bn}pickReprobeCandidate(t,r){let n=r-Kn,o,i=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;}},mr=new fr;function Tt(e,t,r,n,o){let i=x.resilience;if(!i.adaptiveTimeout||o)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(i.adaptiveTimeoutFloorMs,i.adaptiveTimeoutFactor*s)))}function yr(e,t,r,n){r instanceof qe?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof Z?e.recordFailure(t,n):e.recordFailure(t);}function Nn(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let o=n.head_block_number;typeof o=="number"&&e.recordHeadBlock(t,o);}function ms(){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 hr(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(ms()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function Ft(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),o=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",o,{once:true});let i=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o);};return {signal:r.signal,cleanup:i}}var at=async(e,t,r,n=x.timeout,o=false,i)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:c,cleanup:p}=hr(n),{signal:l,cleanup:d}=Ft(c,i),m=()=>{p(),d();};try{let g=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...gr()},signal:l});if(g.status===429)throw new qe(e,"HTTP 429 Rate Limited",{rateLimitMs:qn(g.headers.get("Retry-After")),isRateLimit:!0});if(g.status>=500&&g.status<600)throw new qe(e,`HTTP ${g.status} from ${e}`);let h=await g.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 P=h.error;throw "message"in P&&"code"in P?new Z(P):h.error}throw h}catch(g){if(g instanceof Z||g instanceof qe||i?.aborted)throw g;if(o)return at(e,t,r,n,false,i);throw g}finally{m();}};function Ct(){return ot(50+Math.random()*50)}function gs(e){let{method:t,params:r,api:n,primary:o,hedgePool:i,callerTimeout:s,explicitTimeout:a,deadlineAt:c,externalSignal:p,onHedgeFired:l,validate:d}=e;return new Promise((m,g)=>{let h=false,P=0,O=false,T=false,F,ue,A=0,$=[],N=J=>{if(!h){h=true,ue!==void 0&&(clearTimeout(ue),ue=void 0);for(let I of $)I.signal.aborted||I.abort();J();}},H=(J,I)=>{P++;let me=new AbortController;$.push(me);let nt=Ft(me.signal,p),Li=Tt(j,J,t,s,a),tr=Date.now();I||(A=tr),at(J,t,r,Li,false,nt.signal).then(oe=>{if(nt.cleanup(),P--,I||(T=true),!h){if(d&&!d(oe)){if(j.recordDefectiveResponse(J,n),F=new Error(`[hive-tx] response validation failed for ${t} from ${J}`),!I&&!O){N(()=>g(F));return}P===0&&N(()=>g(F));return}j.recordSuccess(J,n,Date.now()-tr,t),Nn(j,J,t,oe),I?T||j.recordCensoredLatency(o,Date.now()-A,t):O||mr.refill(),N(()=>m(oe));}}).catch(oe=>{if(nt.cleanup(),P--,I||(T=true),!h){if(p?.aborted){N(()=>g(oe));return}if(oe instanceof Z&&!lr(oe.code,oe.message)){N(()=>g(oe));return}if(yr(j,J,oe,n),j.recordSlowFailure(J,Date.now()-tr,t),F=oe,!I&&!O){N(()=>g(oe));return}P===0&&N(()=>g(F));}});};H(o,false);let z=j.getUsableLatencyMs(o,t)??0,L=Tt(j,o,t,s,a),rt=Math.min(Math.max(x.resilience.hedgeDelayFloorMs,x.resilience.hedgeDelayFactor*z),.8*L);ue=setTimeout(()=>{if(ue=void 0,h||p?.aborted||Date.now()>=c)return;let J=i.filter(me=>j.isNodeHealthy(me,n));if(J.length===0)return;let I=J[Math.floor(Math.random()*J.length)];mr.trySpend()&&(O=true,l(I),H(I,true));},rt);})}var y=async(e,t=[],r,n=x.retry,o,i)=>{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=Dn(e),p=xt;if(p&&In&&p.methodSet.has(e))if(Date.now()=p.failureThreshold&&(Cn=Date.now()+p.cooldownMs,kt=0);}let l=Date.now()+x.resilience.totalBudgetFactor*a,d=new Set,m;for(let g=0;g<=n&&!(g>0&&Date.now()>=l);g++){let h=j.getOrderedNodes(x.nodes,c),P=h.find(F=>!d.has(F));P||(d.clear(),P=h[0]),d.add(P);let O=[];if(x.resilience.hedge&&j.getUsableLatencyMs(P,e)!==void 0&&(O=h.filter(F=>!d.has(F)&&j.isNodeHealthy(F,c)).slice(0,3)),O.length>0)try{return await gs({method:e,params:t,api:c,primary:P,hedgePool:O,callerTimeout:a,explicitTimeout:s,deadlineAt:l,externalSignal:o,onHedgeFired:F=>d.add(F),validate:i})}catch(F){if(F instanceof Z&&!lr(F.code,F.message)||o?.aborted)throw F;m=F,g{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 o=Dn(e),i=new Set,s;for(let a=0;a!i.has(l));if(!p)break;if(i.add(p),n?.aborted)throw new Error("Aborted");try{let l=await at(p,e,t,r,!1,n);return j.recordSuccess(p,o),l}catch(l){if(l instanceof Z||n?.aborted||(yr(j,p,l,o),s=l,!us(l)))throw l}}throw s},ys={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 te(e,t,r,n,o=x.retry,i){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,d=new Set,m,g=false;for(let h=0;h<=o&&!(h>0&&Date.now()>=c);h++){let P=ke.getOrderedNodes(l,e),O=P.find(I=>!d.has(I));O||(d.clear(),O=P[0]),d.add(O);let T=O+ys[e],F=t,ue=r||{},A=new Set;Object.entries(ue).forEach(([I,me])=>{F.includes(`{${I}}`)&&(F=F.replace(`{${I}}`,encodeURIComponent(String(me))),A.add(I));});let $=new URL(T+F);if(Object.entries(ue).forEach(([I,me])=>{A.has(I)||(Array.isArray(me)?me.forEach(nt=>$.searchParams.append(I,String(nt))):$.searchParams.set(I,String(me)));}),i?.aborted)throw new Error("Aborted");g=false;let{signal:N,cleanup:H}=hr(Tt(ke,O,p,a,s)),{signal:z,cleanup:L}=Ft(N,i),rt=()=>{H(),L();},J=Date.now();try{let I=await fetch($.toString(),{signal:z,headers:gr()});if(I.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(I.status===429)throw ke.recordRateLimit(O,qn(I.headers.get("Retry-After"))||void 0),g=!0,new Error(`HTTP 429 Rate Limited by ${O}`);if(I.status===503)throw ke.recordFailure(O,e),g=!0,new Error(`HTTP 503 Service Unavailable from ${O}`);if(!I.ok)throw ke.recordFailure(O,e),g=!0,new Error(`HTTP ${I.status} from ${O}`);return ke.recordSuccess(O,e,Date.now()-J,p),I.json()}catch(I){if(I?.message?.includes("HTTP 404")||i?.aborted)throw I;g||ke.recordFailure(O,e),ke.recordSlowFailure(O,Date.now()-J,p),m=I,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 i=(c=>{let p=[...c];for(let l=p.length-1;l>0;l--){let d=Math.floor(Math.random()*(l+1));[p[l],p[d]]=[p[d],p[l]];}return p})(x.nodes),s=Math.min(r,i.length),a=[];for(;s>0&&i.length>0;){let c=i.splice(0,s),p=[],l=[];for(let m=0;ml.push(g)).catch(()=>{}));await Promise.all(p),a.push(...l);let d=hs(a,r);if(d)return d;if(s=Math.min(r,i.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function hs(e,t){let r=new Map;for(let o of e){let i=JSON.stringify(o);r.has(i)||r.set(i,[]),r.get(i).push(o);}let n=Array.from(r.values()).find(o=>o.length>=t);return n?n[0]:null}var bs=hexToBytes(x.chain_id),De=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 o of t){let i=o.sign(r);this.transaction.signatures.push(i.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 Le("condenser_api.broadcast_transaction",[this.transaction]);}catch(i){if(!(i instanceof Z&&i.message.includes("Duplicate transaction check failed")))throw i}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await ot(1e3);let n=await this.checkStatus(),o=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&o{let r=await y("condenser_api.get_dynamic_global_properties",[]),n=hexToBytes(r.head_block_id),o=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),i=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:i,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:o,signatures:[]};}};var Ln=new Uint8Array([128]),U=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(As(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 o=0;o>6,128|i&63);else if(i>=55296&&i<=56319&&o+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else n.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(n);}return new e(sha256(t))}static fromLogin(t,r,n="active"){let o=t+n+r;return e.fromSeed(o)}sign(t){let r=secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(bytesToHex(r.subarray(0,1)),16);return Ee.from((n+31).toString(16)+bytesToHex(r.subarray(1)))}createPublic(t){return new Y(secp256k1.getPublicKey(this.key),t)}toString(){return Ps(new Uint8Array([...Ln,...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)}},$n=e=>sha256(sha256(e)),Ps=e=>{let t=$n(e);return vn.encode(new Uint8Array([...e,...t.slice(0,4)]))},As=e=>{let t=vn.decode(e);if(!Vn(t.slice(0,1),Ln))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),o=$n(n).slice(0,4);if(!Vn(r,o))throw new Error("Private key checksum mismatch");return n},Vn=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;nJn(e,t,n,r),zn=(e,t,r,n,o)=>Jn(e,t,r,n,o).message,Jn=(e,t,r,n,o)=>{let i=r,s=e.getSharedSecret(t),a=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);a.writeUint64(i),a.append(s),a.flip();let c=sha512(new Uint8Array(a.toBuffer())),p=c.subarray(32,48),l=c.subarray(0,32),d=sha256(c).subarray(0,4),m=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);m.append(d),m.flip();let g=m.readUint32();if(o!==void 0){if(g!==o)throw new Error("Invalid key");n=Ss(n,l,p);}else n=ks(n,l,p);return {nonce:i,message:n,checksum:g}},Ss=(e,t,r)=>{let n=e;return n=cbc(t,r).decrypt(n),n},ks=(e,t,r)=>{let n=e;return n=cbc(t,r).encrypt(n),n},br=null,Cs=()=>{if(br===null){let r=secp256k1.utils.randomSecretKey();br=r[0]<<8|r[1];}let e=BigInt(Date.now()),t=++br%65536;return e=e<{let t=Ds(e,33);return new Y(t)},Ts=e=>e.readUint64(),Fs=e=>e.readUint32(),Is=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},qs=e=>t=>{let r={},n=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);n.append(t),n.flip();for(let[o,i]of e)try{r[o]=i(n);}catch(s){throw s.message=`${o}: ${s.message}`,s}return r};function Ds(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 Ks=qs([["from",Yn],["to",Yn],["nonce",Ts],["check",Fs],["encrypted",Is]]),Xn={Memo:Ks};var eo=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),ro(),e=no(e),t=Bs(t);let o=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);o.writeVString(r);let i=new Uint8Array(o.copy(0,o.offset).toBuffer()),{nonce:s,message:a,checksum:c}=Gn(e,t,i,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 "#"+vn.encode(l)},to=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),ro(),e=no(e);let r=Xn.Memo(vn.decode(t)),{from:n,to:o,nonce:i,check:s,encrypted:a}=r,p=e.createPublic().toString()===new Y(n.key).toString()?new Y(o.key):new Y(n.key);r=zn(e,p,i,a,s);let l=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},qt,ro=()=>{if(qt===void 0){let e;qt=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=eo(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=to(t,n);}finally{qt=e==="#memo\u7231";}}if(qt===false)throw new Error("This environment does not support encryption.")},no=e=>typeof e=="string"?U.fromString(e):e,Bs=e=>typeof e=="string"?Y.fromString(e):e,oo={decode:to,encode:eo};var ne={};vt(ne,{buildWitnessSetProperties:()=>Vs,makeBitMaskFilter:()=>Hs,operations:()=>Qs,validateUsername:()=>Ns});var Ns=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("."),o=n.length;for(let i=0;ie.reduce(Us,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),Us=([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 o;switch(n){case "key":case "new_signing_key":o=de.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":o=de.UInt32;break;case "hbd_interest_rate":o=de.UInt16;break;case "url":o=de.String;break;case "hbd_exchange_rate":o=de.Price;break;case "account_creation_fee":o=de.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,js(o,t[n])]);}return r.props.sort((n,o)=>n[0].localeCompare(o[0])),["witness_set_properties",r]},js=(e,t)=>{let r=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return e(r,t),r.flip(),bytesToHex(new Uint8Array(r.toBuffer()))};function ug(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|o&63);else if(o>=55296&&o<=56319&&n+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else r.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(r);}else t=e;return sha256(t)}function io(e){try{return U.fromString(e),!0}catch{return false}}async function ee(e,t){let r=new De;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),Le("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function so(e,t){let r=new De;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var $s=432e3;function ao(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/$s,o=Math.round(n/e*1e4);return !isFinite(o)||o<0?o=0:o>1e4&&(o=1e4),{current_mana:n,max_mana:e,percentage:o}}function Ws(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),o=parseFloat(e.vesting_withdraw_rate),i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t-s-r+n}function wr(e){let t=Ws(e)*1e6;return ao(t,e.voting_manabar)}function Dt(e){return ao(Number(e.max_rc),e.rc_manabar)}var co=(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))(co||{});function $e(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",o=t||r||String(e||""),i=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||o&&a.test(o));if(i(/please wait to transact/i)||i(/insufficient rc/i)||i(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(i(/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(i(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(i(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(i(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(i(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(i(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(i(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(i(/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(i(/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(i(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(i(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(i(/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"||i(/token expired/i)||i(/invalid token/i)||i(/\bunauthorized\b/i)||i(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(i(/has already reblogged/i)||i(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(i(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(i(/econnrefused/i)||i(/connection refused/i)||i(/failed to fetch/i)||i(/\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(i(/timeout/i)||i(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(i(/account.*does not exist/i)||i(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(i(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(i(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(i(/\b(invalid|validation)\b/i))return {message:(e?.message||o).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}`:o&&o!=="[object Object]"?s=o.substring(0,150):s="Unknown error occurred":s=o.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function Gs(e){let t=$e(e);return [t.message,t.type]}function we(e){let{type:t}=$e(e);return t==="missing_authority"||t==="token_expired"}function zs(e){let{type:t}=$e(e);return t==="insufficient_resource_credits"}function Js(e){let{type:t}=$e(e);return t==="info"}function Ys(e){let{type:t}=$e(e);return t==="network"||t==="timeout"}async function ve(e,t,r,n,o="posting",i,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=i;if(p===void 0)switch(o){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 ${o} key available for ${t}`);let l=U.fromString(p);return a==="async"?await so(r,l):await ee(r,l)}case "hiveauth":{if(!c?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await c.broadcastWithHiveAuth(t,r,o)}case "hivesigner":{if(!c)throw new Error("No adapter provided for HiveSigner auth");if(o!=="posting"){if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);throw new Error(`HiveSigner access token cannot sign ${o} operations. No platform broadcast available.`)}let p=s!==void 0?s:await c.getAccessToken(t);if(p)try{return (await new uo.Client({accessToken:p}).broadcast(r)).result}catch(l){if(c.broadcastWithHiveSigner&&we(l))return await c.broadcastWithHiveSigner(t,r,o);throw l}if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);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,o)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,o)}default:throw new Error(`Unknown auth method: ${e}`)}}async function Zs(e,t,r,n="posting",o="async"){let i=r?.adapter;if(i?.getLoginType){let l=await i.getLoginType(e,n);if(l){let d=i.hasPostingAuthorization?await i.hasPostingAuthorization(e):false;if(n==="posting"&&d&&l==="key")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&d&&l==="keychain")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to keychain/snap:",m);}if(n==="posting"&&d&&l==="hiveauth")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!we(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await ve(l,e,t,r,n,void 0,void 0,o)}catch(m){if(we(m)&&i.showAuthUpgradeUI&&(n==="posting"||n==="active")){let g=t.length>0?t[0][0]:"unknown",h=await i.showAuthUpgradeUI(n,g);if(!h)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ve(h,e,t,r,n,void 0,void 0,o)}throw m}}if(n==="posting")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(d){if(we(d)&&i.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",g=await i.showAuthUpgradeUI(n,m);if(!g)throw new Error(`No login type available for ${e}. Please log in again.`);return await ve(g,e,t,r,n,void 0,void 0,o)}throw d}else if(n==="active"&&i.showAuthUpgradeUI){let d=t.length>0?t[0][0]:"unknown",m=await i.showAuthUpgradeUI(n,d);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ve(m,e,t,r,n,void 0,void 0,o)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let d=!1,m="",g,h;switch(l){case "key":if(!i)d=!0,m="No adapter provided";else {let P;switch(n){case "owner":i.getOwnerKey&&(P=await i.getOwnerKey(e));break;case "active":i.getActiveKey&&(P=await i.getActiveKey(e));break;case "memo":i.getMemoKey&&(P=await i.getMemoKey(e));break;default:P=await i.getPostingKey(e);break}P?g=P:(d=!0,m=`No ${n} key available`);}break;case "hiveauth":i?.broadcastWithHiveAuth||(d=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!i)d=!0,m="No adapter provided";else {let P=await i.getAccessToken(e);P&&(h=P);}break;case "keychain":i?.broadcastWithKeychain||(d=!0,m="Keychain not supported by adapter");break;case "custom":r?.broadcast||(d=!0,m="No custom broadcast function provided");break}if(d){a.set(l,new Error(`Skipped: ${m}`));continue}return await ve(l,e,t,r,n,g,h,o)}catch(d){if(a.set(l,d),!we(d))throw d}if(!Array.from(a.values()).some(l=>!l.message.startsWith("Skipped:"))){let l=Array.from(a.entries()).map(([d,m])=>`${d}: ${m.message}`).join(", ");throw new Error(`[SDK][Broadcast] No auth methods attempted for ${e}. ${l}`)}let p=Array.from(a.entries()).map(([l,d])=>`${l}: ${d.message}`).join(", ");throw new Error(`[SDK][Broadcast] All auth methods failed for ${e}. Errors: ${p}`)}function v(e=[],t,r,n=()=>{},o,i="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(o?.enableFallback!==!1&&o?.adapter)return await Zs(t,p,o,i,a);if(o?.broadcast)return await o.broadcast(p,i);let l=o?.postingKey;if(l){if(i!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${i}' was requested. Use AuthContextV2 with an adapter for ${i} operations.`);let m=U.fromString(l);return await ee(p,m)}let d=o?.accessToken;if(d)return (await new uo.Client({accessToken:d}).broadcast(p)).result;throw new Error("[SDK][Broadcast] \u2013 cannot broadcast w/o posting key or token")}catch(l){throw l instanceof Z?new Error(l.message):l}}})}async function po(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let o={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",o]],"posting");let i=n?.postingKey;if(i){let c=U.fromString(i);return ee([["custom_json",o]],c)}let s=n?.accessToken;if(s)return (await new uo.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let c=[["custom_json",o]];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 xg=4e3;function E(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function Pe(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,o=()=>{let i=t.aborted?t.reason:r.reason;n.abort(i),t.removeEventListener("abort",o),r.removeEventListener("abort",o);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",o,{once:true}),r.addEventListener("abort",o,{once:true})),n.signal}var Ke=(()=>{try{return process.env?.NODE_ENV==="development"}catch{return false}})(),ra=()=>{try{return process.env?.VITE_HELIUS_API_KEY}catch{return}},Ae=1e4,lo=120*1e3,Kt,na;function oa(){return Kt?Kt():na??=new QueryClient}var f={privateApiHost:"https://ecency.com",defaultObserver:"ecency",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return x.nodes},heliusApiKey:ra(),get queryClient(){return oa()},set queryClient(e){Kt=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false},Q;(ue=>{function e(A){f.queryClient=A;}ue.setQueryClient=e;function t(A){Kt=A;}ue.setQueryClientResolver=t;function r(A){f.privateApiHost=A;}ue.setPrivateApiHost=r;function n(A){f.clientId=A;}ue.setClientId=n;function o(A){if(typeof A!="string"||A.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.");f.defaultObserver=A;}ue.setDefaultObserver=o;function i(){return f.privateApiHost?f.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}ue.getValidatedBaseUrl=i;function s(A){f.pollsApiHost=A;}ue.setPollsApiHost=s;function a(A){f.imageHost=A;}ue.setImageHost=a;function c(A){or(A);}ue.setHiveNodes=c;function p(A){ir(A);}ue.setRestNodes=p;function l(A){sr(A);}ue.setRestNodesByApi=l;function d(A){ar(A);}ue.setUserAgent=d;function m(A){cr(A);}ue.setResilience=m;function g(A){rr(A);}ue.setServerRpcProxy=g;function h(){return Ce}ue.getServerRpcProxyStats=h;function P(A){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(A))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(A))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(A))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(A)||/\.\+\.\+/.test(A))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let $=/\.?\{(\d+),(\d+)\}/g,N;for(;(N=$.exec(A))!==null;){let[,H,z]=N;if(parseInt(z,10)-parseInt(H,10)>1e3)return {safe:false,reason:`excessive range: {${H},${z}}`}}return {safe:true}}function O(A){let $=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],N=5;for(let H of $){let z=Date.now();try{A.test(H);let L=Date.now()-z;if(L>N)return {safe:!1,reason:`runtime test exceeded ${N}ms (took ${L}ms on input length ${H.length})`}}catch(L){return {safe:false,reason:`runtime test threw error: ${L}`}}}return {safe:true}}function T(A,$=200){try{if(!A)return Ke&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(A.length>$)return Ke&&console.warn(`[SDK] DMCA pattern rejected: length ${A.length} exceeds max ${$} - pattern: ${A.substring(0,50)}...`),null;let N=P(A);if(!N.safe)return Ke&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${N.reason}) - pattern: ${A.substring(0,50)}...`),null;let H;try{H=new RegExp(A);}catch(L){return Ke&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${A.substring(0,50)}...`,L),null}let z=O(H);return z.safe?H:(Ke&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${z.reason}) - pattern: ${A.substring(0,50)}...`),null)}catch(N){return Ke&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${A.substring(0,50)}...`,N),null}}function F(A={}){let $=L=>Array.isArray(L)?L.filter(rt=>typeof rt=="string"):[],N=A||{},H={accounts:$(N.accounts),tags:$(N.tags),patterns:$(N.posts)};f.dmcaAccounts=H.accounts,f.dmcaTags=H.tags,f.dmcaPatterns=H.patterns,f.dmcaTagRegexes=H.tags.map(L=>T(L)).filter(L=>L!==null),f.dmcaPatternRegexes=[];let z=H.tags.length-f.dmcaTagRegexes.length;!f._dmcaInitialized&&Ke&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${H.accounts.length}`),console.log(` - Tag patterns: ${f.dmcaTagRegexes.length}/${H.tags.length} compiled (${z} rejected)`),console.log(` - Post patterns: ${H.patterns.length} (using exact string matching)`),z>0&&console.warn(`[SDK] ${z} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),f._dmcaInitialized=true;}ue.setDmcaLists=F;})(Q||={});function Bg(){return new QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var w=()=>f.queryClient,ca;(s=>{function e(a){return w().getQueryData(a)}s.getQueryData=e;function t(a){return w().getQueryData(a)}s.getInfiniteQueryData=t;async function r(a){return await w().prefetchQuery(a),e(a.queryKey)}s.prefetchQuery=r;async function n(a){return await w().prefetchInfiniteQuery(a),t(a.queryKey)}s.prefetchInfiniteQuery=n;function o(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>useQuery(a),fetchAndGet:()=>w().fetchQuery(a)}}s.generateClientServerQuery=o;function i(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>useInfiniteQuery(a),fetchAndGet:()=>w().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=i;})(ca||={});function Ng(e){return btoa(JSON.stringify(e))}function Qg(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var fo=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(fo||{}),Bt=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(Bt||{});function k(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:fo[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:Bt[e.nai]}}var vr;function _(){if(!vr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");vr=globalThis.fetch.bind(globalThis);}return vr}function mo(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function ua(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function se(e,t){return ua(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function We(e,t){return e/1e6*t}function go(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var yo=60*1e3;function Oe(){return queryOptions({queryKey:u.core.dynamicProps(),refetchInterval:yo,staleTime:yo,queryFn:async({signal:e})=>{let[t,r,n,o,i]=await Promise.all([y("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),y("condenser_api.get_feed_history",[],void 0,void 0,e),y("condenser_api.get_chain_properties",[],void 0,void 0,e),y("condenser_api.get_reward_fund",["post"],void 0,void 0,e),y("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=k(t.total_vesting_shares).amount,a=k(t.total_vesting_fund_hive).amount,c=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(c=a/s*1e6);let p=k(r.current_median_history.base).amount,l=k(r.current_median_history.quote).amount,d=parseFloat(o.recent_claims),m=k(o.reward_balance).amount,g=Number(t.vote_power_reserve_rate??0),h=o.author_reward_curve??"linear",P=Number(o.content_constant??0),O=String(i.current_hardfork_version??"0.0.0"),T=Number(i.last_hardfork??0),F=t.hbd_print_rate,ue=t.hbd_interest_rate,A=t.head_block_number,$=a,N=s,H=k(t.virtual_supply).amount,z=t.vesting_reward_percent||0,L=n.account_creation_fee;return {hivePerMVests:c,base:p,quote:l,fundRecentClaims:d,fundRewardBalance:m,votePowerReserveRate:g,authorRewardCurve:h,contentConstant:P,currentHardforkVersion:O,lastHardfork:T,hbdPrintRate:F,hbdInterestRate:ue,headBlock:A,totalVestingFund:$,totalVestingShares:N,virtualSupply:H,vestingRewardPercent:z,accountCreationFee:L,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:o,hardforkProps:i}}}})}function ry(e="post"){return queryOptions({queryKey:u.core.rewardFund(e),queryFn:()=>y("condenser_api.get_reward_fund",[e])})}function Be(...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,o,i)=>["posts","account-posts-page",e,t,r,n,o,i],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)=>Be("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>Be("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>Be("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>Be("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,o,i)=>["posts","posts-ranked-page",e,t,r,n,o,i],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)=>Be("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)=>Be("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,o,i)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,o,i],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,o,i)=>Be("search","api",e,t,r,n,o,i)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,o)=>["witnesses","voters",e,t,r,n,o],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 ut(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 cy(e){return queryOptions({queryKey:u.ai.prices(),queryFn:async()=>{let r=await _()(f.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 dy(e,t){return queryOptions({queryKey:u.ai.assistPrices(e),queryFn:async()=>{let n=await _()(f.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 yy(e,t){return queryOptions({queryKey:u.ai.transcribePrice(e),queryFn:async()=>{let n=await _()(f.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 ya(){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 wy(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 o=await _()(f.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??ya()})});if(!o.ok){let s=await o.text(),a={};try{a=JSON.parse(s);}catch{}let c=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${o.status}${s?`: ${s}`:""}`);throw c.status=o.status,c.data=a,c}if(o.status===202){let s={};try{s=await o.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await o.json()},onSuccess:()=>{e&&w().invalidateQueries({queryKey:u.points._prefix(e)});}})}function _a(){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 Oy(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 o=await _()(f.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:_a()})});if(!o.ok){let i=await o.text(),s={};try{s=JSON.parse(i);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${o.status}${i?`: ${i}`:""}`);throw a.status=o.status,a.data=s,a}return await o.json()},onSuccess:r=>{e&&(r.cost>0&&w().invalidateQueries({queryKey:u.points._prefix(e)}),w().invalidateQueries({queryKey:u.ai.assistPrices(e)}));}})}function wa(){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 ky(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 o=new FormData;o.append("code",n),o.append("duration_ms",String(Math.round(r.durationMs))),o.append("idempotency_key",r.idempotency_key??wa()),o.append("audio",r.audio,r.fileName??"clip.webm");let s=await _()(f.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:o});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&&w().invalidateQueries({queryKey:u.points._prefix(e)}),w().invalidateQueries({queryKey:u.ai.transcribePrice(e)}));}})}function Pr(e){return !e.posting_json_metadata&&!e.json_metadata}function Pa(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([y("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),y("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 o=r[0];if(Pr(o)&&Pa(n?.metadata?.profile)){let p=await y("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]))o=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let i=Me(o.posting_json_metadata),s=n?.stats,a=s?{account:o.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,c=n?.reputation??0;return {name:o.name,owner:o.owner,active:o.active,posting:o.posting,memo_key:o.memo_key,post_count:o.post_count,created:o.created,posting_json_metadata:o.posting_json_metadata,last_vote_time:o.last_vote_time,last_post:o.last_post,json_metadata:o.json_metadata,reward_hive_balance:o.reward_hive_balance,reward_hbd_balance:o.reward_hbd_balance,reward_vesting_hive:o.reward_vesting_hive,reward_vesting_balance:o.reward_vesting_balance,balance:o.balance,hbd_balance:o.hbd_balance,savings_balance:o.savings_balance,savings_hbd_balance:o.savings_hbd_balance,savings_hbd_last_interest_payment:o.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:o.savings_hbd_seconds_last_update,savings_hbd_seconds:o.savings_hbd_seconds,next_vesting_withdrawal:o.next_vesting_withdrawal,pending_claimed_accounts:o.pending_claimed_accounts,vesting_shares:o.vesting_shares,delegated_vesting_shares:o.delegated_vesting_shares,received_vesting_shares:o.received_vesting_shares,vesting_withdraw_rate:o.vesting_withdraw_rate,to_withdraw:o.to_withdraw,withdrawn:o.withdrawn,witness_votes:o.witness_votes,proxy:o.proxy,recovery_account:o.recovery_account,proxied_vsf_votes:o.proxied_vsf_votes,voting_manabar:o.voting_manabar,voting_power:o.voting_power,downvote_manabar:o.downvote_manabar,follow_stats:a,reputation:c,profile:i}},enabled:!!e,staleTime:6e4})}var Aa=new Set(["__proto__","constructor","prototype"]);function Mt(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ho(e,t){let r={...e};for(let n of Object.keys(t)){if(Aa.has(n))continue;let o=t[n],i=r[n];Mt(o)&&Mt(i)?r[n]=ho(i,o):r[n]=o;}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:o,...i}=t;return {...r,meta:i}})}function Me(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 _o(e){return Me(e?.posting_json_metadata)}function bo(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(Me(e.posting_json_metadata)).length;return Object.keys(Me(t.posting_json_metadata)).length>r?t:e}function xa(e){if(!e)return {};try{let t=JSON.parse(e);if(Mt(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function wo({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=xa(e),o=Mt(n.profile)?n.profile:{},i=Ar({existingProfile:o,profile:t,tokens:r});return JSON.stringify({...n,profile:i})}function Ar({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:o,...i}=t??{},s=ho(e??{},i);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 Nt(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=Me(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let o=JSON.parse(t.json_metadata||"{}");o.profile&&(n=o.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function Ea(e){return new TextEncoder().encode(e).length}function Ge(e){return e?Ea(e)<=16:false}function jy(e){return queryOptions({queryKey:u.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(Ge);if(t.length===0)return [];let r=await y("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return Nt(r??[])}})}function zy(e){return queryOptions({queryKey:u.accounts.followCount(e),queryFn:()=>y("condenser_api.get_follow_count",[e])})}function eh(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.followers(e,t,r,n),queryFn:()=>y("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function ih(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.following(e,t,r,n),queryFn:()=>y("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var vo=1e3,Fa=20;function ph(e){return queryOptions({queryKey:u.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(i[0]===r&&(i=i.slice(1)),!i.length||(t.push(...i),o.lengthGe(e)?y("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function vh(e,t=5,r=[]){return queryOptions({queryKey:u.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await y("condenser_api.lookup_accounts",[e,t])).filter(o=>r.length>0?!r.includes(o):true)})}var Ka=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function xh(e,t){return queryOptions({queryKey:u.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await _()(f.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 o=await n.json(),i=Array.isArray(o)?o.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={},d=typeof a.address=="string"&&a.address?a.address:void 0,g=(typeof a.status=="number"?a.status===3:void 0)??false;d&&(l.address=d),l.show=g;let h={symbol:c,currency:c,address:d,show:g,type:"CHAIN",meta:l},P=[];for(let[O,T]of Object.entries(p))typeof O=="string"&&(Ka.has(O)||typeof T!="string"||!T||/^[A-Z0-9]{2,10}$/.test(O)&&P.push({symbol:O,currency:O,address:T,show:g,type:"CHAIN",meta:{address:T,show:g}}));return [h,...P]}):[];return {exist:i.length>0,tokens:i.length?i:void 0,wallets:i.length?i:void 0}},refetchOnMount:true})}function Po(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 y("bridge.get_relationship_between_accounts",[e,t])??r}})}function qh(e){return queryOptions({queryKey:u.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await y("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function Mh(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 _()(f.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function Nh(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 i=await _()(`${f.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch bookmarks: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Vh(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 _()(f.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function jh(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 i=await _()(`${f.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch favorites: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Gh(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 o=await _()(f.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!o.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${o.status}: ${o.statusText}`);let i=await o.json();if(typeof i!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof i}`);return i}})}function Xh(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 _()(f.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function n_(e){return queryOptions({enabled:!!e,queryKey:u.accounts.pendingRecovery(e),queryFn:()=>y("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function u_(e,t=50){return queryOptions({queryKey:u.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!Ge(e)?[]:y("condenser_api.get_account_reputations",[e,t])})}var K=ne.operations,Ao={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]},Ga=Array.from(new Set(Object.values(Ao).flat()));function za(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function Ja(e){return e.replace(/_operation$/,"")}function Ya(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function Xa(e){if(!Ya(e))return e;let t=k(e),r=Bt[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function Za(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Xa(n);return t}function h_(e,t=20,r=""){let n=r?Ao[r]:Ga;return infiniteQueryOptions({queryKey:u.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:o,signal:i})=>{if(!e)return {entries:[],currentPage:0};let s=async d=>{let m={"account-name":e,"operation-types":n.join(","),"page-size":t};return d!==null&&(m.page=d),await te("hafah","/accounts/{account-name}/operations",m,void 0,void 0,i)},a=d=>d.operations_result.map(m=>{let g=Ja(m.op.type);return {...Za(m.op.value),num:za(m),type:g,timestamp:m.timestamp,trx_id:m.trx_id}}),c=await s(o),p=a(c),l=o??c.total_pages;if(o===null&&p.length1)try{let d=await s(c.total_pages-1);p=[...p,...a(d)],l=c.total_pages-1;}catch(d){if(i?.aborted)throw d}return {entries:p,currentPage:l}},getNextPageParam:o=>{let i=o.currentPage-1;return i>=1?i:void 0}})}function v_(){return queryOptions({queryKey:u.accounts.bots(),queryFn:async()=>{let e=await fetch(f.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 x_(e){return infiniteQueryOptions({queryKey:u.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=Q.getValidatedBaseUrl(),o=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&o.searchParams.set("max_id",r.toString());let i=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch referrals: ${i.status}`);return i.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function C_(e){return queryOptions({queryKey:u.accounts.referralsStats(e),queryFn:async()=>{let t=await fetch(f.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 D_(e,t,r){let{followType:n="blog",limit:o=100,enabled:i=true}=r??{};return infiniteQueryOptions({queryKey:u.accounts.friends(e,t,n,o),initialPageParam:{startFollowing:""},enabled:i,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await y(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,o])).map(g=>t==="following"?g.following:g.follower);return (await y("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(g=>({name:g.name,reputation:g.reputation,active:g.active}))},getNextPageParam:s=>s&&s.length===o?{startFollowing:s[s.length-1].name}:void 0})}var ic=30;function Q_(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 y(`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,ic);return (await y("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 L_(e=20){return infiniteQueryOptions({queryKey:u.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>y("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 Y_(e=250){return infiniteQueryOptions({queryKey:u.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>y("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!mo(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function ze(e,t){return queryOptions({queryKey:u.posts.fragments(e),queryFn:async()=>t?(await _()(f.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function tb(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 i=await _()(`${f.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch fragments: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function ib(e="feed"){return queryOptions({queryKey:u.posts.promoted(e),queryFn:async()=>{let t=Q.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 pb(e){return queryOptions({queryKey:u.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>y("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function gb(e,t,r){return queryOptions({queryKey:u.posts.userPostVote(e,t,r),queryFn:async()=>(await y("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function wb(e,t){return queryOptions({queryKey:u.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content",[e,t])})}function xb(e,t){return queryOptions({queryKey:u.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content_replies",{author:e,permlink:t})})}function Rb(e,t){return queryOptions({queryKey:u.posts.postHeader(e,t),queryFn:async()=>y("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function re(e){return Array.isArray(e)?e.map(t=>Oo(t)):Oo(e)}function Oo(e){if(!e)return e;let t=`@${e.author}/${e.permlink}`;return f.dmcaPatterns.includes(t)||f.dmcaPatternRegexes.some(n=>n.test(t))?{...e,body:"This post is not available due to a copyright/fraudulent claim.",title:""}:e}async function xo(e,t,r){try{let n=await It("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 Eo(e,t,r="",n){let o=t?.trim(),i=`/@${e}/${o??""}`;return queryOptions({queryKey:u.posts.entry(i),queryFn:async()=>{if(!o||o==="undefined")return null;let s=await y("bridge.get_post",{author:e,permlink:o,observer:r});if(!s){let c=await xo(e,o,r);if(!c)return null;let p=n!==void 0?{...c,num:n}:c;return re(p)}let a=n!==void 0?{...s,num:n}:s;return re(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function ae(e,t,r){return y(`bridge.${e}`,t,void 0,void 0,r)}async function So(e,t,r,n){let{json_metadata:o}=e;if(o?.original_author&&o?.original_permlink&&o.tags?.[0]==="cross-post")try{let i=await hc(o.original_author,o.original_permlink,t,r,n);return i?{...e,original_entry:i,num:r}:e}catch{return e}return {...e,num:r}}async function ko(e,t,r){let n=e.map(pt),o=await Promise.all(n.map(i=>So(i,t,void 0,r)));return re(o)}async function Co(e,t="",r="",n=20,o="",i="",s){let a=await ae("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:o,observer:i},s);return Array.isArray(a)?ko(a,i,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 Or(e,t,r="",n="",o=20,i="",s){if(f.dmcaAccounts.includes(t))return [];let a=await ae("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:o,observer:i},s);return Array.isArray(a)?ko(a,i,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 pt(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 hc(e="",t="",r="",n,o){let i=await ae("get_post",{author:e,permlink:t,observer:r},o);if(i){let s=pt(i),a=await So(s,r,n,o);return re(a)}}async function Lb(e="",t=""){let r=await ae("get_post_header",{author:e,permlink:t});return r&&pt(r)}async function Ro(e,t,r){let n=await ae("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let o={};for(let[i,s]of Object.entries(n))o[i]=pt(s);return o}return n}async function To(e,t=""){return ae("get_community",{name:e,observer:t})}async function $b(e="",t=100,r,n="rank",o=""){return ae("list_communities",{last:e,limit:t,query:r,sort:n,observer:o})}async function Fo(e){let t=await ae("normalize_post",{post:e});return t&&pt(t)}async function Wb(e){return ae("list_all_subscriptions",{account:e})}async function Gb(e){return ae("list_subscribers",{community:e})}async function zb(e,t){return ae("get_relationship_between_accounts",[e,t])}async function Qt(e,t){return ae("get_profiles",{accounts:e,observer:t})}var qo=(o=>(o.trending="trending",o.author_reputation="author_reputation",o.votes="votes",o.created="created",o))(qo||{});function xr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function _c(e,t,r){let n=l=>xr(l.pending_payout_value).amount+xr(l.author_payout_value).amount+xr(l.curator_payout_value).amount,o=l=>l.net_rshares<0,i=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,d)=>{if(o(l))return 1;if(o(d))return -1;let m=n(l),g=n(d);return m!==g?g-m:0},author_reputation:(l,d)=>{let m=l.author_reputation,g=d.author_reputation;return m>g?-1:m{let m=l.children,g=d.children;return m>g?-1:m{if(o(l))return 1;if(o(d))return -1;let m=Date.parse(l.created),g=Date.parse(d.created);return m>g?-1:mi(l)),p=a[c];return c>=0&&(a.splice(c,1),a.unshift(p)),a}function Do(e,t="created",r=true,n){let o=n||f.defaultObserver;return queryOptions({queryKey:u.posts.discussions(e?.author,e?.permlink,t,o),queryFn:async()=>{if(!e)return [];let i=await y("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:o}),s=i?Array.from(Object.values(i)):[];return re(s)},enabled:r&&!!e,select:i=>_c(e,i,t),structuralSharing:(i,s)=>{if(!i||!s)return s;let a=i.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 rw(e,t,r,n=true){let o=r||f.defaultObserver;return queryOptions({queryKey:u.posts.discussion(e,t,o),enabled:n&&!!e&&!!t,queryFn:async()=>Ro(e,t,o)})}function uw(e,t="posts",r=20,n="",o=true){return infiniteQueryOptions({queryKey:u.posts.accountPosts(e??"",t,r,n),enabled:!!e&&o,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:i,signal:s})=>{if(!i?.hasNextPage||!e)return [];let a=await Or(t,e,i.author??"",i.permlink??"",r,n,s);return re(a??[])},getNextPageParam:i=>{let s=i?.[i.length-1],a=(i?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function pw(e,t="posts",r="",n="",o=20,i="",s=true){return queryOptions({queryKey:u.posts.accountPostsPage(e??"",t,r,n,o,i),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let c=await Or(t,e,r,n,o,i,a);return re(c??[])}})}var Ko=new Map;function Ac(e){let t=Ko.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>Oc(n,e))}),Ko.set(e,t)),t}function Oc(e,t){let r=e.filter(i=>i.stats?.is_pinned),n=e.filter(i=>!i.stats?.is_pinned);if(t==="hot")return [...r,...n];let o=[...n].sort((i,s)=>new Date(s.created).getTime()-new Date(i.created).getTime());return [...r,...o]}function _w(e,t,r=20,n="",o=true,i={}){return infiniteQueryOptions({queryKey:u.posts.postsRanked(e,t,r,n),queryFn:async({pageParam:s,signal:a})=>{let c=t;f.dmcaTagRegexes.some(l=>l.test(t))&&(c="");let p=await y("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 re(p)},select:Ac(e),enabled:o,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 bw(e,t="",r="",n=20,o="",i="",s=true){return queryOptions({queryKey:u.posts.postsRankedPage(e,t,r,n,o,i),enabled:s,queryFn:async({signal:a}={})=>{let c=o;f.dmcaTagRegexes.some(l=>l.test(o))&&(c="");let p=await Co(e,t,r,n,c,i,a);return re(p??[])}})}function Ow(e,t,r=200){return queryOptions({queryKey:u.posts.reblogs(e??"",r),queryFn:async()=>(await y("condenser_api.get_blog_entries",[e??t,0,r])).filter(o=>o.author!==t&&!o.reblogged_on.startsWith("1970-")).map(o=>({author:o.author,permlink:o.permlink})),enabled:!!e})}function Cw(e,t){return queryOptions({queryKey:u.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await y("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function Iw(e,t){return queryOptions({queryKey:u.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(f.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 qw(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 i=await _()(`${f.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch schedules: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Mw(e,t){return queryOptions({queryKey:u.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await _()(f.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 Nw(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 i=await _()(`${f.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch drafts: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function Mo(e){let r=await _()(f.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 Vw(e,t){return queryOptions({queryKey:u.posts.images(e),queryFn:async()=>!e||!t?[]:Mo(t),enabled:!!e&&!!t})}function jw(e,t){return queryOptions({queryKey:u.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:Mo(t),enabled:!!e&&!!t})}function Lw(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 i=await _()(`${f.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch images: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function zw(e,t,r=false){return queryOptions({queryKey:u.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let o=await fetch(f.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(!o.ok)throw new Error(`Failed to fetch comment history: ${o.status}`);return o.json()},enabled:!!e&&!!t})}function qc(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let o=r.replace(/^@+/,""),i=n.replace(/^\/+/,"");if(!o||!i)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${o}/${i}`}function Zw(e,t){let r=t?.trim(),n=e?.trim(),o=!!n&&!!r&&r!=="undefined",i=o?qc(n,r):"";return queryOptions({queryKey:u.posts.deletedEntry(i),queryFn:async({signal:s})=>{let a=await fetch(f.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:o})}function nv(e,t,r=true){return queryOptions({queryKey:u.posts.tips(e,t),queryFn:async()=>{let n=`/private-api/post-tips/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,o=await fetch(f.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch post tips: ${o.status}`);return o.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function Kc(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function Bc(e){return {...e,id:e.id??e.post_id}}function he(e,t){if(!e)return null;let r=e.container??e,n=Kc(r,t),o=e.parent?Bc(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:o}}function Mc(e){return Array.isArray(e)?e:[]}async function No(e){let t=Do(e,"created",true),r=await f.queryClient.fetchQuery(t),n=Mc(r);if(n.length<=1)return [];let o=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return o.length===0?[]:o.filter(s=>!s.stats?.gray)}function Qo(e,t,r){return e.length===0?[]:e.map(n=>{let o=e.find(i=>i.author===n.parent_author&&i.permlink===n.parent_permlink&&i.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:o}}).filter(n=>n.container.post_id!==n.post_id).sort((n,o)=>new Date(o.created).getTime()-new Date(n.created).getTime())}var Hc=20;function Ho(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??Hc}}async function Uo({containers:e,tag:t,following:r,author:n,observer:o,limit:i},s,a){let c=Q.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",c);p.searchParams.set("limit",String(i)),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),o&&p.searchParams.set("observer",o);let l=await fetch(p.toString(),{method:"GET",signal:a});if(!l.ok)throw new Error(`Failed to fetch waves feed: ${l.status}`);let d=await l.json();return !Array.isArray(d)||d.length===0?[]:d.map(m=>{let g=he(m,m.host??"");return g?{...g,_cursor:m._cursor}:null}).filter(m=>!!m)}function lv(e={}){let t=Ho(e),{containers:r,tag:n,following:o,author:i,observer:s,limit:a}=t;return infiniteQueryOptions({queryKey:u.posts.wavesFeed({containers:r,tag:n,following:o,author:i,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:c,signal:p})=>Uo(t,c,p),getNextPageParam:c=>{if(!(c.lengthUo(t,void 0,c)})}var Vc=20;function jc(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??Vc}}async function Lc({containers:e,tag:t,author:r,observer:n,limit:o},i,s){let a=Q.getValidatedBaseUrl(),c=new URL("/private-api/waves/shorts",a);c.searchParams.set("limit",String(o)),i&&c.searchParams.set("cursor",i),e.forEach(d=>c.searchParams.append("container",d)),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(d=>{let m=he(d,d.host??"");return m?{...m,active_votes:m.active_votes??[],video:d.video,_cursor:d._cursor}:null}).filter(d=>!!d)}function hv(e={}){let t=jc(e),{containers:r,tag:n,author:o,observer:i,limit:s}=t;return infiniteQueryOptions({queryKey:u.posts.shortsFeed({containers:r,tag:n,author:o,observer:i,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:c})=>Lc(t,a,c),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of c){if(i&&l.post_id===i){i=void 0;continue}if(o+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let d;try{d=await No(l);}catch(m){console.error("[SDK] getThreads get_discussion error:",m),r=l.author,n=l.permlink;continue}if(d.length===0){r=l.author,n=l.permlink;continue}return {entries:Qo(d,l,e)}}let p=c[c.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function Ov(e){return infiniteQueryOptions({queryKey:u.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await zc(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var Yc=40;function Cv(e,t,r=Yc){return infiniteQueryOptions({queryKey:u.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let o=Q.getValidatedBaseUrl(),i=new URL("/private-api/waves/tags",o);i.searchParams.set("container",e),i.searchParams.set("tag",t);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves by tag",o),[]}},getNextPageParam:()=>{}})}function qv(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 o=Q.getValidatedBaseUrl(),i=new URL("/private-api/waves/following",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves following feed",o),[]}},getNextPageParam:()=>{}})}function Mv(e,t=24){let r=e?.trim()||void 0;return queryOptions({queryKey:u.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let o=Q.getValidatedBaseUrl(),i=new URL("/private-api/waves/trending/tags",o);r&&i.searchParams.set("container",r),i.searchParams.set("hours",t.toString());let s=await fetch(i.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(o){return console.error("[SDK] Failed to fetch waves trending tags",o),[]}}})}function Vv(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 o=Q.getValidatedBaseUrl(),i=new URL("/private-api/waves/account",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){throw console.error("[SDK] Failed to fetch waves for account",o),o}},getNextPageParam:()=>{}})}function Wv(e){return queryOptions({queryKey:u.posts.wavesTrendingAuthors(e),queryFn:async({signal:t})=>{try{let r=Q.getValidatedBaseUrl(),n=new URL("/private-api/waves/trending/authors",r);n.searchParams.set("container",e);let o=await fetch(n.toString(),{method:"GET",signal:t});if(!o.ok)throw new Error(`Failed to fetch waves trending authors: ${o.status}`);return (await o.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 Xv(e,t=true){return queryOptions({queryKey:u.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>Fo(e)})}function ou(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Vo(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function s0(e,t){let{limit:r=20,filters:n=[],dayLimit:o=7}=t??{};return infiniteQueryOptions({queryKey:u.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:i})=>{let{start:s}=i,a=await y("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,g])=>({...g.op[1],num:m,timestamp:g.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Vo(m.timestamp)<=o),l=[];for(let m of p){let g=await f.queryClient.fetchQuery(Eo(m.author,m.permlink));ou(g)&&l.push(g);}let[d]=a;return {lastDate:d?Vo(d[1].timestamp):0,lastItemFetched:d?d[0]:s,entries:l}},getNextPageParam:i=>({start:i.lastItemFetched})})}function l0(e,t,r=true){return queryOptions({queryKey:u.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Qt(e,t)})}function h0(e,t="HIVE",r=200){return infiniteQueryOptions({queryKey:u.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:o})=>{if(!e)return {entries:[],currentPage:0};let i={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(i.page=n);let s=await te("balance","/accounts/{account-name}/balance-history",i,void 0,void 0,o);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let o=n.currentPage-1;return o>=1?o:void 0},enabled:!!e})}function P0(e,t="HIVE",r="yearly"){return queryOptions({queryKey:u.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await te("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function E0(){return queryOptions({queryKey:u.accounts.proMembers(),queryFn:async()=>{let e=await fetch(f.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 S0(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function I0(e,t,r){let n=useQueryClient(),{data:o}=useQuery(M(e));return v(["accounts","update"],e,i=>{let s=bo(n.getQueryData(M(e).queryKey),o);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:wo({existingPostingJsonMetadata:s.posting_json_metadata,profile:i.profile,tokens:i.tokens})}]]},async(i,s)=>{n.setQueryData(M(e).queryKey,a=>{if(!a)return a;let c=JSON.parse(JSON.stringify(a));return c.profile=Ar({existingProfile:_o(a),profile:s.profile,tokens:s.tokens}),c}),await E(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 M0(e,t,r,n,o){return useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async i=>{let s=Po(e,t);await w().prefetchQuery(s);let a=w().getQueryData(s.queryKey);return await po(e,"follow",["follow",{follower:e,following:t,what:[...i==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...i==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:i==="toggle-ignore"?!a?.ignores:a?.ignores,follows:i==="toggle-follow"?!a?.follows:a?.follows}},onError:o,onSuccess(i){n(i),w().setQueryData(u.accounts.relations(e,t),i),t&&w().invalidateQueries(M(t));}})}function Er(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,o,i,s){if(!e||!t||n===void 0||!i)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:o,body:i,json_metadata:JSON.stringify(s)}]}function Qe(e,t,r,n,o,i,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:o,allow_curation_rewards:i,extensions:s}]}function Sr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function kr(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let o={account:e,author:t,permlink:r};return n&&(o.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",o]),required_auths:[],required_posting_auths:[e]}]}function He(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 du(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(i=>He(e,i.trim(),r,n))}function fu(e,t,r,n,o,i){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(o<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:o,executions:i,extensions:[]}]}function Je(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 Ue(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:o}]}function jo(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 lt(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [Ue(e,t,r,n,o),jo(e,o)]}function dt(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 ft(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function mt(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 gt(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 yt(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 Cr(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 Ve(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 Rr(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function Tr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(o=>o.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 Fr(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 Ht(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 mu(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 Ht(e,t)}function Ir(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]}],o=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,o]}function qr(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 Dr(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 Br(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 yu(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 hu(e,t,r,n,o){if(e==null||typeof e!="number"||!t||!r||!n||!o)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:o,extensions:[]}]}function Mr(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 Nr(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 Qr(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 Hr(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 Ur(e,t,r,n,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function Vr(e,t,r,n,o,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:o}]),required_auths:[],required_posting_auths:[e]}]}function _u(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function bu(e,t,r,n,o){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:o}]),required_auths:[],required_posting_auths:[e]}]}var Lo=(r=>(r.Buy="buy",r.Sell="sell",r))(Lo||{}),$o=(r=>(r.EMPTY="",r.SWAP="9",r))($o||{});function Vt(e,t,r,n,o,i){if(!e||!t||!r||!o||i===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:i,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:o}]}function Ut(e,t=3){return e.toFixed(t)}function wu(e,t,r,n,o=""){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 i=new Date(Date.now());i.setDate(i.getDate()+27);let s=i.toISOString().split(".")[0],a=+`${o}${Math.floor(Date.now()/1e3).toString().slice(2)}`,c=n==="buy"?`${Ut(t,3)} HBD`:`${Ut(t,3)} HIVE`,p=n==="buy"?`${Ut(r,3)} HIVE`:`${Ut(r,3)} HBD`;return Vt(e,c,p,false,s,a)}function jr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function Lr(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 vu(e,t,r,n,o,i){if(!e||!o)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:o,json_metadata:i}]}function Pu(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 $r(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let o={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={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:o,active:i,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Wr(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]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},i={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:o,posting:i,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Gr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function zr(e,t,r,n,o,i){if(!e||!t||!r||!o)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:o,json_metadata:i}]}function Au(e,t,r,n,o){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let i={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:i,memo_key:n,json_metadata:o}]}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 xu(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 Eu(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 Yr(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 Xr(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 Ye(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let o=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:o,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function Su(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let o=t.trim().split(/[\s,]+/).filter(Boolean);if(o.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return o.map(i=>Ye(e,i.trim(),r,n))}function Zr(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 ku(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 Cu(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 iP(e,t,r){return v(["accounts","follow"],e,({following:n})=>[Fr(e,n)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function uP(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[Ht(e,n)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function fP(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:o,permlink:i})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(f.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:o,permlink:i,code:t})})).json()},onSuccess:()=>{r(),w().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function hP(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await _()(f.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:o,code:t})})).json()},onSuccess:()=>{r(),w().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function vP(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await _()(f.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})})).json()},onSuccess:(o,i)=>{r();let s=w();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,i)});},onError:n})}function EP(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await _()(f.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async o=>{if(!e)return;let i=w(),s=u.accounts.favorites(e),a=u.accounts.favoritesInfinite(e),c=u.accounts.checkFavorite(e,o);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a}),i.cancelQueries({queryKey:c})]);let p=i.getQueryData(s);p&&i.setQueryData(s,p.filter(g=>g.account!==o));let l=i.getQueryData(c);i.setQueryData(c,false);let d=i.getQueriesData({queryKey:a}),m=new Map(d);for(let[g,h]of d)h&&i.setQueryData(g,{...h,pages:h.pages.map(P=>({...P,data:P.data.filter(O=>O.account!==o)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(o,i)=>{r();let s=w();s.invalidateQueries({queryKey:u.accounts.favorites(e)}),s.invalidateQueries({queryKey:u.accounts.favoritesInfinite(e)}),s.invalidateQueries({queryKey:u.accounts.checkFavorite(e,i)});},onError:(o,i,s)=>{let a=w();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,i),s.previousCheck),n(o);}})}function Ku(e,t){let r=new Map;return e.forEach(([n,o])=>{r.set(n.toString(),o);}),t.forEach(([n,o])=>{r.set(n.toString(),o);}),Array.from(r.entries()).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>[n,o])}function Wo(e,t){let{data:r}=useQuery(M(e));return useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:o=false,currentKey:i,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:[]],g=o?l.key_auths.filter(([h])=>!m.includes(h.toString())):[];return l.key_auths=Ku(g,n.map((h,P)=>[h[p].createPublic().toString(),P+1])),l};return ee([["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()}]],i)},...t})}function KP(e,t){let{data:r}=useQuery(M(e)),{mutateAsync:n}=Wo(e);return useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:o,currentPassword:i,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=U.fromLogin(e,i,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:U.fromLogin(e,o,"owner"),active:U.fromLogin(e,o,"active"),posting:U.fromLogin(e,o,"posting"),memo_key:U.fromLogin(e,o,"memo")}]})},...t})}function UP(e,t,r){let n=useQueryClient(),{data:o}=useQuery(M(e));return useMutation({mutationKey:["accounts","revoke-posting",o?.name],mutationFn:async({accountName:i,type:s,key:a})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let c=JSON.parse(JSON.stringify(o.posting));c.account_auths=c.account_auths.filter(([l])=>l!==i);let p={account:o.name,posting:c,memo_key:o.memo_key,json_metadata:o.json_metadata};if(s==="key"&&a)return ee([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(o.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."),uo.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(i,s,a)=>{t.onSuccess?.(i,s,a),n.setQueryData(M(e).queryKey,c=>({...c,posting:{...c?.posting,account_auths:c?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function zP(e,t,r,n){let{data:o}=useQuery(M(e));return useMutation({mutationKey:["accounts","recovery",o?.name],mutationFn:async({accountName:i,type:s,key:a,email:c})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:o.name,new_recovery_account:i,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let d=await _()(f.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:c,publicKeys:[...o.owner.key_auths,...o.active.key_auths,...o.posting.key_auths,o.memo_key]})});if(!d.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${d.status}`);return d}else {if(s==="key"&&a)return ee([["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(o.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."),uo.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function YP(e,t){let r=e.key_auths.filter(([o])=>!t.has(String(o))).reduce((o,[,i])=>o+i,0),n=(e.account_auths??[]).reduce((o,[,i])=>o+i,0);return r+n>=e.weight_threshold}function Go(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),o=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([c])=>!r.has(c.toString())),a},i=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:i?o(e.owner):void 0,active:o(e.active),posting:o(e.posting),memo_key:e.memo_key}}function nA(e,t){let{data:r}=useQuery(M(e));return useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:o})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let i=Array.isArray(o)?o:[o],s=Go(r,i);return ee([["account_update",s]],n)},...t})}function aA(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:o="0.000 HIVE"})=>[Gr(n,o)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(o.creator)]);},t,"active",{broadcastMode:r})}function lA(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[zr(e,n.currentPosting,n.grantedAccount,n.weightThreshold,n.memoKey,n.jsonMetadata)],async()=>{await E(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}function gA(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?Wr(e,n.newAccountName,n.keys):$r(e,n.newAccountName,n.keys,n.fee)],async()=>{await E(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}var en=300*60*24,Gu=1e4,zu=5e7;function zo(e){let t=k(e.vesting_shares).amount,r=k(e.received_vesting_shares).amount,n=k(e.delegated_vesting_shares).amount,o=k(e.vesting_withdraw_rate).amount,i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t+r-n-s}function Ju(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function Yu(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 Xu(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 o=zo(e);if(!Number.isFinite(o)||o<=0)return 0;let i=o*1e6,s=Math.ceil(i*r*60*60*24/Gu/(n*en)),a=wr(e),c=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(c)||s>c?0:Math.max(s-zu,0)}function Zu(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(Yu(t))return Xu(e,t,n);let o=0;try{if(o=zo(e),!Number.isFinite(o))return 0}catch{return 0}return Ju(o,r,n)}function bA(e){return wr(e).percentage/100}function wA(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*en/1e4}function vA(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 o=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/en;o>n&&(o=n);let i=o*100/n;return isNaN(i)?0:i>100?100:i}function PA(e){return Dt(e).percentage/100}function AA(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:o,fundRewardBalance:i,base:s,quote:a}=t;if(!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(a)||o===0||a===0)return 0;let c=Zu(e,t,r,n);return Number.isFinite(c)?c/o*i*(s/a):0}var ep={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 tp(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 rp(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function np(e){let t=e[0];return t==="custom_json"?tp(e):t==="create_proposal"||t==="update_proposal"?rp(e):ep[t]??"posting"}function xA(e){let t="posting";for(let r of e){let n=np(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function RA(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"):io(r)?n=U.fromString(r):n=U.from(r),ee([t],n)}})}function IA(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 BA(e="/"){return useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>uo.sendOperation(t,{callback:e},()=>{})})}function HA(){return queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await y("condenser_api.get_chain_properties",[])})}function Jo(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function Yo(e,t){return {...e??{},title:t.title,body:t.body}}function zA(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 i=await _()(f.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${i.status}`);return i.json()},onSuccess(r,n){let o=w(),i=Yo(r,n);o.setQueryData(ze(e,t).queryKey,s=>[i,...s??[]]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,c)=>c===0?{...a,data:[i,...a.data]}:a)});}})}function rO(e,t){return useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:o})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await _()(f.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:o}),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 o=w(),i=s=>Jo(s,r,n);o.setQueryData(ze(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?i(a):a)??[]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(c=>c.id===n.fragmentId?i(c):c)}))});}})}function cO(e,t){return useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await _()(f.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${o.status}`);return o},onSuccess(r,n){let o=w();o.setQueryData(ze(e,t).queryKey,i=>[...i??[]].filter(({id:s})=>s!==n.fragmentId)),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},i=>i&&{...i,pages:i.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 lO(e,t,r,n){let i=await _()(f.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(i);return {status:i.status,data:s}}async function dO(e){let r=await _()(f.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 fO(e,t,r="",n=""){let o={code:e,ty:t};r&&(o.bl=r),n&&(o.tx=n);let s=await _()(f.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});await G(s);}async function mO(e,t,r=null,n=null){let o={code:e};t&&(o.filter=t),r&&(o.since=r),n&&(o.user=n);let s=await _()(f.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return G(s)}async function gO(e,t,r,n,o,i){let s={code:e,username:t,token:i,system:r,allows_notify:n,notify_types:o},c=await _()(f.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function yO(e,t,r){let n={code:e,username:t,token:r},i=await _()(f.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}async function Xo(e,t){let r={code:e};t&&(r.id=t);let o=await _()(f.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function Zo(e,t){let r={code:e,url:t},o=await _()(f.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}var dp="https://i.ecency.com";async function ei(e,t,r){let n=_(),o=new FormData;o.append("file",e);let i=await n(`${dp}/hs/${t}`,{method:"POST",body:o,signal:r});return G(i)}async function hO(e,t,r,n){let o=_(),i=new FormData;i.append("file",e);let s=await o(`${f.imageHost}/${t}/${r}`,{method:"POST",body:i,signal:n});return G(s)}async function ti(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function ri(e,t,r,n,o){let i={code:e,title:t,body:r,tags:n,meta:o},a=await _()(f.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return G(a)}async function ni(e,t,r,n,o,i){let s={code:e,id:t,title:r,body:n,tags:o,meta:i},c=await _()(f.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function oi(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function ii(e,t,r,n,o,i,s,a){let c={code:e,permlink:t,title:r,body:n,meta:o,schedule:s,reblog:a};i&&(c.options=i);let l=await _()(f.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});return G(l)}async function si(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function ai(e,t){let r={code:e,id:t},o=await _()(f.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function _O(e,t,r){let n={code:e,author:t,permlink:r},i=await _()(f.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}async function bO(e,t,r){let n={username:e,email:t,friend:r},i=await _()(f.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}function OO(e,t,r,n){return useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:o,body:i,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return ri(t,o,i,s,a)},onSuccess:o=>{r?.();let i=w();o?.drafts?i.setQueryData(u.posts.drafts(e),o.drafts):i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function CO(e,t,r,n){return useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:o,title:i,body:s,tags:a,meta:c})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return ni(t,o,i,s,a,c)},onSuccess:()=>{r?.();let o=w();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function DO(e,t,r,n){return useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return oi(t,o)},onMutate:async({draftId:o})=>{if(!e)return;let i=w(),s=u.posts.drafts(e),a=u.posts.draftsInfinite(e);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a})]);let c=i.getQueryData(s);c&&i.setQueryData(s,c.filter(d=>d._id!==o));let p=i.getQueriesData({queryKey:a}),l=new Map(p);for(let[d,m]of p)m&&i.setQueryData(d,{...m,pages:m.pages.map(g=>({...g,data:g.data.filter(h=>h._id!==o)}))});return {previousList:c,previousInfinite:l}},onSuccess:()=>{r?.();let o=w();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:(o,i,s)=>{let a=w();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?.(o);}})}function QO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:o,title:i,body:s,meta:a,options:c,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return ii(t,o,i,s,a,c,p,l)},onSuccess:()=>{r?.(),w().invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function LO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return si(t,o)},onSuccess:o=>{r?.();let i=w();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function JO(e,t,r,n){return useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return ai(t,o)},onSuccess:o=>{r?.();let i=w();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)}),i.invalidateQueries({queryKey:u.posts.drafts(e)});},onError:n})}function tx(e,t,r,n){return useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:o,code:i})=>{let s=i??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return Zo(s,o)},onSuccess:()=>{r?.(),w().invalidateQueries({queryKey:u.posts.images(e)});},onError:n})}function sx(e,t,r,n){return useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return ti(t,o)},onSuccess:(o,i)=>{r?.();let s=w(),{imageId:a}=i;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 px(e,t){return useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:o})=>ei(r,n,o),onSuccess:e,onError:t})}function Lt(e,t){return `/@${e}/${t}`}function Pp(e,t,r){return (r??w()).getQueryData(u.posts.entry(Lt(e,t)))}function Ap(e,t){(t??w()).setQueryData(u.posts.entry(Lt(e.author,e.permlink)),e);}function jt(e,t,r,n){let o=n??w(),i=Lt(e,t),s=o.getQueryData(u.posts.entry(i));if(!s)return;let a=r(s);return o.setQueryData(u.posts.entry(i),a),s}var je;(a=>{function e(c,p,l,d,m){jt(c,p,g=>({...g,active_votes:l,stats:{...g.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:g.stats?.flag_weight||0},total_votes:l.length,payout:d,pending_payout_value:String(d)}),m);}a.updateVotes=e;function t(c,p,l,d){jt(c,p,m=>({...m,reblogs:l}),d);}a.updateReblogsCount=t;function r(c,p,l,d){jt(c,p,m=>({...m,children:l}),d);}a.updateRepliesCount=r;function n(c,p,l,d){jt(p,l,m=>({...m,children:m.children+1,replies:[c,...m.replies]}),d);}a.addReply=n;function o(c,p){c.forEach(l=>Ap(l,p));}a.updateEntries=o;function i(c,p,l){(l??w()).invalidateQueries({queryKey:u.posts.entry(Lt(c,p))});}a.invalidateEntry=i;function s(c,p,l){return Pp(c,p,l)}a.getEntry=s;})(je||={});function Op(e,t,r){let n=e.some(o=>o.voter===t);return r!==0?n:!n}function xp(e,t,r){let n=je.getEntry(t.author,t.permlink,r);if(!n?.active_votes||Op(n.active_votes,e,t.weight))return;let o=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],i=n.payout+(t.estimated??0);je.updateVotes(t.author,t.permlink,o,i,r);}function hx(e,t,r){return v(["posts","vote"],e,({author:n,permlink:o,weight:i})=>[Er(e,n,o,i)],async(n,o)=>{xp(e,o);let i=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(120,i,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([u.posts.entry(`/@${o.author}/${o.permlink}`),u.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function Px(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:o,deleteReblog:i})=>[kr(e,n,o,i??false)],async(n,o)=>{let i=je.getEntry(o.author,o.permlink);if(i){let p=Math.max(0,(i.reblogs??0)+(o.deleteReblog?-1:1));je.updateReblogsCount(o.author,o.permlink,p);}let s=n?.id??n?.tx_id;t?.adapter?.recordActivity&&s&&t.adapter.recordActivity(130,s,n?.block_num).catch(()=>{});let a=()=>{w().invalidateQueries({queryKey:u.posts.accountPostsBlogPrefix(e)}),t?.adapter?.invalidateQueries&&t.adapter.invalidateQueries([u.posts.entry(`/@${o.author}/${o.permlink}`),u.posts.rebloggedBy(o.author,o.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function Ep(e){return e.isUpdate?null:e.parentAuthor?110:100}function Ex(e,t,r){return v(["posts","comment"],e,n=>{let o=[];if(o.push(Ne(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let d=[...p].sort((m,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:d.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(Qe(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{let i=!o.parentAuthor,s=Ep(o),a=n?.id??n?.tx_id;if(s!==null&&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(!i){c.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let p=o.rootAuthor||o.parentAuthor,l=o.rootPermlink||o.parentPermlink;c.push({predicate:d=>{let m=d.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 Cx(e,t,r,n){let o=n??w(),i=o.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 i)a&&o.setQueryData(s,[e,...a]);}function ci(e,t,r,n,o){let i=o??w(),s=new Map,a=i.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),i.setQueryData(c,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function ui(e,t){let r=t??w();for(let[n,o]of e)r.setQueryData(n,o);}function Rx(e,t,r,n){let o=n??w(),i=`/@${e}/${t}`,s=o.getQueryData(u.posts.entry(i));return s&&o.setQueryData(u.posts.entry(i),{...s,...r}),s}function Tx(e,t,r,n){let o=n??w(),i=`/@${e}/${t}`;o.setQueryData(u.posts.entry(i),r);}function Kx(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:o})=>[Sr(n,o)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e)];if(o.parentAuthor&&o.parentPermlink){i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let o=n.rootAuthor||n.parentAuthor,i=n.rootPermlink||n.parentPermlink;return o&&i?{snapshots:ci(n.author,n.permlink,o,i)}:{}},onError:(n,o,i)=>{let{snapshots:s}=i??{};s&&ui(s);}})}function Qx(e,t,r){return v(["posts","cross-post"],e,n=>{let o=[];if(o.push(Ne(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true}=n.options;o.push(Qe(n.author,n.permlink,i,s,a,c,[]));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.parentPermlink}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"async"})}function jx(e,t,r){return v(["posts","update-reply"],e,n=>{let o=[];if(o.push(Ne(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true,beneficiaries:p=[]}=n.options,l=[];if(p.length>0){let d=[...p].sort((m,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:d.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(Qe(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.resourceCredits.account(e)];i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r})}function Gx(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:o,duration:i})=>[Xr(e,n,o,i)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.posts._promotedPrefix],[...u.points._prefix(e)],u.posts.entry(`/@${o.author}/${o.permlink}`)]);},t,"active",{broadcastMode:r})}var Sp=[3e3,3e3,3e3],kp=e=>new Promise(t=>setTimeout(t,e));async function Cp(e,t){return y("condenser_api.get_content",[e,t])}async function Rp(e,t,r=0,n){let o=n?.delays??Sp,i;try{i=await Cp(e,t);}catch{i=void 0;}if(i||r>=o.length)return;let s=o[r];return s>0&&await kp(s),Rp(e,t,r+1,n)}var Xe={};vt(Xe,{useRecordActivity:()=>tn});function Fp(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function tn(e,t,r){return useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=_(),o=Fp(),i=r?.url??o.url,s=r?.domain??o.domain;try{await n(f.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:i,domain:s,props:{username:e}})});}catch{}}})}function oE(e){return queryOptions({queryKey:["analytics","discover-leaderboard",e],queryFn:async({signal:t})=>{let r=await fetch(f.privateApiHost+`/private-api/leaderboard/${e}`,{signal:t});if(!r.ok)throw new Error(`Failed to fetch leaderboard: ${r.status}`);return r.json()}})}function uE(e){return queryOptions({queryKey:["analytics","discover-curation",e],queryFn:async({signal:t})=>{let r=await fetch(f.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(),o=n.map(s=>s.account),i=await y("condenser_api.get_accounts",[o]);for(let s=0;sa.efficiency-s.efficiency),n}})}function fE(e,t=[],r=["visitors","pageviews","visit_duration"],n){let o=[...t].sort(),i=[...r].sort();return queryOptions({queryKey:["analytics","page-stats",e,o,i,n],queryFn:async({signal:s})=>{let a=await fetch(f.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 $t="threespeakfund",bE=1100;function Kp(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function wE(e,t){if(!Kp(t))return e;let r=e.find(n=>n.account===$t);return r&&r.weight===1100?e:r?e.map(n=>n.account===$t?{...n,weight:1100}:n):[...e,{account:$t,weight:1100}]}function vE(e){return e===$t}var on={};vt(on,{getAccountTokenQueryOptions:()=>nn,getAccountVideosQueryOptions:()=>Up});var rn={};vt(rn,{getDecodeMemoQueryOptions:()=>Np});function Np(e,t,r){return queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new uo.Client({accessToken:r}).decode(t)}})}var pi={queries:rn};function nn(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"}}),o=pi.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await w().prefetchQuery(o);let{memoDecoded:i}=w().getQueryData(o.queryKey);return i.replace("#","")}})}function Up(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=nn(e,t);await w().prefetchQuery(r);let n=w().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 ME={queries:on};function jE(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 GE({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:o,enabled:i=true}){return queryOptions({queryKey:["integrations","plausible",e,t,r,n,o],queryFn:async()=>{let a=await _()(`${f.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...o?{date_range:o}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&i,retry:1})}function XE(){return queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await y("rc_api.get_rc_stats",{})).rc_stats})}function rS(e){return queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await y("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}function aS(){return queryOptions({queryKey:u.resourceCredits.resourceParams(),staleTime:1440*60*1e3,gcTime:1/0,queryFn:async()=>await y("rc_api.get_resource_params",{})})}var Wt=["resource_history_bytes","resource_new_accounts","resource_market_bytes","resource_state_bytes","resource_execution_time"];var Gp=11,zp=65,Jp=16,Ze=e=>BigInt(typeof e=="string"?e:Math.trunc(e));function sn(e,t,r,n){if(r<=0||n<=0)return 0;let o=Ze(e.coeff_a),i=Ze(e.coeff_b),s=Ze(e.shift),a=Ze(n)*o>>s;a+=1n,a*=Ze(r);let c=i+(t>0?Ze(t):0n);return c===0n?0:Number(a/c+1n)}function an({transactionBytes:e,permlinkLength:t,signatures:r=1,beneficiaries:n=0,hasCommentOptions:o=false},i){let s=i.resource_state_bytes,a=i.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+(o?a.comment_options_time:0)}}var _e=e=>{let t=ut(e);return ye(t)+t},Yp=e=>1+_e(e.parent_author)+_e(e.parent_permlink)+_e(e.author)+_e(e.permlink)+_e(e.title)+_e(e.body)+_e(e.json_metadata),Xp=(e,t)=>{let r=t.beneficiaries??[],n=1+_e(e.author)+_e(e.permlink)+Jp+2+2;return n+=ye(r.length>0?1:0),r.length>0&&(n+=1+ye(r.length),r.forEach(o=>{n+=_e(o.account)+2;})),n};function cn({op:e,options:t,signatures:r=1}){let n=[Yp(e)];return t&&n.push(Xp(e,t)),Gp+ye(n.length)+n.reduce((o,i)=>o+i,0)+ye(r)+zp*r}var Zp={ready:false,cost:0,transactionBytes:0,breakdown:[]};function dS({op:e,options:t,rcParams:r,rcStats:n,signatures:o=1}){if(!r?.resource_params||!r.size_info||!n?.pool||!n.share)return Zp;let i=cn({op:e,options:t,signatures:o}),s=an({transactionBytes:i,permlinkLength:ut(e.permlink),signatures:o,beneficiaries:t?.beneficiaries?.length??0,hasCommentOptions:!!t},r.size_info),a=Number(n.regen),c=0,p=[];return Wt.forEach((l,d)=>{let m=r.resource_params[l],g=Number(n.pool[d]??0),h=Number(n.share[d]??0);if(!m||h<=0)return;let P=s[l]*Number(m.resource_dynamics_params.resource_unit??1),O=Number(BigInt(a)*BigInt(h)/10000n),T=sn(m.price_curve_params,g,P,O);c+=T,p.push({resource:l,usage:P,cost:T});}),{ready:true,cost:c,transactionBytes:i,breakdown:p}}function un(e,t,r){let n=Number(r.regen),o=0,i=[];return Wt.forEach((s,a)=>{let c=t.resource_params[s],p=Number(r.pool[a]??0),l=Number(r.share[a]??0);if(!c||l<=0)return;let d=e[s]*Number(c.resource_dynamics_params.resource_unit??1),m=Number(BigInt(n)*BigInt(l)/10000n),g=sn(c.price_curve_params,p,d,m);o+=g,i.push({resource:s,usage:d,cost:g});}),{cost:o,breakdown:i}}var el=11,tl=65,pn=e=>{let t=ut(e);return ye(t)+t},rl=()=>({resource_history_bytes:0,resource_new_accounts:0,resource_market_bytes:0,resource_state_bytes:0,resource_execution_time:0});function li(e,t=1){let r=1+pn(e.voter)+pn(e.author)+pn(e.permlink)+2;return el+ye(1)+r+ye(t)+tl*t}function di({transactionBytes:e,signatures:t=1},r){let n=r.resource_state_bytes,o=r.resource_execution_time;return {...rl(),resource_history_bytes:e,resource_state_bytes:n.vote_size+n.transaction_base_size,resource_execution_time:o.vote_time+o.transaction_time+o.verify_authority_time*t}}var fi={ready:false,currentMana:0,maxMana:0,avgCost:0,cost:0,transactionBytes:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function AS({rcAccount:e,rcStats:t,rcParams:r,operation:n,payload:o,fallback:i="minimal",buffer:s=1.2}){if(!e||!t?.ops)return fi;let{current_mana:a,max_mana:c}=Dt(e),p=nl(n,o,i,r,t);if(!p)return {...fi,currentMana:a,maxMana:c};let{cost:l,transactionBytes:d}=p,m=Number.isFinite(s)&&s>0?s:1.2,g=l*m,h=a0?{cost:r,transactionBytes:0}:null}var il={author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa",parent_author:"",parent_permlink:"hive-100000",title:"",body:"",json_metadata:"{}"},sl={voter:"aaaaaaaaaa",author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa"};function SS(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 _()(f.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}async function ul(e,t,r){let o=await _()(f.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:t,code:e,key:r}),headers:{"Content-Type":"application/json"}}),i=(o.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),s=await o.text();if(!o.ok){let a=s&&i.includes("json")?`: ${s.slice(0,200)}`:"";throw new Error(`[SDK][Games] \u2013 failed with status ${o.status}${a}`)}if(!i.includes("json"))throw new Error(`[SDK][Games] \u2013 expected JSON but received "${i||"empty"}" response (status ${o.status})`);try{return JSON.parse(s)}catch{throw new Error(`[SDK][Games] \u2013 malformed JSON response (status ${o.status})`)}}function FS(e,t,r,n){let{mutateAsync:o}=tn(e,"spin-rolled");return useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return ul(t,r,n)},onSuccess(){o();}})}function KS(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 _()(f.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 ll=[{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 MS(e,t){return ll.find(r=>r.tier===e&&r.id===t)}var dl=25;function fl(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function NS(e){return fl(e)>dl}var QS=300,HS=2;function yl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function hl(e){let r=await _()(f.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:yl()})});if(!r.ok){let n;try{n=await r.json();}catch{}let o=n?.message??`Failed to buy streak freeze: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function LS(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 hl(t)},onSuccess(){n&&r.invalidateQueries({queryKey:u.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:u.quests.status(n)});}})}function zS(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[Mr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"async"})}function ZS(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[Nr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"sync"})}function nk(e,t,r){return v(["communities","mutePost"],e,({community:n,author:o,permlink:i,notes:s,mute:a})=>[Vr(e,n,o,i,s,a)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.posts.entry(`/@${o.author}/${o.permlink}`),["community","single",o.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.community}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"sync"})}function ak(e,t,r,n){return v(["communities","set-role",e],t,({account:o,role:i})=>[Qr(t,e,o,i)],async(o,i)=>{w().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>{if(!a)return a;let c=[...a.team??[]],p=c.findIndex(([l])=>l===i.account);return p>=0?c[p]=[c[p][0],i.role,c[p][2]??""]:c.push([i.account,i.role,""]),{...a,team:c}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)],u.communities.context(i.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function lk(e,t,r,n){return v(["communities","update",e],t,o=>[Hr(t,e,o)],async(o,i)=>{w().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>a&&{...a,...i}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function gk(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[Zr(n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.communities.singlePrefix(o.name)],[...u.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function bk(e,t,r){return v(["communities","pin-post"],e,({community:n,account:o,permlink:i,pin:s})=>[Ur(e,n,o,i,s)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.posts.entry(`/@${o.account}/${o.permlink}`),[...u.communities.singlePrefix(o.community)]]);},t,"posting",{broadcastMode:r??"async"})}function Ok(e,t,r=100,n=void 0,o=true){return queryOptions({queryKey:u.communities.list(e,t??"",r),enabled:o,queryFn:async()=>{let i=await y("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return i?e==="hot"?i.sort(()=>Math.random()-.5):i:[]}})}function Ck(e,t){return queryOptions({queryKey:u.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await y("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function qk(e,t="",r=true){return queryOptions({queryKey:u.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>To(e??"",t)})}var mi=100;async function gi(e,t){return await y("bridge.list_subscribers",{community:e,limit:mi,...t?{last:t}:{}})??[]}function Qk(e){return queryOptions({queryKey:u.communities.subscribers(e),queryFn:async()=>gi(e,null),staleTime:6e4})}function Hk(e){return infiniteQueryOptions({queryKey:u.communities.subscribersInfinite(e),initialPageParam:null,queryFn:async({pageParam:t})=>gi(e,t),getNextPageParam:t=>t?.length>=mi?t[t.length-1]?.[0]??null:null,staleTime:6e4})}function Wk(e,t){return infiniteQueryOptions({queryKey:u.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await y("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function Yk(){return queryOptions({queryKey:u.communities.rewarded(),queryFn:async()=>{let e=await fetch(f.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 xl=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(xl||{}),Zk={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function tC(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function rC({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),o=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),i=["owner","admin","mod"].includes(t);return {canPost:n,canComment:o,isModerator:i}}function sC(e,t){return queryOptions({queryKey:u.notifications.unreadCount(e),queryFn:async()=>t?(await(await fetch(`${f.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 pC(e,t,r=void 0){return infiniteQueryOptions({queryKey:u.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let o={code:t,filter:r,since:n,user:void 0},i=await fetch(f.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)return [];try{return await i.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var kl=(g=>(g.VOTES="rvotes",g.MENTIONS="mentions",g.FAVORITES="nfavorites",g.BOOKMARKS="nbookmarks",g.FOLLOWS="follows",g.REPLIES="replies",g.REBLOGS="reblogs",g.TRANSFERS="transfers",g.DELEGATIONS="delegations",g.PAYOUTS="payouts",g.SCHEDULED_PUBLISHED="scheduled_published",g.ACCOUNT_UPDATES="account_updates",g.WEEKLY_EARNINGS="weekly_earnings",g))(kl||{});var Cl=(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))(Cl||{}),yi=[1,2,3,4,5,6,10,13,15,19,20,21,22],Rl=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(Rl||{});function hC(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 o=await fetch(f.privateApiHost+"/private-api/detail-device",{body:JSON.stringify({code:t,username:e,token:n}),method:"POST",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch notification settings: ${o.status}`);return o.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...yi]})})}function vC(){return queryOptions({queryKey:u.notifications.announcements(),queryFn:async()=>{let e=await fetch(f.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 xC(e){return queryOptions({queryKey:u.notifications.spotlights(),queryFn:async()=>{let t=await fetch(f.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 Dl(e,t){return {...e,read:!t||t===e.id?1:e.read}}function hi(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function FC(e,t,r,n){let o=w();return useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:i})=>{if(!e||!t){process.env.NODE_ENV!=="production"&&console.warn("[SDK][Notifications] \u2013 missing auth for markNotifications");return}return Xo(t,i)},onMutate:async({id:i})=>{if(!e||!t)return {previousData:[]};await o.cancelQueries({queryKey:u.notifications._prefix});let s=[],a=o.getQueriesData({queryKey:u.notifications._prefix,predicate:l=>{let d=l.state.data;return hi(d)}});a.forEach(([l,d])=>{if(d&&hi(d)){s.push([l,d]);let m={...d,pages:d.pages.map(g=>g.map(h=>Dl(h,i)))};o.setQueryData(l,m);}});let c=u.notifications.unreadCount(e),p=o.getQueryData(c);return typeof p=="number"&&p>0&&(s.push([c,p]),i?a.some(([,d])=>d?.pages.some(m=>m.some(g=>g.id===i&&g.read===0)))&&o.setQueryData(c,p-1):o.setQueryData(c,0)),{previousData:s}},onSuccess:i=>{let s=typeof i=="object"&&i!==null?i.unread:void 0;typeof s=="number"&&o.setQueryData(u.notifications.unreadCount(e),s),r?.(s);},onError:(i,s,a)=>{a?.previousData&&a.previousData.forEach(([c,p])=>{o.setQueryData(c,p);}),n?.(i);},onSettled:()=>{o.invalidateQueries({queryKey:u.notifications._prefix});}})}function KC(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>Ir(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function QC(e){return queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await y("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 y("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(o=>o.status==="expired");return [...t.filter(o=>o.status!=="expired"),...r]}})}function JC(e,t,r){return infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await y("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 y("condenser_api.get_accounts",[s.map(l=>l.voter)]),c=Nt(a);return s.map(l=>({...l,voterAccount:c.find(d=>l.voter===d.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function eR(e){return queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await y("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 oR(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:o})=>[Br(e,n,o)],async n=>{try{let o=n?.id??n?.tx_id;t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(150,o,n?.block_num).catch(i=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:o,error:i});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.proposals.list(),u.proposals.votesByUser(e)]);}catch(o){console.warn("[useProposalVote] Post-broadcast side-effect failed:",o);}},t,"active",{broadcastMode:r})}function cR(e,t,r){return v(["proposals","create"],e,n=>[Kr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.proposals.list()]);},t,"active",{broadcastMode:r})}function dR(e,t=50){return infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,o=await y("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&o.length>0&&o[0]?.delegatee===r?o.slice(1,t+1):o},getNextPageParam:r=>!r||r.lengthte("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function wR(e){return queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await y("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function OR(e){return queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>y("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function kR(e){return queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>y("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function FR(e){return queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>y("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function KR(e){return queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function QR(e){return queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>y("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function LR(e,t=100){return infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let o=(await y("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(i=>i)).rc_direct_delegations||[];return r&&(o=o.filter(i=>i.to!==r)),o},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function zR(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 _()(`${f.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function ZR(e){return queryOptions({queryKey:["wallet","received-vesting-shares",e],queryFn:async()=>{let t=await fetch(f.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 nT(e){return queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>y("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 o=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(o){let i=Number.parseFloat(o[0]);if(Number.isFinite(i))return i}}}function Zl(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 ed(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 o of ["wallets","tokens","assets","items","portfolio","balances"]){let i=n[o];if(Array.isArray(i))return i}}return []}function td(e){if(!e||typeof e!="object")return;let t=e;return fe(t.username)??fe(t.name)??fe(t.account)}function _i(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=`${Q.getValidatedBaseUrl()}/wallet-api/portfolio-v2`,o=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!o.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${o.status})`);let i=await o.json(),s=ed(i).map(a=>Zl(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:td(i)??e,currency:fe(i?.fiatCurrency??i?.currency)?.toUpperCase(),wallets:s}}})}function Gt(e){return queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await w().prefetchQuery(Oe()),await w().prefetchQuery(M(e));let t=w().getQueryData(Oe().queryKey),r=w().getQueryData(M(e).queryKey),n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:0};let i=k(r.balance).amount,s=k(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:i+s,parts:[{name:"current",balance:i},{name:"savings",balance:s}]}}})}function bi(e){return queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await w().prefetchQuery(Oe()),await w().prefetchQuery(M(e));let t=w().getQueryData(M(e).queryKey),r=w().getQueryData(Oe().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:k(t.hbd_balance).amount+k(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:k(t.hbd_balance).amount},{name:"savings",balance:k(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function id(e){let c=9.5-(e.headBlock-7e6)/25e4*.01;c<.95&&(c=.95);let p=e.vestingRewardPercent/1e4,l=e.virtualSupply,d=e.totalVestingFund;return (l*c*p/d).toFixed(3)}function wi(e){return queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await w().prefetchQuery(Oe()),await w().prefetchQuery(M(e));let t=w().getQueryData(Oe().queryKey),r=w().getQueryData(M(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??""),i=Number.isFinite(o)?o:t.base/t.quote,s=k(r.vesting_shares).amount,a=k(r.delegated_vesting_shares).amount,c=k(r.received_vesting_shares).amount,p=k(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),d=go(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+We(s,t.hivePerMVests).toFixed(3),g=+We(a,t.hivePerMVests).toFixed(3),h=+We(c,t.hivePerMVests).toFixed(3),P=+We(l,t.hivePerMVests).toFixed(3),O=+We(d,t.hivePerMVests).toFixed(3),T=Math.max(m-P,0),F=Math.max(m-g,0);return {name:"HP",title:"Hive Power",price:i,accountBalance:+T.toFixed(3),apr:id(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+F.toFixed(3)},{name:"outgoing_delegations",balance:g},{name:"incoming_delegations",balance:h},...P>0?[{name:"pending_power_down",balance:+P.toFixed(3)}]:[],...O>0&&O!==P?[{name:"next_power_down",balance:+O.toFixed(3)}]:[]]}}})}var B=ne.operations,ln={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 kT=Object.keys(ne.operations);var vi=ne.operations,TT=vi,FT=Object.entries(vi).reduce((e,[t,r])=>(e[r]=t,e),{});var Pi=ne.operations;function ad(e){return Object.prototype.hasOwnProperty.call(Pi,e)}function ht(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),o=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),i=new Set;r||n.forEach(a=>{if(a in ln){ln[a].forEach(c=>i.add(c));return}ad(a)&&i.add(Pi[a]);});let s=pd(Array.from(i));return {filterKey:o,filterArgs:s}}function dn(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function cd(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function ud(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function pd(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await y("condenser_api.get_account_history",[e,s,ud(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 k(p.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(p.amount).symbol==="HIVE";case "transfer_from_savings":case "fill_transfer_from_savings":return k(p.amount).symbol==="HIVE";case "fill_recurrent_transfer":let d=k(p.amount);return ["HIVE"].includes(d.symbol);case "claim_reward_balance":return k(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 i.has(p.type)}}))})})}function VT(e,t=20,r=[]){let{filterKey:n}=ht(r),o=dn(r);return infiniteQueryOptions({...zt(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:i,pageParams:s})=>({pageParams:s,pages:i.map(a=>a.filter(c=>{switch(c.type){case "author_reward":case "comment_benefactor_reward":return k(c.hbd_payout).amount>0;case "claim_reward_balance":return k(c.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(c.amount).symbol==="HBD";case "transfer_from_savings":case "fill_transfer_from_savings":return k(c.amount).symbol==="HBD";case "fill_recurrent_transfer":let d=k(c.amount);return ["HBD"].includes(d.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 o.has(c.type)}}))})})}function GT(e,t=20,r=[]){let{filterKey:n}=ht(r),o=new Set(Array.isArray(r)?r:[r]),i=o.has("")||o.size===0;return infiniteQueryOptions({...zt(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 k(p.vesting_payout).amount>0;case "claim_reward_balance":return k(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(k(p.amount).symbol);case "fill_recurrent_transfer":let m=k(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 i||o.has(p.type)}}))})})}function Ai(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 fn(e,t){return new Date(e.getTime()-t*1e3)}function XT(e=86400){return infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await y("condenser_api.get_market_history",[e,Ai(t),Ai(r)])).map(({hive:o,non_hive:i,open:s})=>({close:i.close/o.close,open:i.open/o.open,low:i.low/o.low,high:i.high/o.high,volume:o.volume,time:new Date(s)})),initialPageParam:[fn(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[fn(n,Math.max(100*e,28800)),fn(n,e)]})}function rF(e){return queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function sF(e,t=50){return queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>y("condenser_api.get_vesting_delegations",[e,"",t])})}function lF(e){return queryOptions({queryKey:["assets","hive-power","delegatings",e],queryFn:async()=>(await(await fetch(f.privateApiHost+`/private-api/received-vesting/${e}`,{headers:{"Content-Type":"application/json"}})).json()).list,select:t=>t.sort((r,n)=>k(n.vesting_shares).amount-k(r.vesting_shares).amount)})}function gF(e=500){return queryOptions({queryKey:["market","order-book",e],queryFn:()=>y("condenser_api.get_order_book",[e])})}function bF(){return queryOptions({queryKey:["market","statistics"],queryFn:()=>y("condenser_api.get_ticker",[])})}function AF(e,t,r){let n=o=>o.toISOString().replace(/\.\d{3}Z$/,"");return queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>y("condenser_api.get_market_history",[e,n(t),n(r)])})}function SF(){return queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await y("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),o=await y("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:o[0]?o[0].non_hive.open/o[0].hive.open:0,high:o[0]?o[0].non_hive.high/o[0].hive.high:0,low:o[0]?o[0].non_hive.low/o[0].hive.low:0,percent:o[0]?100-o[0].non_hive.open/o[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function TF(e,t,r,n){return queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:o})=>{let i=_(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await i(s,{signal:o});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function Oi(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function DF(e=1e3,t,r){let n=r??new Date,o=t??new Date(n.getTime()-600*60*1e3);return queryOptions({queryKey:["market","trade-history",e,o.getTime(),n.getTime()],queryFn:()=>y("condenser_api.get_trade_history",[Oi(o),Oi(n),e])})}function NF(){return queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await y("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function VF(){return queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await y("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function WF(e,t,r){return v(["market","limit-order-create"],e,n=>[Vt(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 YF(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[jr(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 _t(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 eI(e,t,r,n){let o=_(),i=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await o(i);return _t(s)}async function xi(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 _t(n)).hive_dollar[e]}async function tI(e,t){let n=await _()(f.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return _t(n)}async function rI(){let t=await _()(f.privateApiHost+"/private-api/market-data/latest");return _t(t)}async function nI(){let t=await _()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return _t(t)}var xd={"Content-type":"application/json"};async function Ed(e){let t=_(),r=Q.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:xd});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function Te(e,t){try{return await Ed(e)}catch{return t}}async function sI(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,o]=await Promise.all([Te({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),Te({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),i=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),d=Number(p.price??0);return l-d});return {buy:i(n),sell:s(o)}}async function aI(e,t=50){return Te({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 cI(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},[o,i]=await Promise.all([Te({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),Te({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=o.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=i.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 Sd(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return Te({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function et(e,t){return Sd(t,e)}async function Jt(e){return Te({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function Yt(e){return Te({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function Ei(e,t,r,n){let o=_(),i=Q.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",i);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 o(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 Si(e,t="daily"){let r=_(),n=Q.getValidatedBaseUrl(),o=new URL("/private-api/engine-chart-api",n);o.searchParams.set("symbol",e),o.searchParams.set("interval",t);let i=await r(o.toString(),{headers:{"Content-type":"application/json"}});if(!i.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${i.status}`);return await i.json()}async function ki(e){let t=_(),r=Q.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 Xt(e){return queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Jt(e)})}function gI(){return queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>et()})}function Ci(e){return queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Yt(e)})}function PI(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 Ei(e,t,r,n)},getNextPageParam:(n,o,i)=>(n?.length??0)===r?i+r:void 0,getPreviousPageParam:(n,o,i)=>i>0?i-r:void 0})}function EI(e,t="daily"){return queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Si(e,t)})}function RI(e){return queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await ki(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function Ri(e,t){return queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>et(e,t)})}function tt(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:o,suffix:i}=r,s="";o&&(s+=o+" ");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}),i&&(s+=" "+i),s}var Zt=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()?`(${tt(this.stake,{fractionDigits:this.precision})} + ${tt(this.delegationsIn,{fractionDigits:this.precision})} - ${tt(this.delegationsOut,{fractionDigits:this.precision})})`:"";staked=()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():tt(this.stakedBalance,{fractionDigits:this.precision}):"-";balanced=()=>this.balance<1e-4?this.balance.toString():tt(this.balance,{fractionDigits:this.precision})};function HI(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),o=await Yt(n.map(p=>p.symbol)),i=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 et(void 0,a):[]];return n.map(p=>{let l=o.find(O=>O.symbol===p.symbol),d;if(l?.metadata)try{d=JSON.parse(l.metadata);}catch{d=void 0;}let m=c.find(O=>O.symbol===p.symbol),g=Number(m?.lastPrice??"0"),h=Number(p.balance),P=p.symbol==="SWAP.HIVE"?i*h:g===0?0:Number((g*i*h).toFixed(10));return new Zt({symbol:p.symbol,name:l?.name??p.symbol,icon:d?.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:P})})},enabled:!!e})}function Ti(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=w(),n=Gt(e);await r.prefetchQuery(n);let o=r.getQueryData(n.queryKey),i=await r.ensureQueryData(Ci([t])),s=await r.ensureQueryData(Xt(e)),a=await r.ensureQueryData(Ri(void 0,t)),c=i?.find(O=>O.symbol===t),p=s?.find(O=>O.symbol===t),d=+(a?.find(O=>O.symbol===t)?.lastPrice??"0"),m=parseFloat(p?.balance??"0"),g=parseFloat(p?.stake??"0"),h=parseFloat(p?.pendingUnstake??"0"),P=[{name:"liquid",balance:m},{name:"staked",balance:g}];return h>0&&P.push({name:"unstaking",balance:h}),{name:t,title:c?.name??"",price:d===0?0:Number(d*(o?.price??0)),accountBalance:m+g,layer:"ENGINE",parts:P}}})}function bt(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(f.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 o=await n.json(),i=await fetch(f.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!i.ok)throw new Error(`Failed to fetch point transactions: ${i.status}`);let s=await i.json();return {points:o.points,uPoints:o.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function Fi(e){return queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await w().prefetchQuery(bt(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(w().getQueryData(bt(e).queryKey)?.points??0)})})}function iq(e,t){return queryOptions({queryKey:["assets","points","transactions",e,t],queryFn:async()=>(await(await fetch(`${f.privateApiHost}/private-api/point-list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:e,type:t??0})})).json()).map(({created:o,type:i,amount:s,id:a,sender:c,receiver:p,memo:l})=>({created:new Date(o),type:i,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:c??void 0,to:p??void 0,memo:l??void 0}))})}function hq(e,t,r={refetch:false}){let n=w(),o=r.currency??"usd",i=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||o==="usd")return p;try{let l=await xi(o);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${o}:`,l),p}},a=_i(e,o,true),c=async()=>{try{let l=(await n.fetchQuery(a)).wallets.find(m=>m.symbol.toUpperCase()===t.toUpperCase());if(!l)return;let d=[];if(l.liquid!==void 0&&l.liquid!==null&&d.push({name:"liquid",balance:l.liquid}),l.staked!==void 0&&l.staked!==null&&l.staked>0&&d.push({name:"staked",balance:l.staked}),l.savings!==void 0&&l.savings!==null&&l.savings>0&&d.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 g=m.dataKey,h=m.value;if(typeof h=="string"){let O=h.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(O){let T=Math.abs(Number.parseFloat(O[1]));g==="delegated_hive_power"?d.push({name:"outgoing_delegations",balance:T}):g==="received_hive_power"?d.push({name:"incoming_delegations",balance:T}):g==="powering_down_hive_power"&&d.push({name:"pending_power_down",balance:T});}}}return {name:l.symbol,title:l.name,price:l.fiatRate,accountBalance:l.balance,apr:l.apr?.toString(),layer:l.layer,pendingRewards:l.pendingRewards,parts:d}}catch{return}};return queryOptions({queryKey:["ecency-wallets","asset-info",e,t,o],queryFn:async()=>{let p=await c();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await i(Gt(e));else if(t==="HP")l=await i(wi(e));else if(t==="HBD")l=await i(bi(e));else if(t==="POINTS")l=await i(Fi(e));else if((await n.ensureQueryData(Xt(e))).some(m=>m.symbol===t))l=await i(Ti(e,t));else {if(p)return p;throw new Error(`[SDK][Wallet] \u2013 unrecognized asset "${t}"`)}if(p&&l&&l.price>0){let d=await s(l);return {...p,price:d.price}}return await s(l)}})}var Hd=(T=>(T.Transfer="transfer",T.TransferToSavings="transfer-saving",T.WithdrawFromSavings="withdraw-saving",T.Delegate="delegate",T.PowerUp="power-up",T.PowerDown="power-down",T.WithdrawRoutes="withdraw-routes",T.ClaimInterest="claim-interest",T.Swap="swap",T.Convert="convert",T.Gift="gift",T.Promote="promote",T.Claim="claim",T.Buy="buy",T.Stake="stake",T.Unstake="unstake",T.Undelegate="undelegate",T))(Hd||{});function Aq(e,t,r){return v(["wallet","transfer"],e,n=>[He(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function kq(e,t,r){return v(["wallet","transfer-point"],e,n=>[Ye(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Iq(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[mt(e,n.delegatee,n.vestingShares)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Mq(e,t,r){return v(["wallet","set-withdraw-vesting-route"],e,n=>[gt(e,n.toAccount,n.percent,n.autoVest)],async(n,o)=>{await E(t?.adapter,r,[u.wallet.withdrawRoutes(e),u.accounts.full(e),u.accounts.full(o.toAccount)]);},t,"active",{broadcastMode:r})}function Uq(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Wq(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[Je(e,n.to,n.amount,n.memo)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function Xq(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[Ue(e,n.to,n.amount,n.memo,n.requestId)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function nD(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[dt(e,n.to,n.amount)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function cD(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[ft(e,n.vestingShares)],async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function fD(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?Cr(e,n.amount,n.requestId):yt(e,n.amount,n.requestId)],async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function _D(e,t,r){return v(["wallet","claim-interest"],e,n=>lt(e,n.to,n.amount,n.memo,n.requestId),async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}var Ud=5e3,er=new Map;function AD(e,t,r){return v(["wallet","claim-rewards"],e,n=>[Lr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",o=[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)],i=er.get(n);i&&(clearTimeout(i),er.delete(n));let s=setTimeout(async()=>{try{let a=w(),p=(await Promise.allSettled(o.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{er.delete(n);}},Ud);er.set(n,s);},t,"posting",{broadcastMode:r})}function SD(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function TD(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let o=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:o}]]},async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function DD(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.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 o=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:o}]]},async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function VD(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let o=JSON.stringify(n.tokens.map(i=>({symbol:i})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:o}]]},async()=>{await E(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function WD(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let o,i;n.action==="cancel"?(i="cancel",o={type:n.orderType,id:n.orderId}):(i=n.action,o={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:i,contractPayload:o});return [["custom_json",{id:"ssc-mainnet-hive",required_auths:[e],required_posting_auths:[],json:s}]]},async()=>{await E(t?.adapter,r,[u.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:o="",amount:i="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [He(n,o,i,s)];case "transfer-saving":return [Je(n,o,i,s)];case "withdraw-saving":return [Ue(n,o,i,s,a)];case "power-up":return [dt(n,o,i)]}break;case "HBD":switch(t){case "transfer":return [He(n,o,i,s)];case "transfer-saving":return [Je(n,o,i,s)];case "withdraw-saving":return [Ue(n,o,i,s,a)];case "claim-interest":return lt(n,o,i,s,a);case "convert":return [yt(n,i,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [ft(n,i)];case "delegate":return [mt(n,o,i)];case "withdraw-routes":return [gt(r.from_account??n,r.to_account??o,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [Ye(n,o,i,s)];break}return null}function jd(e,t,r){let{from:n,to:o="",amount:i=""}=r,s=typeof i=="string"&&i.includes(" ")?i.split(" ")[0]:String(i);switch(t){case "transfer":return [Ve(n,"transfer",{symbol:e,to:o,quantity:s,memo:r.memo??""})];case "stake":return [Ve(n,"stake",{symbol:e,to:o,quantity:s})];case "unstake":return [Ve(n,"unstake",{symbol:e,to:o,quantity:s})];case "delegate":return [Ve(n,"delegate",{symbol:e,to:o,quantity:s})];case "undelegate":return [Ve(n,"undelegate",{symbol:e,from:o,quantity:s})];case "claim":return [Rr(n,[e])]}return null}function Ld(e){return e==="claim"?"posting":"active"}function ZD(e,t,r,n,o){let{mutateAsync:i}=Xe.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=Vd(t,r,s);if(a)return a;let c=jd(t,r,s);if(c)return c;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{i();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=>{w().invalidateQueries({queryKey:a});});},5e3);},n,Ld(r),{broadcastMode:o})}function nK(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:o})=>[Tr(e,n,o)],async(n,o)=>{await E(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),u.resourceCredits.account(e),u.resourceCredits.account(o.to)]);},t,"active",{broadcastMode:r})}function aK(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:o})=>[qr(e,n,o)],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 lK(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[Dr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function Wd(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 hK(e){return infiniteQueryOptions({queryKey:u.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await te("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(Wd),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function _K(e,t,r,n="vests",o="desc"){return queryOptions({queryKey:u.witnesses.voters(e,t,r,n,o),queryFn:async({signal:i})=>await te("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:o},void 0,void 0,i),enabled:!!e,staleTime:6e4})}function bK(e){return queryOptions({queryKey:u.witnesses.voterCount(e),queryFn:async()=>await te("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var Gd=(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))(Gd||{});async function Jd(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 _()(f.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),o=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),i=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(i)}catch{return {message:i,code:n.status}}let s=i&&o.includes("json")?`: ${i.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!o.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${o||"empty"}" response (status ${n.status})`);try{return JSON.parse(i)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function EK(e,t,r,n){let{mutateAsync:o}=Xe.useRecordActivity(e,"points-claimed");return useMutation({mutationFn:()=>Jd(e,t),onError:n,onSuccess:()=>{o(),w().setQueryData(bt(e).queryKey,i=>i&&{...i,points:(parseFloat(i.points)+parseFloat(i.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var qi=/(^|\s)author:([^\s]+)/g,Di=/(^|\s)type:([^\s]+)/g,Ki=/(^|\s)category:([^\s]+)/g,Bi=/(^|\s)tag:([^\s]+)/g;var Ni=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(Ni||{}),kK=5,CK=100;function Qi(e){return e.trim().split(/\s+/)[0]??""}function Yd(e){return Qi(e).replace(/^@+/,"").toLowerCase()}function Xd(e){return Qi(e).replace(/^#+/,"").toLowerCase()}function Zd(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 RK({search:e="",author:t="",type:r="",category:n="",tags:o=[]}){let i=e.trim().replace(/\s+/g," "),s=Yd(t),a=Xd(n),c=Zd(Array.isArray(o)?o.join(","):o),p=[i];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:i,author:s,type:r,category:a,tags:c}}var Mi=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(qi);};grabType=()=>{let t=this.grab(Di);Object.values(Ni).includes(t)&&(this.type=t);};grabCategory=()=>{this.category=this.grab(Ki);};grabTags=()=>{let t=new Set;this.tags=[...this.query.matchAll(Bi)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));};grabSearch=()=>{for([qi,Di,Ki,Bi].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 xe(e,t){let n=await(async()=>{let o;try{o=await e.text();}catch{return}if(o!=="")try{return JSON.parse(o)}catch{return e.ok?void 0:o}})();if(!e.ok){let o=new Error(`Request failed with status ${e.status}`);throw o.status=e.status,o.data=n,o}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 Fe(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var tf=isServer?0:3;function wt(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),o&&(a.scroll_id=o),i&&(a.votes=i);let c=await fetch(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(a),signal:Pe(Ae,s)});return xe(c,Fe)},retry:wt})}function HK(e,t,r=true){return infiniteQueryOptions({queryKey:u.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:o})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let i,s=new Date;switch(t){case "today":i=new Date(s.getTime()-1440*60*1e3);break;case "week":i=new Date(s.getTime()-10080*60*1e3);break;case "month":i=new Date(s.getTime()-720*60*60*1e3);break;case "year":i=new Date(s.getTime()-365*24*60*60*1e3);break;default:i=void 0;}let a="* type:post",c=e==="rising"?"children":e,p=i?i.toISOString().split(".")[0]:void 0,l="0",d=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=d);let g=await fetch(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(m),signal:Pe(Ae,o)});return xe(g,Fe)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:wt})}async function LK(e,t,r,n,o,i,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),o&&(a.scroll_id=o),i&&(a.votes=i);let p=await _()(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(a),signal:Pe(Ae,s)});return xe(p,Fe)}async function Hi(e,t,r=Ae){let o=await _()(f.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(e),signal:Pe(r,t)});return xe(o,Fe)}async function $K(e,t){let n=await _()(f.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify({q:e}),signal:Pe(Ae,t)}),o=await xe(n,Array.isArray);return o?.length>0?o:[e]}var sf=4368*60*60*1e3,af=4,cf=3e3,uf=2e3,pf=4e3,YK=2;function lf(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function df(e){let t=5381;for(let r=0;r>>0).toString(36)}function XK(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),o=lf(e.body??"",cf),i=df(`${t}|${n.join(",")}|${o}`);return queryOptions({queryKey:u.search.similarEntries(e.author,e.permlink,i),queryFn:async({signal:s})=>{let a=new Date(Date.now()-sf).toISOString().slice(0,19),c=await Hi({author:e.author,permlink:e.permlink,title:t,body:o,tags:n,since:a},s,typeof window>"u"?uf:pf),p=[],l=new Set;for(let d of c.results){if(p.length>=af)break;d.permlink!==e.permlink&&(d.tags??[]).indexOf("nsfw")===-1&&(l.has(d.author)||(l.add(d.author),p.push(d)));}return p},staleTime:300*1e3,retry:false})}function oB(e,t=5){let r=e.trim();return queryOptions({queryKey:u.search.account(r,t),queryFn:async()=>{let n=await y("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Qt(n)},enabled:!!r})}function uB(e,t=10){let r=e.trim();return queryOptions({queryKey:u.search.topics(r,t),queryFn:async()=>(await y("condenser_api.get_trending_tags",[r,t+1])).map(o=>o.name).filter(o=>o!==""&&!o.startsWith("hive-")).slice(0,t),enabled:!!r})}function gB(e,t,r,n,o,i){return infiniteQueryOptions({queryKey:u.search.api(e,t,r,n,o,i),queryFn:async({pageParam:s,signal:a})=>{let c={q:e,sort:t,hide_low:r};n&&(c.since=n),s&&(c.scroll_id=s),o!==void 0&&(c.votes=o),i&&(c.include_nsfw=1);let p=await fetch(f.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.clientId},body:JSON.stringify(c),signal:Pe(Ae,a)});return xe(p,Fe)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:wt})}function bB(e){return queryOptions({queryKey:["search","path",e],queryFn:async()=>{let t=await fetch(f.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":f.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 _f(e){let r=await _()(f.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 o=n?.message??`Failed to fetch support settings: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function AB(e,t){let r=e?.replace("@","");return queryOptions({queryKey:u.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return _f(t)},enabled:!!r&&!!t})}async function vf(e,t){let n=await _()(f.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 o;try{o=await n.json();}catch{}let i=o?.message??`Failed to update support settings: ${n.status}`,s=new Error(i);throw s.status=n.status,s.data=o,s}return await n.json()}function Pf(e,t,r){return e.setQueryData(u.support.settings(t),r),e.invalidateQueries({queryKey:u.support.settings(t)})}function kB(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["support","settings-update",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return vf(t,o)},onSuccess(o){n&&Pf(r,n,o);}})}function FB(e){return queryOptions({queryKey:["promotions","boost-plus-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(f.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 KB(e){return queryOptions({queryKey:["promotions","rc-delegation-prices"],queryFn:async()=>{if(!e)return [];let t=await fetch(f.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 QB(e,t){return queryOptions({queryKey:["promotions","rc-delegation-active",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(f.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 jB(e){return queryOptions({queryKey:["promotions","promote-price"],queryFn:async()=>{let t=await fetch(f.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 GB(e,t){return queryOptions({queryKey:["promotions","boost-plus-accounts",e],queryFn:async()=>{if(!t||!e)return null;let r=await fetch(f.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 XB(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:o})=>[Jr(e,n,o)],async(n,{account:o})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.promotions.boostPlusAccounts(o)]);},t,"active",{broadcastMode:r})}function rM(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[Yr(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 iM(e){let r=await _()(f.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let o;try{o=await r.json();}catch{o=void 0;}let i=new Error(`Failed to refresh token: ${r.status}`);throw i.status=r.status,i.data=o,i}return await r.json()}var Cf="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function uM(){return queryOptions({queryKey:u.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(Cf,{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 lM=1.1,Rf=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(Rf||{});function dM(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 If(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,o=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}}),i=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:o,poll_voters:i,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 hM(e,t){return queryOptions({queryKey:u.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:isServer?lo:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=_(),n=`${f.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,o=await r(n);if(!o.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${o.status}`);let i=await o.json();if(!Array.isArray(i)||!i[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return If(i[0])}})}function wM(e,t,r){return v(u.polls.vote(),e??"",({pollTrxId:n,choices:o})=>{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:o})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}var qf=-1e10,Df=5,Kf=30;var Ui=e=>Math.abs(e)>0&&Math.abs(e)<=100;function Vi(e){if(typeof e=="number"&&Ui(e)||typeof e=="string"&&(e=Number(e),Ui(e)))return Math.floor(e);if(e===0)return 25;let t=false;e<0&&(t=true);let r=Math.log10(Math.abs(e));return r=Math.max(r-9,0),r<0&&(r=0),t&&(r*=-1),r=r*9+25,Math.floor(r)}var Bf=["ecency.com","ecency.app","hive.blog","hive.io","hiveblocks.com","peakd.com","snapie.io","hivesuite.app","leofinance.io","inleo.io","3speak.tv","d.buzz","waivio.com"],Mf=["imgur.com","images.hive.blog","files.peakd.com","i.ecency.com","images.ecency.com","steemitimages.com","cdn.steemitimages.com","media.giphy.com"],Nf=/\.(jpe?g|png|gif|webp|svg|bmp|avif)(\?|#|$)/i,Qf=/(?:https?:)?\/\/[^\s)<>"'\]]+/gi,Hf=/[.,;:!?'"]+$/;function Uf(e){let t=/^(?:https?:)?\/\/([^/?#]+)/i.exec(e);return t?t[1].toLowerCase().replace(/^www\./,""):""}function Vf(e){let t=e.replace(Hf,"");if(Nf.test(t))return false;let r=Uf(t);if(!r.includes("."))return false;let n=o=>r===o||r.endsWith("."+o);return !(Bf.some(n)||Mf.some(n))}function ji(e){if(!e)return false;let t=e.match(Qf);return t?t.some(Vf):false}var jf=(n=>(n.MOD_MUTED="mod_muted",n.DOWNVOTED="downvoted",n.LOW_TRUST="low_trust",n))(jf||{});function Lf(e){return e?.stats?.total_votes??e?.active_votes?.length??0}function $f(e,t){return (e??0)<-1e10&&t>=5}function Wf(e){let t=e?.author_reputation;return t==null?false:Vi(t)<30&&ji(e?.body)}function SM(e,t){return !!e&&!!t?.includes(e)}function kM(e){return e?e.stats?.gray||e.stats?.hide?"mod_muted":$f(e.net_rshares,Lf(e))?"downvoted":Wf(e)?"low_trust":null:null}/** +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 xn 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 mo from'hivesigner';var as=Object.defineProperty;var Ot=(e,t)=>{for(var r in t)as(e,r,{get:t[r],enumerable:true});};var xt=new ArrayBuffer(0),St=null,Et=null;function us(){return St||(typeof TextEncoder<"u"?St=new TextEncoder:St={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)}}),St}function _n(){return Et||(typeof TextDecoder<"u"?Et=new TextDecoder:Et={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+(i&1023)));}return r}}),Et}var D=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?xt:new ArrayBuffer(t),this.view=t===0?new DataView(xt):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(xt));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 o;return t instanceof e?(o=new Uint8Array(t.buffer,t.offset,t.limit-t.offset),t.offset+=o.length):t instanceof Uint8Array?o=t:t instanceof ArrayBuffer?o=new Uint8Array(t):o=new Uint8Array(t),o.length<=0?this:(r+o.length>this.buffer.byteLength&&this.resize(r+o.length),new Uint8Array(this.buffer).set(o,r),n&&(this.offset+=o.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,o=new e(n,this.littleEndian);return o.offset=0,o.limit=n,new Uint8Array(o.buffer).set(new Uint8Array(this.buffer).subarray(t,r),0),o}copyTo(t,r,n,o){let i=typeof r>"u",s=typeof n>"u";r=i?t.offset:r,n=s?this.offset:n,o=o===void 0?this.limit:o;let a=o-n;return a===0?t:(t.ensureCapacity(r+a),new Uint8Array(t.buffer).set(new Uint8Array(this.buffer).subarray(n,o),r),s&&(this.offset+=a),i&&(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?xt: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 o=this.calculateVarint32(t);for(r+o>this.buffer.byteLength&&this.resize(r+o),t>>>=0;t>=128;)this.view.setUint8(r++,t&127|128),t>>>=7;return this.view.setUint8(r++,t),n?(this.offset=r,this):o}readVarint32(t){let r=typeof t>"u";typeof t>"u"&&(t=this.offset);let n=0,o=0,i;do i=this.view.getUint8(t++),n<5&&(o|=(i&127)<<7*n),++n;while((i&128)!==0);return o|=0,r?(this.offset=t,o):{value:o,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",o=n?this.offset:r,i=us().encode(t),s=i.length,a=this.calculateVarint32(s);return o+a+s>this.buffer.byteLength&&this.resize(o+a+s),this.writeVarint32(s,o),o+=a,new Uint8Array(this.buffer).set(i,o),o+=s,n?(this.offset=o,this):o-(r||0)}readVString(t){let r=typeof t>"u";r?t=this.offset:t=t;let n=t,o=this.readVarint32(t),i=o.value,s=o.length;t+=s;let a=_n().decode(new Uint8Array(this.buffer,t,i));return t+=i,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 o=_n().decode(new Uint8Array(this.buffer,r,t));return n?(this.offset+=t,o):{string:o,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}},wn=["bridge.get_ranked_posts","bridge.get_account_posts","bridge.get_post","bridge.get_discussion","bridge.get_profile","bridge.get_profiles","bridge.get_community","bridge.list_communities","condenser_api.get_accounts","condenser_api.get_content","condenser_api.get_dynamic_global_properties","condenser_api.get_trending_tags"],kt=null,sr=e=>{if(e===null){kt=null;return}if(!e||typeof e!="object")return;let t=typeof e.url=="string"?e.url.trim():"";if(!/^https?:\/\//i.test(t))return;let r={};if(e.headers&&typeof e.headers=="object")for(let[s,a]of Object.entries(e.headers))typeof a=="string"&&a&&!/[\u0000-\u001f\u007f]/.test(a)&&!/[\u0000-\u001f\u007f]/.test(s)&&(r[s]=a);let n=typeof e.timeoutMs=="number"&&Number.isFinite(e.timeoutMs)&&e.timeoutMs>0?e.timeoutMs:2e3,o=e.methods===void 0?[...wn]:Array.isArray(e.methods)?e.methods.filter(s=>typeof s=="string"&&s.includes(".")):[];if(o.length===0)return;let i=(s,a)=>typeof s=="number"&&Number.isFinite(s)&&s>0?s:a;kt={url:t,headers:r,timeoutMs:n,methods:o,failureThreshold:Math.floor(i(e.failureThreshold,3)),cooldownMs:i(e.cooldownMs,1e4),methodSet:new Set(o)};},ar=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)))]:[],ur=e=>{let t=ar(e);t.length&&(x.nodes=t);},cr=e=>{let t=ar(e);t.length&&(x.restNodes=t);},pr=e=>{if(!e||typeof e!="object")return;let t={...x.restNodesByApi};for(let[r,n]of Object.entries(e)){let o=ar(n);o.length?t[r]=o:delete t[r];}x.restNodesByApi=t;},lr=e=>{if(typeof e!="string")return;let t=e.trim();!t||/[\u0000-\u001f\u007f]/.test(t)||(x.userAgent=t);},dr=e=>{if(!e||typeof e!="object")return;let t=x.resilience,r=o=>typeof o=="boolean",n=o=>typeof o=="number"&&Number.isFinite(o)&&o>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 Se=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,o=true;n<0&&(o=false,n=n+4);let i=r.subarray(1);return new e(i,n,o)}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 Y(n.recoverPublicKey(t).toBytes())}};var Y=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 o;try{o=xn.decode(t.slice(r.length));}catch{throw new Error("Invalid public key encoding")}if(o.length!==37)throw new Error("Invalid public key length");let i=o.subarray(0,33),s=o.subarray(33,37),a=ripemd160(i).subarray(0,4);if(!ps(s,a))throw new Error("Public key checksum mismatch");try{secp256k1.Point.fromBytes(i);}catch{throw new Error("Invalid public key")}return new e(i,n)}static from(t){return t instanceof e?t:e.fromString(t)}verify(t,r){return typeof r=="string"&&(r=Se.from(r)),secp256k1.verify(r.data,t,this.key,{prehash:false,format:"compact"})}toString(){return cs(this.key,this.prefix)}toJSON(){return this.toString()}inspect(){return `PublicKey: ${this.toString()}`}},cs=(e,t)=>{let r=ripemd160(e);return t+xn.encode(new Uint8Array([...e,...r.subarray(0,4)]))},ps=(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);},fs=(e,t)=>{e.writeInt16(t);},En=(e,t)=>{e.writeInt64(t);},Sn=(e,t)=>{e.writeUint8(t);},pe=(e,t)=>{e.writeUint16(t);},X=(e,t)=>{e.writeUint32(t);},kn=(e,t)=>{e.writeUint64(t);},we=(e,t)=>{e.writeByte(t?1:0);},Cn=e=>(t,r)=>{let[n,o]=r;t.writeVarint32(n),e[n](t,o);},I=(e,t)=>{let r=Ct.from(t),n=r.getPrecision();e.writeInt64(Math.round(r.amount*Math.pow(10,n))),e.writeUint8(n);for(let o=0;o<7;o++)e.writeUint8(r.symbol.charCodeAt(o)||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(Y.from(t).key);},Rn=(e=null)=>(t,r)=>{r=Rt.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);},Tn=Rn(),fr=(e,t)=>(r,n)=>{r.writeVarint32(n.length);for(let[o,i]of n)e(r,o),t(r,i);},V=e=>(t,r)=>{t.writeVarint32(r.length);for(let n of r)e(t,n);},le=e=>(t,r)=>{for(let[n,o]of e)try{o(t,r[n]);}catch(i){throw i.message=`${n}: ${i.message}`,i}},Ie=e=>(t,r)=>{r!==void 0?(t.writeByte(1),e(t,r)):t.writeByte(0);},W=le([["weight_threshold",X],["account_auths",fr(w,pe)],["key_auths",fr(ge,pe)]]),ms=le([["account",w],["weight",pe]]),mr=le([["base",I],["quote",I]]),gs=le([["account_creation_fee",I],["maximum_block_size",X],["hbd_interest_rate",pe]]),R=(e,t)=>{let r=le(t);return (n,o)=>{n.writeVarint32(e),r(n,o);}},E={};E.account_create=R(C.account_create,[["fee",I],["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",w]]);E.account_create_with_delegation=R(C.account_create_with_delegation,[["fee",I],["delegation",I],["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",w],["extensions",V(ie)]]);E.account_update=R(C.account_update,[["account",w],["owner",Ie(W)],["active",Ie(W)],["posting",Ie(W)],["memo_key",ge],["json_metadata",w]]);E.account_witness_proxy=R(C.account_witness_proxy,[["account",w],["proxy",w]]);E.account_witness_vote=R(C.account_witness_vote,[["account",w],["witness",w],["approve",we]]);E.cancel_transfer_from_savings=R(C.cancel_transfer_from_savings,[["from",w],["request_id",X]]);E.change_recovery_account=R(C.change_recovery_account,[["account_to_recover",w],["new_recovery_account",w],["extensions",V(ie)]]);E.claim_account=R(C.claim_account,[["creator",w],["fee",I],["extensions",V(ie)]]);E.claim_reward_balance=R(C.claim_reward_balance,[["account",w],["reward_hive",I],["reward_hbd",I],["reward_vests",I]]);E.comment=R(C.comment,[["parent_author",w],["parent_permlink",w],["author",w],["permlink",w],["title",w],["body",w],["json_metadata",w]]);E.comment_options=R(C.comment_options,[["author",w],["permlink",w],["max_accepted_payout",I],["percent_hbd",pe],["allow_votes",we],["allow_curation_rewards",we],["extensions",V(Cn([le([["beneficiaries",V(ms)]])]))]]);E.convert=R(C.convert,[["owner",w],["requestid",X],["amount",I]]);E.create_claimed_account=R(C.create_claimed_account,[["creator",w],["new_account_name",w],["owner",W],["active",W],["posting",W],["memo_key",ge],["json_metadata",w],["extensions",V(ie)]]);E.custom=R(C.custom,[["required_auths",V(w)],["id",pe],["data",Tn]]);E.custom_json=R(C.custom_json,[["required_auths",V(w)],["required_posting_auths",V(w)],["id",w],["json",w]]);E.decline_voting_rights=R(C.decline_voting_rights,[["account",w],["decline",we]]);E.delegate_vesting_shares=R(C.delegate_vesting_shares,[["delegator",w],["delegatee",w],["vesting_shares",I]]);E.delete_comment=R(C.delete_comment,[["author",w],["permlink",w]]);E.escrow_approve=R(C.escrow_approve,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",X],["approve",we]]);E.escrow_dispute=R(C.escrow_dispute,[["from",w],["to",w],["agent",w],["who",w],["escrow_id",X]]);E.escrow_release=R(C.escrow_release,[["from",w],["to",w],["agent",w],["who",w],["receiver",w],["escrow_id",X],["hbd_amount",I],["hive_amount",I]]);E.escrow_transfer=R(C.escrow_transfer,[["from",w],["to",w],["hbd_amount",I],["hive_amount",I],["escrow_id",X],["agent",w],["fee",I],["json_meta",w],["ratification_deadline",Ee],["escrow_expiration",Ee]]);E.feed_publish=R(C.feed_publish,[["publisher",w],["exchange_rate",mr]]);E.limit_order_cancel=R(C.limit_order_cancel,[["owner",w],["orderid",X]]);E.limit_order_create=R(C.limit_order_create,[["owner",w],["orderid",X],["amount_to_sell",I],["min_to_receive",I],["fill_or_kill",we],["expiration",Ee]]);E.limit_order_create2=R(C.limit_order_create2,[["owner",w],["orderid",X],["amount_to_sell",I],["exchange_rate",mr],["fill_or_kill",we],["expiration",Ee]]);E.recover_account=R(C.recover_account,[["account_to_recover",w],["new_owner_authority",W],["recent_owner_authority",W],["extensions",V(ie)]]);E.request_account_recovery=R(C.request_account_recovery,[["recovery_account",w],["account_to_recover",w],["new_owner_authority",W],["extensions",V(ie)]]);E.reset_account=R(C.reset_account,[["reset_account",w],["account_to_reset",w],["new_owner_authority",W]]);E.set_reset_account=R(C.set_reset_account,[["account",w],["current_reset_account",w],["reset_account",w]]);E.set_withdraw_vesting_route=R(C.set_withdraw_vesting_route,[["from_account",w],["to_account",w],["percent",pe],["auto_vest",we]]);E.transfer=R(C.transfer,[["from",w],["to",w],["amount",I],["memo",w]]);E.transfer_from_savings=R(C.transfer_from_savings,[["from",w],["request_id",X],["to",w],["amount",I],["memo",w]]);E.transfer_to_savings=R(C.transfer_to_savings,[["from",w],["to",w],["amount",I],["memo",w]]);E.transfer_to_vesting=R(C.transfer_to_vesting,[["from",w],["to",w],["amount",I]]);E.vote=R(C.vote,[["voter",w],["author",w],["permlink",w],["weight",fs]]);E.withdraw_vesting=R(C.withdraw_vesting,[["account",w],["vesting_shares",I]]);E.witness_update=R(C.witness_update,[["owner",w],["url",w],["block_signing_key",ge],["props",gs],["fee",I]]);E.witness_set_properties=R(C.witness_set_properties,[["owner",w],["props",fr(w,Tn)],["extensions",V(ie)]]);E.account_update2=R(C.account_update2,[["account",w],["owner",Ie(W)],["active",Ie(W)],["posting",Ie(W)],["memo_key",Ie(ge)],["json_metadata",w],["posting_json_metadata",w],["extensions",V(ie)]]);E.create_proposal=R(C.create_proposal,[["creator",w],["receiver",w],["start_date",Ee],["end_date",Ee],["daily_pay",I],["subject",w],["permlink",w],["extensions",V(ie)]]);E.update_proposal_votes=R(C.update_proposal_votes,[["voter",w],["proposal_ids",V(En)],["approve",we],["extensions",V(ie)]]);E.remove_proposal=R(C.remove_proposal,[["proposal_owner",w],["proposal_ids",V(En)],["extensions",V(ie)]]);var ys=le([["end_date",Ee]]);E.update_proposal=R(C.update_proposal,[["proposal_id",kn],["creator",w],["daily_pay",I],["subject",w],["permlink",w],["extensions",V(Cn([ie,ys]))]]);E.collateralized_convert=R(C.collateralized_convert,[["owner",w],["requestid",X],["amount",I]]);E.recurrent_transfer=R(C.recurrent_transfer,[["from",w],["to",w],["amount",I],["memo",w],["recurrence",pe],["executions",pe],["extensions",V(le([["type",Sn],["value",le([["pair_id",Sn]])]]))]]);var hs=(e,t)=>{let r=E[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}},_s=le([["ref_block_num",pe],["ref_block_prefix",X],["expiration",Ee],["operations",V(hs)],["extensions",V(w)]]),ws=le([["from",ge],["to",ge],["nonce",kn],["check",X],["encrypted",Rn()]]),de={Asset:I,Memo:ws,Price:mr,PublicKey:ge,String:w,Transaction:_s,UInt16:pe,UInt32:X};var st=e=>new Promise(t=>setTimeout(t,e));var Nn=(()=>{try{return !(typeof navigator<"u"&&navigator.product==="ReactNative")&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}catch{return false}})();function wr(){return Nn?{"User-Agent":x.userAgent}:{}}var Ce={served:0,fallback:0,skipped:0,fallbackByReason:{status:0,rpcerror:0,timeout:0,transport:0,validate:0,parse:0}},Re=class extends Error{constructor(r,n){super(n);this.reason=r;}reason},qn=e=>e instanceof Error?e.message:typeof e=="string"?e:String(e),Tt=0,Fn=0;async function bs(e,t,r,n,o,i){let s=t.indexOf(".");if(s<=0||s===t.length-1)throw new Re("transport",`method without an api prefix: ${t}`);let{signal:a,cleanup:c}=vr(Math.min(e.timeoutMs,n)),{signal:p,cleanup:l}=Dt(a,o);try{let f;try{f=await fetch(e.url,{method:"POST",body:JSON.stringify({api:t.slice(0,s),method:t.slice(s+1),params:r}),headers:{"Content-Type":"application/json",...wr(),...e.headers},signal:p});}catch(g){throw o?.aborted?g:new Re(a.aborted?"timeout":"transport",qn(g))}if(f.status!==200){try{await f.body?.cancel();}catch{}let g=f.status===502&&(f.headers.get("x-ssr-cache")??"").toUpperCase()==="RPCERROR";throw new Re(g?"rpcerror":"status",g?"proxy relayed a node error":`proxy answered ${f.status}`)}let m;try{m=await f.json();}catch(g){throw o?.aborted?g:new Re(a.aborted?"timeout":"parse",qn(g))}if(i&&!i(m))throw new Re("validate","proxy result rejected by validator");return m}finally{c(),l();}}var Z=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);}},De=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 Bn(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 vs=["ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"],Ps=["Failed to fetch","NetworkError when attempting to fetch","Load failed","fetch failed"];function As(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 Os(e){if(!e)return false;if(e instanceof De)return true;if(e instanceof Z)return false;let t=As(e);return !!(vs.some(r=>t.includes(r))||Ps.some(r=>t.includes(r))||e instanceof SyntaxError||/Unexpected token|JSON\.parse|Unexpected end of JSON/i.test(t))}function gr(e,t){return !!(e===-32603||e<=-32e3&&e>=-32099||e===-32601||e===-32602&&/unable to parse|endpoint data|internal/i.test(t))}function Mn(e){let t=e.indexOf(".");return t>0?e.slice(0,t):e}var xs=1e4,Ss=6e4,Es=12e4,In=2,Dn=6e4,Kn=12e4,ks=30,at=.3,yr=3,ut=5*6e4,Qn=6e4,Hn=1e3,Un=2e3,Ft=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,o){let i=this.getOrCreate(t);if(i.consecutiveFailures=0,i.rateLimitStreak=0,r){let s=i.apiFailures.get(r);(!s||!(s.defective&&s.cooldownUntil>Date.now()))&&i.apiFailures.delete(r);}typeof n=="number"&&Number.isFinite(n)&&n>=0&&this.recordLatency(i,n,o??r);}recordSlowFailure(t,r,n){!Number.isFinite(r)||r=yr&&o-i.updatedAt<=ut?i.ewmaMs:void 0}return this.isLatencyUsable(n,o)?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 o=Date.now();if(t.latencyUpdatedAt>0&&o-t.latencyUpdatedAt>ut&&(t.ewmaLatencyMs=void 0,t.latencySampleCount=0,t.apiLatency.clear()),t.ewmaLatencyMs=t.ewmaLatencyMs===void 0?r:at*r+(1-at)*t.ewmaLatencyMs,t.latencySampleCount++,t.latencyUpdatedAt=o,n!==void 0){let i=t.apiLatency.get(n);!i||o-i.updatedAt>ut?t.apiLatency.set(n,{ewmaMs:r,sampleCount:1,updatedAt:o}):(i.ewmaMs=at*r+(1-at)*i.ewmaMs,i.sampleCount++,i.updatedAt=o);}}recordFailure(t,r){let n=this.getOrCreate(t);if(r){let o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};(i.cooldownUntil>0&&i.cooldownUntil<=o||i.lastFailureTime>0&&o-i.lastFailureTime>3e4)&&(i.count=0,i.cooldownUntil=0),i.count++,i.lastFailureTime=o,i.count>=In&&(i.cooldownUntil=o+Dn),n.apiFailures.set(r,i);}else n.consecutiveFailures++,n.lastFailureTime=Date.now();}recordDefectiveResponse(t,r){let n=this.getOrCreate(t),o=Date.now(),i=n.apiFailures.get(r)??{count:0,cooldownUntil:0,lastFailureTime:0};i.count=Math.max(i.count+1,In),i.lastFailureTime=o,i.cooldownUntil=o+Dn,i.defective=true,n.apiFailures.set(r,i);}recordRateLimit(t,r){let n=this.getOrCreate(t),o=Date.now();n.rateLimitStreak>0&&o-n.lastRateLimitAt>Es&&(n.rateLimitStreak=0);let i=typeof r=="number"&&Number.isFinite(r)&&r>0,s=i?r:Math.min(xs*2**n.rateLimitStreak,Ss);i||n.rateLimitStreak++,n.lastRateLimitAt=o,n.rateLimitedUntil=i?o+s:Math.max(n.rateLimitedUntil,o+s),n.consecutiveFailures++,n.lastFailureTime=o;}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<=Kn&&r.push(n.headBlock);return r.length<2?0:(r.sort((n,o)=>n-o),r[Math.floor((r.length-1)/2)])}isNodeHealthy(t,r){let n=this.health.get(t);if(!n)return true;let o=Date.now();if(n.rateLimitedUntil>o||n.consecutiveFailures>=3&&o-n.lastFailureTime<3e4)return false;if(r){let s=n.apiFailures.get(r);if(s&&s.cooldownUntil>o)return false}let i=this.consensusHeadBlock();return !(i>0&&n.headBlock>0&&o-n.headBlockUpdatedAt<=Kn&&i-n.headBlock>ks)}getOrderedNodes(t,r){let n=[],o=[];for(let c of t)this.isNodeHealthy(c,r)?n.push(c):o.push(c);if(n.length<=1)return [...n,...o];let i=Date.now(),s=n.map((c,p)=>({node:c,i:p,score:this.scoreNode(c,i)})).sort((c,p)=>c.score-p.score||c.i-p.i).map(c=>c.node),a=this.pickReprobeCandidate(n,i);return a&&s[0]!==a?[a,...s.filter(c=>c!==a),...o]:[...s,...o]}isLatencyUsable(t,r){return !!t&&t.ewmaLatencyMs!==void 0&&t.latencySampleCount>=yr&&r-t.latencyUpdatedAt<=ut}scoreNode(t,r){let n=this.health.get(t);return this.isLatencyUsable(n,r)?n.ewmaLatencyMs:Hn}pickReprobeCandidate(t,r){let n=r-Qn,o,i=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;}},_r=new hr;function It(e,t,r,n,o){let i=x.resilience;if(!i.adaptiveTimeout||o)return n;let s=e.getUsableLatencyMs(t,r);return s===void 0?n:Math.ceil(Math.min(n,Math.max(i.adaptiveTimeoutFloorMs,i.adaptiveTimeoutFactor*s)))}function br(e,t,r,n){r instanceof De?r.isRateLimit?e.recordRateLimit(t,r.rateLimitMs||void 0):e.recordFailure(t,n):r instanceof Z?e.recordFailure(t,n):e.recordFailure(t);}function Vn(e,t,r,n){if(!n||typeof n!="object"||!r.includes("get_dynamic_global_properties"))return;let o=n.head_block_number;typeof o=="number"&&e.recordHeadBlock(t,o);}function Cs(){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 vr(e){if(e=Math.ceil(e),typeof AbortSignal.timeout=="function")return {signal:AbortSignal.timeout(e),cleanup:()=>{}};let t=new AbortController,r=setTimeout(()=>t.abort(Cs()),e);return {signal:t.signal,cleanup:()=>clearTimeout(r)}}function Dt(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),o=()=>r.abort(t.reason);e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",o,{once:true});let i=()=>{e.removeEventListener("abort",n),t.removeEventListener("abort",o);};return {signal:r.signal,cleanup:i}}var ct=async(e,t,r,n=x.timeout,o=false,i)=>{let s=Math.floor(Math.random()*1e8),a={jsonrpc:"2.0",method:t,params:r,id:s},{signal:c,cleanup:p}=vr(n),{signal:l,cleanup:f}=Dt(c,i),m=()=>{p(),f();};try{let g=await fetch(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json",...wr()},signal:l});if(g.status===429)throw new De(e,"HTTP 429 Rate Limited",{rateLimitMs:Bn(g.headers.get("Retry-After")),isRateLimit:!0});if(g.status>=500&&g.status<600)throw new De(e,`HTTP ${g.status} from ${e}`);let _=await g.json();if(!_||typeof _.id>"u"||_.id!==s||_.jsonrpc!=="2.0")throw new Error("JSONRPC id mismatch");if("result"in _)return _.result;if("error"in _){let P=_.error;throw "message"in P&&"code"in P?new Z(P):_.error}throw _}catch(g){if(g instanceof Z||g instanceof De||i?.aborted)throw g;if(o)return ct(e,t,r,n,false,i);throw g}finally{m();}};function qt(){return st(50+Math.random()*50)}function Rs(e){let{method:t,params:r,api:n,primary:o,hedgePool:i,callerTimeout:s,explicitTimeout:a,deadlineAt:c,externalSignal:p,onHedgeFired:l,validate:f}=e;return new Promise((m,g)=>{let _=false,P=0,O=false,T=false,q,ce,A=0,$=[],M=J=>{if(!_){_=true,ce!==void 0&&(clearTimeout(ce),ce=void 0);for(let F of $)F.signal.aborted||F.abort();J();}},H=(J,F)=>{P++;let me=new AbortController;$.push(me);let it=Dt(me.signal,p),ss=It(j,J,t,s,a),ir=Date.now();F||(A=ir),ct(J,t,r,ss,false,it.signal).then(oe=>{if(it.cleanup(),P--,F||(T=true),!_){if(f&&!f(oe)){if(j.recordDefectiveResponse(J,n),q=new Error(`[hive-tx] response validation failed for ${t} from ${J}`),!F&&!O){M(()=>g(q));return}P===0&&M(()=>g(q));return}j.recordSuccess(J,n,Date.now()-ir,t),Vn(j,J,t,oe),F?T||j.recordCensoredLatency(o,Date.now()-A,t):O||_r.refill(),M(()=>m(oe));}}).catch(oe=>{if(it.cleanup(),P--,F||(T=true),!_){if(p?.aborted){M(()=>g(oe));return}if(oe instanceof Z&&!gr(oe.code,oe.message)){M(()=>g(oe));return}if(br(j,J,oe,n),j.recordSlowFailure(J,Date.now()-ir,t),q=oe,!F&&!O){M(()=>g(oe));return}P===0&&M(()=>g(q));}});};H(o,false);let z=j.getUsableLatencyMs(o,t)??0,L=It(j,o,t,s,a),ot=Math.min(Math.max(x.resilience.hedgeDelayFloorMs,x.resilience.hedgeDelayFactor*z),.8*L);ce=setTimeout(()=>{if(ce=void 0,_||p?.aborted||Date.now()>=c)return;let J=i.filter(me=>j.isNodeHealthy(me,n));if(J.length===0)return;let F=J[Math.floor(Math.random()*J.length)];_r.trySpend()&&(O=true,l(F),H(F,true));},ot);})}var y=async(e,t=[],r,n=x.retry,o,i)=>{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=Mn(e),p=kt;if(p&&Nn&&p.methodSet.has(e))if(Date.now()=p.failureThreshold&&(Fn=Date.now()+p.cooldownMs,Tt=0);}let l=Date.now()+x.resilience.totalBudgetFactor*a,f=new Set,m;for(let g=0;g<=n&&!(g>0&&Date.now()>=l);g++){let _=j.getOrderedNodes(x.nodes,c),P=_.find(q=>!f.has(q));P||(f.clear(),P=_[0]),f.add(P);let O=[];if(x.resilience.hedge&&j.getUsableLatencyMs(P,e)!==void 0&&(O=_.filter(q=>!f.has(q)&&j.isNodeHealthy(q,c)).slice(0,3)),O.length>0)try{return await Rs({method:e,params:t,api:c,primary:P,hedgePool:O,callerTimeout:a,explicitTimeout:s,deadlineAt:l,externalSignal:o,onHedgeFired:q=>f.add(q),validate:i})}catch(q){if(q instanceof Z&&!gr(q.code,q.message)||o?.aborted)throw q;m=q,g{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 o=Mn(e),i=new Set,s;for(let a=0;a!i.has(l));if(!p)break;if(i.add(p),n?.aborted)throw new Error("Aborted");try{let l=await ct(p,e,t,r,!1,n);return j.recordSuccess(p,o),l}catch(l){if(l instanceof Z||n?.aborted||(br(j,p,l,o),s=l,!Os(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 te(e,t,r,n,o=x.retry,i){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,g=false;for(let _=0;_<=o&&!(_>0&&Date.now()>=c);_++){let P=ke.getOrderedNodes(l,e),O=P.find(F=>!f.has(F));O||(f.clear(),O=P[0]),f.add(O);let T=O+Ts[e],q=t,ce=r||{},A=new Set;Object.entries(ce).forEach(([F,me])=>{q.includes(`{${F}}`)&&(q=q.replace(`{${F}}`,encodeURIComponent(String(me))),A.add(F));});let $=new URL(T+q);if(Object.entries(ce).forEach(([F,me])=>{A.has(F)||(Array.isArray(me)?me.forEach(it=>$.searchParams.append(F,String(it))):$.searchParams.set(F,String(me)));}),i?.aborted)throw new Error("Aborted");g=false;let{signal:M,cleanup:H}=vr(It(ke,O,p,a,s)),{signal:z,cleanup:L}=Dt(M,i),ot=()=>{H(),L();},J=Date.now();try{let F=await fetch($.toString(),{signal:z,headers:wr()});if(F.status===404)throw new Error("HTTP 404 - Hint: can happen on wrong params");if(F.status===429)throw ke.recordRateLimit(O,Bn(F.headers.get("Retry-After"))||void 0),g=!0,new Error(`HTTP 429 Rate Limited by ${O}`);if(F.status===503)throw ke.recordFailure(O,e),g=!0,new Error(`HTTP 503 Service Unavailable from ${O}`);if(!F.ok)throw ke.recordFailure(O,e),g=!0,new Error(`HTTP ${F.status} from ${O}`);return ke.recordSuccess(O,e,Date.now()-J,p),F.json()}catch(F){if(F?.message?.includes("HTTP 404")||i?.aborted)throw F;g||ke.recordFailure(O,e),ke.recordSlowFailure(O,Date.now()-J,p),m=F,_{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 i=(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,i.length),a=[];for(;s>0&&i.length>0;){let c=i.splice(0,s),p=[],l=[];for(let m=0;ml.push(g)).catch(()=>{}));await Promise.all(p),a.push(...l);let f=qs(a,r);if(f)return f;if(s=Math.min(r,i.length),s===0)throw new Error("No more nodes available.")}throw new Error("Couldn't reach quorum.")};function qs(e,t){let r=new Map;for(let o of e){let i=JSON.stringify(o);r.has(i)||r.set(i,[]),r.get(i).push(o);}let n=Array.from(r.values()).find(o=>o.length>=t);return n?n[0]:null}var Is=hexToBytes(x.chain_id),Ke=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 o of t){let i=o.sign(r);this.transaction.signatures.push(i.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 We("condenser_api.broadcast_transaction",[this.transaction]);}catch(i){if(!(i instanceof Z&&i.message.includes("Duplicate transaction check failed")))throw i}if(this.txId||(this.txId=this.digest().txId),!t)return {tx_id:this.txId,status:"unknown"};let r=60;await st(1e3);let n=await this.checkStatus(),o=1;for(;n?.status!=="within_irreversible_block"&&n?.status!=="expired_irreversible"&&n?.status!=="too_old"&&o{let r=await y("condenser_api.get_dynamic_global_properties",[]),n=hexToBytes(r.head_block_id),o=Number(new Uint32Array(n.buffer,n.byteOffset+4,1)[0]),i=new Date(Date.now()+t).toISOString().slice(0,-5);this.transaction={expiration:i,extensions:[],operations:[],ref_block_num:r.head_block_number&65535,ref_block_prefix:o,signatures:[]};}};var zn=new Uint8Array([128]),U=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(Bs(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 o=0;o>6,128|i&63);else if(i>=55296&&i<=56319&&o+1>18,128|i>>12&63,128|i>>6&63,128|i&63);}else n.push(224|i>>12,128|i>>6&63,128|i&63);}t=new Uint8Array(n);}return new e(sha256(t))}static fromLogin(t,r,n="active"){let o=t+n+r;return e.fromSeed(o)}sign(t){let r=secp256k1.sign(t,this.key,{extraEntropy:true,format:"recovered",prehash:false}),n=parseInt(bytesToHex(r.subarray(0,1)),16);return Se.from((n+31).toString(16)+bytesToHex(r.subarray(1)))}createPublic(t){return new Y(secp256k1.getPublicKey(this.key),t)}toString(){return Ns(new Uint8Array([...zn,...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)}},Jn=e=>sha256(sha256(e)),Ns=e=>{let t=Jn(e);return xn.encode(new Uint8Array([...e,...t.slice(0,4)]))},Bs=e=>{let t=xn.decode(e);if(!Wn(t.slice(0,1),zn))throw new Error("Private key network id mismatch");let r=t.slice(-4),n=t.slice(0,-4),o=Jn(n).slice(0,4);if(!Wn(r,o))throw new Error("Private key checksum mismatch");return n},Wn=(e,t)=>{if(e===t)return true;if(e.byteLength!==t.byteLength)return false;let r=e.byteLength,n=0;for(;neo(e,t,n,r),Zn=(e,t,r,n,o)=>eo(e,t,r,n,o).message,eo=(e,t,r,n,o)=>{let i=r,s=e.getSharedSecret(t),a=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);a.writeUint64(i),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 g=m.readUint32();if(o!==void 0){if(g!==o)throw new Error("Invalid key");n=Us(n,l,p);}else n=Vs(n,l,p);return {nonce:i,message:n,checksum:g}},Us=(e,t,r)=>{let n=e;return n=cbc(t,r).decrypt(n),n},Vs=(e,t,r)=>{let n=e;return n=cbc(t,r).encrypt(n),n},Ar=null,js=()=>{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=Js(e,33);return new Y(t)},$s=e=>e.readUint64(),Ws=e=>e.readUint32(),Gs=e=>{let t=e.readVarint32(),r=e.copy(e.offset,e.offset+t);return e.skip(t),new Uint8Array(r.toBuffer())},zs=e=>t=>{let r={},n=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);n.append(t),n.flip();for(let[o,i]of e)try{r[o]=i(n);}catch(s){throw s.message=`${o}: ${s.message}`,s}return r};function Js(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=zs([["from",to],["to",to],["nonce",$s],["check",Ws],["encrypted",Gs]]),ro={Memo:Ys};var oo=(e,t,r,n)=>{if(!r.startsWith("#"))return r;r=r.substring(1),so(),e=ao(e),t=Xs(t);let o=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);o.writeVString(r);let i=new Uint8Array(o.copy(0,o.offset).toBuffer()),{nonce:s,message:a,checksum:c}=Xn(e,t,i,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 "#"+xn.encode(l)},io=(e,t)=>{if(!t.startsWith("#"))return t;t=t.substring(1),so(),e=ao(e);let r=ro.Memo(xn.decode(t)),{from:n,to:o,nonce:i,check:s,encrypted:a}=r,p=e.createPublic().toString()===new Y(n.key).toString()?new Y(o.key):new Y(n.key);r=Zn(e,p,i,a,s);let l=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return l.append(r),l.flip(),"#"+l.readVString()},Nt,so=()=>{if(Nt===void 0){let e;Nt=true;try{let t="5JdeC9P7Pbd1uGdFVEsJ41EkEnADbbHGq6p1BwFxm6txNBsQnsw",n=oo(t,"STM8m5UgaFAAYQRuaNejYdS8FVLVp9Ss3K1qAVk5de6F8s3HnVbvA","#memo\u7231");e=io(t,n);}finally{Nt=e==="#memo\u7231";}}if(Nt===false)throw new Error("This environment does not support encryption.")},ao=e=>typeof e=="string"?U.fromString(e):e,Xs=e=>typeof e=="string"?Y.fromString(e):e,uo={decode:io,encode:oo};var ne={};Ot(ne,{buildWitnessSetProperties:()=>oa,makeBitMaskFilter:()=>ra,operations:()=>ta,validateUsername:()=>ea});var ea=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("."),o=n.length;for(let i=0;ie.reduce(na,[BigInt(0),BigInt(0)]).map(t=>t!==BigInt(0)?t.toString():null),na=([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 o;switch(n){case "key":case "new_signing_key":o=de.PublicKey;break;case "account_subsidy_budget":case "account_subsidy_decay":case "maximum_block_size":o=de.UInt32;break;case "hbd_interest_rate":o=de.UInt16;break;case "url":o=de.String;break;case "hbd_exchange_rate":o=de.Price;break;case "account_creation_fee":o=de.Asset;break;default:throw new Error(`Unknown witness prop: ${n}`)}r.props.push([n,ia(o,t[n])]);}return r.props.sort((n,o)=>n[0].localeCompare(o[0])),["witness_set_properties",r]},ia=(e,t)=>{let r=new D(D.DEFAULT_CAPACITY,D.LITTLE_ENDIAN);return e(r,t),r.flip(),bytesToHex(new Uint8Array(r.toBuffer()))};function Dg(e){let t;if(typeof e=="string"){let r=[];for(let n=0;n>6,128|o&63);else if(o>=55296&&o<=56319&&n+1>18,128|o>>12&63,128|o>>6&63,128|o&63);}else r.push(224|o>>12,128|o>>6&63,128|o&63);}t=new Uint8Array(r);}else t=e;return sha256(t)}function co(e){try{return U.fromString(e),!0}catch{return false}}async function ee(e,t){let r=new Ke;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),We("condenser_api.broadcast_transaction_synchronous",[r.transaction])}async function po(e,t){let r=new Ke;for(let n of e)await r.addOperation(n[0],n[1]);return r.sign(t),r.broadcast(false)}var aa=432e3;function lo(e,t){let r=Date.now()/1e3-t.last_update_time,n=Number(t.current_mana)+r*e/aa,o=Math.round(n/e*1e4);return !isFinite(o)||o<0?o=0:o>1e4&&(o=1e4),{current_mana:n,max_mana:e,percentage:o}}function ua(e){let t=parseFloat(e.vesting_shares),r=parseFloat(e.delegated_vesting_shares),n=parseFloat(e.received_vesting_shares),o=parseFloat(e.vesting_withdraw_rate),i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t-s-r+n}function Or(e){let t=ua(e)*1e6;return lo(t,e.voting_manabar)}function Bt(e){return lo(Number(e.max_rc),e.rc_manabar)}var fo=(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))(fo||{});function Ge(e){let t=e?.error_description?String(e.error_description):"",r=e?.message?String(e.message):"",n=e?.error?String(e.error):"",o=t||r||String(e||""),i=a=>!!(n&&a.test(n)||t&&a.test(t)||r&&a.test(r)||o&&a.test(o));if(i(/please wait to transact/i)||i(/insufficient rc/i)||i(/rc mana|rc account|resource credits/i))return {message:"Insufficient Resource Credits. Please wait or power up.",type:"insufficient_resource_credits",originalError:e};if(i(/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(i(/your current vote on this comment is identical/i))return {message:"You have already voted with the same weight.",type:"info",originalError:e};if(i(/must claim something/i))return {message:"You must claim rewards before performing this action.",type:"info",originalError:e};if(i(/cannot claim that much vests/i))return {message:"Cannot claim that amount. Please check your pending rewards.",type:"info",originalError:e};if(i(/cannot delete a comment with net positive/i))return {message:"Cannot delete a comment with positive votes.",type:"info",originalError:e};if(i(/children == 0/i))return {message:"Cannot delete a comment with replies.",type:"common",originalError:e};if(i(/comment_cashout/i))return {message:"Cannot modify a comment that has already been paid out.",type:"common",originalError:e};if(i(/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(i(/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(i(/missing (required )?active authority/i))return {message:"Missing active authority. This operation requires your active key.",type:"missing_authority",originalError:e};if(i(/missing (required )?owner authority/i))return {message:"Missing owner authority. This operation requires your owner key.",type:"missing_authority",originalError:e};if(i(/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"||i(/token expired/i)||i(/invalid token/i)||i(/\bunauthorized\b/i)||i(/\bforbidden\b/i))return {message:"Authentication token expired. Please log in again.",type:"token_expired",originalError:e};if(i(/has already reblogged/i)||i(/already reblogged this post/i))return {message:"You have already reblogged this post.",type:"info",originalError:e};if(i(/duplicate transaction/i))return {message:"This transaction has already been processed.",type:"info",originalError:e};if(i(/econnrefused/i)||i(/connection refused/i)||i(/failed to fetch/i)||i(/\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(i(/timeout/i)||i(/timed out/i))return {message:"Request timed out. Please try again.",type:"timeout",originalError:e};if(i(/account.*does not exist/i)||i(/account not found/i))return {message:"Account not found. Please check the username.",type:"validation",originalError:e};if(i(/invalid memo key/i))return {message:"Invalid memo key. Cannot encrypt message.",type:"validation",originalError:e};if(i(/(?:insufficient.*(?:funds|balance)|(?:funds|balance).*insufficient)/i))return {message:"Insufficient funds for this transaction.",type:"validation",originalError:e};if(i(/\b(invalid|validation)\b/i))return {message:(e?.message||o).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}`:o&&o!=="[object Object]"?s=o.substring(0,150):s="Unknown error occurred":s=o.substring(0,150)||"Unknown error occurred",{message:s,type:"common",originalError:e}}function ca(e){let t=Ge(e);return [t.message,t.type]}function be(e){let{type:t}=Ge(e);return t==="missing_authority"||t==="token_expired"}function pa(e){let{type:t}=Ge(e);return t==="insufficient_resource_credits"}function la(e){let{type:t}=Ge(e);return t==="info"}function da(e){let{type:t}=Ge(e);return t==="network"||t==="timeout"}async function ve(e,t,r,n,o="posting",i,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=i;if(p===void 0)switch(o){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 ${o} key available for ${t}`);let l=U.fromString(p);return a==="async"?await po(r,l):await ee(r,l)}case "hiveauth":{if(!c?.broadcastWithHiveAuth)throw new Error("HiveAuth not supported by adapter");return await c.broadcastWithHiveAuth(t,r,o)}case "hivesigner":{if(!c)throw new Error("No adapter provided for HiveSigner auth");if(o!=="posting"){if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);throw new Error(`HiveSigner access token cannot sign ${o} operations. No platform broadcast available.`)}let p=s!==void 0?s:await c.getAccessToken(t);if(p)try{return (await new mo.Client({accessToken:p}).broadcast(r)).result}catch(l){if(c.broadcastWithHiveSigner&&be(l))return await c.broadcastWithHiveSigner(t,r,o);throw l}if(c.broadcastWithHiveSigner)return await c.broadcastWithHiveSigner(t,r,o);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,o)}case "custom":{if(!n?.broadcast)throw new Error("No custom broadcast function provided");return await n.broadcast(r,o)}default:throw new Error(`Unknown auth method: ${e}`)}}async function ma(e,t,r,n="posting",o="async"){let i=r?.adapter;if(i?.getLoginType){let l=await i.getLoginType(e,n);if(l){let f=i.hasPostingAuthorization?await i.hasPostingAuthorization(e):false;if(n==="posting"&&f&&l==="key")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!be(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to key:",m);}if(n==="posting"&&f&&l==="keychain")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!be(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 ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(m){if(!be(m))throw m;console.warn("[SDK] HiveSigner token auth failed, falling back to HiveAuth:",m);}try{return await ve(l,e,t,r,n,void 0,void 0,o)}catch(m){if(be(m)&&i.showAuthUpgradeUI&&(n==="posting"||n==="active")){let g=t.length>0?t[0][0]:"unknown",_=await i.showAuthUpgradeUI(n,g);if(!_)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ve(_,e,t,r,n,void 0,void 0,o)}throw m}}if(n==="posting")try{return await ve("hivesigner",e,t,r,n,void 0,void 0,o)}catch(f){if(be(f)&&i.showAuthUpgradeUI){let m=t.length>0?t[0][0]:"unknown",g=await i.showAuthUpgradeUI(n,m);if(!g)throw new Error(`No login type available for ${e}. Please log in again.`);return await ve(g,e,t,r,n,void 0,void 0,o)}throw f}else if(n==="active"&&i.showAuthUpgradeUI){let f=t.length>0?t[0][0]:"unknown",m=await i.showAuthUpgradeUI(n,f);if(!m)throw new Error(`Operation requires ${n} authority. User declined alternate auth.`);return await ve(m,e,t,r,n,void 0,void 0,o)}}let s=r?.fallbackChain??["key","hiveauth","hivesigner","keychain","custom"],a=new Map;for(let l of s)try{let f=!1,m="",g,_;switch(l){case "key":if(!i)f=!0,m="No adapter provided";else {let P;switch(n){case "owner":i.getOwnerKey&&(P=await i.getOwnerKey(e));break;case "active":i.getActiveKey&&(P=await i.getActiveKey(e));break;case "memo":i.getMemoKey&&(P=await i.getMemoKey(e));break;default:P=await i.getPostingKey(e);break}P?g=P:(f=!0,m=`No ${n} key available`);}break;case "hiveauth":i?.broadcastWithHiveAuth||(f=!0,m="HiveAuth not supported by adapter");break;case "hivesigner":if(!i)f=!0,m="No adapter provided";else {let P=await i.getAccessToken(e);P&&(_=P);}break;case "keychain":i?.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 ve(l,e,t,r,n,g,_,o)}catch(f){if(a.set(l,f),!be(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=()=>{},o,i="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(o?.enableFallback!==!1&&o?.adapter)return await ma(t,p,o,i,a);if(o?.broadcast)return await o.broadcast(p,i);let l=o?.postingKey;if(l){if(i!=="posting")throw new Error(`[SDK][Broadcast] Legacy auth only supports posting authority, but '${i}' was requested. Use AuthContextV2 with an adapter for ${i} operations.`);let m=U.fromString(l);return await ee(p,m)}let f=o?.accessToken;if(f)return (await new mo.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 Z?new Error(l.message):l}}})}async function go(e,t,r,n){if(!e)throw new Error("[Core][Broadcast] Attempted to call broadcast API with anon user");let o={id:t,required_auths:[],required_posting_auths:[e],json:JSON.stringify(r)};if(n?.broadcast)return n.broadcast([["custom_json",o]],"posting");let i=n?.postingKey;if(i){let c=U.fromString(i);return ee([["custom_json",o]],c)}let s=n?.accessToken;if(s)return (await new mo.Client({accessToken:s}).customJson([],[e],t,JSON.stringify(r))).result;let a=n?.adapter;if(a){let c=[["custom_json",o]];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 Yg=4e3;function S(e,t,r){if(e?.invalidateQueries){if(t==="sync")return e.invalidateQueries(r);setTimeout(()=>e.invalidateQueries?.(r),4e3);}}function Pe(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,o=()=>{let i=t.aborted?t.reason:r.reason;n.abort(i),t.removeEventListener("abort",o),r.removeEventListener("abort",o);};return t.aborted?n.abort(t.reason):r.aborted?n.abort(r.reason):(t.addEventListener("abort",o,{once:true}),r.addEventListener("abort",o,{once:true})),n.signal}var Ne=(()=>{try{return process.env?.NODE_ENV==="development"}catch{return false}})(),ha=()=>{try{return process.env?.VITE_HELIUS_API_KEY}catch{return}},Ae=1e4,yo=120*1e3,Mt,_a;function wa(){return Mt?Mt():_a??=new QueryClient}var d={privateApiHost:"https://ecency.com",defaultObserver:"ecency",clientId:"ecency-sdk",imageHost:"https://i.ecency.com",get hiveNodes(){return x.nodes},heliusApiKey:ha(),get queryClient(){return wa()},set queryClient(e){Mt=()=>e;},pollsApiHost:"https://poll.ecency.com",plausibleHost:"https://pl.ecency.com",dmcaAccounts:[],dmcaTags:[],dmcaPatterns:[],dmcaTagRegexes:[],dmcaPatternRegexes:[],_dmcaInitialized:false},Q;(ce=>{function e(A){d.queryClient=A;}ce.setQueryClient=e;function t(A){Mt=A;}ce.setQueryClientResolver=t;function r(A){d.privateApiHost=A;}ce.setPrivateApiHost=r;function n(A){d.clientId=A;}ce.setClientId=n;function o(A){if(typeof A!="string"||A.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=A;}ce.setDefaultObserver=o;function i(){return d.privateApiHost?d.privateApiHost:typeof window<"u"&&window.location?.origin?window.location.origin:"https://ecency.com"}ce.getValidatedBaseUrl=i;function s(A){d.pollsApiHost=A;}ce.setPollsApiHost=s;function a(A){d.imageHost=A;}ce.setImageHost=a;function c(A){ur(A);}ce.setHiveNodes=c;function p(A){cr(A);}ce.setRestNodes=p;function l(A){pr(A);}ce.setRestNodesByApi=l;function f(A){lr(A);}ce.setUserAgent=f;function m(A){dr(A);}ce.setResilience=m;function g(A){sr(A);}ce.setServerRpcProxy=g;function _(){return Ce}ce.getServerRpcProxyStats=_;function P(A){if(/(\([^)]*[*+{][^)]*\))[*+{]/.test(A))return {safe:false,reason:"nested quantifiers detected"};if(/\([^|)]*\|[^)]*\)[*+{]/.test(A))return {safe:false,reason:"alternation with quantifier (potential overlap)"};if(/\([^)]*[*+][^)]*\)[*+]/.test(A))return {safe:false,reason:"repeated quantifiers (catastrophic backtracking risk)"};if(/\.\*\.\*/.test(A)||/\.\+\.\+/.test(A))return {safe:false,reason:"multiple greedy quantifiers on wildcards"};let $=/\.?\{(\d+),(\d+)\}/g,M;for(;(M=$.exec(A))!==null;){let[,H,z]=M;if(parseInt(z,10)-parseInt(H,10)>1e3)return {safe:false,reason:`excessive range: {${H},${z}}`}}return {safe:true}}function O(A){let $=["a".repeat(50)+"x","ab".repeat(50)+"x","x".repeat(100),"aaa".repeat(30)+"bbb".repeat(30)+"x"],M=5;for(let H of $){let z=Date.now();try{A.test(H);let L=Date.now()-z;if(L>M)return {safe:!1,reason:`runtime test exceeded ${M}ms (took ${L}ms on input length ${H.length})`}}catch(L){return {safe:false,reason:`runtime test threw error: ${L}`}}}return {safe:true}}function T(A,$=200){try{if(!A)return Ne&&console.warn("[SDK] DMCA pattern rejected: empty pattern"),null;if(A.length>$)return Ne&&console.warn(`[SDK] DMCA pattern rejected: length ${A.length} exceeds max ${$} - pattern: ${A.substring(0,50)}...`),null;let M=P(A);if(!M.safe)return Ne&&console.warn(`[SDK] DMCA pattern rejected: static analysis failed (${M.reason}) - pattern: ${A.substring(0,50)}...`),null;let H;try{H=new RegExp(A);}catch(L){return Ne&&console.warn(`[SDK] DMCA pattern rejected: compilation failed - pattern: ${A.substring(0,50)}...`,L),null}let z=O(H);return z.safe?H:(Ne&&console.warn(`[SDK] DMCA pattern rejected: runtime test failed (${z.reason}) - pattern: ${A.substring(0,50)}...`),null)}catch(M){return Ne&&console.warn(`[SDK] DMCA pattern rejected: unexpected error - pattern: ${A.substring(0,50)}...`,M),null}}function q(A={}){let $=L=>Array.isArray(L)?L.filter(ot=>typeof ot=="string"):[],M=A||{},H={accounts:$(M.accounts),tags:$(M.tags),patterns:$(M.posts)};d.dmcaAccounts=H.accounts,d.dmcaTags=H.tags,d.dmcaPatterns=H.patterns,d.dmcaTagRegexes=H.tags.map(L=>T(L)).filter(L=>L!==null),d.dmcaPatternRegexes=[];let z=H.tags.length-d.dmcaTagRegexes.length;!d._dmcaInitialized&&Ne&&(console.log("[SDK] DMCA configuration loaded:"),console.log(` - Accounts: ${H.accounts.length}`),console.log(` - Tag patterns: ${d.dmcaTagRegexes.length}/${H.tags.length} compiled (${z} rejected)`),console.log(` - Post patterns: ${H.patterns.length} (using exact string matching)`),z>0&&console.warn(`[SDK] ${z} DMCA tag patterns were rejected due to security validation. Check warnings above for details.`)),d._dmcaInitialized=true;}ce.setDmcaLists=q;})(Q||={});function cy(){return new QueryClient({defaultOptions:{queries:{refetchOnWindowFocus:false,refetchOnMount:false}}})}var b=()=>d.queryClient,Aa;(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 o(a){return {prefetch:()=>r(a),getData:()=>e(a.queryKey),useClientQuery:()=>useQuery(a),fetchAndGet:()=>b().fetchQuery(a)}}s.generateClientServerQuery=o;function i(a){return {prefetch:()=>n(a),getData:()=>t(a.queryKey),useClientQuery:()=>useInfiniteQuery(a),fetchAndGet:()=>b().fetchInfiniteQuery(a)}}s.generateClientServerInfiniteQuery=i;})(Aa||={});function ly(e){return btoa(JSON.stringify(e))}function dy(e){let t=atob(e);if(t[0]==="{")return JSON.parse(t)}var ho=(n=>(n.HIVE="HIVE",n.HBD="HBD",n.VESTS="VESTS",n))(ho||{}),Qt=(e=>(e["@@000000021"]="HIVE",e["@@000000013"]="HBD",e["@@000000037"]="VESTS",e))(Qt||{});function k(e){if(typeof e=="string"){let t=e.split(" ");return {amount:parseFloat(t[0]),symbol:ho[t[1]]}}else return {amount:parseFloat(e.amount.toString())/Math.pow(10,e.precision),symbol:Qt[e.nai]}}var xr;function h(){if(!xr){if(typeof globalThis.fetch!="function")throw new Error("[Ecency][SDK] - global fetch is not available");xr=globalThis.fetch.bind(globalThis);}return xr}function _o(e){return typeof e=="string"?/^hive-\d+$/.test(e):false}function Oa(e){return e&&typeof e=="object"&&"data"in e&&"pagination"in e&&Array.isArray(e.data)}function se(e,t){return Oa(e)?e:{data:Array.isArray(e)?e:[],pagination:{total:Array.isArray(e)?e.length:0,limit:t,offset:0,has_next:false}}}function ze(e,t){return e/1e6*t}function wo(e){return e===void 0?true:parseInt(e.split("-")[0],10)<1980}var bo=60*1e3;function Oe(){return queryOptions({queryKey:u.core.dynamicProps(),refetchInterval:bo,staleTime:bo,queryFn:async({signal:e})=>{let[t,r,n,o,i]=await Promise.all([y("condenser_api.get_dynamic_global_properties",[],void 0,void 0,e),y("condenser_api.get_feed_history",[],void 0,void 0,e),y("condenser_api.get_chain_properties",[],void 0,void 0,e),y("condenser_api.get_reward_fund",["post"],void 0,void 0,e),y("database_api.get_hardfork_properties",{},void 0,void 0,e).catch(()=>({current_hardfork_version:"1.28.0",last_hardfork:28}))]),s=k(t.total_vesting_shares).amount,a=k(t.total_vesting_fund_hive).amount,c=0;Number.isFinite(s)&&s!==0&&Number.isFinite(a)&&(c=a/s*1e6);let p=k(r.current_median_history.base).amount,l=k(r.current_median_history.quote).amount,f=parseFloat(o.recent_claims),m=k(o.reward_balance).amount,g=Number(t.vote_power_reserve_rate??0),_=o.author_reward_curve??"linear",P=Number(o.content_constant??0),O=String(i.current_hardfork_version??"0.0.0"),T=Number(i.last_hardfork??0),q=t.hbd_print_rate,ce=t.hbd_interest_rate,A=t.head_block_number,$=a,M=s,H=k(t.virtual_supply).amount,z=t.vesting_reward_percent||0,L=n.account_creation_fee;return {hivePerMVests:c,base:p,quote:l,fundRecentClaims:f,fundRewardBalance:m,votePowerReserveRate:g,authorRewardCurve:_,contentConstant:P,currentHardforkVersion:O,lastHardfork:T,hbdPrintRate:q,hbdInterestRate:ce,headBlock:A,totalVestingFund:$,totalVestingShares:M,virtualSupply:H,vestingRewardPercent:z,accountCreationFee:L,raw:{globalDynamic:t,feedHistory:r,chainProps:n,rewardFund:o,hardforkProps:i}}}})}function ky(e="post"){return queryOptions({queryKey:u.core.rewardFund(e),queryFn:()=>y("condenser_api.get_reward_fund",[e])})}function Be(...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,o,i)=>["posts","account-posts-page",e,t,r,n,o,i],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)=>Be("posts","drafts","infinite",e,t),schedules:e=>["posts","schedules",e],schedulesInfinite:(e,t)=>Be("posts","schedules","infinite",e,t),fragments:e=>["posts","fragments",e],fragmentsInfinite:(e,t)=>Be("posts","fragments","infinite",e,t),images:e=>["posts","images",e],galleryImages:e=>["posts","gallery-images",e],imagesInfinite:(e,t)=>Be("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,o,i)=>["posts","posts-ranked-page",e,t,r,n,o,i],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)=>Be("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)=>Be("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,o,i)=>["search",e,t,typeof r=="string"?r==="1"||r==="true":r,n,o,i],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,o,i)=>Be("search","api",e,t,r,n,o,i)},witnesses:{list:e=>["witnesses","list",e],votes:e=>["witnesses","votes",e],proxy:()=>["witnesses","proxy"],voters:(e,t,r,n,o)=>["witnesses","voters",e,t,r,n,o],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]},newsletter:{subscriptions:e=>["newsletter","subscriptions",e],sender:(e,t,r)=>["newsletter","sender",e,t,r],issues:(e,t,r)=>["newsletter","issues",e,t,r],posts:(e,t,r,n)=>["newsletter","posts",e,t,r,n],_prefix:["newsletter"]},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 lt(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 Iy(e){return queryOptions({queryKey:u.ai.prices(),queryFn:async()=>{let r=await h()(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 By(e,t){return queryOptions({queryKey:u.ai.assistPrices(e),queryFn:async()=>{let n=await h()(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 Uy(e,t){return queryOptions({queryKey:u.ai.transcribePrice(e),queryFn:async()=>{let n=await h()(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 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 $y(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 o=await h()(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??Ta()})});if(!o.ok){let s=await o.text(),a={};try{a=JSON.parse(s);}catch{}let c=new Error(`[SDK][AI][GenerateImage] \u2013 failed with status ${o.status}${s?`: ${s}`:""}`);throw c.status=o.status,c.data=a,c}if(o.status===202){let s={};try{s=await o.json();}catch{}let a=new Error("[SDK][AI][GenerateImage] \u2013 delivery pending");throw a.status=202,a.data=s,a}return await o.json()},onSuccess:()=>{e&&b().invalidateQueries({queryKey:u.points._prefix(e)});}})}function Fa(){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 Jy(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 o=await h()(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:Fa()})});if(!o.ok){let i=await o.text(),s={};try{s=JSON.parse(i);}catch{}let a=new Error(`[SDK][AI][Assist] \u2013 failed with status ${o.status}${i?`: ${i}`:""}`);throw a.status=o.status,a.data=s,a}return await o.json()},onSuccess:r=>{e&&(r.cost>0&&b().invalidateQueries({queryKey:u.points._prefix(e)}),b().invalidateQueries({queryKey:u.ai.assistPrices(e)}));}})}function Da(){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 eh(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 o=new FormData;o.append("code",n),o.append("duration_ms",String(Math.round(r.durationMs))),o.append("idempotency_key",r.idempotency_key??Da()),o.append("audio",r.audio,r.fileName??"clip.webm");let s=await h()(d.privateApiHost+"/private-api/ai-transcribe",{method:"POST",body:o});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 Sr(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 B(e){return queryOptions({queryKey:u.accounts.full(e),queryFn:async({signal:t})=>{if(!e)return null;let[r,n]=await Promise.all([y("condenser_api.get_accounts",[[e]],void 0,void 0,t,p=>Array.isArray(p)),y("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 o=r[0];if(Sr(o)&&Na(n?.metadata?.profile)){let p=await y("condenser_api.get_accounts",[[e]],void 0,void 0,t,l=>Array.isArray(l)&&(!l[0]||!Sr(l[0])));if(p[0]&&!Sr(p[0]))o=p[0];else throw new Error(`[SDK][Accounts] \u2013 inconsistent account row for ${e}: empty json metadata while hivemind profile is populated`)}let i=Me(o.posting_json_metadata),s=n?.stats,a=s?{account:o.name,follower_count:s.followers??0,following_count:s.following??0}:void 0,c=n?.reputation??0;return {name:o.name,owner:o.owner,active:o.active,posting:o.posting,memo_key:o.memo_key,post_count:o.post_count,created:o.created,posting_json_metadata:o.posting_json_metadata,last_vote_time:o.last_vote_time,last_post:o.last_post,json_metadata:o.json_metadata,reward_hive_balance:o.reward_hive_balance,reward_hbd_balance:o.reward_hbd_balance,reward_vesting_hive:o.reward_vesting_hive,reward_vesting_balance:o.reward_vesting_balance,balance:o.balance,hbd_balance:o.hbd_balance,savings_balance:o.savings_balance,savings_hbd_balance:o.savings_hbd_balance,savings_hbd_last_interest_payment:o.savings_hbd_last_interest_payment,savings_hbd_seconds_last_update:o.savings_hbd_seconds_last_update,savings_hbd_seconds:o.savings_hbd_seconds,next_vesting_withdrawal:o.next_vesting_withdrawal,pending_claimed_accounts:o.pending_claimed_accounts,vesting_shares:o.vesting_shares,delegated_vesting_shares:o.delegated_vesting_shares,received_vesting_shares:o.received_vesting_shares,vesting_withdraw_rate:o.vesting_withdraw_rate,to_withdraw:o.to_withdraw,withdrawn:o.withdrawn,witness_votes:o.witness_votes,proxy:o.proxy,recovery_account:o.recovery_account,proxied_vsf_votes:o.proxied_vsf_votes,voting_manabar:o.voting_manabar,voting_power:o.voting_power,downvote_manabar:o.downvote_manabar,follow_stats:a,reputation:c,profile:i}},enabled:!!e,staleTime:6e4})}var Ba=new Set(["__proto__","constructor","prototype"]);function Ht(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function vo(e,t){let r={...e};for(let n of Object.keys(t)){if(Ba.has(n))continue;let o=t[n],i=r[n];Ht(o)&&Ht(i)?r[n]=vo(i,o):r[n]=o;}return r}function Ma(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:o,...i}=t;return {...r,meta:i}})}function Me(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 Po(e){return Me(e?.posting_json_metadata)}function Ao(e,t){if(!e)return t;if(!t)return e;let r=Object.keys(Me(e.posting_json_metadata)).length;return Object.keys(Me(t.posting_json_metadata)).length>r?t:e}function Qa(e){if(!e)return {};try{let t=JSON.parse(e);if(Ht(t))return t}catch(t){console.warn("[SDK] Failed to parse posting_json_metadata root:",t,{length:e?.length??0});}return {}}function Oo({existingPostingJsonMetadata:e,profile:t,tokens:r}){let n=Qa(e),o=Ht(n.profile)?n.profile:{},i=Er({existingProfile:o,profile:t,tokens:r});return JSON.stringify({...n,profile:i})}function Er({existingProfile:e,profile:t,tokens:r}){let{tokens:n,version:o,...i}=t??{},s=vo(e??{},i);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=Ma(s.tokens),s.version=2,s}function Ut(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=Me(t.posting_json_metadata);if(!n||Object.keys(n).length===0)try{let o=JSON.parse(t.json_metadata||"{}");o.profile&&(n=o.profile);}catch{}return (!n||Object.keys(n).length===0)&&(n={about:"",cover_image:"",location:"",name:"",profile_image:"",website:""}),{...r,profile:n}})}function Ha(e){return new TextEncoder().encode(e).length}function Je(e){return e?Ha(e)<=16:false}function yh(e){return queryOptions({queryKey:u.accounts.list(...e),enabled:e.length>0,queryFn:async()=>{let t=e.filter(Je);if(t.length===0)return [];let r=await y("condenser_api.get_accounts",[t],void 0,void 0,void 0,n=>Array.isArray(n));return Ut(r??[])}})}function vh(e){return queryOptions({queryKey:u.accounts.followCount(e),queryFn:()=>y("condenser_api.get_follow_count",[e])})}function Sh(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.followers(e,t,r,n),queryFn:()=>y("condenser_api.get_followers",[e,t,r,n]),enabled:!!e})}function Th(e,t,r="blog",n=100){return queryOptions({queryKey:u.accounts.following(e,t,r,n),queryFn:()=>y("condenser_api.get_following",[e,t,r,n]),enabled:!!e})}var xo=1e3,Wa=20;function Kh(e){return queryOptions({queryKey:u.accounts.mutedUsers(e),queryFn:async()=>{let t=[],r="";for(let n=0;ns.following);if(i[0]===r&&(i=i.slice(1)),!i.length||(t.push(...i),o.lengthJe(e)?y("condenser_api.lookup_accounts",[e,t]):[],enabled:!!e,staleTime:1/0})}function Wh(e,t=5,r=[]){return queryOptions({queryKey:u.accounts.search(e,r),enabled:!!e,queryFn:async()=>(await y("condenser_api.lookup_accounts",[e,t])).filter(o=>r.length>0?!r.includes(o):true)})}var Ya=new Set(["ownerPublicKey","activePublicKey","postingPublicKey","memoPublicKey"]);function Yh(e,t){return queryOptions({queryKey:u.accounts.checkWalletPending(e,t??null),queryFn:async()=>{if(!e||!t)return {exist:false};let n=await h()(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 o=await n.json(),i=Array.isArray(o)?o.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,g=(typeof a.status=="number"?a.status===3:void 0)??false;f&&(l.address=f),l.show=g;let _={symbol:c,currency:c,address:f,show:g,type:"CHAIN",meta:l},P=[];for(let[O,T]of Object.entries(p))typeof O=="string"&&(Ya.has(O)||typeof T!="string"||!T||/^[A-Z0-9]{2,10}$/.test(O)&&P.push({symbol:O,currency:O,address:T,show:g,type:"CHAIN",meta:{address:T,show:g}}));return [_,...P]}):[];return {exist:i.length>0,tokens:i.length?i:void 0,wallets:i.length?i:void 0}},refetchOnMount:true})}function So(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 y("bridge.get_relationship_between_accounts",[e,t])??r}})}function s_(e){return queryOptions({queryKey:u.accounts.subscriptions(e),enabled:!!e,queryFn:async({signal:t})=>await y("bridge.list_all_subscriptions",{account:e},void 0,void 0,t)??[]})}function p_(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 h()(d.privateApiHost+"/private-api/bookmarks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function l_(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 i=await h()(`${d.privateApiHost}/private-api/bookmarks?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch bookmarks: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function g_(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 h()(d.privateApiHost+"/private-api/favorites",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function y_(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 i=await h()(`${d.privateApiHost}/private-api/favorites?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch favorites: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function b_(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 o=await h()(d.privateApiHost+"/private-api/favorites-check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,account:r})});if(!o.ok)throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check failed with status ${o.status}: ${o.statusText}`);let i=await o.json();if(typeof i!="boolean")throw new Error(`[SDK][Accounts][Favorites] \u2013 favorites-check returned invalid type: expected boolean, got ${typeof i}`);return i}})}function O_(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 h()(d.privateApiHost+"/private-api/recoveries",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})})).json()}})}function C_(e){return queryOptions({enabled:!!e,queryKey:u.accounts.pendingRecovery(e),queryFn:()=>y("database_api.find_change_recovery_account_requests",{accounts:[e]})})}function D_(e,t=50){return queryOptions({queryKey:u.accounts.reputations(e,t),enabled:!!e,queryFn:async()=>!e||!Je(e)?[]:y("condenser_api.get_account_reputations",[e,t])})}var K=ne.operations,Eo={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]},cu=Array.from(new Set(Object.values(Eo).flat()));function pu(e){return e.block*1e7+e.trx_in_block*100+e.op_pos}function lu(e){return e.replace(/_operation$/,"")}function du(e){return typeof e=="object"&&e!==null&&"nai"in e&&"amount"in e&&"precision"in e}function fu(e){if(!du(e))return e;let t=k(e),r=Qt[e.nai]??"UNKNOWN";return `${t.amount.toFixed(e.precision)} ${r}`}function mu(e){let t={};for(let[r,n]of Object.entries(e))t[r]=fu(n);return t}function V_(e,t=20,r=""){let n=r?Eo[r]:cu;return infiniteQueryOptions({queryKey:u.accounts.transactions(e??"",r,t),initialPageParam:null,queryFn:async({pageParam:o,signal:i})=>{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 te("hafah","/accounts/{account-name}/operations",m,void 0,void 0,i)},a=f=>f.operations_result.map(m=>{let g=lu(m.op.type);return {...mu(m.op.value),num:pu(m),type:g,timestamp:m.timestamp,trx_id:m.trx_id}}),c=await s(o),p=a(c),l=o??c.total_pages;if(o===null&&p.length1)try{let f=await s(c.total_pages-1);p=[...p,...a(f)],l=c.total_pages-1;}catch(f){if(i?.aborted)throw f}return {entries:p,currentPage:l}},getNextPageParam:o=>{let i=o.currentPage-1;return i>=1?i:void 0}})}function W_(){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 Y_(e){return infiniteQueryOptions({queryKey:u.accounts.referrals(e),initialPageParam:{maxId:void 0},queryFn:async({pageParam:t})=>{let{maxId:r}=t??{},n=Q.getValidatedBaseUrl(),o=new URL(`/private-api/referrals/${e}`,n);r!==void 0&&o.searchParams.set("max_id",r.toString());let i=await fetch(o.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`Failed to fetch referrals: ${i.status}`);return i.json()},getNextPageParam:t=>{let r=t?.[t.length-1]?.id;return typeof r=="number"?{maxId:r}:void 0}})}function tw(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 aw(e,t,r){let{followType:n="blog",limit:o=100,enabled:i=true}=r??{};return infiniteQueryOptions({queryKey:u.accounts.friends(e,t,n,o),initialPageParam:{startFollowing:""},enabled:i,refetchOnMount:true,queryFn:async({pageParam:s})=>{let{startFollowing:a}=s,l=(await y(`condenser_api.${t==="following"?"get_following":"get_followers"}`,[e,a===""?null:a,n,o])).map(g=>t==="following"?g.following:g.follower);return (await y("bridge.get_profiles",{accounts:l,observer:void 0})??[]).map(g=>({name:g.name,reputation:g.reputation,active:g.active}))},getNextPageParam:s=>s&&s.length===o?{startFollowing:s[s.length-1].name}:void 0})}var bu=30;function dw(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 y(`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,bu);return (await y("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 hw(e=20){return infiniteQueryOptions({queryKey:u.posts.trendingTags(),queryFn:async({pageParam:{afterTag:t}})=>y("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 Aw(e=250){return infiniteQueryOptions({queryKey:u.posts.trendingTagsWithStats(e),queryFn:async({pageParam:{afterTag:t}})=>y("condenser_api.get_trending_tags",[t,e]).then(r=>r.filter(n=>n.name!=="").filter(n=>!_o(n.name))),initialPageParam:{afterTag:""},getNextPageParam:t=>t?.length?{afterTag:t[t.length-1].name}:void 0,staleTime:1/0})}function Ye(e,t){return queryOptions({queryKey:u.posts.fragments(e),queryFn:async()=>t?(await h()(d.privateApiHost+"/private-api/fragments",{method:"POST",body:JSON.stringify({code:t}),headers:{"Content-Type":"application/json"}})).json():[],enabled:!!e&&!!t})}function Ew(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 i=await h()(`${d.privateApiHost}/private-api/fragments?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch fragments: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function Tw(e="feed"){return queryOptions({queryKey:u.posts.promoted(e),queryFn:async()=>{let t=Q.getValidatedBaseUrl(),r=new URL("/private-api/promoted-entries",t);return e==="waves"&&r.searchParams.append("short_content","1"),await(await h()(r.toString(),{method:"GET",headers:{"Content-Type":"application/json"}})).json()}})}function Kw(e){return queryOptions({queryKey:u.posts.entryActiveVotes(e?.author,e?.permlink),queryFn:async()=>y("condenser_api.get_active_votes",[e?.author,e?.permlink]),enabled:!!e})}function Hw(e,t,r){return queryOptions({queryKey:u.posts.userPostVote(e,t,r),queryFn:async()=>(await y("database_api.list_votes",{start:[e,t,r],limit:1,order:"by_voter_comment"}))?.votes?.[0]||null,enabled:!!e&&!!t&&!!r})}function $w(e,t){return queryOptions({queryKey:u.posts.content(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content",[e,t])})}function Yw(e,t){return queryOptions({queryKey:u.posts.contentReplies(e,t),enabled:!!e&&!!t,queryFn:async()=>y("condenser_api.get_content_replies",{author:e,permlink:t})})}function rb(e,t){return queryOptions({queryKey:u.posts.postHeader(e,t),queryFn:async()=>y("bridge.get_post_header",{author:e,permlink:t}),initialData:null})}function re(e){return Array.isArray(e)?e.map(t=>ko(t)):ko(e)}function ko(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 Co(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 Ro(e,t,r="",n){let o=t?.trim(),i=`/@${e}/${o??""}`;return queryOptions({queryKey:u.posts.entry(i),queryFn:async()=>{if(!o||o==="undefined")return null;let s=await y("bridge.get_post",{author:e,permlink:o,observer:r});if(!s){let c=await Co(e,o,r);if(!c)return null;let p=n!==void 0?{...c,num:n}:c;return re(p)}let a=n!==void 0?{...s,num:n}:s;return re(a)},enabled:!!e&&!!t&&t.trim()!==""&&t.trim()!=="undefined"})}function ae(e,t,r){return y(`bridge.${e}`,t,void 0,void 0,r)}async function To(e,t,r,n){let{json_metadata:o}=e;if(o?.original_author&&o?.original_permlink&&o.tags?.[0]==="cross-post")try{let i=await qu(o.original_author,o.original_permlink,t,r,n);return i?{...e,original_entry:i,num:r}:e}catch{return e}return {...e,num:r}}async function qo(e,t,r){let n=e.map(dt),o=await Promise.all(n.map(i=>To(i,t,void 0,r)));return re(o)}async function Fo(e,t="",r="",n=20,o="",i="",s){let a=await ae("get_ranked_posts",{sort:e,start_author:t,start_permlink:r,limit:n,tag:o,observer:i},s);return Array.isArray(a)?qo(a,i,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 kr(e,t,r="",n="",o=20,i="",s){if(d.dmcaAccounts.includes(t))return [];let a=await ae("get_account_posts",{sort:e,account:t,start_author:r,start_permlink:n,limit:o,observer:i},s);return Array.isArray(a)?qo(a,i,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 dt(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 qu(e="",t="",r="",n,o){let i=await ae("get_post",{author:e,permlink:t,observer:r},o);if(i){let s=dt(i),a=await To(s,r,n,o);return re(a)}}async function hb(e="",t=""){let r=await ae("get_post_header",{author:e,permlink:t});return r&&dt(r)}async function Io(e,t,r){let n=await ae("get_discussion",{author:e,permlink:t,observer:r||e});if(n){let o={};for(let[i,s]of Object.entries(n))o[i]=dt(s);return o}return n}async function Do(e,t=""){return ae("get_community",{name:e,observer:t})}async function _b(e="",t=100,r,n="rank",o=""){return ae("list_communities",{last:e,limit:t,query:r,sort:n,observer:o})}async function Ko(e){let t=await ae("normalize_post",{post:e});return t&&dt(t)}async function wb(e){return ae("list_all_subscriptions",{account:e})}async function bb(e){return ae("list_subscribers",{community:e})}async function vb(e,t){return ae("get_relationship_between_accounts",[e,t])}async function Vt(e,t){return ae("get_profiles",{accounts:e,observer:t})}var Bo=(o=>(o.trending="trending",o.author_reputation="author_reputation",o.votes="votes",o.created="created",o))(Bo||{});function Cr(e){let t=e.match(/^(\d+\.?\d*)\s*([A-Z]+)$/);return t?{amount:parseFloat(t[1]),symbol:t[2]}:{amount:0,symbol:""}}function Fu(e,t,r){let n=l=>Cr(l.pending_payout_value).amount+Cr(l.author_payout_value).amount+Cr(l.curator_payout_value).amount,o=l=>l.net_rshares<0,i=l=>e.json_metadata?.pinned_reply===`${l.author}/${l.permlink}`,s={trending:(l,f)=>{if(o(l))return 1;if(o(f))return -1;let m=n(l),g=n(f);return m!==g?g-m:0},author_reputation:(l,f)=>{let m=l.author_reputation,g=f.author_reputation;return m>g?-1:m{let m=l.children,g=f.children;return m>g?-1:m{if(o(l))return 1;if(o(f))return -1;let m=Date.parse(l.created),g=Date.parse(f.created);return m>g?-1:mi(l)),p=a[c];return c>=0&&(a.splice(c,1),a.unshift(p)),a}function Mo(e,t="created",r=true,n){let o=n||d.defaultObserver;return queryOptions({queryKey:u.posts.discussions(e?.author,e?.permlink,t,o),queryFn:async()=>{if(!e)return [];let i=await y("bridge.get_discussion",{author:e.author,permlink:e.permlink,observer:o}),s=i?Array.from(Object.values(i)):[];return re(s)},enabled:r&&!!e,select:i=>Fu(e,i,t),structuralSharing:(i,s)=>{if(!i||!s)return s;let a=i.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 kb(e,t,r,n=true){let o=r||d.defaultObserver;return queryOptions({queryKey:u.posts.discussion(e,t,o),enabled:n&&!!e&&!!t,queryFn:async()=>Io(e,t,o)})}function Db(e,t="posts",r=20,n="",o=true){return infiniteQueryOptions({queryKey:u.posts.accountPosts(e??"",t,r,n),enabled:!!e&&o,initialPageParam:{author:void 0,permlink:void 0,hasNextPage:true},queryFn:async({pageParam:i,signal:s})=>{if(!i?.hasNextPage||!e)return [];let a=await kr(t,e,i.author??"",i.permlink??"",r,n,s);return re(a??[])},getNextPageParam:i=>{let s=i?.[i.length-1],a=(i?.length??0)===r;if(a)return {author:s?.author,permlink:s?.permlink,hasNextPage:a}}})}function Kb(e,t="posts",r="",n="",o=20,i="",s=true){return queryOptions({queryKey:u.posts.accountPostsPage(e??"",t,r,n,o,i),enabled:!!e&&s,queryFn:async({signal:a}={})=>{if(!e)return [];let c=await kr(t,e,r,n,o,i,a);return re(c??[])}})}var Qo=new Map;function Bu(e){let t=Qo.get(e);return t||(t=r=>({...r,pages:r.pages.map(n=>Mu(n,e))}),Qo.set(e,t)),t}function Mu(e,t){let r=e.filter(i=>i.stats?.is_pinned),n=e.filter(i=>!i.stats?.is_pinned);if(t==="hot")return [...r,...n];let o=[...n].sort((i,s)=>new Date(s.created).getTime()-new Date(i.created).getTime());return [...r,...o]}function jb(e,t,r=20,n="",o=true,i={}){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 y("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 re(p)},select:Bu(e),enabled:o,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 Lb(e,t="",r="",n=20,o="",i="",s=true){return queryOptions({queryKey:u.posts.postsRankedPage(e,t,r,n,o,i),enabled:s,queryFn:async({signal:a}={})=>{let c=o;d.dmcaTagRegexes.some(l=>l.test(o))&&(c="");let p=await Fo(e,t,r,n,c,i,a);return re(p??[])}})}function Jb(e,t,r=200){return queryOptions({queryKey:u.posts.reblogs(e??"",r),queryFn:async()=>(await y("condenser_api.get_blog_entries",[e??t,0,r])).filter(o=>o.author!==t&&!o.reblogged_on.startsWith("1970-")).map(o=>({author:o.author,permlink:o.permlink})),enabled:!!e})}function tv(e,t){return queryOptions({queryKey:u.posts.rebloggedBy(e??"",t??""),queryFn:async()=>{if(!e||!t)return [];let r=await y("condenser_api.get_reblogged_by",[e,t]);return Array.isArray(r)?r:[]},enabled:!!e&&!!t})}function iv(e,t){return queryOptions({queryKey:u.posts.schedules(e),queryFn:async()=>{if(!e||!t)return [];let n=await h()(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 sv(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 i=await h()(`${d.privateApiHost}/private-api/schedules?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch schedules: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function pv(e,t){return queryOptions({queryKey:u.posts.drafts(e),queryFn:async()=>{if(!e||!t)return [];let n=await h()(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 lv(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 i=await h()(`${d.privateApiHost}/private-api/drafts?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch drafts: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}async function Uo(e){let r=await h()(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 gv(e,t){return queryOptions({queryKey:u.posts.images(e),queryFn:async()=>!e||!t?[]:Uo(t),enabled:!!e&&!!t})}function yv(e,t){return queryOptions({queryKey:u.posts.galleryImages(e),queryFn:async()=>!e||!t?[]:Uo(t),enabled:!!e&&!!t})}function hv(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 i=await h()(`${d.privateApiHost}/private-api/images?format=wrapped&offset=${n}&limit=${r}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})});if(!i.ok)throw new Error(`Failed to fetch images: ${i.status}`);let s=await i.json();return se(s,r)},initialPageParam:0,getNextPageParam:n=>{if(n.pagination.has_next)return n.pagination.offset+n.pagination.limit},enabled:!!e&&!!t})}function vv(e,t,r=false){return queryOptions({queryKey:u.posts.commentHistory(e,t,r),queryFn:async({signal:n})=>{let o=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(!o.ok)throw new Error(`Failed to fetch comment history: ${o.status}`);return o.json()},enabled:!!e&&!!t})}function zu(e,t){let r=e?.trim(),n=t?.trim();if(!r||!n)throw new Error("Invalid entry path: author and permlink are required");let o=r.replace(/^@+/,""),i=n.replace(/^\/+/,"");if(!o||!i)throw new Error("Invalid entry path: author and permlink cannot be empty after normalization");return `@${o}/${i}`}function xv(e,t){let r=t?.trim(),n=e?.trim(),o=!!n&&!!r&&r!=="undefined",i=o?zu(n,r):"";return queryOptions({queryKey:u.posts.deletedEntry(i),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:o})}function Cv(e,t,r=true){return queryOptions({queryKey:u.posts.tips(e,t),queryFn:async()=>{let n=`/private-api/post-tips/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,o=await fetch(d.privateApiHost+n,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`Failed to fetch post tips: ${o.status}`);return o.json()},enabled:!!e&&!!t&&r,staleTime:60*1e3})}function Yu(e,t){return {...e,id:e.id??e.post_id,created:e.created??e.timestamp,host:t}}function Xu(e){return {...e,id:e.id??e.post_id}}function he(e,t){if(!e)return null;let r=e.container??e,n=Yu(r,t),o=e.parent?Xu(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:o}}function Zu(e){return Array.isArray(e)?e:[]}async function Vo(e){let t=Mo(e,"created",true),r=await d.queryClient.fetchQuery(t),n=Zu(r);if(n.length<=1)return [];let o=n.filter(({parent_author:s,parent_permlink:a})=>s===e.author&&a===e.permlink);return o.length===0?[]:o.filter(s=>!s.stats?.gray)}function jo(e,t,r){return e.length===0?[]:e.map(n=>{let o=e.find(i=>i.author===n.parent_author&&i.permlink===n.parent_permlink&&i.author!==r);return {...n,id:n.post_id,host:r,container:t,parent:o}}).filter(n=>n.container.post_id!==n.post_id).sort((n,o)=>new Date(o.created).getTime()-new Date(n.created).getTime())}var rc=20;function Lo(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??rc}}async function $o({containers:e,tag:t,following:r,author:n,observer:o,limit:i},s,a){let c=Q.getValidatedBaseUrl(),p=new URL("/private-api/waves/feed",c);p.searchParams.set("limit",String(i)),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),o&&p.searchParams.set("observer",o);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 g=he(m,m.host??"");return g?{...g,_cursor:m._cursor}:null}).filter(m=>!!m)}function Nv(e={}){let t=Lo(e),{containers:r,tag:n,following:o,author:i,observer:s,limit:a}=t;return infiniteQueryOptions({queryKey:u.posts.wavesFeed({containers:r,tag:n,following:o,author:i,observer:s,limit:a}),initialPageParam:void 0,queryFn:({pageParam:c,signal:p})=>$o(t,c,p),getNextPageParam:c=>{if(!(c.length$o(t,void 0,c)})}var oc=20;function ic(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 sc({containers:e,tag:t,author:r,observer:n,limit:o},i,s){let a=Q.getValidatedBaseUrl(),c=new URL("/private-api/waves/shorts",a);c.searchParams.set("limit",String(o)),i&&c.searchParams.set("cursor",i),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=he(f,f.host??"");return m?{...m,active_votes:m.active_votes??[],video:f.video,_cursor:f._cursor}:null}).filter(f=>!!f)}function Vv(e={}){let t=ic(e),{containers:r,tag:n,author:o,observer:i,limit:s}=t;return infiniteQueryOptions({queryKey:u.posts.shortsFeed({containers:r,tag:n,author:o,observer:i,limit:s}),initialPageParam:void 0,queryFn:({pageParam:a,signal:c})=>sc(t,a,c),getNextPageParam:a=>{if(!(a.length(l.id=l.post_id,l.host=e,l));for(let l of c){if(i&&l.post_id===i){i=void 0;continue}if(o+=1,l.stats?.gray){r=l.author,n=l.permlink;continue}let f;try{f=await Vo(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:jo(f,l,e)}}let p=c[c.length-1];if(!p)return null;r=p.author,n=p.permlink;}return null}function Jv(e){return infiniteQueryOptions({queryKey:u.posts.wavesByHost(e),initialPageParam:void 0,queryFn:async({pageParam:t})=>{let r=await pc(e,t);return r?r.entries:[]},getNextPageParam:t=>t?.[0]?.container})}var dc=40;function t0(e,t,r=dc){return infiniteQueryOptions({queryKey:u.posts.wavesByTag(e,t),initialPageParam:void 0,queryFn:async({signal:n})=>{try{let o=Q.getValidatedBaseUrl(),i=new URL("/private-api/waves/tags",o);i.searchParams.set("container",e),i.searchParams.set("tag",t);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p).sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves by tag",o),[]}},getNextPageParam:()=>{}})}function s0(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 o=Q.getValidatedBaseUrl(),i=new URL("/private-api/waves/following",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){return console.error("[SDK] Failed to fetch waves following feed",o),[]}},getNextPageParam:()=>{}})}function p0(e,t=24){let r=e?.trim()||void 0;return queryOptions({queryKey:u.posts.wavesTrendingTags(r??"",t),queryFn:async({signal:n})=>{try{let o=Q.getValidatedBaseUrl(),i=new URL("/private-api/waves/trending/tags",o);r&&i.searchParams.set("container",r),i.searchParams.set("hours",t.toString());let s=await fetch(i.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(o){return console.error("[SDK] Failed to fetch waves trending tags",o),[]}}})}function g0(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 o=Q.getValidatedBaseUrl(),i=new URL("/private-api/waves/account",o);i.searchParams.set("container",e),i.searchParams.set("username",r);let s=await fetch(i.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=>he(p,e)).filter(p=>!!p);return c.length===0?[]:c.sort((p,l)=>new Date(l.created).getTime()-new Date(p.created).getTime())}catch(o){throw console.error("[SDK] Failed to fetch waves for account",o),o}},getNextPageParam:()=>{}})}function w0(e){return queryOptions({queryKey:u.posts.wavesTrendingAuthors(e),queryFn:async({signal:t})=>{try{let r=Q.getValidatedBaseUrl(),n=new URL("/private-api/waves/trending/authors",r);n.searchParams.set("container",e);let o=await fetch(n.toString(),{method:"GET",signal:t});if(!o.ok)throw new Error(`Failed to fetch waves trending authors: ${o.status}`);return (await o.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 O0(e,t=true){return queryOptions({queryKey:u.posts.normalize(e?.author??"",e?.permlink??""),enabled:t&&!!e,queryFn:async()=>Ko(e)})}function wc(e){return !!e&&typeof e=="object"&&"author"in e&&"permlink"in e&&"active_votes"in e}function Wo(e){let t=new Date(e);return (new Date().getTime()-t.getTime())/(1e3*60*60*24)}function q0(e,t){let{limit:r=20,filters:n=[],dayLimit:o=7}=t??{};return infiniteQueryOptions({queryKey:u.accounts.voteHistory(e,r),initialPageParam:{start:-1},queryFn:async({pageParam:i})=>{let{start:s}=i,a=await y("condenser_api.get_account_history",[e,s,r,...n]),p=a.map(([m,g])=>({...g.op[1],num:m,timestamp:g.timestamp})).filter(m=>m.voter===e&&m.weight!==0&&Wo(m.timestamp)<=o),l=[];for(let m of p){let g=await d.queryClient.fetchQuery(Ro(m.author,m.permlink));wc(g)&&l.push(g);}let[f]=a;return {lastDate:f?Wo(f[1].timestamp):0,lastItemFetched:f?f[0]:s,entries:l}},getNextPageParam:i=>({start:i.lastItemFetched})})}function N0(e,t,r=true){return queryOptions({queryKey:u.accounts.profiles(e,t??""),enabled:r&&e.length>0,queryFn:async()=>Vt(e,t)})}function V0(e,t="HIVE",r=200){return infiniteQueryOptions({queryKey:u.wallet.balanceHistory(e??"",t,r),initialPageParam:null,queryFn:async({pageParam:n,signal:o})=>{if(!e)return {entries:[],currentPage:0};let i={"account-name":e,"coin-type":t,"page-size":r,direction:"desc"};n!==null&&(i.page=n);let s=await te("balance","/accounts/{account-name}/balance-history",i,void 0,void 0,o);return {entries:s.operations_result,currentPage:n??s.total_pages}},getNextPageParam:n=>{let o=n.currentPage-1;return o>=1?o:void 0},enabled:!!e})}function G0(e,t="HIVE",r="yearly"){return queryOptions({queryKey:u.wallet.aggregatedHistory(e??"",t,r),queryFn:async()=>e?await te("balance","/accounts/{account-name}/aggregated-history",{"account-name":e,"coin-type":t,granularity:r}):[],enabled:!!e,staleTime:6e4})}function X0(){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 Z0(e){return new Set((e??[]).map(t=>t.toLowerCase()))}function iP(e,t,r){let n=useQueryClient(),{data:o}=useQuery(B(e));return v(["accounts","update"],e,i=>{let s=Ao(n.getQueryData(B(e).queryKey),o);if(!s)throw new Error("[SDK][Accounts] \u2013 cannot update not existing account");return [["account_update2",{account:e,json_metadata:"",extensions:[],posting_json_metadata:Oo({existingPostingJsonMetadata:s.posting_json_metadata,profile:i.profile,tokens:i.tokens})}]]},async(i,s)=>{n.setQueryData(B(e).queryKey,a=>{if(!a)return a;let c=JSON.parse(JSON.stringify(a));return c.profile=Er({existingProfile:Po(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({...B(e),staleTime:0});}catch{}}})}function pP(e,t,r,n,o){return useMutation({mutationKey:["accounts","relation","update",e,t],mutationFn:async i=>{let s=So(e,t);await b().prefetchQuery(s);let a=b().getQueryData(s.queryKey);return await go(e,"follow",["follow",{follower:e,following:t,what:[...i==="toggle-ignore"&&!a?.ignores?["ignore"]:[],...i==="toggle-follow"&&!a?.follows?["blog"]:[]]}],r),{...a,ignores:i==="toggle-ignore"?!a?.ignores:a?.ignores,follows:i==="toggle-follow"?!a?.follows:a?.follows}},onError:o,onSuccess(i){n(i),b().setQueryData(u.accounts.relations(e,t),i),t&&b().invalidateQueries(B(t));}})}function Rr(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 Qe(e,t,r,n,o,i,s){if(!e||!t||n===void 0||!i)throw new Error("[SDK][buildCommentOp] Missing required parameters");return ["comment",{parent_author:r,parent_permlink:n,author:e,permlink:t,title:o,body:i,json_metadata:JSON.stringify(s)}]}function He(e,t,r,n,o,i,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:o,allow_curation_rewards:i,extensions:s}]}function Tr(e,t){if(!e||!t)throw new Error("[SDK][buildDeleteCommentOp] Missing required parameters");return ["delete_comment",{author:e,permlink:t}]}function qr(e,t,r,n=false){if(!e||!t||!r)throw new Error("[SDK][buildReblogOp] Missing required parameters");let o={account:e,author:t,permlink:r};return n&&(o.delete="delete"),["custom_json",{id:"follow",json:JSON.stringify(["reblog",o]),required_auths:[],required_posting_auths:[e]}]}function Ue(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 Ec(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiTransferOps] Missing required parameters");return t.trim().split(/[\s,]+/).filter(Boolean).map(i=>Ue(e,i.trim(),r,n))}function kc(e,t,r,n,o,i){if(!e||!t||!r)throw new Error("[SDK][buildRecurrentTransferOp] Missing required parameters");if(o<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:o,executions:i,extensions:[]}]}function Xe(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 Ve(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildTransferFromSavingsOp] Missing required parameters");return ["transfer_from_savings",{from:e,to:t,amount:r,memo:n||"",request_id:o}]}function Go(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 ft(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildClaimInterestOps] Missing required parameters");return [Ve(e,t,r,n,o),Go(e,o)]}function mt(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 gt(e,t){if(!e||!t)throw new Error("[SDK][buildWithdrawVestingOp] Missing required parameters");return ["withdraw_vesting",{account:e,vesting_shares:t}]}function yt(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 ht(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 _t(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 Fr(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 je(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 Ir(e,t){return ["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:JSON.stringify(t.map(r=>({symbol:r})))}]}function Dr(e,t,r){if(!e||!t||r===void 0)throw new Error("[SDK][buildDelegateRcOp] Missing required parameters");let n=t.includes(",")?t.split(",").map(o=>o.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 Kr(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 jt(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 Cc(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 Rc(e,t){if(!e||!t)throw new Error("[SDK][buildUnignoreOp] Missing required parameters");return jt(e,t)}function Nr(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]}],o=["custom_json",{id:"ecency_notify",json:JSON.stringify(["setLastRead",{date:r}]),required_auths:[],required_posting_auths:[e]}];return [n,o]}function Br(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 Mr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildWitnessProxyOp] Missing required parameters");return ["account_witness_proxy",{account:e,proxy:t}]}function Qr(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 Hr(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 Tc(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 qc(e,t,r,n,o){if(e==null||typeof e!="number"||!t||!r||!n||!o)throw new Error("[SDK][buildUpdateProposalOp] Missing required parameters");return ["update_proposal",{proposal_id:e,creator:t,daily_pay:r,subject:n,permlink:o,extensions:[]}]}function Ur(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 Vr(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 jr(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 Lr(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 $r(e,t,r,n,o){if(!e||!t||!r||!n||o===void 0)throw new Error("[SDK][buildPinPostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"pinPost":"unpinPost",{community:t,account:r,permlink:n}]),required_auths:[],required_posting_auths:[e]}]}function Wr(e,t,r,n,o,i){if(!e||!t||!r||!n||i===void 0)throw new Error("[SDK][buildMutePostOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([i?"mutePost":"unmutePost",{community:t,account:r,permlink:n,notes:o}]),required_auths:[],required_posting_auths:[e]}]}function Fc(e,t,r,n,o){if(!e||!t||!r||o===void 0)throw new Error("[SDK][buildMuteUserOp] Missing required parameters");return ["custom_json",{id:"community",json:JSON.stringify([o?"muteUser":"unmuteUser",{community:t,account:r,notes:n}]),required_auths:[],required_posting_auths:[e]}]}function Ic(e,t,r,n,o){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:o}]),required_auths:[],required_posting_auths:[e]}]}var zo=(r=>(r.Buy="buy",r.Sell="sell",r))(zo||{}),Jo=(r=>(r.EMPTY="",r.SWAP="9",r))(Jo||{});function $t(e,t,r,n,o,i){if(!e||!t||!r||!o||i===void 0)throw new Error("[SDK][buildLimitOrderCreateOp] Missing required parameters");return ["limit_order_create",{owner:e,orderid:i,amount_to_sell:t,min_to_receive:r,fill_or_kill:n,expiration:o}]}function Lt(e,t=3){return e.toFixed(t)}function Dc(e,t,r,n,o=""){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 i=new Date(Date.now());i.setDate(i.getDate()+27);let s=i.toISOString().split(".")[0],a=+`${o}${Math.floor(Date.now()/1e3).toString().slice(2)}`,c=n==="buy"?`${Lt(t,3)} HBD`:`${Lt(t,3)} HIVE`,p=n==="buy"?`${Lt(r,3)} HIVE`:`${Lt(r,3)} HBD`;return $t(e,c,p,false,s,a)}function Gr(e,t){if(!e||t===void 0)throw new Error("[SDK][buildLimitOrderCancelOp] Missing required parameters");return ["limit_order_cancel",{owner:e,orderid:t}]}function zr(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 Kc(e,t,r,n,o,i){if(!e||!o)throw new Error("[SDK][buildAccountUpdateOp] Missing required parameters");return ["account_update",{account:e,owner:t,active:r,posting:n,memo_key:o,json_metadata:i}]}function Nc(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 Jr(e,t,r,n){if(!e||!t||!r||!n)throw new Error("[SDK][buildAccountCreateOp] Missing required parameters");let o={weight_threshold:1,account_auths:[],key_auths:[[r.ownerPublicKey,1]]},i={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:o,active:i,posting:s,memo_key:r.memoPublicKey,json_metadata:"",fee:n}]}function Yr(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]]},o={weight_threshold:1,account_auths:[],key_auths:[[r.activePublicKey,1]]},i={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:o,posting:i,memo_key:r.memoPublicKey,json_metadata:"",extensions:[]}]}function Xr(e,t){if(!e||!t)throw new Error("[SDK][buildClaimAccountOp] Missing required parameters");return ["claim_account",{creator:e,fee:t,extensions:[]}]}function Zr(e,t,r,n,o,i){if(!e||!t||!r||!o)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:o,json_metadata:i}]}function Bc(e,t,r,n,o){if(!e||!t||!r||!n)throw new Error("[SDK][buildRevokePostingPermissionOp] Missing required parameters");let i={...t,account_auths:t.account_auths.filter(([s])=>s!==r)};return ["account_update",{account:e,posting:i,memo_key:n,json_metadata:o}]}function Mc(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 Qc(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 Hc(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 en(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 tn(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 rn(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 Ze(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildPointTransferOp] Missing required parameters");let o=r.replace(/POINTS\b/,"POINT");return ["custom_json",{id:"ecency_point_transfer",json:JSON.stringify({sender:e,receiver:t,amount:o,memo:n||""}),required_auths:[e],required_posting_auths:[]}]}function Uc(e,t,r,n){if(!e||!t||!r)throw new Error("[SDK][buildMultiPointTransferOps] Missing required parameters");let o=t.trim().split(/[\s,]+/).filter(Boolean);if(o.length===0)throw new Error("[SDK][buildMultiPointTransferOps] Missing valid destinations");return o.map(i=>Ze(e,i.trim(),r,n))}function nn(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 Vc(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 jc(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 TP(e,t,r){return v(["accounts","follow"],e,({following:n})=>[Kr(e,n)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function DP(e,t,r){return v(["accounts","unfollow"],e,({following:n})=>[jt(e,n)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.relations(e,o.following),u.accounts.full(o.following),u.accounts.followCount(o.following),u.accounts.followCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function MP(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","add",e],mutationFn:async({author:o,permlink:i})=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/bookmarks-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({author:o,permlink:i,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function VP(e,t,r,n){return useMutation({mutationKey:["accounts","bookmarks","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Bookmarks] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/bookmarks-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:o,code:t})})).json()},onSuccess:()=>{r(),b().invalidateQueries({queryKey:["accounts","bookmarks",e]});},onError:n})}function WP(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","add",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");return (await h()(d.privateApiHost+"/private-api/favorites-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})})).json()},onSuccess:(o,i)=>{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,i)});},onError:n})}function XP(e,t,r,n){return useMutation({mutationKey:["accounts","favorites","delete",e],mutationFn:async o=>{if(!e||!t)throw new Error("[SDK][Account][Favorites] \u2013 missing auth");let s=await h()(d.privateApiHost+"/private-api/favorites-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({account:o,code:t})});if(!s.ok)throw new Error(`Failed to delete favorite: ${s.status}`);return s.json()},onMutate:async o=>{if(!e)return;let i=b(),s=u.accounts.favorites(e),a=u.accounts.favoritesInfinite(e),c=u.accounts.checkFavorite(e,o);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a}),i.cancelQueries({queryKey:c})]);let p=i.getQueryData(s);p&&i.setQueryData(s,p.filter(g=>g.account!==o));let l=i.getQueryData(c);i.setQueryData(c,false);let f=i.getQueriesData({queryKey:a}),m=new Map(f);for(let[g,_]of f)_&&i.setQueryData(g,{..._,pages:_.pages.map(P=>({...P,data:P.data.filter(O=>O.account!==o)}))});return {previousList:p,previousInfinite:m,previousCheck:l}},onSuccess:(o,i)=>{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,i)});},onError:(o,i,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,i),s.previousCheck),n(o);}})}function Yc(e,t){let r=new Map;return e.forEach(([n,o])=>{r.set(n.toString(),o);}),t.forEach(([n,o])=>{r.set(n.toString(),o);}),Array.from(r.entries()).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>[n,o])}function Yo(e,t){let{data:r}=useQuery(B(e));return useMutation({mutationKey:["accounts","keys-update",e],mutationFn:async({keys:n,keepCurrent:o=false,currentKey:i,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:[]],g=o?l.key_auths.filter(([_])=>!m.includes(_.toString())):[];return l.key_auths=Yc(g,n.map((_,P)=>[_[p].createPublic().toString(),P+1])),l};return ee([["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()}]],i)},...t})}function uA(e,t){let{data:r}=useQuery(B(e)),{mutateAsync:n}=Yo(e);return useMutation({mutationKey:["accounts","password-update",e],mutationFn:async({newPassword:o,currentPassword:i,keepCurrent:s})=>{if(!r)throw new Error("[SDK][Update password] \u2013 cannot update password for anon user");let a=U.fromLogin(e,i,"owner");return n({currentKey:a,keepCurrent:s,keys:[{owner:U.fromLogin(e,o,"owner"),active:U.fromLogin(e,o,"active"),posting:U.fromLogin(e,o,"posting"),memo_key:U.fromLogin(e,o,"memo")}]})},...t})}function mA(e,t,r){let n=useQueryClient(),{data:o}=useQuery(B(e));return useMutation({mutationKey:["accounts","revoke-posting",o?.name],mutationFn:async({accountName:i,type:s,key:a})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot revoke posting for anonymous user");let c=JSON.parse(JSON.stringify(o.posting));c.account_auths=c.account_auths.filter(([l])=>l!==i);let p={account:o.name,posting:c,memo_key:o.memo_key,json_metadata:o.json_metadata};if(s==="key"&&a)return ee([["account_update",p]],a);if(s==="keychain"){if(!r?.adapter?.broadcastWithKeychain)throw new Error("[SDK][Accounts] \u2013 missing keychain broadcaster");return r.adapter.broadcastWithKeychain(o.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."),mo.sendOperation(["account_update",p],t.hsCallbackUrl?{callback:t.hsCallbackUrl}:{},()=>{})},onError:t.onError,onSuccess:(i,s,a)=>{t.onSuccess?.(i,s,a),n.setQueryData(B(e).queryKey,c=>({...c,posting:{...c?.posting,account_auths:c?.posting?.account_auths?.filter(([p])=>p!==s.accountName)??[]}}));}})}function vA(e,t,r,n){let{data:o}=useQuery(B(e));return useMutation({mutationKey:["accounts","recovery",o?.name],mutationFn:async({accountName:i,type:s,key:a,email:c})=>{if(!o)throw new Error("[SDK][Accounts] \u2013\xA0cannot change recovery for anonymous user");let p={account_to_recover:o.name,new_recovery_account:i,extensions:[]};if(s==="ecency"){if(!t)throw new Error("[SDK][Accounts] \u2013 missing access token");let f=await h()(d.privateApiHost+"/private-api/recoveries-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t,email:c,publicKeys:[...o.owner.key_auths,...o.active.key_auths,...o.posting.key_auths,o.memo_key]})});if(!f.ok)throw new Error(`[SDK][Accounts] Failed to add recovery: ${f.status}`);return f}else {if(s==="key"&&a)return ee([["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(o.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."),mo.sendOperation(["change_recovery_account",p],r.hsCallbackUrl?{callback:r.hsCallbackUrl}:{},()=>{})}},onError:r.onError,onSuccess:r.onSuccess})}function AA(e,t){let r=e.key_auths.filter(([o])=>!t.has(String(o))).reduce((o,[,i])=>o+i,0),n=(e.account_auths??[]).reduce((o,[,i])=>o+i,0);return r+n>=e.weight_threshold}function Xo(e,t){let r=new Set(t.map(s=>s.toString())),n=s=>s.key_auths.some(([a])=>r.has(String(a))),o=s=>{let a=JSON.parse(JSON.stringify(s));return a.key_auths=a.key_auths.filter(([c])=>!r.has(c.toString())),a},i=n(e.owner);return {account:e.name,json_metadata:e.json_metadata,owner:i?o(e.owner):void 0,active:o(e.active),posting:o(e.posting),memo_key:e.memo_key}}function CA(e,t){let{data:r}=useQuery(B(e));return useMutation({mutationKey:["accounts","revoke-key",r?.name],mutationFn:async({currentKey:n,revokingKey:o})=>{if(!r)throw new Error("[SDK][Revoke key] \u2013 cannot update keys for anon user");let i=Array.isArray(o)?o:[o],s=Xo(r,i);return ee([["account_update",s]],n)},...t})}function FA(e,t,r){return v(["accounts","claimAccount"],e,({creator:n,fee:o="0.000 HIVE"})=>[Xr(n,o)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(o.creator)]);},t,"active",{broadcastMode:r})}function NA(e,t,r){return v(["accounts","grant-posting-permission"],e,n=>[Zr(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 HA(e,t,r){return v(["accounts","create"],e,n=>[n.useClaimed?Yr(e,n.newAccountName,n.keys):Jr(e,n.newAccountName,n.keys,n.fee)],async()=>{await S(t?.adapter,r,[u.accounts.full(e)]);},t,"active",{broadcastMode:r})}var on=300*60*24,cp=1e4,pp=5e7;function Zo(e){let t=k(e.vesting_shares).amount,r=k(e.received_vesting_shares).amount,n=k(e.delegated_vesting_shares).amount,o=k(e.vesting_withdraw_rate).amount,i=(Number(e.to_withdraw)-Number(e.withdrawn))/1e6,s=Math.min(o,i);return t+r-n-s}function lp(e,t,r){let n=e*1e6;return (t*r/1e4/50+1)*n/1e4}function dp(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 fp(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 o=Zo(e);if(!Number.isFinite(o)||o<=0)return 0;let i=o*1e6,s=Math.ceil(i*r*60*60*24/cp/(n*on)),a=Or(e),c=Math.min(a.current_mana,a.max_mana);return !Number.isFinite(c)||s>c?0:Math.max(s-pp,0)}function mp(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;if(dp(t))return fp(e,t,n);let o=0;try{if(o=Zo(e),!Number.isFinite(o))return 0}catch{return 0}return lp(o,r,n)}function LA(e){return Or(e).percentage/100}function $A(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*on/1e4}function WA(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 o=parseFloat(e.downvote_manabar.current_mana.toString())+r*n/on;o>n&&(o=n);let i=o*100/n;return isNaN(i)?0:i>100?100:i}function GA(e){return Bt(e).percentage/100}function zA(e,t,r,n=1e4){if(!Number.isFinite(r)||!Number.isFinite(n))return 0;let{fundRecentClaims:o,fundRewardBalance:i,base:s,quote:a}=t;if(!Number.isFinite(o)||!Number.isFinite(i)||!Number.isFinite(s)||!Number.isFinite(a)||o===0||a===0)return 0;let c=mp(e,t,r,n);return Number.isFinite(c)?c/o*i*(s/a):0}var gp={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 yp(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 hp(e){let t=e[0];if(t!=="create_proposal"&&t!=="update_proposal")throw new Error("Operation is not a proposal operation");return "active"}function _p(e){let t=e[0];return t==="custom_json"?yp(e):t==="create_proposal"||t==="update_proposal"?hp(e):gp[t]??"posting"}function YA(e){let t="posting";for(let r of e){let n=_p(r);if(n==="owner")return "owner";n==="active"&&t==="posting"&&(t="active");}return t}function rO(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"):co(r)?n=U.fromString(r):n=U.from(r),ee([t],n)}})}function iO(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 cO(e="/"){return useMutation({mutationKey:["operations","sign-hivesigner",e],mutationFn:async({operation:t})=>mo.sendOperation(t,{callback:e},()=>{})})}function fO(){return queryOptions({queryKey:["operations","chain-properties"],queryFn:async()=>await y("condenser_api.get_chain_properties",[])})}function ei(e,t,r){return {...e,...t??{},title:r.title,body:r.body}}function ti(e,t){return {...e??{},title:t.title,body:t.body}}function vO(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 i=await h()(d.privateApiHost+"/private-api/fragments-add",{method:"POST",body:JSON.stringify({code:t,title:r,body:n}),headers:{"Content-Type":"application/json"}});if(!i.ok)throw new Error(`[SDK][Posts] Failed to add fragment: ${i.status}`);return i.json()},onSuccess(r,n){let o=b(),i=ti(r,n);o.setQueryData(Ye(e,t).queryKey,s=>[i,...s??[]]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map((a,c)=>c===0?{...a,data:[i,...a.data]}:a)});}})}function kO(e,t){return useMutation({mutationKey:["posts","edit-fragment",e],mutationFn:async({fragmentId:r,title:n,body:o})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let s=await h()(d.privateApiHost+"/private-api/fragments-update",{method:"POST",body:JSON.stringify({code:t,id:r,title:n,body:o}),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 o=b(),i=s=>ei(s,r,n);o.setQueryData(Ye(e,t).queryKey,s=>s?.map(a=>a.id===n.fragmentId?i(a):a)??[]),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},s=>s&&{...s,pages:s.pages.map(a=>({...a,data:a.data.map(c=>c.id===n.fragmentId?i(c):c)}))});}})}function IO(e,t){return useMutation({mutationKey:["posts","remove-fragment",e],mutationFn:async({fragmentId:r})=>{if(!t)throw new Error("[SDK][Posts] Missing access token");let o=await h()(d.privateApiHost+"/private-api/fragments-delete",{method:"POST",body:JSON.stringify({code:t,id:r}),headers:{"Content-Type":"application/json"}});if(!o.ok)throw new Error(`[SDK][Posts] Failed to delete fragment: ${o.status}`);return o},onSuccess(r,n){let o=b();o.setQueryData(Ye(e,t).queryKey,i=>[...i??[]].filter(({id:s})=>s!==n.fragmentId)),o.setQueriesData({queryKey:["posts","fragments","infinite",e]},i=>i&&{...i,pages:i.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 NO(e,t,r,n){let i=await h()(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(i);return {status:i.status,data:s}}async function BO(e){let r=await h()(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 MO(e,t,r="",n=""){let o={code:e,ty:t};r&&(o.bl=r),n&&(o.tx=n);let s=await h()(d.privateApiHost+"/private-api/usr-activity",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});await G(s);}async function QO(e,t,r=null,n=null){let o={code:e};t&&(o.filter=t),r&&(o.since=r),n&&(o.user=n);let s=await h()(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});return G(s)}async function HO(e,t,r,n,o,i){let s={code:e,username:t,token:i,system:r,allows_notify:n,notify_types:o},c=await h()(d.privateApiHost+"/private-api/register-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function UO(e,t,r){let n={code:e,username:t,token:r},i=await h()(d.privateApiHost+"/private-api/detail-device",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}async function ri(e,t){let r={code:e};t&&(r.id=t);let o=await h()(d.privateApiHost+"/private-api/notifications/mark",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function ni(e,t){let r={code:e,url:t},o=await h()(d.privateApiHost+"/private-api/images-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}var Ep="https://i.ecency.com";async function oi(e,t,r){let n=h(),o=new FormData;o.append("file",e);let i=await n(`${Ep}/hs/${t}`,{method:"POST",body:o,signal:r});return G(i)}async function VO(e,t,r,n){let o=h(),i=new FormData;i.append("file",e);let s=await o(`${d.imageHost}/${t}/${r}`,{method:"POST",body:i,signal:n});return G(s)}async function ii(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/images-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function si(e,t,r,n,o){let i={code:e,title:t,body:r,tags:n,meta:o},a=await h()(d.privateApiHost+"/private-api/drafts-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return G(a)}async function ai(e,t,r,n,o,i){let s={code:e,id:t,title:r,body:n,tags:o,meta:i},c=await h()(d.privateApiHost+"/private-api/drafts-update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return G(c)}async function ui(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/drafts-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function ci(e,t,r,n,o,i,s,a){let c={code:e,permlink:t,title:r,body:n,meta:o,schedule:s,reblog:a};i&&(c.options=i);let l=await h()(d.privateApiHost+"/private-api/schedules-add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)});return G(l)}async function pi(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/schedules-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function li(e,t){let r={code:e,id:t},o=await h()(d.privateApiHost+"/private-api/schedules-move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});return G(o)}async function jO(e,t,r){let n={code:e,author:t,permlink:r},i=await h()(d.privateApiHost+"/private-api/promoted-post",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}async function LO(e,t,r){let n={username:e,email:t,friend:r},i=await h()(d.privateApiHost+"/private-api/account-create-friend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return G(i)}function JO(e,t,r,n){return useMutation({mutationKey:["posts","drafts","add",e],mutationFn:async({title:o,body:i,tags:s,meta:a})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addDraft");return si(t,o,i,s,a)},onSuccess:o=>{r?.();let i=b();o?.drafts?i.setQueryData(u.posts.drafts(e),o.drafts):i.invalidateQueries({queryKey:u.posts.drafts(e)}),i.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function tx(e,t,r,n){return useMutation({mutationKey:["posts","drafts","update",e],mutationFn:async({draftId:o,title:i,body:s,tags:a,meta:c})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for updateDraft");return ai(t,o,i,s,a,c)},onSuccess:()=>{r?.();let o=b();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:n})}function ax(e,t,r,n){return useMutation({mutationKey:["posts","drafts","delete",e],mutationFn:async({draftId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteDraft");return ui(t,o)},onMutate:async({draftId:o})=>{if(!e)return;let i=b(),s=u.posts.drafts(e),a=u.posts.draftsInfinite(e);await Promise.all([i.cancelQueries({queryKey:s}),i.cancelQueries({queryKey:a})]);let c=i.getQueryData(s);c&&i.setQueryData(s,c.filter(f=>f._id!==o));let p=i.getQueriesData({queryKey:a}),l=new Map(p);for(let[f,m]of p)m&&i.setQueryData(f,{...m,pages:m.pages.map(g=>({...g,data:g.data.filter(_=>_._id!==o)}))});return {previousList:c,previousInfinite:l}},onSuccess:()=>{r?.();let o=b();o.invalidateQueries({queryKey:u.posts.drafts(e)}),o.invalidateQueries({queryKey:u.posts.draftsInfinite(e)});},onError:(o,i,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?.(o);}})}function dx(e,t,r,n){return useMutation({mutationKey:["posts","schedules","add",e],mutationFn:async({permlink:o,title:i,body:s,meta:a,options:c,schedule:p,reblog:l})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for addSchedule");return ci(t,o,i,s,a,c,p,l)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function hx(e,t,r,n){return useMutation({mutationKey:["posts","schedules","delete",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteSchedule");return pi(t,o)},onSuccess:o=>{r?.();let i=b();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)});},onError:n})}function Px(e,t,r,n){return useMutation({mutationKey:["posts","schedules","move",e],mutationFn:async({id:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for moveSchedule");return li(t,o)},onSuccess:o=>{r?.();let i=b();o?i.setQueryData(u.posts.schedules(e),o):i.invalidateQueries({queryKey:u.posts.schedules(e)}),i.invalidateQueries({queryKey:u.posts.drafts(e)});},onError:n})}function Ex(e,t,r,n){return useMutation({mutationKey:["posts","images","add",e],mutationFn:async({url:o,code:i})=>{let s=i??t;if(!e||!s)throw new Error("[SDK][Posts] \u2013 missing auth for addImage");return ni(s,o)},onSuccess:()=>{r?.(),b().invalidateQueries({queryKey:u.posts.images(e)});},onError:n})}function qx(e,t,r,n){return useMutation({mutationKey:["posts","images","delete",e],mutationFn:async({imageId:o})=>{if(!e||!t)throw new Error("[SDK][Posts] \u2013 missing auth for deleteImage");return ii(t,o)},onSuccess:(o,i)=>{r?.();let s=b(),{imageId:a}=i;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 Kx(e,t){return useMutation({mutationKey:["posts","images","upload"],mutationFn:async({file:r,token:n,signal:o})=>oi(r,n,o),onSuccess:e,onError:t})}function Gt(e,t){return `/@${e}/${t}`}function Np(e,t,r){return (r??b()).getQueryData(u.posts.entry(Gt(e,t)))}function Bp(e,t){(t??b()).setQueryData(u.posts.entry(Gt(e.author,e.permlink)),e);}function Wt(e,t,r,n){let o=n??b(),i=Gt(e,t),s=o.getQueryData(u.posts.entry(i));if(!s)return;let a=r(s);return o.setQueryData(u.posts.entry(i),a),s}var Le;(a=>{function e(c,p,l,f,m){Wt(c,p,g=>({...g,active_votes:l,stats:{...g.stats||{gray:false,hide:false,flag_weight:0,total_votes:0},total_votes:l.length,flag_weight:g.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){Wt(c,p,m=>({...m,reblogs:l}),f);}a.updateReblogsCount=t;function r(c,p,l,f){Wt(c,p,m=>({...m,children:l}),f);}a.updateRepliesCount=r;function n(c,p,l,f){Wt(p,l,m=>({...m,children:m.children+1,replies:[c,...m.replies]}),f);}a.addReply=n;function o(c,p){c.forEach(l=>Bp(l,p));}a.updateEntries=o;function i(c,p,l){(l??b()).invalidateQueries({queryKey:u.posts.entry(Gt(c,p))});}a.invalidateEntry=i;function s(c,p,l){return Np(c,p,l)}a.getEntry=s;})(Le||={});function Mp(e,t,r){let n=e.some(o=>o.voter===t);return r!==0?n:!n}function Qp(e,t,r){let n=Le.getEntry(t.author,t.permlink,r);if(!n?.active_votes||Mp(n.active_votes,e,t.weight))return;let o=[...n.active_votes.filter(s=>s.voter!==e),...t.weight!==0?[{rshares:t.weight,voter:e}]:[]],i=n.payout+(t.estimated??0);Le.updateVotes(t.author,t.permlink,o,i,r);}function Vx(e,t,r){return v(["posts","vote"],e,({author:n,permlink:o,weight:i})=>[Rr(e,n,o,i)],async(n,o)=>{Qp(e,o);let i=n?.id??n?.tx_id;if(t?.adapter?.recordActivity&&i&&t.adapter.recordActivity(120,i,n?.block_num).catch(()=>{}),t?.adapter?.invalidateQueries){let s=()=>{t.adapter.invalidateQueries([u.posts.entry(`/@${o.author}/${o.permlink}`),u.accounts.full(e)]);};(r??"async")==="async"?setTimeout(s,4e3):s();}},t,"posting",{broadcastMode:r??"async"})}function Gx(e,t,r){return v(["posts","reblog"],e,({author:n,permlink:o,deleteReblog:i})=>[qr(e,n,o,i??false)],async(n,o)=>{let i=Le.getEntry(o.author,o.permlink);if(i){let p=Math.max(0,(i.reblogs??0)+(o.deleteReblog?-1:1));Le.updateReblogsCount(o.author,o.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(`/@${o.author}/${o.permlink}`),u.posts.rebloggedBy(o.author,o.permlink)]);};(r??"async")==="async"?setTimeout(a,4e3):a();},t,"posting",{broadcastMode:r??"async"})}function Hp(e){return e.isUpdate?null:e.parentAuthor?110:100}function Xx(e,t,r){return v(["posts","comment"],e,n=>{let o=[];if(o.push(Qe(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="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,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(He(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{let i=!o.parentAuthor,s=Hp(o),a=n?.id??n?.tx_id;if(s!==null&&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(!i){c.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let p=o.rootAuthor||o.parentAuthor,l=o.rootPermlink||o.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 tS(e,t,r,n){let o=n??b(),i=o.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 i)a&&o.setQueryData(s,[e,...a]);}function di(e,t,r,n,o){let i=o??b(),s=new Map,a=i.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),i.setQueryData(c,p.filter(l=>l.author!==e||l.permlink!==t)));return s}function fi(e,t){let r=t??b();for(let[n,o]of e)r.setQueryData(n,o);}function rS(e,t,r,n){let o=n??b(),i=`/@${e}/${t}`,s=o.getQueryData(u.posts.entry(i));return s&&o.setQueryData(u.posts.entry(i),{...s,...r}),s}function nS(e,t,r,n){let o=n??b(),i=`/@${e}/${t}`;o.setQueryData(u.posts.entry(i),r);}function uS(e,t,r){return v(["posts","deleteComment"],e,({author:n,permlink:o})=>[Tr(n,o)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e)];if(o.parentAuthor&&o.parentPermlink){i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r,onMutate:async n=>{let o=n.rootAuthor||n.parentAuthor,i=n.rootPermlink||n.parentPermlink;return o&&i?{snapshots:di(n.author,n.permlink,o,i)}:{}},onError:(n,o,i)=>{let{snapshots:s}=i??{};s&&fi(s);}})}function dS(e,t,r){return v(["posts","cross-post"],e,n=>{let o=[];if(o.push(Qe(n.author,n.permlink,"",n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="1000000.000 HBD",percentHbd:s=1e4,allowVotes:a=true,allowCurationRewards:c=true}=n.options;o.push(He(n.author,n.permlink,i,s,a,c,[]));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.accounts.full(e),{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.parentPermlink}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"async"})}function yS(e,t,r){return v(["posts","update-reply"],e,n=>{let o=[];if(o.push(Qe(n.author,n.permlink,n.parentAuthor,n.parentPermlink,n.title,n.body,n.jsonMetadata)),n.options){let{maxAcceptedPayout:i="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,g)=>m.account.localeCompare(g.account));l.push([0,{beneficiaries:f.map(m=>({account:m.account,weight:m.weight}))}]);}o.push(He(n.author,n.permlink,i,s,a,c,l));}return o},async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.resourceCredits.account(e)];i.push(u.posts.entry(`/@${o.parentAuthor}/${o.parentPermlink}`));let s=o.rootAuthor||o.parentAuthor,a=o.rootPermlink||o.parentPermlink;i.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(i);}},t,"posting",{broadcastMode:r})}function bS(e,t,r){return v(["ecency","promote"],e,({author:n,permlink:o,duration:i})=>[rn(e,n,o,i)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.posts._promotedPrefix],[...u.points._prefix(e)],u.posts.entry(`/@${o.author}/${o.permlink}`)]);},t,"active",{broadcastMode:r})}var Up=[3e3,3e3,3e3],Vp=e=>new Promise(t=>setTimeout(t,e));async function jp(e,t){return y("condenser_api.get_content",[e,t])}async function Lp(e,t,r=0,n){let o=n?.delays??Up,i;try{i=await jp(e,t);}catch{i=void 0;}if(i||r>=o.length)return;let s=o[r];return s>0&&await Vp(s),Lp(e,t,r+1,n)}var et={};Ot(et,{useRecordActivity:()=>sn});function Wp(){return typeof window<"u"&&window.location?{url:window.location.href,domain:window.location.host}:{url:"",domain:""}}function sn(e,t,r){return useMutation({mutationKey:["analytics",t],mutationFn:async()=>{if(!t)throw new Error("[SDK][Analytics] \u2013 no activity type provided");let n=h(),o=Wp(),i=r?.url??o.url,s=r?.domain??o.domain;try{await n(d.plausibleHost+"/api/event",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,url:i,domain:s,props:{username:e}})});}catch{}}})}function RS(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 DS(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(),o=n.map(s=>s.account),i=await y("condenser_api.get_accounts",[o]);for(let s=0;sa.efficiency-s.efficiency),n}})}function MS(e,t=[],r=["visitors","pageviews","visit_duration"],n){let o=[...t].sort(),i=[...r].sort();return queryOptions({queryKey:["analytics","page-stats",e,o,i,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 zt="threespeakfund",LS=1100;function Yp(e){return /https?:\/\/([a-z0-9-]+\.)*3speak\.tv\/embed[?/]/i.test(e)}function $S(e,t){if(!Yp(t))return e;let r=e.find(n=>n.account===zt);return r&&r.weight===1100?e:r?e.map(n=>n.account===zt?{...n,weight:1100}:n):[...e,{account:zt,weight:1100}]}function WS(e){return e===zt}var cn={};Ot(cn,{getAccountTokenQueryOptions:()=>un,getAccountVideosQueryOptions:()=>nl});var an={};Ot(an,{getDecodeMemoQueryOptions:()=>el});function el(e,t,r){return queryOptions({queryKey:["integrations","hivesigner","decode-memo",e],queryFn:async()=>{if(r)return new mo.Client({accessToken:r}).decode(t)}})}var mi={queries:an};function un(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 h()(`https://studio.3speak.tv/mobile/login?username=${e}&hivesigner=true`,{headers:{"Content-Type":"application/json"}}),o=mi.queries.getDecodeMemoQueryOptions(e,(await n.json()).memo,t);await b().prefetchQuery(o);let{memoDecoded:i}=b().getQueryData(o.queryKey);return i.replace("#","")}})}function nl(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=un(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 h()("https://studio.3speak.tv/mobile/api/my-videos",{headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}})).json()}})}var pE={queries:cn};function yE(e){return queryOptions({queryKey:["integrations","hiveposh","links",e],retry:false,queryFn:async()=>{try{let r=await h()(`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 bE({url:e,dimensions:t=[],metrics:r=["visitors","pageviews","visit_duration"],filterBy:n="event:page",dateRange:o,enabled:i=true}){return queryOptions({queryKey:["integrations","plausible",e,t,r,n,o],queryFn:async()=>{let a=await h()(`${d.privateApiHost}/api/stats`,{method:"POST",body:JSON.stringify({metrics:r,url:encodeURIComponent(e),dimensions:t,filterBy:n,...o?{date_range:o}:{}}),headers:{"Content-Type":"application/json"}});if(!a.ok)throw new Error(`Failed to fetch Plausible stats: ${a.status}`);return await a.json()},enabled:!!e&&i,retry:1})}function OE(){return queryOptions({queryKey:["resource-credits","stats"],queryFn:async()=>(await y("rc_api.get_rc_stats",{})).rc_stats})}function kE(e){return queryOptions({queryKey:["resource-credits","account",e],queryFn:async()=>(await y("rc_api.find_rc_accounts",{accounts:[e]})).rc_accounts,enabled:!!e})}function FE(){return queryOptions({queryKey:u.resourceCredits.resourceParams(),staleTime:1440*60*1e3,gcTime:1/0,queryFn:async()=>await y("rc_api.get_resource_params",{})})}var Jt=["resource_history_bytes","resource_new_accounts","resource_market_bytes","resource_state_bytes","resource_execution_time"];var cl=11,pl=65,ll=16,tt=e=>BigInt(typeof e=="string"?e:Math.trunc(e));function pn(e,t,r,n){if(r<=0||n<=0)return 0;let o=tt(e.coeff_a),i=tt(e.coeff_b),s=tt(e.shift),a=tt(n)*o>>s;a+=1n,a*=tt(r);let c=i+(t>0?tt(t):0n);return c===0n?0:Number(a/c+1n)}function ln({transactionBytes:e,permlinkLength:t,signatures:r=1,beneficiaries:n=0,hasCommentOptions:o=false},i){let s=i.resource_state_bytes,a=i.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+(o?a.comment_options_time:0)}}var _e=e=>{let t=lt(e);return ye(t)+t},dl=e=>1+_e(e.parent_author)+_e(e.parent_permlink)+_e(e.author)+_e(e.permlink)+_e(e.title)+_e(e.body)+_e(e.json_metadata),fl=(e,t)=>{let r=t.beneficiaries??[],n=1+_e(e.author)+_e(e.permlink)+ll+2+2;return n+=ye(r.length>0?1:0),r.length>0&&(n+=1+ye(r.length),r.forEach(o=>{n+=_e(o.account)+2;})),n};function dn({op:e,options:t,signatures:r=1}){let n=[dl(e)];return t&&n.push(fl(e,t)),cl+ye(n.length)+n.reduce((o,i)=>o+i,0)+ye(r)+pl*r}var ml={ready:false,cost:0,transactionBytes:0,breakdown:[]};function BE({op:e,options:t,rcParams:r,rcStats:n,signatures:o=1}){if(!r?.resource_params||!r.size_info||!n?.pool||!n.share)return ml;let i=dn({op:e,options:t,signatures:o}),s=ln({transactionBytes:i,permlinkLength:lt(e.permlink),signatures:o,beneficiaries:t?.beneficiaries?.length??0,hasCommentOptions:!!t},r.size_info),a=Number(n.regen),c=0,p=[];return Jt.forEach((l,f)=>{let m=r.resource_params[l],g=Number(n.pool[f]??0),_=Number(n.share[f]??0);if(!m||_<=0)return;let P=s[l]*Number(m.resource_dynamics_params.resource_unit??1),O=Number(BigInt(a)*BigInt(_)/10000n),T=pn(m.price_curve_params,g,P,O);c+=T,p.push({resource:l,usage:P,cost:T});}),{ready:true,cost:c,transactionBytes:i,breakdown:p}}function fn(e,t,r){let n=Number(r.regen),o=0,i=[];return Jt.forEach((s,a)=>{let c=t.resource_params[s],p=Number(r.pool[a]??0),l=Number(r.share[a]??0);if(!c||l<=0)return;let f=e[s]*Number(c.resource_dynamics_params.resource_unit??1),m=Number(BigInt(n)*BigInt(l)/10000n),g=pn(c.price_curve_params,p,f,m);o+=g,i.push({resource:s,usage:f,cost:g});}),{cost:o,breakdown:i}}var gl=11,yl=65,mn=e=>{let t=lt(e);return ye(t)+t},hl=()=>({resource_history_bytes:0,resource_new_accounts:0,resource_market_bytes:0,resource_state_bytes:0,resource_execution_time:0});function gi(e,t=1){let r=1+mn(e.voter)+mn(e.author)+mn(e.permlink)+2;return gl+ye(1)+r+ye(t)+yl*t}function yi({transactionBytes:e,signatures:t=1},r){let n=r.resource_state_bytes,o=r.resource_execution_time;return {...hl(),resource_history_bytes:e,resource_state_bytes:n.vote_size+n.transaction_base_size,resource_execution_time:o.vote_time+o.transaction_time+o.verify_authority_time*t}}var hi={ready:false,currentMana:0,maxMana:0,avgCost:0,cost:0,transactionBytes:0,estimatedCost:0,willLikelyFail:false,deficit:0,remaining:0};function zE({rcAccount:e,rcStats:t,rcParams:r,operation:n,payload:o,fallback:i="minimal",buffer:s=1.2}){if(!e||!t?.ops)return hi;let{current_mana:a,max_mana:c}=Bt(e),p=_l(n,o,i,r,t);if(!p)return {...hi,currentMana:a,maxMana:c};let{cost:l,transactionBytes:f}=p,m=Number.isFinite(s)&&s>0?s:1.2,g=l*m,_=a0?{cost:r,transactionBytes:0}:null}var bl={author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa",parent_author:"",parent_permlink:"hive-100000",title:"",body:"",json_metadata:"{}"},vl={voter:"aaaaaaaaaa",author:"aaaaaaaaaa",permlink:"aaaaaaaaaaaaaaaaaaaa"};function ZE(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 h()(d.privateApiHost+"/private-api/get-game",{method:"POST",body:JSON.stringify({game_type:r,code:t}),headers:{"Content-Type":"application/json"}})).json()}})}async function Ol(e,t,r){let o=await h()(d.privateApiHost+"/private-api/post-game",{method:"POST",body:JSON.stringify({game_type:t,code:e,key:r}),headers:{"Content-Type":"application/json"}}),i=(o.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),s=await o.text();if(!o.ok){let a=s&&i.includes("json")?`: ${s.slice(0,200)}`:"";throw new Error(`[SDK][Games] \u2013 failed with status ${o.status}${a}`)}if(!i.includes("json"))throw new Error(`[SDK][Games] \u2013 expected JSON but received "${i||"empty"}" response (status ${o.status})`);try{return JSON.parse(s)}catch{throw new Error(`[SDK][Games] \u2013 malformed JSON response (status ${o.status})`)}}function ok(e,t,r,n){let{mutateAsync:o}=sn(e,"spin-rolled");return useMutation({mutationKey:["games","post",r,e],mutationFn:async()=>{if(!e||!t)throw new Error("[SDK][Games] \u2013 missing auth");return Ol(t,r,n)},onSuccess(){o();}})}function uk(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 h()(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 Sl=[{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 pk(e,t){return Sl.find(r=>r.tier===e&&r.id===t)}var El=25;function kl(e){return Array.from((e??"").replace(/https?:\/\/\S+/g,"")).length}function lk(e){return kl(e)>El}var dk=300,fk=2;function Tl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}async function ql(e){let r=await h()(d.privateApiHost+"/private-api/streak-freeze/buy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,idempotency_key:Tl()})});if(!r.ok){let n;try{n=await r.json();}catch{}let o=n?.message??`Failed to buy streak freeze: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function hk(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 ql(t)},onSuccess(){n&&r.invalidateQueries({queryKey:u.points._prefix(n)});},onSettled(){n&&r.invalidateQueries({queryKey:u.quests.status(n)});}})}function vk(e,t,r){return v(["communities","subscribe"],e,({community:n})=>[Ur(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"async"})}function xk(e,t,r){return v(["communities","unsubscribe"],e,({community:n})=>[Vr(e,n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.subscriptions(e),[...u.communities.singlePrefix(o.community)],u.communities.context(e,o.community)]);},t,"posting",{broadcastMode:r??"sync"})}function Ck(e,t,r){return v(["communities","mutePost"],e,({community:n,author:o,permlink:i,notes:s,mute:a})=>[Wr(e,n,o,i,s,a)],async(n,o)=>{if(t?.adapter?.invalidateQueries){let i=[u.posts.entry(`/@${o.author}/${o.permlink}`),["community","single",o.community],{predicate:s=>{let a=s.queryKey;return Array.isArray(a)&&a[0]==="posts"&&a[1]==="posts-ranked"&&a[3]===o.community}}];await t.adapter.invalidateQueries(i);}},t,"posting",{broadcastMode:r??"sync"})}function Fk(e,t,r,n){return v(["communities","set-role",e],t,({account:o,role:i})=>[jr(t,e,o,i)],async(o,i)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>{if(!a)return a;let c=[...a.team??[]],p=c.findIndex(([l])=>l===i.account);return p>=0?c[p]=[c[p][0],i.role,c[p][2]??""]:c.push([i.account,i.role,""]),{...a,team:c}}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)],u.communities.context(i.account,e)]);},r,"posting",{broadcastMode:n??"async"})}function Nk(e,t,r,n){return v(["communities","update",e],t,o=>[Lr(t,e,o)],async(o,i)=>{b().setQueriesData({queryKey:u.communities.singlePrefix(e)},a=>a&&{...a,...i}),r?.adapter?.invalidateQueries&&await r.adapter.invalidateQueries([[...u.communities.singlePrefix(e)]]);},r,"posting",{broadcastMode:n??"async"})}function Hk(e,t,r){return v(["communities","registerRewards"],e,({name:n})=>[nn(n)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([[...u.communities.singlePrefix(o.name)],[...u.points._prefix(e)]]);},t,"active",{broadcastMode:r})}function Lk(e,t,r){return v(["communities","pin-post"],e,({community:n,account:o,permlink:i,pin:s})=>[$r(e,n,o,i,s)],async(n,o)=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.posts.entry(`/@${o.account}/${o.permlink}`),[...u.communities.singlePrefix(o.community)]]);},t,"posting",{broadcastMode:r??"async"})}function Jk(e,t,r=100,n=void 0,o=true){return queryOptions({queryKey:u.communities.list(e,t??"",r),enabled:o,queryFn:async()=>{let i=await y("bridge.list_communities",{last:"",limit:r,sort:e==="hot"?"rank":e,query:t||null,observer:n});return i?e==="hot"?i.sort(()=>Math.random()-.5):i:[]}})}function tC(e,t){return queryOptions({queryKey:u.communities.context(e,t),enabled:!!e&&!!t,queryFn:async()=>{let r=await y("bridge.get_community_context",{account:e,name:t});return {role:r?.role??"guest",subscribed:r?.subscribed??false}}})}function sC(e,t="",r=true){return queryOptions({queryKey:u.communities.single(e,t),enabled:r&&!!e,queryFn:async()=>Do(e??"",t)})}var _i=100;async function wi(e,t){return await y("bridge.list_subscribers",{community:e,limit:_i,...t?{last:t}:{}})??[]}function dC(e){return queryOptions({queryKey:u.communities.subscribers(e),queryFn:async()=>wi(e,null),staleTime:6e4})}function fC(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 wC(e,t){return infiniteQueryOptions({queryKey:u.communities.accountNotifications(e,t),initialPageParam:null,queryFn:async({pageParam:r})=>await y("bridge.account_notifications",{account:e,limit:t,last_id:r??void 0})??[],getNextPageParam:r=>r?.length>=t?r[r.length-1].id:null})}function AC(){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 Ql=(s=>(s.OWNER="owner",s.ADMIN="admin",s.MOD="mod",s.MEMBER="member",s.GUEST="guest",s.MUTED="muted",s))(Ql||{}),xC={owner:["admin","mod","member","guest","muted"],admin:["mod","member","guest","muted"],mod:["member","guest","muted"]};function EC(e,t){return e.startsWith("hive-3")||t===3?"Council":e.startsWith("hive-2")||t===2?"Journal":"Topic"}function kC({communityType:e,userRole:t,subscribed:r}){let n=t==="muted"?false:e==="Topic"?true:["owner","admin","mod","member"].includes(t),o=(()=>{if(t==="muted")return false;switch(e){case "Topic":return true;case "Journal":return t!=="guest"||r;case "Council":return n}})(),i=["owner","admin","mod"].includes(t);return {canPost:n,canComment:o,isModerator:i}}function qC(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 KC(e,t,r=void 0){return infiniteQueryOptions({queryKey:u.notifications.list(e,r),queryFn:async({pageParam:n})=>{if(!t)return [];let o={code:t,filter:r,since:n,user:void 0},i=await fetch(d.privateApiHost+"/private-api/notifications",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok)return [];try{return await i.json()}catch{return []}},enabled:!!e&&!!t,initialPageParam:"",getNextPageParam:n=>n?.[n.length-1]?.id??"",refetchOnMount:true})}var Vl=(g=>(g.VOTES="rvotes",g.MENTIONS="mentions",g.FAVORITES="nfavorites",g.BOOKMARKS="nbookmarks",g.FOLLOWS="follows",g.REPLIES="replies",g.REBLOGS="reblogs",g.TRANSFERS="transfers",g.DELEGATIONS="delegations",g.PAYOUTS="payouts",g.SCHEDULED_PUBLISHED="scheduled_published",g.ACCOUNT_UPDATES="account_updates",g.WEEKLY_EARNINGS="weekly_earnings",g))(Vl||{});var jl=(_=>(_[_.VOTE=1]="VOTE",_[_.MENTION=2]="MENTION",_[_.FOLLOW=3]="FOLLOW",_[_.COMMENT=4]="COMMENT",_[_.RE_BLOG=5]="RE_BLOG",_[_.TRANSFERS=6]="TRANSFERS",_[_.DELEGATIONS=10]="DELEGATIONS",_[_.FAVORITES=13]="FAVORITES",_[_.BOOKMARKS=15]="BOOKMARKS",_[_.PAYOUTS=19]="PAYOUTS",_[_.ACCOUNT_UPDATE=20]="ACCOUNT_UPDATE",_[_.WEEKLY_EARNINGS=21]="WEEKLY_EARNINGS",_[_.SCHEDULED_PUBLISHED=22]="SCHEDULED_PUBLISHED",_.ALLOW_NOTIFY="ALLOW_NOTIFY",_))(jl||{}),bi=[1,2,3,4,5,6,10,13,15,19,20,21,22],Ll=(n=>(n.ALL="All",n.UNREAD="Unread",n.READ="Read",n))(Ll||{});function VC(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 o=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(!o.ok)throw new Error(`Failed to fetch notification settings: ${o.status}`);return o.json()},enabled:!!e&&!!t,refetchOnMount:false,initialData:()=>({status:0,system:"web",allows_notify:0,notify_types:r?[]:[...bi]})})}function WC(){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 YC(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 Jl(e,t){return {...e,read:!t||t===e.id?1:e.read}}function vi(e){return typeof e=="object"&&e!==null&&"pages"in e&&"pageParams"in e&&Array.isArray(e.pages)}function oR(e,t,r,n){let o=b();return useMutation({mutationKey:["notifications","mark-read",e],mutationFn:async({id:i})=>{if(!e||!t){process.env.NODE_ENV!=="production"&&console.warn("[SDK][Notifications] \u2013 missing auth for markNotifications");return}return ri(t,i)},onMutate:async({id:i})=>{if(!e||!t)return {previousData:[]};await o.cancelQueries({queryKey:u.notifications._prefix});let s=[],a=o.getQueriesData({queryKey:u.notifications._prefix,predicate:l=>{let f=l.state.data;return vi(f)}});a.forEach(([l,f])=>{if(f&&vi(f)){s.push([l,f]);let m={...f,pages:f.pages.map(g=>g.map(_=>Jl(_,i)))};o.setQueryData(l,m);}});let c=u.notifications.unreadCount(e),p=o.getQueryData(c);return typeof p=="number"&&p>0&&(s.push([c,p]),i?a.some(([,f])=>f?.pages.some(m=>m.some(g=>g.id===i&&g.read===0)))&&o.setQueryData(c,p-1):o.setQueryData(c,0)),{previousData:s}},onSuccess:i=>{let s=typeof i=="object"&&i!==null?i.unread:void 0;typeof s=="number"&&o.setQueryData(u.notifications.unreadCount(e),s),r?.(s);},onError:(i,s,a)=>{a?.previousData&&a.previousData.forEach(([c,p])=>{o.setQueryData(c,p);}),n?.(i);},onSettled:()=>{o.invalidateQueries({queryKey:u.notifications._prefix});}})}function uR(e,t,r){return v(["notifications","set-last-read"],e,({date:n})=>Nr(e,n),async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.notifications.unreadCount(e)]);},t,"posting",{broadcastMode:r??"async"})}function dR(e){return queryOptions({queryKey:["proposals","proposal",e],queryFn:async()=>{let r=(await y("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 y("database_api.list_proposals",{start:[-1],limit:500,order:"by_total_votes",order_direction:"descending",status:"all"})).proposals,r=t.filter(o=>o.status==="expired");return [...t.filter(o=>o.status!=="expired"),...r]}})}function PR(e,t,r){return infiniteQueryOptions({queryKey:["proposals","votes",e,t,r],initialPageParam:t,refetchOnMount:true,staleTime:0,queryFn:async({pageParam:n})=>{let s=(await y("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 y("condenser_api.get_accounts",[s.map(l=>l.voter)]),c=Ut(a);return s.map(l=>({...l,voterAccount:c.find(f=>l.voter===f.name)}))},getNextPageParam:n=>n?.[n.length-1]?.voter??void 0})}function SR(e){return queryOptions({queryKey:["proposals","votes","by-user",e],enabled:!!e&&e!=="",staleTime:60*1e3,queryFn:async()=>!e||e===""?[]:((await y("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 RR(e,t,r){return v(["proposals","vote"],e,({proposalIds:n,approve:o})=>[Hr(e,n,o)],async n=>{try{let o=n?.id??n?.tx_id;t?.adapter?.recordActivity&&o&&t.adapter.recordActivity(150,o,n?.block_num).catch(i=>{console.debug("[SDK][Proposals][useProposalVote] recordActivity failed",{activityType:150,blockNum:n?.block_num,transactionId:o,error:i});}),t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.proposals.list(),u.proposals.votesByUser(e)]);}catch(o){console.warn("[useProposalVote] Post-broadcast side-effect failed:",o);}},t,"active",{broadcastMode:r})}function IR(e,t,r){return v(["proposals","create"],e,n=>[Qr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.proposals.list()]);},t,"active",{broadcastMode:r})}function BR(e,t=50){return infiniteQueryOptions({queryKey:["wallet","vesting-delegations",e,t],initialPageParam:"",queryFn:async({pageParam:r})=>{let n=r?t+1:t,o=await y("condenser_api.get_vesting_delegations",[e,r||"",n]);return r&&o.length>0&&o[0]?.delegatee===r?o.slice(1,t+1):o},getNextPageParam:r=>!r||r.lengthte("balance","/accounts/{account-name}/delegations",{"account-name":e},void 0,void 0,t)})}function $R(e){return queryOptions({queryKey:["wallet","vesting-delegation-expirations",e],queryFn:async()=>e?(await y("database_api.find_vesting_delegation_expirations",{account:e})).delegations:[],enabled:!!e})}function JR(e){return queryOptions({queryKey:["wallet","conversion-requests",e],queryFn:()=>y("condenser_api.get_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function eT(e){return queryOptions({queryKey:["wallet","collateralized-conversion-requests",e],queryFn:()=>y("condenser_api.get_collateralized_conversion_requests",[e]),select:t=>t.sort((r,n)=>r.requestid-n.requestid)})}function oT(e){return queryOptions({queryKey:["wallet","savings-withdraw",e],queryFn:()=>y("condenser_api.get_savings_withdraw_from",[e]),select:t=>t.sort((r,n)=>r.request_id-n.request_id)})}function uT(e){return queryOptions({queryKey:["wallet","withdraw-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"])})}function dT(e){return queryOptions({queryKey:["wallet","open-orders",e],queryFn:()=>y("condenser_api.get_open_orders",[e]),select:t=>t.sort((r,n)=>r.orderid-n.orderid),enabled:!!e})}function hT(e,t=100){return infiniteQueryOptions({queryKey:["wallet","outgoing-rc-delegations",e,t],initialPageParam:null,queryFn:async({pageParam:r})=>{let o=(await y("rc_api.list_rc_direct_delegations",{start:[e,r??""],limit:t}).then(i=>i)).rc_direct_delegations||[];return r&&(o=o.filter(i=>i.to!==r)),o},getNextPageParam:r=>r.length===t?r[r.length-1].to:null})}function vT(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 h()(`${d.privateApiHost}/private-api/received-rc/${e}`);if(!r.ok)throw new Error(`Failed to fetch incoming RC: ${r.status}`);return r.json()}})}function xT(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 CT(e){return queryOptions({queryKey:["wallet","recurrent-transfers",e],queryFn:()=>y("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 o=t.replace(/,/g,"").match(/[-+]?\d+(?:\.\d+)?/);if(o){let i=Number.parseFloat(o[0]);if(Number.isFinite(i))return i}}}function md(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 gd(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 o of ["wallets","tokens","assets","items","portfolio","balances"]){let i=n[o];if(Array.isArray(i))return i}}return []}function yd(e){if(!e||typeof e!="object")return;let t=e;return fe(t.username)??fe(t.name)??fe(t.account)}function Pi(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=`${Q.getValidatedBaseUrl()}/wallet-api/portfolio-v2`,o=await fetch(n,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({username:e,onlyEnabled:r,currency:t})});if(!o.ok)throw new Error(`[SDK][Wallet] \u2013 Portfolio request failed (${o.status})`);let i=await o.json(),s=gd(i).map(a=>md(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:yd(i)??e,currency:fe(i?.fiatCurrency??i?.currency)?.toUpperCase(),wallets:s}}})}function Yt(e){return queryOptions({queryKey:["assets","hive","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Oe()),await b().prefetchQuery(B(e));let t=b().getQueryData(Oe().queryKey),r=b().getQueryData(B(e).queryKey),n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??"");if(!r)return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:0};let i=k(r.balance).amount,s=k(r.savings_balance).amount;return {name:"HIVE",title:"Hive",price:Number.isFinite(o)?o:t?t.base/t.quote:0,accountBalance:i+s,parts:[{name:"current",balance:i},{name:"savings",balance:s}]}}})}function Ai(e){return queryOptions({queryKey:["assets","hbd","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Oe()),await b().prefetchQuery(B(e));let t=b().getQueryData(B(e).queryKey),r=b().getQueryData(Oe().queryKey),n=1;return t?{name:"HBD",title:"Hive Dollar",price:n,accountBalance:k(t.hbd_balance).amount+k(t?.savings_hbd_balance).amount,apr:((r?.hbdInterestRate??0)/100).toFixed(3),parts:[{name:"current",balance:k(t.hbd_balance).amount},{name:"savings",balance:k(t.savings_hbd_balance).amount}]}:{name:"HBD",title:"Hive Dollar",price:n,accountBalance:0}}})}function bd(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 Oi(e){return queryOptions({queryKey:["assets","hive-power","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>{await b().prefetchQuery(Oe()),await b().prefetchQuery(B(e));let t=b().getQueryData(Oe().queryKey),r=b().getQueryData(B(e).queryKey);if(!t||!r)return {name:"HP",title:"Hive Power",price:0,accountBalance:0};let n=await y("condenser_api.get_ticker",[]).catch(()=>{}),o=Number.parseFloat(n?.latest??""),i=Number.isFinite(o)?o:t.base/t.quote,s=k(r.vesting_shares).amount,a=k(r.delegated_vesting_shares).amount,c=k(r.received_vesting_shares).amount,p=k(r.vesting_withdraw_rate).amount,l=Math.max((Number(r.to_withdraw)-Number(r.withdrawn))/1e6,0),f=wo(r.next_vesting_withdrawal)?0:Math.min(p,l),m=+ze(s,t.hivePerMVests).toFixed(3),g=+ze(a,t.hivePerMVests).toFixed(3),_=+ze(c,t.hivePerMVests).toFixed(3),P=+ze(l,t.hivePerMVests).toFixed(3),O=+ze(f,t.hivePerMVests).toFixed(3),T=Math.max(m-P,0),q=Math.max(m-g,0);return {name:"HP",title:"Hive Power",price:i,accountBalance:+T.toFixed(3),apr:bd(t),parts:[{name:"hp_balance",balance:m},{name:"available",balance:+q.toFixed(3)},{name:"outgoing_delegations",balance:g},{name:"incoming_delegations",balance:_},...P>0?[{name:"pending_power_down",balance:+P.toFixed(3)}]:[],...O>0&&O!==P?[{name:"next_power_down",balance:+O.toFixed(3)}]:[]]}}})}var N=ne.operations,gn={transfers:[N.transfer,N.transfer_to_savings,N.transfer_from_savings,N.cancel_transfer_from_savings,N.recurrent_transfer,N.fill_recurrent_transfer,N.escrow_transfer,N.fill_recurrent_transfer],"market-orders":[N.fill_convert_request,N.fill_order,N.fill_collateralized_convert_request,N.limit_order_create2,N.limit_order_create,N.limit_order_cancel],interests:[N.interest],"stake-operations":[N.return_vesting_delegation,N.withdraw_vesting,N.transfer_to_vesting,N.set_withdraw_vesting_route,N.update_proposal_votes,N.fill_vesting_withdraw,N.account_witness_proxy,N.delegate_vesting_shares],rewards:[N.author_reward,N.curation_reward,N.producer_reward,N.claim_reward_balance,N.comment_benefactor_reward,N.liquidity_reward,N.proposal_pay],"":[]};var eq=Object.keys(ne.operations);var xi=ne.operations,nq=xi,oq=Object.entries(xi).reduce((e,[t,r])=>(e[r]=t,e),{});var Si=ne.operations;function Pd(e){return Object.prototype.hasOwnProperty.call(Si,e)}function wt(e){let t=Array.isArray(e)?e:[e],r=t.includes(""),n=Array.from(new Set(t.filter(a=>a!=null&&a!==""))),o=r||n.length===0?"all":n.map(a=>a.toString()).sort().join("|"),i=new Set;r||n.forEach(a=>{if(a in gn){gn[a].forEach(c=>i.add(c));return}Pd(a)&&i.add(Si[a]);});let s=xd(Array.from(i));return {filterKey:o,filterArgs:s}}function yn(e){let t=Array.isArray(e)?e:[e];return new Set(t.filter(r=>r!=null&&r!==""))}function Ad(e){if(!e?.length)return;let t=Number(e[0]?.num??0);return Number.isFinite(t)&&t>0?t-1:void 0}function Od(e,t){return !Number.isFinite(e)||e<0?t:Math.min(t,e+1)}function xd(e){let t=0n,r=0n;return e.forEach(n=>{n<64?t|=1n<(await y("condenser_api.get_account_history",[e,s,Od(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 k(p.hive_payout).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(p.amount).symbol==="HIVE";case "transfer_from_savings":case "fill_transfer_from_savings":return k(p.amount).symbol==="HIVE";case "fill_recurrent_transfer":let f=k(p.amount);return ["HIVE"].includes(f.symbol);case "claim_reward_balance":return k(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 i.has(p.type)}}))})})}function gq(e,t=20,r=[]){let{filterKey:n}=wt(r),o=yn(r);return infiniteQueryOptions({...Xt(e,t,r),queryKey:["assets","hbd","transactions",e,t,n],select:({pages:i,pageParams:s})=>({pageParams:s,pages:i.map(a=>a.filter(c=>{switch(c.type){case "author_reward":case "comment_benefactor_reward":return k(c.hbd_payout).amount>0;case "claim_reward_balance":return k(c.reward_hbd).amount>0;case "transfer":case "transfer_to_savings":case "transfer_to_vesting":case "recurrent_transfer":return k(c.amount).symbol==="HBD";case "transfer_from_savings":case "fill_transfer_from_savings":return k(c.amount).symbol==="HBD";case "fill_recurrent_transfer":let f=k(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 o.has(c.type)}}))})})}function bq(e,t=20,r=[]){let{filterKey:n}=wt(r),o=new Set(Array.isArray(r)?r:[r]),i=o.has("")||o.size===0;return infiniteQueryOptions({...Xt(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 k(p.vesting_payout).amount>0;case "claim_reward_balance":return k(p.reward_vests).amount>0;case "transfer_to_vesting":return true;case "transfer":case "transfer_to_savings":case "recurrent_transfer":return ["VESTS","HP"].includes(k(p.amount).symbol);case "fill_recurrent_transfer":let m=k(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 i||o.has(p.type)}}))})})}function Ei(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 hn(e,t){return new Date(e.getTime()-t*1e3)}function Oq(e=86400){return infiniteQueryOptions({queryKey:["assets","hive","metrics",e],queryFn:async({pageParam:[t,r]})=>(await y("condenser_api.get_market_history",[e,Ei(t),Ei(r)])).map(({hive:o,non_hive:i,open:s})=>({close:i.close/o.close,open:i.open/o.open,low:i.low/o.low,high:i.high/o.high,volume:o.volume,time:new Date(s)})),initialPageParam:[hn(new Date,Math.max(100*e,28800)),new Date],getNextPageParam:(t,r,[n])=>[hn(n,Math.max(100*e,28800)),hn(n,e)]})}function kq(e){return queryOptions({queryKey:["assets","hive","withdrawal-routes",e],queryFn:()=>y("condenser_api.get_withdraw_routes",[e,"outgoing"]),enabled:!!e})}function qq(e,t=50){return queryOptions({queryKey:["assets","hive-power","delegates",e],enabled:!!e,queryFn:()=>y("condenser_api.get_vesting_delegations",[e,"",t])})}function Nq(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)=>k(n.vesting_shares).amount-k(r.vesting_shares).amount)})}function Hq(e=500){return queryOptions({queryKey:["market","order-book",e],queryFn:()=>y("condenser_api.get_order_book",[e])})}function Lq(){return queryOptions({queryKey:["market","statistics"],queryFn:()=>y("condenser_api.get_ticker",[])})}function zq(e,t,r){let n=o=>o.toISOString().replace(/\.\d{3}Z$/,"");return queryOptions({queryKey:["market","history",e,t.getTime(),r.getTime()],queryFn:()=>y("condenser_api.get_market_history",[e,n(t),n(r)])})}function Zq(){return queryOptions({queryKey:["market","hive-hbd-stats"],queryFn:async()=>{let e=await y("condenser_api.get_ticker",[]),t=new Date,r=new Date(t.getTime()-864e5),n=s=>s.toISOString().replace(/\.\d{3}Z$/,""),o=await y("condenser_api.get_market_history",[86400,n(r),n(t)]);return {price:+e.latest,close:o[0]?o[0].non_hive.open/o[0].hive.open:0,high:o[0]?o[0].non_hive.high/o[0].hive.high:0,low:o[0]?o[0].non_hive.low/o[0].hive.low:0,percent:o[0]?100-o[0].non_hive.open/o[0].hive.open*100/+e.latest:0,totalFromAsset:e.hive_volume.split(" ")[0],totalToAsset:e.hbd_volume.split(" ")[0]}}})}function nF(e,t,r,n){return queryOptions({queryKey:["market","data",e,t,r,n],queryFn:async({signal:o})=>{let i=h(),s=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,a=await i(s,{signal:o});if(!a.ok)throw new Error(`Failed to fetch market data: ${a.status}`);return a.json()}})}function ki(e){return e.toISOString().replace(/\.\d{3}Z$/,"")}function aF(e=1e3,t,r){let n=r??new Date,o=t??new Date(n.getTime()-600*60*1e3);return queryOptions({queryKey:["market","trade-history",e,o.getTime(),n.getTime()],queryFn:()=>y("condenser_api.get_trade_history",[ki(o),ki(n),e])})}function lF(){return queryOptions({queryKey:["market","feed-history"],queryFn:async()=>{try{return await y("condenser_api.get_feed_history",[])}catch(e){throw e}}})}function gF(){return queryOptions({queryKey:["market","current-median-history-price"],queryFn:async()=>{try{return await y("condenser_api.get_current_median_history_price",[])}catch(e){throw e}}})}function wF(e,t,r){return v(["market","limit-order-create"],e,n=>[$t(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 AF(e,t,r){return v(["market","limit-order-cancel"],e,({orderId:n})=>[Gr(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 bt(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 o=h(),i=`https://api.coingecko.com/api/v3/coins/${e}/market_chart/range?vs_currency=${t}&from=${r}&to=${n}`,s=await o(i);return bt(s)}async function Ci(e){if(e==="hbd")return 1;let t=h(),r=`https://api.coingecko.com/api/v3/simple/price?ids=hive_dollar&vs_currencies=${e}`,n=await t(r);return (await bt(n)).hive_dollar[e]}async function EF(e,t){let n=await h()(d.privateApiHost+`/private-api/market-data/${e==="hbd"?"usd":e}/${t}`);return bt(n)}async function kF(){let t=await h()(d.privateApiHost+"/private-api/market-data/latest");return bt(t)}async function CF(){let t=await h()("https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd");return bt(t)}var Qd={"Content-type":"application/json"};async function Hd(e){let t=h(),r=Q.getValidatedBaseUrl(),n=await t(`${r}/private-api/engine-api`,{method:"POST",body:JSON.stringify(e),headers:Qd});if(!n.ok)throw new Error(`[SDK][HiveEngine] \u2013 request failed with ${n.status}`);return (await n.json()).result}async function Te(e,t){try{return await Hd(e)}catch{return t}}async function qF(e,t=50){let r={jsonrpc:"2.0",method:"find",params:{contract:"market",query:{symbol:e},limit:t,offset:0},id:1},[n,o]=await Promise.all([Te({...r,params:{...r.params,table:"buyBook",indexes:[{index:"price",descending:true}]}},[]),Te({...r,params:{...r.params,table:"sellBook",indexes:[{index:"price",descending:false}]}},[])]),i=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:i(n),sell:s(o)}}async function FF(e,t=50){return Te({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 IF(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},[o,i]=await Promise.all([Te({...n,params:{...n.params,table:"buyBook",indexes:[{index:"timestamp",descending:true}]}},[]),Te({...n,params:{...n.params,table:"sellBook",indexes:[{index:"timestamp",descending:true}]}},[])]),s=(p,l)=>(Number(p||0)*Number(l||0)).toFixed(8),a=o.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=i.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 Ud(e,t){if(Array.isArray(e)&&e.length===0)return [];let r=Array.isArray(e)?{symbol:{$in:e}}:e?{symbol:e}:{};return Te({jsonrpc:"2.0",method:"find",params:{contract:"market",table:"metrics",query:{...r,...t?{account:t}:{}}},id:1},[])}async function rt(e,t){return Ud(t,e)}async function Zt(e){return Te({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"balances",query:{account:e}},id:1},[])}async function er(e){return Te({jsonrpc:"2.0",method:"find",params:{contract:"tokens",table:"tokens",query:{symbol:{$in:e}}},id:2},[])}async function Ri(e,t,r,n){let o=h(),i=Q.getValidatedBaseUrl(),s=new URL("/private-api/engine-account-history",i);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 o(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 Ti(e,t="daily"){let r=h(),n=Q.getValidatedBaseUrl(),o=new URL("/private-api/engine-chart-api",n);o.searchParams.set("symbol",e),o.searchParams.set("interval",t);let i=await r(o.toString(),{headers:{"Content-type":"application/json"}});if(!i.ok)throw new Error(`[SDK][HiveEngine] \u2013 chart failed with ${i.status}`);return await i.json()}async function qi(e){let t=h(),r=Q.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 tr(e){return queryOptions({queryKey:["assets","hive-engine","balances",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Zt(e)})}function HF(){return queryOptions({queryKey:["assets","hive-engine","markets"],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>rt()})}function Fi(e){return queryOptions({queryKey:["assets","hive-engine","metadata-list",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>er(e)})}function GF(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 Ri(e,t,r,n)},getNextPageParam:(n,o,i)=>(n?.length??0)===r?i+r:void 0,getPreviousPageParam:(n,o,i)=>i>0?i-r:void 0})}function XF(e,t="daily"){return queryOptions({queryKey:["assets","hive-engine",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>Ti(e,t)})}function rI(e){return queryOptions({queryKey:["assets","hive-engine","unclaimed",e],staleTime:6e4,refetchInterval:9e4,enabled:!!e,queryFn:async()=>{try{let t=await qi(e);return Object.values(t).filter(({pending_token:r})=>r>0)}catch{return []}}})}function Ii(e,t){return queryOptions({queryKey:["assets","hive-engine","all-tokens",e,t],queryFn:async()=>rt(e,t)})}function nt(e,t=void 0){let r={fractionDigits:3,prefix:"",suffix:""};t&&(r={...r,...t});let{fractionDigits:n,prefix:o,suffix:i}=r,s="";o&&(s+=o+" ");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}),i&&(s+=" "+i),s}var rr=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()?`(${nt(this.stake,{fractionDigits:this.precision})} + ${nt(this.delegationsIn,{fractionDigits:this.precision})} - ${nt(this.delegationsOut,{fractionDigits:this.precision})})`:"";staked=()=>this.stakingEnabled?this.stakedBalance<1e-4?this.stakedBalance.toString():nt(this.stakedBalance,{fractionDigits:this.precision}):"-";balanced=()=>this.balance<1e-4?this.balance.toString():nt(this.balance,{fractionDigits:this.precision})};function fI(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 Zt(e),o=await er(n.map(p=>p.symbol)),i=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 rt(void 0,a):[]];return n.map(p=>{let l=o.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),g=Number(m?.lastPrice??"0"),_=Number(p.balance),P=p.symbol==="SWAP.HIVE"?i*_:g===0?0:Number((g*i*_).toFixed(10));return new rr({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:P})})},enabled:!!e})}function Di(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=Yt(e);await r.prefetchQuery(n);let o=r.getQueryData(n.queryKey),i=await r.ensureQueryData(Fi([t])),s=await r.ensureQueryData(tr(e)),a=await r.ensureQueryData(Ii(void 0,t)),c=i?.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"),g=parseFloat(p?.stake??"0"),_=parseFloat(p?.pendingUnstake??"0"),P=[{name:"liquid",balance:m},{name:"staked",balance:g}];return _>0&&P.push({name:"unstaking",balance:_}),{name:t,title:c?.name??"",price:f===0?0:Number(f*(o?.price??0)),accountBalance:m+g,layer:"ENGINE",parts:P}}})}function vt(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 o=await n.json(),i=await fetch(d.privateApiHost+"/private-api/point-list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:r,type:t})});if(!i.ok)throw new Error(`Failed to fetch point transactions: ${i.status}`);let s=await i.json();return {points:o.points,uPoints:o.unclaimed_points,transactions:s}},staleTime:3e4,refetchOnMount:true,enabled:!!e})}function Ki(e){return queryOptions({queryKey:["assets","points","general-info",e],staleTime:6e4,refetchInterval:9e4,queryFn:async()=>(await b().prefetchQuery(vt(e)),{name:"POINTS",title:"Ecency Points",price:.002,accountBalance:+(b().getQueryData(vt(e).queryKey)?.points??0)})})}function TI(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:o,type:i,amount:s,id:a,sender:c,receiver:p,memo:l})=>({created:new Date(o),type:i,results:[{amount:parseFloat(s),asset:"POINTS"}],id:a,from:c??void 0,to:p??void 0,memo:l??void 0}))})}function VI(e,t,r={refetch:false}){let n=b(),o=r.currency??"usd",i=async p=>(r.refetch?await n.fetchQuery(p):await n.prefetchQuery(p),n.getQueryData(p.queryKey)),s=async p=>{if(!p||o==="usd")return p;try{let l=await Ci(o);return {...p,price:p.price*l}}catch(l){return console.warn(`Failed to convert price from USD to ${o}:`,l),p}},a=Pi(e,o,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 g=m.dataKey,_=m.value;if(typeof _=="string"){let O=_.replace(/,/g,"").match(/[+-]?\s*(\d+(?:\.\d+)?)/);if(O){let T=Math.abs(Number.parseFloat(O[1]));g==="delegated_hive_power"?f.push({name:"outgoing_delegations",balance:T}):g==="received_hive_power"?f.push({name:"incoming_delegations",balance:T}):g==="powering_down_hive_power"&&f.push({name:"pending_power_down",balance:T});}}}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,o],queryFn:async()=>{let p=await c();if(p&&p.price>0)return p;let l;if(t==="HIVE")l=await i(Yt(e));else if(t==="HP")l=await i(Oi(e));else if(t==="HBD")l=await i(Ai(e));else if(t==="POINTS")l=await i(Ki(e));else if((await n.ensureQueryData(tr(e))).some(m=>m.symbol===t))l=await i(Di(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 rf=(T=>(T.Transfer="transfer",T.TransferToSavings="transfer-saving",T.WithdrawFromSavings="withdraw-saving",T.Delegate="delegate",T.PowerUp="power-up",T.PowerDown="power-down",T.WithdrawRoutes="withdraw-routes",T.ClaimInterest="claim-interest",T.Swap="swap",T.Convert="convert",T.Gift="gift",T.Promote="promote",T.Claim="claim",T.Buy="buy",T.Stake="stake",T.Unstake="unstake",T.Undelegate="undelegate",T))(rf||{});function zI(e,t,r){return v(["wallet","transfer"],e,n=>[Ue(e,n.to,n.amount,n.memo)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function eD(e,t,r){return v(["wallet","transfer-point"],e,n=>[Ze(e,n.to,n.amount,n.memo)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function iD(e,t,r){return v(["wallet","delegate-vesting-shares"],e,n=>[yt(e,n.delegatee,n.vestingShares)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.delegatee),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function pD(e,t,r){return v(["wallet","set-withdraw-vesting-route"],e,n=>[ht(e,n.toAccount,n.percent,n.autoVest)],async(n,o)=>{await S(t?.adapter,r,[u.wallet.withdrawRoutes(e),u.accounts.full(e),u.accounts.full(o.toAccount)]);},t,"active",{broadcastMode:r})}function mD(e,t,r){return v(["wallet","transfer-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function wD(e,t,r){return v(["wallet","transfer-to-savings"],e,n=>[Xe(e,n.to,n.amount,n.memo)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function OD(e,t,r){return v(["wallet","transfer-from-savings"],e,n=>[Ve(e,n.to,n.amount,n.memo,n.requestId)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function CD(e,t,r){return v(["wallet","transfer-to-vesting"],e,n=>[mt(e,n.to,n.amount)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function ID(e,t,r){return v(["wallet","withdraw-vesting"],e,n=>[gt(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 MD(e,t,r){return v(["wallet","convert"],e,n=>[n.collateralized?Fr(e,n.amount,n.requestId):_t(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 jD(e,t,r){return v(["wallet","claim-interest"],e,n=>ft(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 nf=5e3,nr=new Map;function zD(e,t,r){return v(["wallet","claim-rewards"],e,n=>[zr(e,n.rewardHive,n.rewardHbd,n.rewardVests)],()=>{let n=e??"__anonymous__",o=[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)],i=nr.get(n);i&&(clearTimeout(i),nr.delete(n));let s=setTimeout(async()=>{try{let a=b(),p=(await Promise.allSettled(o.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{nr.delete(n);}},nf);nr.set(n,s);},t,"posting",{broadcastMode:r})}function ZD(e,t,r){return v(["wallet","delegate-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function nK(e,t,r){return v(["wallet","undelegate-engine-token"],e,n=>{let o=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:o}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function aK(e,t,r){return v(["wallet","stake-engine-token"],e,n=>{let o=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:o}]]},async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function lK(e,t,r){return v(["wallet","unstake-engine-token"],e,n=>{let o=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:o}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"active",{broadcastMode:r})}function gK(e,t,r){return v(["wallet","claim-engine-rewards"],e,n=>{let o=JSON.stringify(n.tokens.map(i=>({symbol:i})));return [["custom_json",{id:"scot_claim_token",required_auths:[],required_posting_auths:[e],json:o}]]},async()=>{await S(t?.adapter,r,[u.accounts.full(e),["ecency-wallets","asset-info",e],["wallet","portfolio","v2",e]]);},t,"posting",{broadcastMode:r})}function wK(e,t,r){return v(["wallet","engine-market-order"],e,n=>{let o,i;n.action==="cancel"?(i="cancel",o={type:n.orderType,id:n.orderId}):(i=n.action,o={symbol:n.symbol,quantity:n.quantity,price:n.price});let s=JSON.stringify({contractName:"market",contractAction:i,contractPayload:o});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 of(e,t,r){let{from:n,to:o="",amount:i="",memo:s=""}=r,a=r.request_id??Date.now()>>>0;switch(e){case "HIVE":switch(t){case "transfer":return [Ue(n,o,i,s)];case "transfer-saving":return [Xe(n,o,i,s)];case "withdraw-saving":return [Ve(n,o,i,s,a)];case "power-up":return [mt(n,o,i)]}break;case "HBD":switch(t){case "transfer":return [Ue(n,o,i,s)];case "transfer-saving":return [Xe(n,o,i,s)];case "withdraw-saving":return [Ve(n,o,i,s,a)];case "claim-interest":return ft(n,o,i,s,a);case "convert":return [_t(n,i,Math.floor(Date.now()/1e3))]}break;case "HP":switch(t){case "power-down":return [gt(n,i)];case "delegate":return [yt(n,o,i)];case "withdraw-routes":return [ht(r.from_account??n,r.to_account??o,r.percent??0,r.auto_vest??false)]}break;case "POINTS":if(t==="transfer"||t==="gift")return [Ze(n,o,i,s)];break}return null}function sf(e,t,r){let{from:n,to:o="",amount:i=""}=r,s=typeof i=="string"&&i.includes(" ")?i.split(" ")[0]:String(i);switch(t){case "transfer":return [je(n,"transfer",{symbol:e,to:o,quantity:s,memo:r.memo??""})];case "stake":return [je(n,"stake",{symbol:e,to:o,quantity:s})];case "unstake":return [je(n,"unstake",{symbol:e,to:o,quantity:s})];case "delegate":return [je(n,"delegate",{symbol:e,to:o,quantity:s})];case "undelegate":return [je(n,"undelegate",{symbol:e,from:o,quantity:s})];case "claim":return [Ir(n,[e])]}return null}function af(e){return e==="claim"?"posting":"active"}function xK(e,t,r,n,o){let{mutateAsync:i}=et.useRecordActivity(e,r);return v(["ecency-wallets",t,r],e,s=>{let a=of(t,r,s);if(a)return a;let c=sf(t,r,s);if(c)return c;throw new Error(`[SDK][Wallet] \u2013 no operation builder for asset="${t}" operation="${r}"`)},()=>{i();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,af(r),{broadcastMode:o})}function CK(e,t,r){return v(["wallet","delegate-rc"],e,({to:n,maxRc:o})=>[Dr(e,n,o)],async(n,o)=>{await S(t?.adapter,r,[u.accounts.full(e),u.accounts.full(o.to),u.resourceCredits.account(e),u.resourceCredits.account(o.to)]);},t,"active",{broadcastMode:r})}function FK(e,t,r){return v(["witnesses","vote"],e,({witness:n,approve:o})=>[Br(e,n,o)],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 NK(e,t,r){return v(["witnesses","proxy"],e,({proxy:n})=>[Mr(e,n)],async()=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.witnesses.proxy()]);},t,"active",{broadcastMode:r})}function cf(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 VK(e){return infiniteQueryOptions({queryKey:u.witnesses.list(e),initialPageParam:1,queryFn:async({pageParam:t})=>(await te("hafbe","/witnesses",{"page-size":e,page:t})).witnesses.map(cf),getNextPageParam:(t,r,n)=>t.length===e?n+1:void 0})}function jK(e,t,r,n="vests",o="desc"){return queryOptions({queryKey:u.witnesses.voters(e,t,r,n,o),queryFn:async({signal:i})=>await te("hafbe","/witnesses/{witness-name}/voters",{"witness-name":e,"page-size":r,page:t,sort:n,direction:o},void 0,void 0,i),enabled:!!e,staleTime:6e4})}function LK(e){return queryOptions({queryKey:u.witnesses.voterCount(e),queryFn:async()=>await te("hafbe","/witnesses/{witness-name}/voters/count",{"witness-name":e}),enabled:!!e,staleTime:6e4})}var pf=(_=>(_[_.CHECKIN=10]="CHECKIN",_[_.LOGIN=20]="LOGIN",_[_.CHECKIN_EXTRA=30]="CHECKIN_EXTRA",_[_.POST=100]="POST",_[_.COMMENT=110]="COMMENT",_[_.VOTE=120]="VOTE",_[_.REBLOG=130]="REBLOG",_[_.DELEGATION=150]="DELEGATION",_[_.REFERRAL=160]="REFERRAL",_[_.COMMUNITY=170]="COMMUNITY",_[_.TRANSFER_SENT=998]="TRANSFER_SENT",_[_.TRANSFER_INCOMING=999]="TRANSFER_INCOMING",_[_.MINTED=991]="MINTED",_[_.BURNED=997]="BURNED",_))(pf||{});async function df(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 h()(d.privateApiHost+"/private-api/points-claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:t})}),o=(n.headers.get("content-type")??"").split(";")[0].trim().toLowerCase(),i=await n.text();if(!n.ok){if(n.status===406)try{return JSON.parse(i)}catch{return {message:i,code:n.status}}let s=i&&o.includes("json")?`: ${i.slice(0,200)}`:"";throw new Error(`[SDK][Points][Claim] \u2013 failed with status ${n.status}${s}`)}if(!o.includes("json"))throw new Error(`[SDK][Points][Claim] \u2013 expected JSON but received "${o||"empty"}" response (status ${n.status})`);try{return JSON.parse(i)}catch{throw new Error(`[SDK][Points][Claim] \u2013 malformed JSON response (status ${n.status})`)}}function XK(e,t,r,n){let{mutateAsync:o}=et.useRecordActivity(e,"points-claimed");return useMutation({mutationFn:()=>df(e,t),onError:n,onSuccess:()=>{o(),b().setQueryData(vt(e).queryKey,i=>i&&{...i,points:(parseFloat(i.points)+parseFloat(i.uPoints)).toFixed(3),uPoints:"0"}),r?.();}})}var Bi=/(^|\s)author:([^\s]+)/g,Mi=/(^|\s)type:([^\s]+)/g,Qi=/(^|\s)category:([^\s]+)/g,Hi=/(^|\s)tag:([^\s]+)/g;var Vi=(n=>(n.ALL="",n.POST="post",n.COMMENT="comment",n))(Vi||{}),eN=5,tN=100;function ji(e){return e.trim().split(/\s+/)[0]??""}function ff(e){return ji(e).replace(/^@+/,"").toLowerCase()}function mf(e){return ji(e).replace(/^#+/,"").toLowerCase()}function gf(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 rN({search:e="",author:t="",type:r="",category:n="",tags:o=[]}){let i=e.trim().replace(/\s+/g," "),s=ff(t),a=mf(n),c=gf(Array.isArray(o)?o.join(","):o),p=[i];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:i,author:s,type:r,category:a,tags:c}}var Ui=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(Bi);};grabType=()=>{let t=this.grab(Mi);Object.values(Vi).includes(t)&&(this.type=t);};grabCategory=()=>{this.category=this.grab(Qi);};grabTags=()=>{let t=new Set;this.tags=[...this.query.matchAll(Hi)].flatMap(r=>r[2].split(",")).map(r=>r.trim()).filter(r=>r===""||t.has(r)?false:(t.add(r),true));};grabSearch=()=>{for([Bi,Mi,Qi,Hi].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 xe(e,t){let n=await(async()=>{let o;try{o=await e.text();}catch{return}if(o!=="")try{return JSON.parse(o)}catch{return e.ok?void 0:o}})();if(!e.ok){let o=new Error(`Request failed with status ${e.status}`);throw o.status=e.status,o.data=n,o}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 qe(e){return typeof e=="object"&&e!==null&&Array.isArray(e.results)}var hf=isServer?0:3;function Pt(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),o&&(a.scroll_id=o),i&&(a.votes=i);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:Pe(Ae,s)});return xe(c,qe)},retry:Pt})}function fN(e,t,r=true){return infiniteQueryOptions({queryKey:u.search.controversialRising(e,t),initialPageParam:{sid:void 0,hasNextPage:true},queryFn:async({pageParam:n,signal:o})=>{if(!n.hasNextPage)return {hits:0,took:0,results:[]};let i,s=new Date;switch(t){case "today":i=new Date(s.getTime()-1440*60*1e3);break;case "week":i=new Date(s.getTime()-10080*60*1e3);break;case "month":i=new Date(s.getTime()-720*60*60*1e3);break;case "year":i=new Date(s.getTime()-365*24*60*60*1e3);break;default:i=void 0;}let a="* type:post",c=e==="rising"?"children":e,p=i?i.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 g=await fetch(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(m),signal:Pe(Ae,o)});return xe(g,qe)},getNextPageParam:n=>({sid:n?.scroll_id,hasNextPage:n.results.length>0}),enabled:r,retry:Pt})}async function hN(e,t,r,n,o,i,s){let a={q:e,sort:t,hide_low:r};n&&(a.since=n),o&&(a.scroll_id=o),i&&(a.votes=i);let p=await h()(d.privateApiHost+"/search-api/search",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(a),signal:Pe(Ae,s)});return xe(p,qe)}async function Li(e,t,r=Ae){let o=await h()(d.privateApiHost+"/search-api/similar",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify(e),signal:Pe(r,t)});return xe(o,qe)}async function _N(e,t){let n=await h()(d.privateApiHost+"/search-api/search-path",{method:"POST",headers:{"Content-Type":"application/json","X-Ecency-Client":d.clientId},body:JSON.stringify({q:e}),signal:Pe(Ae,t)}),o=await xe(n,Array.isArray);return o?.length>0?o:[e]}var vf=4368*60*60*1e3,Pf=4,Af=3e3,Of=2e3,xf=4e3,AN=2;function Sf(e,t){return e.replace(/!\[[^\]]*\]\([^)]*\)/g," ").replace(/\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]+>/g," ").replace(/https?:\/\/\S+/g," ").replace(/\s+/g," ").trim().slice(0,t)}function Ef(e){let t=5381;for(let r=0;r>>0).toString(36)}function ON(e){let t=e.title??"",r=e.json_metadata?.tags,n=(Array.isArray(r)?r:[]).filter(s=>typeof s=="string"&&s!==""),o=Sf(e.body??"",Af),i=Ef(`${t}|${n.join(",")}|${o}`);return queryOptions({queryKey:u.search.similarEntries(e.author,e.permlink,i),queryFn:async({signal:s})=>{let a=new Date(Date.now()-vf).toISOString().slice(0,19),c=await Li({author:e.author,permlink:e.permlink,title:t,body:o,tags:n,since:a},s,typeof window>"u"?Of:xf),p=[],l=new Set;for(let f of c.results){if(p.length>=Pf)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 RN(e,t=5){let r=e.trim();return queryOptions({queryKey:u.search.account(r,t),queryFn:async()=>{let n=await y("condenser_api.lookup_accounts",[r,t]);return n.length===0?[]:Vt(n)},enabled:!!r})}function DN(e,t=10){let r=e.trim();return queryOptions({queryKey:u.search.topics(r,t),queryFn:async()=>(await y("condenser_api.get_trending_tags",[r,t+1])).map(o=>o.name).filter(o=>o!==""&&!o.startsWith("hive-")).slice(0,t),enabled:!!r})}function HN(e,t,r,n,o,i){return infiniteQueryOptions({queryKey:u.search.api(e,t,r,n,o,i),queryFn:async({pageParam:s,signal:a})=>{let c={q:e,sort:t,hide_low:r};n&&(c.since=n),s&&(c.scroll_id=s),o!==void 0&&(c.votes=o),i&&(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:Pe(Ae,a)});return xe(p,qe)},initialPageParam:void 0,getNextPageParam:s=>s?.scroll_id,enabled:!!e,retry:Pt})}function LN(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 Ff(e){let r=await h()(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 o=n?.message??`Failed to fetch support settings: ${r.status}`,i=new Error(o);throw i.status=r.status,i.data=n,i}return await r.json()}function zN(e,t){let r=e?.replace("@","");return queryOptions({queryKey:u.support.settings(r),queryFn:()=>{if(!t)throw new Error("[SDK][Support] missing auth");return Ff(t)},enabled:!!r&&!!t})}async function Kf(e,t){let n=await h()(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 o;try{o=await n.json();}catch{}let i=o?.message??`Failed to update support settings: ${n.status}`,s=new Error(i);throw s.status=n.status,s.data=o,s}return await n.json()}function Nf(e,t,r){return e.setQueryData(u.support.settings(t),r),e.invalidateQueries({queryKey:u.support.settings(t)})}function eB(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["support","settings-update",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Support] missing auth");return Kf(t,o)},onSuccess(o){n&&Nf(r,n,o);}})}function oB(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 uB(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 dB(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 yB(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 bB(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 OB(e,t,r){return v(["promotions","boost-plus"],e,({account:n,duration:o})=>[en(e,n,o)],async(n,{account:o})=>{t?.adapter?.invalidateQueries&&await t.adapter.invalidateQueries([u.accounts.full(e),u.promotions.boostPlusAccounts(o)]);},t,"active",{broadcastMode:r})}function kB(e,t,r){return v(["promotions","rc-delegation"],e,({duration:n})=>[tn(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 TB(e){let r=await h()(d.privateApiHost+"/auth-api/hs-token-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e})});if(!r.ok){let o;try{o=await r.json();}catch{o=void 0;}let i=new Error(`Failed to refresh token: ${r.status}`);throw i.status=r.status,i.data=o,i}return await r.json()}var jf="https://raw.githubusercontent.com/openhive-network/watchmen/main/output/flat/badactors.txt";function DB(){return queryOptions({queryKey:u.badActors.list(),queryFn:async({signal:e})=>{let t=await fetch(jf,{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 NB=1.1,Lf=(r=>(r.NUMBER_OF_VOTES="number_of_votes",r.TOKENS="tokens",r))(Lf||{});function BB(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 Gf(e){let t=e.poll_choices??[],r=e.poll_voters??[],n=e.poll_stats,o=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}}),i=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:o,poll_voters:i,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 VB(e,t){return queryOptions({queryKey:u.polls.details(e??"",t??""),enabled:!!e&&!!t,gcTime:isServer?yo:1800*1e3,queryFn:async()=>{if(!e||!t)throw new Error("[SDK][Polls] \u2013 missing author or permlink");let r=h(),n=`${d.pollsApiHost}/rpc/poll?author=eq.${encodeURIComponent(e)}&permlink=eq.${encodeURIComponent(t)}`,o=await r(n);if(!o.ok)throw new Error(`[SDK][Polls] \u2013 fetch failed: ${o.status}`);let i=await o.json();if(!Array.isArray(i)||!i[0])throw new Error("[SDK][Polls] \u2013 no poll data found");return Gf(i[0])}})}function $B(e,t,r){return v(u.polls.vote(),e??"",({pollTrxId:n,choices:o})=>{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:o})}]]},void 0,t,"posting",{broadcastMode:r??"async"})}var zf=-1e10,Jf=5,Yf=30;var $i=e=>Math.abs(e)>0&&Math.abs(e)<=100;function Wi(e){if(typeof e=="number"&&$i(e)||typeof e=="string"&&(e=Number(e),$i(e)))return Math.floor(e);if(e===0)return 25;let t=false;e<0&&(t=true);let r=Math.log10(Math.abs(e));return r=Math.max(r-9,0),r<0&&(r=0),t&&(r*=-1),r=r*9+25,Math.floor(r)}var Xf=["ecency.com","ecency.app","hive.blog","hive.io","hiveblocks.com","peakd.com","snapie.io","hivesuite.app","leofinance.io","inleo.io","3speak.tv","d.buzz","waivio.com"],Zf=["imgur.com","images.hive.blog","files.peakd.com","i.ecency.com","images.ecency.com","steemitimages.com","cdn.steemitimages.com","media.giphy.com"],em=/\.(jpe?g|png|gif|webp|svg|bmp|avif)(\?|#|$)/i,tm=/(?:https?:)?\/\/[^\s)<>"'\]]+/gi,rm=/[.,;:!?'"]+$/;function nm(e){let t=/^(?:https?:)?\/\/([^/?#]+)/i.exec(e);return t?t[1].toLowerCase().replace(/^www\./,""):""}function om(e){let t=e.replace(rm,"");if(em.test(t))return false;let r=nm(t);if(!r.includes("."))return false;let n=o=>r===o||r.endsWith("."+o);return !(Xf.some(n)||Zf.some(n))}function Gi(e){if(!e)return false;let t=e.match(tm);return t?t.some(om):false}var im=(n=>(n.MOD_MUTED="mod_muted",n.DOWNVOTED="downvoted",n.LOW_TRUST="low_trust",n))(im||{});function sm(e){return e?.stats?.total_votes??e?.active_votes?.length??0}function am(e,t){return (e??0)<-1e10&&t>=5}function um(e){let t=e?.author_reputation;return t==null?false:Wi(t)<30&&Gi(e?.body)}function ZB(e,t){return !!e&&!!t?.includes(e)}function eM(e){return e?e.stats?.gray||e.stats?.hide?"mod_muted":am(e.net_rshares,sm(e))?"downvoted":um(e)?"low_trust":null:null}var At=class extends Error{constructor(r,n,o){super(r);this.status=n;this.data=o;}status;data},or=class extends At{constructor(r,n,o,i,s){super(r,n,s);this.code=o;this.taken=i;}code;taken};function Fe(e){return `${d.privateApiHost}/api/newsletter${e}`}async function $e(e){let t=await e.json().catch(()=>{});if(!e.ok)throw new At(t?.error||`Request failed (${e.status})`,e.status,t);if(!t||typeof t!="object")throw new At(`Unexpected response (${e.status})`,e.status);return t}async function zi(e,t){let n=await h()(Fe("/subscribe"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,...t?{code:t}:{}})});return $e(n)}async function Ji(e){let r=await h()(Fe("/subscriptions"),{headers:{"X-HS-Token":e}});return (await $e(r)).subscriptions??[]}async function Yi(e,t){let n=await h()(Fe(`/subscriptions/${encodeURIComponent(e)}`),{method:"DELETE",headers:{"X-HS-Token":t}});await $e(n);}async function Xi(e,t){let n=await h()(Fe("/unsubscribe-all"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:e,code:t})});await $e(n);}async function Zi(e,t,r){let o=await h()(Fe(`/sender?type=${e}&target=${encodeURIComponent(t)}`),{headers:{"X-HS-Token":r}});return $e(o)}async function es(e,t,r){let o=await h()(Fe(`/issues?type=${e}&target=${encodeURIComponent(t)}`),{headers:{"X-HS-Token":r}});return (await $e(o)).issues??[]}async function ts(e,t,r,n=20){let i=await h()(Fe(`/posts?type=${e}&target=${encodeURIComponent(t)}&limit=${n}`),{headers:{"X-HS-Token":r}});return (await $e(i)).posts??[]}async function rs(e,t,r){let o=await h()(Fe(e),{method:"POST",headers:{"Content-Type":"application/json","X-HS-Token":r},body:JSON.stringify(t)}),i=await o.json().catch(()=>{});if(!o.ok)throw new or(i?.error||`Request failed (${o.status})`,o.status,i?.code,i?.taken,i);if(!i||typeof i!="object")throw new or(`Unexpected response (${o.status})`,o.status);return i}function ns(e,t){return rs("/send/preview",e,t)}function os(e,t){return rs("/send",e,t)}function aM(e,t){let r=e?.replace("@","");return queryOptions({queryKey:u.newsletter.subscriptions(r),enabled:!!r&&!!t,queryFn:async()=>{if(!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return Ji(t)},staleTime:6e4,retry:false})}function dM(e,t,r,n){let o=r?.replace("@","");return queryOptions({queryKey:u.newsletter.sender(e,t,o),enabled:!!o&&!!n&&!!t,queryFn:async()=>{if(!n)throw new Error("[SDK][Newsletter] \u2013 missing auth");return Zi(e,t,n)},staleTime:5*6e4})}function hM(e,t,r,n){let o=r?.replace("@","");return queryOptions({queryKey:u.newsletter.issues(e,t,o),enabled:!!o&&!!n&&!!t,queryFn:async()=>{if(!n)throw new Error("[SDK][Newsletter] \u2013 missing auth");return es(e,t,n)},staleTime:6e4})}function PM(e,t,r,n,o=20){let i=r?.replace("@","");return queryOptions({queryKey:u.newsletter.posts(e,t,i,o),enabled:!!i&&!!n&&!!t,queryFn:async()=>{if(!n)throw new Error("[SDK][Newsletter] \u2013 missing auth");return ts(e,t,n,o)},staleTime:6e4})}function EM(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["newsletter","subscribe",n],mutationFn:o=>zi(o,t),onSuccess(){n&&r.invalidateQueries({queryKey:u.newsletter.subscriptions(n)});}})}function qM(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["newsletter","leave",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return Yi(o,t)},onSuccess(o,i){r.setQueryData(u.newsletter.subscriptions(n),s=>(s??[]).filter(a=>a.id!==i));}})}function NM(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["newsletter","unsubscribe-all",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return Xi(o,t)},onSuccess(o,i){r.setQueryData(u.newsletter.subscriptions(n),s=>(s??[]).filter(a=>a.email.toLowerCase()!==i.toLowerCase()));}})}function UM(e,t){let r=e?.replace("@","");return useMutation({mutationKey:["newsletter","send-preview",r],mutationFn:async n=>{if(!r||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return ns(n,t)}})}function VM(e,t){let r=useQueryClient(),n=e?.replace("@","");return useMutation({mutationKey:["newsletter","send",n],mutationFn:async o=>{if(!n||!t)throw new Error("[SDK][Newsletter] \u2013 missing auth");return os(o,t)},onSuccess(o,i){r.invalidateQueries({queryKey:u.newsletter.issues(i.type,i.target,n)}),r.invalidateQueries({queryKey:u.newsletter.sender(i.type,i.target,n)});}})}/** * @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{Ao as ACCOUNT_OPERATION_GROUPS,Ga as ALL_ACCOUNT_OPERATIONS,yi as ALL_NOTIFY_TYPES,Hd as AssetOperation,xg as BROADCAST_INCLUSION_DELAY_MS,Lo as BuySellTransactionType,f as CONFIG,Q as ConfigManager,jf as ContentModerationReason,Xe as EcencyAnalytics,ca as EcencyQueriesManager,je as EntriesCacheManagement,co as ErrorType,Df as HIDDEN_POST_MIN_VOTES,qf as HIDDEN_POST_RSHARES_THRESHOLD,ln as HIVE_ACCOUNT_OPERATION_GROUPS,kT as HIVE_OPERATION_LIST,FT as HIVE_OPERATION_NAME_BY_ID,TT as HIVE_OPERATION_ORDERS,Zt as HiveEngineToken,pi as HiveSignerIntegration,De as HiveTxTransaction,Ae as INTERNAL_API_TIMEOUT_MS,Kf as LOW_TRUST_REPUTATION_THRESHOLD,CK as MAX_SEARCH_QUERY_LENGTH,kK as MAX_SEARCH_TAGS,oo as Memo,Bt as NaiMap,kl as NotificationFilter,Rl as NotificationViewType,Cl as NotifyTypes,ep as OPERATION_AUTHORITY_MAP,$o as OrderIdPrefix,lM as POLLS_PROTOCOL_VERSION,Gd as PointTransactionType,Rf as PollPreferredInterpretation,U as PrivateKey,Y as PublicKey,ll as QUEST_CATALOG,dl as QUEST_MIN_CONTENT_LENGTH,u as QueryKeys,Wt as RC_RESOURCE_NAMES,xl as ROLES,lo as SERVER_GC_TIME_MS,tl as SIGNATURE_BYTES,YK as SIMILAR_ENTRIES_MIN_RENDER,HS as STREAK_FREEZE_MAX_OWNED,QS as STREAK_FREEZE_PRICE,mi as SUBSCRIBERS_PAGE_SIZE,Mi as SearchQuery,Ni as SearchType,Ee as Signature,qo as SortOrder,fo as Symbol,$t as THREESPEAK_BENEFICIARY_ACCOUNT,bE as THREESPEAK_BENEFICIARY_WEIGHT,el as TRANSACTION_HEADER_BYTES,ME as ThreeSpeakIntegration,Ea as accountNameByteLength,ri as addDraft,Zo as addImage,Cx as addOptimisticDiscussionEntry,ii as addSchedule,Pf as applySupportSettingsUpdate,xp as applyVoteCacheUpdate,ae as bridgeApiCall,po as broadcastJson,ee as broadcastOperations,so as broadcastOperationsAsync,$r as buildAccountCreateOp,Pu as buildAccountUpdate2Op,vu as buildAccountUpdateOp,ku as buildActiveCustomJsonOp,Jr as buildBoostPlusOp,jo as buildCancelTransferFromSavingsOp,Ou as buildChangeRecoveryAccountOp,Gr as buildClaimAccountOp,lt as buildClaimInterestOps,Lr as buildClaimRewardBalanceOp,Cr as buildCollateralizedConvertOp,Ne as buildCommentOp,Qe as buildCommentOptionsOp,Zr as buildCommunityRegistrationOp,yt as buildConvertOp,Wr as buildCreateClaimedAccountOp,Tr as buildDelegateRcOp,mt as buildDelegateVestingSharesOp,Sr as buildDeleteCommentOp,Rr as buildEngineClaimOp,Ve as buildEngineOp,bu as buildFlagPostOp,Fr as buildFollowOp,zr as buildGrantPostingPermissionOp,mu as buildIgnoreOp,jr as buildLimitOrderCancelOp,Vt as buildLimitOrderCreateOp,wu as buildLimitOrderCreateOpWithType,Su as buildMultiPointTransferOps,du as buildMultiTransferOps,Vr as buildMutePostOp,_u as buildMuteUserOp,Ur as buildPinPostOp,Ye as buildPointTransferOp,Cu as buildPostingCustomJsonOp,wo as buildPostingJsonMetadata,Ar as buildProfileMetadata,Xr as buildPromoteOp,Kr as buildProposalCreateOp,Br as buildProposalVoteOp,Yr as buildRcDelegationOp,kr as buildReblogOp,Eu as buildRecoverAccountOp,fu as buildRecurrentTransferOp,yu as buildRemoveProposalOp,xu as buildRequestAccountRecoveryOp,Go as buildRevokeKeysOp,Au as buildRevokePostingPermissionOp,RK as buildSearchQuery,Ir as buildSetLastReadOps,Qr as buildSetRoleOp,gt as buildSetWithdrawVestingRouteOp,Mr as buildSubscribeOp,Ue as buildTransferFromSavingsOp,He as buildTransferOp,Je as buildTransferToSavingsOp,dt as buildTransferToVestingOp,Ht as buildUnfollowOp,gu as buildUnignoreOp,Nr as buildUnsubscribeOp,Hr as buildUpdateCommunityOp,hu as buildUpdateProposalOp,Er as buildVoteOp,ft as buildWithdrawVestingOp,Dr as buildWitnessProxyOp,qr as buildWitnessVoteOp,hl as buyStreakFreezeRequest,Dt as calculateRCMana,wr as calculateVPMana,te as callREST,y as callRPC,Le as callRPCBroadcast,It as callWithQuorum,YP as canRevokeFromAuthority,Gh as checkFavoriteQueryOptions,xh as checkUsernameWalletsPendingQueryOptions,Jd as claimPointsRequest,dn as collectRequestedOperations,sn as computeResourceCost,an as countCommentResourceUsage,di as countVoteResourceUsage,Qg as decodeObj,Ku as dedupeAndSortKeyAuths,oi as deleteDraft,ti as deleteImage,si as deleteSchedule,vA as downVotingPower,NS as earnsQuestContentCredit,Ng as encodeObj,wE as enforceThreeSpeakBeneficiary,dS as estimateCommentRcCost,cn as estimateCommentTransactionBytes,AS as estimateRcPrecheck,li as estimateVoteTransactionBytes,_o as extractAccountProfile,Gs as formatError,tt as formattedNumber,ul as gameClaimRequest,yR as getAccountDelegationsQueryOptions,M as getAccountFullQueryOptions,Wk as getAccountNotificationsInfiniteQueryOptions,n_ as getAccountPendingRecoveryQueryOptions,Or as getAccountPosts,uw as getAccountPostsInfiniteQueryOptions,pw as getAccountPostsQueryOptions,rS as getAccountRcQueryOptions,Xh as getAccountRecoveriesQueryOptions,u_ as getAccountReputationsQueryOptions,qh as getAccountSubscriptionsQueryOptions,s0 as getAccountVoteHistoryInfiniteQueryOptions,hq as getAccountWalletAssetInfoQueryOptions,jy as getAccountsQueryOptions,P0 as getAggregatedBalanceQueryOptions,dy as getAiAssistPriceQueryOptions,cy as getAiGeneratePriceQueryOptions,yy as getAiTranscribePriceQueryOptions,Ri as getAllHiveEngineTokensQueryOptions,vC as getAnnouncementsQueryOptions,uM as getBadActorsQueryOptions,h0 as getBalanceHistoryInfiniteQueryOptions,Nh as getBookmarksInfiniteQueryOptions,Mh as getBookmarksQueryOptions,GB as getBoostPlusAccountPricesQueryOptions,FB as getBoostPlusPricesQueryOptions,v_ as getBotsQueryOptions,_ as getBoundFetch,HA as getChainPropertiesQueryOptions,kR as getCollateralizedConversionRequestsQueryOptions,zw as getCommentHistoryQueryOptions,$b as getCommunities,Ok as getCommunitiesQueryOptions,To as getCommunity,Ck as getCommunityContextQueryOptions,rC as getCommunityPermissions,qk as getCommunityQueryOptions,Hk as getCommunitySubscribersInfiniteQueryOptions,Qk as getCommunitySubscribersQueryOptions,tC as getCommunityType,kM as getContentModerationReason,wb as getContentQueryOptions,xb as getContentRepliesQueryOptions,HK as getControversialRisingInfiniteQueryOptions,OR as getConversionRequestsQueryOptions,xi as getCurrencyRate,rI as getCurrencyRates,tI as getCurrencyTokenRate,VF as getCurrentMedianHistoryPriceQueryOptions,tp as getCustomJsonAuthority,Zw as getDeletedEntryQueryOptions,uE as getDiscoverCurationQueryOptions,oE as getDiscoverLeaderboardQueryOptions,Ro as getDiscussion,rw as getDiscussionQueryOptions,Do as getDiscussionsQueryOptions,Nw as getDraftsInfiniteQueryOptions,Mw as getDraftsQueryOptions,Oe as getDynamicPropsQueryOptions,pb as getEntryActiveVotesQueryOptions,jh as getFavoritesInfiniteQueryOptions,Vh as getFavoritesQueryOptions,NF as getFeedHistoryQueryOptions,zy as getFollowCountQueryOptions,eh as getFollowersQueryOptions,ih as getFollowingQueryOptions,tb as getFragmentsInfiniteQueryOptions,ze as getFragmentsQueryOptions,D_ as getFriendsInfiniteQueryOptions,jw as getGalleryImagesQueryOptions,SS as getGameStatusCheckQueryOptions,bi as getHbdAssetGeneralInfoQueryOptions,VT as getHbdAssetTransactionsQueryOptions,Gt as getHiveAssetGeneralInfoQueryOptions,XT as getHiveAssetMetricQueryOptions,zt as getHiveAssetTransactionsQueryOptions,rF as getHiveAssetWithdrawalRoutesQueryOptions,HI as getHiveEngineBalancesWithUsdQueryOptions,Sd as getHiveEngineMetrics,cI as getHiveEngineOpenOrders,sI as getHiveEngineOrderBook,Ti as getHiveEngineTokenGeneralInfoQueryOptions,Si as getHiveEngineTokenMetrics,Ei as getHiveEngineTokenTransactions,PI as getHiveEngineTokenTransactionsQueryOptions,Jt as getHiveEngineTokensBalances,Xt as getHiveEngineTokensBalancesQueryOptions,et as getHiveEngineTokensMarket,gI as getHiveEngineTokensMarketQueryOptions,Yt as getHiveEngineTokensMetadata,Ci as getHiveEngineTokensMetadataQueryOptions,EI as getHiveEngineTokensMetricsQueryOptions,aI as getHiveEngineTradeHistory,ki as getHiveEngineUnclaimedRewards,RI as getHiveEngineUnclaimedRewardsQueryOptions,SF as getHiveHbdStatsQueryOptions,jE as getHivePoshLinksQueryOptions,wi as getHivePowerAssetGeneralInfoQueryOptions,GT as getHivePowerAssetTransactionsQueryOptions,sF as getHivePowerDelegatesInfiniteQueryOptions,lF as getHivePowerDelegatingsQueryOptions,nI as getHivePrice,Lw as getImagesInfiniteQueryOptions,Vw as getImagesQueryOptions,zR as getIncomingRcQueryOptions,eI as getMarketData,TF as getMarketDataQueryOptions,AF as getMarketHistoryQueryOptions,bF as getMarketStatisticsQueryOptions,ph as getMutedUsersQueryOptions,cd as getNextAccountHistoryPageParam,Xv as getNormalizePostQueryOptions,yO as getNotificationSetting,mO as getNotifications,pC as getNotificationsInfiniteQueryOptions,hC as getNotificationsSettingsQueryOptions,sC as getNotificationsUnreadCountQueryOptions,QR as getOpenOrdersQueryOptions,np as getOperationAuthority,gF as getOrderBookQueryOptions,LR as getOutgoingRcDelegationsInfiniteQueryOptions,fE as getPageStatsQueryOptions,Fi as getPointsAssetGeneralInfoQueryOptions,iq as getPointsAssetTransactionsQueryOptions,bt as getPointsQueryOptions,hM as getPollQueryOptions,_i as getPortfolioQueryOptions,hc as getPost,Lb as getPostHeader,Rb as getPostHeaderQueryOptions,Eo as getPostQueryOptions,nv as getPostTipsQueryOptions,Co as getPostsRanked,_w as getPostsRankedInfiniteQueryOptions,bw as getPostsRankedQueryOptions,E0 as getProMembersQueryOptions,Qt as getProfiles,l0 as getProfilesQueryOptions,jB as getPromotePriceQueryOptions,_O as getPromotedPost,ib as getPromotedPostsQuery,rp as getProposalAuthority,QC as getProposalQueryOptions,JC as getProposalVotesInfiniteQueryOptions,jC as getProposalsQueryOptions,w as getQueryClient,MS as getQuestCatalogEntry,KS as getQuestsQueryOptions,QB as getRcDelegationActiveQueryOptions,KB as getRcDelegationPricesQueryOptions,aS as getRcResourceParamsQueryOptions,XE as getRcStatsQueryOptions,Cw as getRebloggedByQueryOptions,Ow as getReblogsQueryOptions,ZR as getReceivedVestingSharesQueryOptions,nT as getRecurrentTransfersQueryOptions,x_ as getReferralsInfiniteQueryOptions,C_ as getReferralsStatsQueryOptions,zb as getRelationshipBetweenAccounts,Po as getRelationshipBetweenAccountsQueryOptions,xA as getRequiredAuthority,ry as getRewardFundQueryOptions,Yk as getRewardedCommunitiesQueryOptions,FR as getSavingsWithdrawFromQueryOptions,qw as getSchedulesInfiniteQueryOptions,Iw as getSchedulesQueryOptions,oB as getSearchAccountQueryOptions,vh as getSearchAccountsByUsernameQueryOptions,gB as getSearchApiInfiniteQueryOptions,Q_ as getSearchFriendsQueryOptions,bB as getSearchPathQueryOptions,uB as getSearchTopicsQueryOptions,hv as getShortsFeedQueryOptions,XK as getSimilarEntriesQueryOptions,xC as getSpotlightsQueryOptions,GE as getStatsQueryOptions,Gb as getSubscribers,Wb as getSubscriptions,AB as getSupportSettingsQueryOptions,_f as getSupportSettingsRequest,DF as getTradeHistoryQueryOptions,h_ as getTransactionsInfiniteQueryOptions,L_ as getTrendingTagsQueryOptions,Y_ as getTrendingTagsWithStatsQueryOptions,gb as getUserPostVoteQueryOptions,eR as getUserProposalVotesQueryOptions,wR as getVestingDelegationExpirationsQueryOptions,dR as getVestingDelegationsQueryOptions,No as getVisibleFirstLevelThreadItems,Vv as getWavesByAccountQueryOptions,Ov as getWavesByHostQueryOptions,Cv as getWavesByTagQueryOptions,lv as getWavesFeedQueryOptions,qv as getWavesFollowingQueryOptions,dv as getWavesLatestFeedQueryOptions,Wv as getWavesTrendingAuthorsQueryOptions,Mv as getWavesTrendingTagsQueryOptions,KR as getWithdrawRoutesQueryOptions,bK as getWitnessVoterCountQueryOptions,_K as getWitnessVotersPageQueryOptions,hK as getWitnessesInfiniteQueryOptions,ji as hasExternalLink,Kp as hasThreeSpeakEmbed,x as hiveTxConfig,ne as hiveTxUtils,iM as hsTokenRenew,E as invalidateAfterBroadcast,SM as isAuthorMuted,mo as isCommunity,go as isEmptyDate,$f as isHiddenPost,Js as isInfoError,Wf as isLowTrustSeoPost,Ys as isNetworkError,Ge as isQueryableAccountName,zs as isResourceCreditsError,vE as isThreeSpeakBeneficiary,Op as isVoteAlreadyReflected,io as isWif,ua as isWrappedResponse,yh as lookupAccountsQueryOptions,Bg as makeQueryClient,dM as mapMetaChoicesToPollChoices,Qo as mapThreadItemsToWaveEntries,Xo as markNotifications,fl as measureQuestContentLength,ai as moveSchedule,Fo as normalizePost,Yd as normalizeSearchAuthor,Xd as normalizeSearchCategory,Zd as normalizeSearchTags,se as normalizeToWrappedResponse,he as normalizeWaveEntryFromApi,bO as onboardEmail,Nt as parseAccounts,k as parseAsset,$e as parseChainError,xa as parsePostingMetadataRoot,Me as parseProfileMetadata,bo as pickRicherMetadataSnapshot,wA as powerRechargeTime,un as priceRcUsage,S0 as proMembersSet,PA as rcPower,ci as removeOptimisticDiscussionEntry,ud as resolveAccountHistoryLimit,Ep as resolveContentActivityType,ht as resolveHiveOperationFilters,So as resolvePost,ui as restoreDiscussionSnapshots,Tx as restoreEntryInCache,Zk as roleMap,gO as saveNotificationSetting,LK as search,$K as searchPath,QK as searchQueryOptions,ug as sha256,we as shouldTriggerAuthFallback,lO as signUp,Hi as similar,_c as sortDiscussions,pn as stringFieldBytes,dO as subscribeEmail,Mc as toEntryArray,ni as updateDraft,Rx as updateEntryInCache,vf as updateSupportSettingsRequest,ei as uploadImage,hO as uploadImageWithSignature,vP as useAccountFavoriteAdd,EP as useAccountFavoriteDelete,M0 as useAccountRelationsUpdate,nA as useAccountRevokeKey,UP as useAccountRevokePosting,I0 as useAccountUpdate,Wo as useAccountUpdateKeyAuths,KP as useAccountUpdatePassword,zP as useAccountUpdateRecovery,OO as useAddDraft,zA as useAddFragment,tx as useAddImage,QO as useAddSchedule,Oy as useAiAssist,ky as useAiTranscribe,fP as useBookmarkAdd,hP as useBookmarkDelete,XB as useBoostPlus,v as useBroadcastMutation,LS as useBuyStreakFreeze,aA as useClaimAccount,VD as useClaimEngineRewards,_D as useClaimInterest,EK as useClaimPoints,AD as useClaimRewards,Ex as useComment,fD as useConvert,gA as useCreateAccount,Qx as useCrossPost,SD as useDelegateEngineToken,nK as useDelegateRc,Iq as useDelegateVestingShares,Kx as useDeleteComment,DO as useDeleteDraft,sx as useDeleteImage,LO as useDeleteSchedule,rO as useEditFragment,WD as useEngineMarketOrder,iP as useFollow,FS as useGameClaim,wy as useGenerateImage,lA as useGrantPostingPermission,YF as useLimitOrderCancel,WF as useLimitOrderCreate,FC as useMarkNotificationsRead,JO as useMoveSchedule,nk as useMutePost,bk as usePinPost,wM as usePollVote,Gx as usePromote,cR as useProposalCreate,oR as useProposalVote,rM as useRcDelegation,Px as useReblog,tn as useRecordActivity,gk as useRegisterCommunityRewards,cO as useRemoveFragment,ak as useSetCommunityRole,KC as useSetLastRead,Mq as useSetWithdrawVestingRoute,BA as useSignOperationByHivesigner,RA as useSignOperationByKey,IA as useSignOperationByKeychain,DD as useStakeEngineToken,zS as useSubscribeCommunity,Aq as useTransfer,Uq as useTransferEngineToken,Xq as useTransferFromSavings,kq as useTransferPoint,Wq as useTransferToSavings,nD as useTransferToVesting,TD as useUndelegateEngineToken,uP as useUnfollow,ND as useUnstakeEngineToken,ZS as useUnsubscribeCommunity,lk as useUpdateCommunity,CO as useUpdateDraft,jx as useUpdateReply,kB as useUpdateSupportSettings,px as useUploadImage,hx as useVote,ZD as useWalletOperation,cD as useWithdrawVesting,lK as useWitnessProxy,aK as useWitnessVote,fO as usrActivity,ut as utf8ByteLength,Rp as validatePostCreating,ye as varintByteLength,xo as verifyPostOnAlternateNode,We as vestsToHp,bA as votingPower,Zu as votingRshares,AA as votingValue,Pe as withTimeoutSignal};//# sourceMappingURL=index.mjs.map + */export{Eo as ACCOUNT_OPERATION_GROUPS,cu as ALL_ACCOUNT_OPERATIONS,bi as ALL_NOTIFY_TYPES,rf as AssetOperation,Yg as BROADCAST_INCLUSION_DELAY_MS,zo as BuySellTransactionType,d as CONFIG,Q as ConfigManager,im as ContentModerationReason,et as EcencyAnalytics,Aa as EcencyQueriesManager,Le as EntriesCacheManagement,fo as ErrorType,Jf as HIDDEN_POST_MIN_VOTES,zf as HIDDEN_POST_RSHARES_THRESHOLD,gn as HIVE_ACCOUNT_OPERATION_GROUPS,eq as HIVE_OPERATION_LIST,oq as HIVE_OPERATION_NAME_BY_ID,nq as HIVE_OPERATION_ORDERS,rr as HiveEngineToken,mi as HiveSignerIntegration,Ke as HiveTxTransaction,Ae as INTERNAL_API_TIMEOUT_MS,Yf as LOW_TRUST_REPUTATION_THRESHOLD,tN as MAX_SEARCH_QUERY_LENGTH,eN as MAX_SEARCH_TAGS,uo as Memo,Qt as NaiMap,At as NewsletterApiError,or as NewsletterSendRefusedError,Vl as NotificationFilter,Ll as NotificationViewType,jl as NotifyTypes,gp as OPERATION_AUTHORITY_MAP,Jo as OrderIdPrefix,NB as POLLS_PROTOCOL_VERSION,pf as PointTransactionType,Lf as PollPreferredInterpretation,U as PrivateKey,Y as PublicKey,Sl as QUEST_CATALOG,El as QUEST_MIN_CONTENT_LENGTH,u as QueryKeys,Jt as RC_RESOURCE_NAMES,Ql as ROLES,yo as SERVER_GC_TIME_MS,yl as SIGNATURE_BYTES,AN as SIMILAR_ENTRIES_MIN_RENDER,fk as STREAK_FREEZE_MAX_OWNED,dk as STREAK_FREEZE_PRICE,_i as SUBSCRIBERS_PAGE_SIZE,Ui as SearchQuery,Vi as SearchType,Se as Signature,Bo as SortOrder,ho as Symbol,zt as THREESPEAK_BENEFICIARY_ACCOUNT,LS as THREESPEAK_BENEFICIARY_WEIGHT,gl as TRANSACTION_HEADER_BYTES,pE as ThreeSpeakIntegration,Ha as accountNameByteLength,si as addDraft,ni as addImage,tS as addOptimisticDiscussionEntry,ci as addSchedule,Nf as applySupportSettingsUpdate,Qp as applyVoteCacheUpdate,ae as bridgeApiCall,go as broadcastJson,ee as broadcastOperations,po as broadcastOperationsAsync,Jr as buildAccountCreateOp,Nc as buildAccountUpdate2Op,Kc as buildAccountUpdateOp,Vc as buildActiveCustomJsonOp,en as buildBoostPlusOp,Go as buildCancelTransferFromSavingsOp,Mc as buildChangeRecoveryAccountOp,Xr as buildClaimAccountOp,ft as buildClaimInterestOps,zr as buildClaimRewardBalanceOp,Fr as buildCollateralizedConvertOp,Qe as buildCommentOp,He as buildCommentOptionsOp,nn as buildCommunityRegistrationOp,_t as buildConvertOp,Yr as buildCreateClaimedAccountOp,Dr as buildDelegateRcOp,yt as buildDelegateVestingSharesOp,Tr as buildDeleteCommentOp,Ir as buildEngineClaimOp,je as buildEngineOp,Ic as buildFlagPostOp,Kr as buildFollowOp,Zr as buildGrantPostingPermissionOp,Cc as buildIgnoreOp,Gr as buildLimitOrderCancelOp,$t as buildLimitOrderCreateOp,Dc as buildLimitOrderCreateOpWithType,Uc as buildMultiPointTransferOps,Ec as buildMultiTransferOps,Wr as buildMutePostOp,Fc as buildMuteUserOp,$r as buildPinPostOp,Ze as buildPointTransferOp,jc as buildPostingCustomJsonOp,Oo as buildPostingJsonMetadata,Er as buildProfileMetadata,rn as buildPromoteOp,Qr as buildProposalCreateOp,Hr as buildProposalVoteOp,tn as buildRcDelegationOp,qr as buildReblogOp,Hc as buildRecoverAccountOp,kc as buildRecurrentTransferOp,Tc as buildRemoveProposalOp,Qc as buildRequestAccountRecoveryOp,Xo as buildRevokeKeysOp,Bc as buildRevokePostingPermissionOp,rN as buildSearchQuery,Nr as buildSetLastReadOps,jr as buildSetRoleOp,ht as buildSetWithdrawVestingRouteOp,Ur as buildSubscribeOp,Ve as buildTransferFromSavingsOp,Ue as buildTransferOp,Xe as buildTransferToSavingsOp,mt as buildTransferToVestingOp,jt as buildUnfollowOp,Rc as buildUnignoreOp,Vr as buildUnsubscribeOp,Lr as buildUpdateCommunityOp,qc as buildUpdateProposalOp,Rr as buildVoteOp,gt as buildWithdrawVestingOp,Mr as buildWitnessProxyOp,Br as buildWitnessVoteOp,ql as buyStreakFreezeRequest,Bt as calculateRCMana,Or as calculateVPMana,te as callREST,y as callRPC,We as callRPCBroadcast,Kt as callWithQuorum,AA as canRevokeFromAuthority,b_ as checkFavoriteQueryOptions,Yh as checkUsernameWalletsPendingQueryOptions,df as claimPointsRequest,yn as collectRequestedOperations,pn as computeResourceCost,ln as countCommentResourceUsage,yi as countVoteResourceUsage,dy as decodeObj,Yc as dedupeAndSortKeyAuths,ui as deleteDraft,ii as deleteImage,pi as deleteSchedule,WA as downVotingPower,lk as earnsQuestContentCredit,ly as encodeObj,$S as enforceThreeSpeakBeneficiary,BE as estimateCommentRcCost,dn as estimateCommentTransactionBytes,zE as estimateRcPrecheck,gi as estimateVoteTransactionBytes,Po as extractAccountProfile,ca as formatError,nt as formattedNumber,Ol as gameClaimRequest,UR as getAccountDelegationsQueryOptions,B as getAccountFullQueryOptions,wC as getAccountNotificationsInfiniteQueryOptions,C_ as getAccountPendingRecoveryQueryOptions,kr as getAccountPosts,Db as getAccountPostsInfiniteQueryOptions,Kb as getAccountPostsQueryOptions,kE as getAccountRcQueryOptions,O_ as getAccountRecoveriesQueryOptions,D_ as getAccountReputationsQueryOptions,s_ as getAccountSubscriptionsQueryOptions,q0 as getAccountVoteHistoryInfiniteQueryOptions,VI as getAccountWalletAssetInfoQueryOptions,yh as getAccountsQueryOptions,G0 as getAggregatedBalanceQueryOptions,By as getAiAssistPriceQueryOptions,Iy as getAiGeneratePriceQueryOptions,Uy as getAiTranscribePriceQueryOptions,Ii as getAllHiveEngineTokensQueryOptions,WC as getAnnouncementsQueryOptions,DB as getBadActorsQueryOptions,V0 as getBalanceHistoryInfiniteQueryOptions,l_ as getBookmarksInfiniteQueryOptions,p_ as getBookmarksQueryOptions,bB as getBoostPlusAccountPricesQueryOptions,oB as getBoostPlusPricesQueryOptions,W_ as getBotsQueryOptions,h as getBoundFetch,fO as getChainPropertiesQueryOptions,eT as getCollateralizedConversionRequestsQueryOptions,vv as getCommentHistoryQueryOptions,_b as getCommunities,Jk as getCommunitiesQueryOptions,Do as getCommunity,tC as getCommunityContextQueryOptions,kC as getCommunityPermissions,sC as getCommunityQueryOptions,fC as getCommunitySubscribersInfiniteQueryOptions,dC as getCommunitySubscribersQueryOptions,EC as getCommunityType,eM as getContentModerationReason,$w as getContentQueryOptions,Yw as getContentRepliesQueryOptions,fN as getControversialRisingInfiniteQueryOptions,JR as getConversionRequestsQueryOptions,Ci as getCurrencyRate,kF as getCurrencyRates,EF as getCurrencyTokenRate,gF as getCurrentMedianHistoryPriceQueryOptions,yp as getCustomJsonAuthority,xv as getDeletedEntryQueryOptions,aM as getDigestSubscriptionsQueryOptions,Ji as getDigestSubscriptionsRequest,DS as getDiscoverCurationQueryOptions,RS as getDiscoverLeaderboardQueryOptions,Io as getDiscussion,kb as getDiscussionQueryOptions,Mo as getDiscussionsQueryOptions,lv as getDraftsInfiniteQueryOptions,pv as getDraftsQueryOptions,Oe as getDynamicPropsQueryOptions,Kw as getEntryActiveVotesQueryOptions,y_ as getFavoritesInfiniteQueryOptions,g_ as getFavoritesQueryOptions,lF as getFeedHistoryQueryOptions,vh as getFollowCountQueryOptions,Sh as getFollowersQueryOptions,Th as getFollowingQueryOptions,Ew as getFragmentsInfiniteQueryOptions,Ye as getFragmentsQueryOptions,aw as getFriendsInfiniteQueryOptions,yv as getGalleryImagesQueryOptions,ZE as getGameStatusCheckQueryOptions,Ai as getHbdAssetGeneralInfoQueryOptions,gq as getHbdAssetTransactionsQueryOptions,Yt as getHiveAssetGeneralInfoQueryOptions,Oq as getHiveAssetMetricQueryOptions,Xt as getHiveAssetTransactionsQueryOptions,kq as getHiveAssetWithdrawalRoutesQueryOptions,fI as getHiveEngineBalancesWithUsdQueryOptions,Ud as getHiveEngineMetrics,IF as getHiveEngineOpenOrders,qF as getHiveEngineOrderBook,Di as getHiveEngineTokenGeneralInfoQueryOptions,Ti as getHiveEngineTokenMetrics,Ri as getHiveEngineTokenTransactions,GF as getHiveEngineTokenTransactionsQueryOptions,Zt as getHiveEngineTokensBalances,tr as getHiveEngineTokensBalancesQueryOptions,rt as getHiveEngineTokensMarket,HF as getHiveEngineTokensMarketQueryOptions,er as getHiveEngineTokensMetadata,Fi as getHiveEngineTokensMetadataQueryOptions,XF as getHiveEngineTokensMetricsQueryOptions,FF as getHiveEngineTradeHistory,qi as getHiveEngineUnclaimedRewards,rI as getHiveEngineUnclaimedRewardsQueryOptions,Zq as getHiveHbdStatsQueryOptions,yE as getHivePoshLinksQueryOptions,Oi as getHivePowerAssetGeneralInfoQueryOptions,bq as getHivePowerAssetTransactionsQueryOptions,qq as getHivePowerDelegatesInfiniteQueryOptions,Nq as getHivePowerDelegatingsQueryOptions,CF as getHivePrice,hv as getImagesInfiniteQueryOptions,gv as getImagesQueryOptions,vT as getIncomingRcQueryOptions,SF as getMarketData,nF as getMarketDataQueryOptions,zq as getMarketHistoryQueryOptions,Lq as getMarketStatisticsQueryOptions,Kh as getMutedUsersQueryOptions,hM as getNewsletterIssuesQueryOptions,es as getNewsletterIssuesRequest,PM as getNewsletterPostsQueryOptions,ts as getNewsletterPostsRequest,dM as getNewsletterSenderQueryOptions,Zi as getNewsletterSenderRequest,Ad as getNextAccountHistoryPageParam,O0 as getNormalizePostQueryOptions,UO as getNotificationSetting,QO as getNotifications,KC as getNotificationsInfiniteQueryOptions,VC as getNotificationsSettingsQueryOptions,qC as getNotificationsUnreadCountQueryOptions,dT as getOpenOrdersQueryOptions,_p as getOperationAuthority,Hq as getOrderBookQueryOptions,hT as getOutgoingRcDelegationsInfiniteQueryOptions,MS as getPageStatsQueryOptions,Ki as getPointsAssetGeneralInfoQueryOptions,TI as getPointsAssetTransactionsQueryOptions,vt as getPointsQueryOptions,VB as getPollQueryOptions,Pi as getPortfolioQueryOptions,qu as getPost,hb as getPostHeader,rb as getPostHeaderQueryOptions,Ro as getPostQueryOptions,Cv as getPostTipsQueryOptions,Fo as getPostsRanked,jb as getPostsRankedInfiniteQueryOptions,Lb as getPostsRankedQueryOptions,X0 as getProMembersQueryOptions,Vt as getProfiles,N0 as getProfilesQueryOptions,yB as getPromotePriceQueryOptions,jO as getPromotedPost,Tw as getPromotedPostsQuery,hp as getProposalAuthority,dR as getProposalQueryOptions,PR as getProposalVotesInfiniteQueryOptions,yR as getProposalsQueryOptions,b as getQueryClient,pk as getQuestCatalogEntry,uk as getQuestsQueryOptions,dB as getRcDelegationActiveQueryOptions,uB as getRcDelegationPricesQueryOptions,FE as getRcResourceParamsQueryOptions,OE as getRcStatsQueryOptions,tv as getRebloggedByQueryOptions,Jb as getReblogsQueryOptions,xT as getReceivedVestingSharesQueryOptions,CT as getRecurrentTransfersQueryOptions,Y_ as getReferralsInfiniteQueryOptions,tw as getReferralsStatsQueryOptions,vb as getRelationshipBetweenAccounts,So as getRelationshipBetweenAccountsQueryOptions,YA as getRequiredAuthority,ky as getRewardFundQueryOptions,AC as getRewardedCommunitiesQueryOptions,oT as getSavingsWithdrawFromQueryOptions,sv as getSchedulesInfiniteQueryOptions,iv as getSchedulesQueryOptions,RN as getSearchAccountQueryOptions,Wh as getSearchAccountsByUsernameQueryOptions,HN as getSearchApiInfiniteQueryOptions,dw as getSearchFriendsQueryOptions,LN as getSearchPathQueryOptions,DN as getSearchTopicsQueryOptions,Vv as getShortsFeedQueryOptions,ON as getSimilarEntriesQueryOptions,YC as getSpotlightsQueryOptions,bE as getStatsQueryOptions,bb as getSubscribers,wb as getSubscriptions,zN as getSupportSettingsQueryOptions,Ff as getSupportSettingsRequest,aF as getTradeHistoryQueryOptions,V_ as getTransactionsInfiniteQueryOptions,hw as getTrendingTagsQueryOptions,Aw as getTrendingTagsWithStatsQueryOptions,Hw as getUserPostVoteQueryOptions,SR as getUserProposalVotesQueryOptions,$R as getVestingDelegationExpirationsQueryOptions,BR as getVestingDelegationsQueryOptions,Vo as getVisibleFirstLevelThreadItems,g0 as getWavesByAccountQueryOptions,Jv as getWavesByHostQueryOptions,t0 as getWavesByTagQueryOptions,Nv as getWavesFeedQueryOptions,s0 as getWavesFollowingQueryOptions,Bv as getWavesLatestFeedQueryOptions,w0 as getWavesTrendingAuthorsQueryOptions,p0 as getWavesTrendingTagsQueryOptions,uT as getWithdrawRoutesQueryOptions,LK as getWitnessVoterCountQueryOptions,jK as getWitnessVotersPageQueryOptions,VK as getWitnessesInfiniteQueryOptions,Gi as hasExternalLink,Yp as hasThreeSpeakEmbed,x as hiveTxConfig,ne as hiveTxUtils,TB as hsTokenRenew,S as invalidateAfterBroadcast,ZB as isAuthorMuted,_o as isCommunity,wo as isEmptyDate,am as isHiddenPost,la as isInfoError,um as isLowTrustSeoPost,da as isNetworkError,Je as isQueryableAccountName,pa as isResourceCreditsError,WS as isThreeSpeakBeneficiary,Mp as isVoteAlreadyReflected,co as isWif,Oa as isWrappedResponse,Yi as leaveDigestRequest,Uh as lookupAccountsQueryOptions,cy as makeQueryClient,BB as mapMetaChoicesToPollChoices,jo as mapThreadItemsToWaveEntries,ri as markNotifications,kl as measureQuestContentLength,li as moveSchedule,Ko as normalizePost,ff as normalizeSearchAuthor,mf as normalizeSearchCategory,gf as normalizeSearchTags,se as normalizeToWrappedResponse,he as normalizeWaveEntryFromApi,LO as onboardEmail,Ut as parseAccounts,k as parseAsset,Ge as parseChainError,Qa as parsePostingMetadataRoot,Me as parseProfileMetadata,Ao as pickRicherMetadataSnapshot,$A as powerRechargeTime,ns as previewNewsletterSendRequest,fn as priceRcUsage,Z0 as proMembersSet,GA as rcPower,di as removeOptimisticDiscussionEntry,Od as resolveAccountHistoryLimit,Hp as resolveContentActivityType,wt as resolveHiveOperationFilters,To as resolvePost,fi as restoreDiscussionSnapshots,nS as restoreEntryInCache,xC as roleMap,HO as saveNotificationSetting,hN as search,_N as searchPath,dN as searchQueryOptions,os as sendNewsletterIssueRequest,Dg as sha256,be as shouldTriggerAuthFallback,NO as signUp,Li as similar,Fu as sortDiscussions,mn as stringFieldBytes,zi as subscribeDigestRequest,BO as subscribeEmail,Zu as toEntryArray,Xi as unsubscribeAllDigestsRequest,ai as updateDraft,rS as updateEntryInCache,Kf as updateSupportSettingsRequest,oi as uploadImage,VO as uploadImageWithSignature,WP as useAccountFavoriteAdd,XP as useAccountFavoriteDelete,pP as useAccountRelationsUpdate,CA as useAccountRevokeKey,mA as useAccountRevokePosting,iP as useAccountUpdate,Yo as useAccountUpdateKeyAuths,uA as useAccountUpdatePassword,vA as useAccountUpdateRecovery,JO as useAddDraft,vO as useAddFragment,Ex as useAddImage,dx as useAddSchedule,Jy as useAiAssist,eh as useAiTranscribe,MP as useBookmarkAdd,VP as useBookmarkDelete,OB as useBoostPlus,v as useBroadcastMutation,hk as useBuyStreakFreeze,FA as useClaimAccount,gK as useClaimEngineRewards,jD as useClaimInterest,XK as useClaimPoints,zD as useClaimRewards,Xx as useComment,MD as useConvert,HA as useCreateAccount,dS as useCrossPost,ZD as useDelegateEngineToken,CK as useDelegateRc,iD as useDelegateVestingShares,uS as useDeleteComment,ax as useDeleteDraft,qx as useDeleteImage,hx as useDeleteSchedule,kO as useEditFragment,wK as useEngineMarketOrder,TP as useFollow,ok as useGameClaim,$y as useGenerateImage,NA as useGrantPostingPermission,qM as useLeaveDigest,AF as useLimitOrderCancel,wF as useLimitOrderCreate,oR as useMarkNotificationsRead,Px as useMoveSchedule,Ck as useMutePost,Lk as usePinPost,$B as usePollVote,UM as usePreviewNewsletterIssue,bS as usePromote,IR as useProposalCreate,RR as useProposalVote,kB as useRcDelegation,Gx as useReblog,sn as useRecordActivity,Hk as useRegisterCommunityRewards,IO as useRemoveFragment,VM as useSendNewsletterIssue,Fk as useSetCommunityRole,uR as useSetLastRead,pD as useSetWithdrawVestingRoute,cO as useSignOperationByHivesigner,rO as useSignOperationByKey,iO as useSignOperationByKeychain,aK as useStakeEngineToken,vk as useSubscribeCommunity,EM as useSubscribeDigest,zI as useTransfer,mD as useTransferEngineToken,OD as useTransferFromSavings,eD as useTransferPoint,wD as useTransferToSavings,CD as useTransferToVesting,nK as useUndelegateEngineToken,DP as useUnfollow,lK as useUnstakeEngineToken,NM as useUnsubscribeAllDigests,xk as useUnsubscribeCommunity,Nk as useUpdateCommunity,tx as useUpdateDraft,yS as useUpdateReply,eB as useUpdateSupportSettings,Kx as useUploadImage,Vx as useVote,xK as useWalletOperation,ID as useWithdrawVesting,NK as useWitnessProxy,FK as useWitnessVote,MO as usrActivity,lt as utf8ByteLength,Lp as validatePostCreating,ye as varintByteLength,Co as verifyPostOnAlternateNode,ze as vestsToHp,LA as votingPower,mp as votingRshares,zA as votingValue,Pe 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 97f9e20d16..00b83e6708 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/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-comment-rc-cost.ts","../../src/modules/resource-credits/utils/price-rc-usage.ts","../../src/modules/resource-credits/utils/count-operation-usage.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","../../src/modules/moderation/constants.ts","../../src/modules/moderation/account-reputation.ts","../../src/modules/moderation/external-links.ts","../../src/modules/moderation/content-moderation.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","DEFAULT_SERVER_RPC_PROXY_METHODS","serverRpcProxy","setServerRpcProxy","opts","url","headers","k","v","timeoutMs","methods","m","pos","fallback","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","r","bool","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","rpcProxyStats","ProxyMiss","reason","errorMessage","proxyConsecutiveMisses","proxyOpenUntil","proxyRpcCall","proxy","method","params","callerTimeoutMs","externalSignal","validate","dot","tSignal","cleanupTimeout","createTimeoutSignal","signal","cleanupMerge","mergeSignals","res","e","relayed","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","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","tryRecordHeadBlock","block","createTimeoutReason","err","controller","timer","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","timeout","shouldRetry","body","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","served","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","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","timeoutSignal","ac","onAbort","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","getServerRpcProxyStats","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","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","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","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","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","resolveContentActivityType","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","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","EMPTY","estimateCommentRcCost","rcParams","rcStats","usage","regen","cost","breakdown","share","scaled","resourceCost","priceRcUsage","emptyUsage","estimateVoteTransactionBytes","operationBytes","countVoteResourceUsage","estimateRcPrecheck","priced","priceOperation","safeBuffer","estimatedCost","willLikelyFail","average","averageCost","MINIMAL_VOTE","MINIMAL_COMMENT","getGameStatusCheckQueryOptions","gameClaimRequest","contentType","detail","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","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","HIDDEN_POST_RSHARES_THRESHOLD","HIDDEN_POST_MIN_VOTES","LOW_TRUST_REPUTATION_THRESHOLD","isHumanReadable","accountReputation","neg","reputationLevel","INTERNAL_HOSTS","IMAGE_HOSTS","IMAGE_EXT_RE","URL_RE","TRAILING_PUNCT_RE","hostOf","isExternalPromoLink","rawUrl","hasExternalLink","ContentModerationReason","countVotes","isHiddenPost","netRshares","activeVotesLength","isLowTrustSeoPost","reputation","isAuthorMuted","mutedAuthors","getContentModerationReason"],"mappings":"whBASA,IAAMA,GAAe,IAAI,WAAA,CAAY,CAAC,CAAA,CAIlCC,EAAAA,CAAqD,IAAA,CACrDC,EAAAA,CAAuD,IAAA,CAE3D,SAASC,IAAgD,CACvD,OAAKF,KACC,OAAO,WAAA,CAAgB,IACzBA,EAAAA,CAAW,IAAI,WAAA,CAEfA,EAAAA,CAAW,CACT,MAAA,CAAOG,EAAuB,CAE5B,IAAMC,EAAiB,EAAC,CACxB,QAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAE,MAAA,CAAQE,CAAAA,EAAAA,CAAK,CACjC,IAAIC,CAAAA,CAAIH,EAAE,UAAA,CAAWE,CAAC,EACtB,GAAIC,CAAAA,CAAI,GAAA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,CAASpsC,CAAM,CACpD,CAcO,SAASqsC,GACdrqC,CAAAA,CACgC,CAChC,OAAKA,CAAAA,CAGDA,CAAAA,CAAQ,OAAO,IAAA,EAAQA,CAAAA,CAAQ,OAAO,IAAA,CACjC,WAAA,CAEL8pC,GAAa9pC,CAAAA,CAAQ,WAAA,CAAa6pC,GAAW7pC,CAAO,CAAC,EAChD,WAAA,CAELiqC,EAAAA,CAAkBjqC,CAAO,CAAA,CACpB,WAAA,CAEF,KAXE,IAYX","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 * Server-side read-through proxy for RPC reads (see `setServerRpcProxy`).\n * `methods` is the allowlist the proxy serves; a read outside it goes straight\n * to the node pool as before.\n */\nexport interface ServerRpcProxyOptions {\n /** Absolute URL of the proxy endpoint (POST `{api, method, params}`). */\n url: string\n /** Headers sent with every proxy call (the shared internal secret). */\n headers: Record\n /** Per-call timeout in ms; on expiry the read falls back to the node pool. */\n timeoutMs: number\n /** Fully qualified method names (`bridge.get_post`) the proxy may answer;\n * omitted = DEFAULT_SERVER_RPC_PROXY_METHODS. An empty list is ignored. */\n methods?: string[]\n /**\n * After this many consecutive proxy misses the proxy is skipped for\n * `cooldownMs`, so a proxy that is down costs one failed call per cooldown\n * window rather than one per read. Default 3 / 10s. A served call resets it.\n */\n failureThreshold?: number\n cooldownMs?: number\n}\n\n/** Default allowlist: the reads a server render makes and the proxy caches. */\nexport const DEFAULT_SERVER_RPC_PROXY_METHODS: readonly string[] = [\n 'bridge.get_ranked_posts',\n 'bridge.get_account_posts',\n 'bridge.get_post',\n 'bridge.get_discussion',\n 'bridge.get_profile',\n 'bridge.get_profiles',\n 'bridge.get_community',\n 'bridge.list_communities',\n 'condenser_api.get_accounts',\n 'condenser_api.get_content',\n 'condenser_api.get_dynamic_global_properties',\n 'condenser_api.get_trending_tags'\n]\n\n/**\n * Active proxy configuration, or null (the default: every read goes to the node\n * pool). Lives outside `config` so the browser bundle never carries it; it is\n * only ever consulted under Node.\n */\nexport interface ServerRpcProxyState extends Required {\n methodSet: Set\n}\n\nexport let serverRpcProxy: ServerRpcProxyState | null = null\n\n/**\n * Route allowlisted server-side reads through a read-through cache in front\n * of the node pool. One cache per host answers the reads every renderer\n * process used to make on its own; a miss there is one upstream call shared by\n * every concurrent reader. The proxy is an optimization, never a dependency:\n * any failure (non-200, timeout, transport error, a response the caller's\n * validator rejects) falls straight through to the existing node loop, so the\n * worst case is the latency of a failed proxy call on top of what happens\n * today. Has no effect outside Node. Pass null to switch it off.\n */\nexport const setServerRpcProxy = (opts: ServerRpcProxyOptions | null): void => {\n if (opts === null) {\n serverRpcProxy = null\n return\n }\n if (!opts || typeof opts !== 'object') return\n const url = typeof opts.url === 'string' ? opts.url.trim() : ''\n if (!/^https?:\\/\\//i.test(url)) return\n const headers: Record = {}\n if (opts.headers && typeof opts.headers === 'object') {\n for (const [k, v] of Object.entries(opts.headers)) {\n if (typeof v === 'string' && v && !/[\\u0000-\\u001f\\u007f]/.test(v) && !/[\\u0000-\\u001f\\u007f]/.test(k)) {\n headers[k] = v\n }\n }\n }\n const timeoutMs =\n typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0\n ? opts.timeoutMs\n : 2_000\n const methods =\n opts.methods === undefined\n ? [...DEFAULT_SERVER_RPC_PROXY_METHODS]\n : Array.isArray(opts.methods)\n ? opts.methods.filter((m): m is string => typeof m === 'string' && m.includes('.'))\n : []\n // Nothing to route through the proxy: keep whatever was configured before.\n if (methods.length === 0) return\n const pos = (v: unknown, fallback: number): number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : fallback\n serverRpcProxy = {\n url,\n headers,\n timeoutMs,\n methods,\n failureThreshold: Math.floor(pos(opts.failureThreshold, 3)),\n cooldownMs: pos(opts.cooldownMs, 10_000),\n methodSet: new Set(methods)\n }\n}\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, serverRpcProxy, type ServerRpcProxyState } 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// ── Server-side read-through proxy ──────────────────────────────────────────\n\n/**\n * Counters for the proxy path, readable by a host's diagnostics (the web\n * tier's event-loop monitor prints them). `served` = answered by the proxy,\n * `fallback` = proxy configured and eligible but the read went to the node\n * pool, with the reason.\n */\nexport const rpcProxyStats = {\n served: 0,\n fallback: 0,\n /** Reads that went straight to the nodes because the breaker was open. */\n skipped: 0,\n fallbackByReason: { status: 0, rpcerror: 0, timeout: 0, transport: 0, validate: 0, parse: 0 } as Record\n}\n\n/**\n * `rpcerror` is a 502 tagged `X-Ssr-Cache: RPCERROR`: the proxy reached a node\n * and relayed the node's own error (a tag or post that does not exist, a bad\n * argument). The read still falls back so the caller sees the node's answer\n * unchanged, but the proxy was healthy, so it does not count toward the\n * breaker; the other reasons do.\n */\ntype ProxyMissReason = 'status' | 'rpcerror' | 'timeout' | 'transport' | 'validate' | 'parse'\n\nclass ProxyMiss extends Error {\n constructor(\n public reason: ProxyMissReason,\n message: string\n ) {\n super(message)\n }\n}\n\nconst errorMessage = (e: unknown): string =>\n e instanceof Error ? e.message : typeof e === 'string' ? e : String(e)\n\n// Breaker: consecutive misses open it for the configured cooldown, a served\n// call closes it. Module state, like the health tracker: one per process.\nlet proxyConsecutiveMisses = 0\nlet proxyOpenUntil = 0\n\n/** Test seam: forget breaker state. */\nexport function resetRpcProxyBreaker(): void {\n proxyConsecutiveMisses = 0\n proxyOpenUntil = 0\n}\n\n/**\n * One proxy call for an eligible read. Resolves with the upstream `result` the\n * proxy served, or throws ProxyMiss; the caller then continues with the node\n * loop exactly as if the proxy did not exist. Never throws anything else,\n * except the caller's own abort.\n */\nasync function proxyRpcCall(\n proxy: ServerRpcProxyState,\n method: string,\n params: unknown,\n callerTimeoutMs: number,\n externalSignal: AbortSignal | undefined,\n validate?: (result: unknown) => boolean\n): Promise {\n const dot = method.indexOf('.')\n if (dot <= 0 || dot === method.length - 1) {\n // Unreachable through setServerRpcProxy (it keeps only dotted names), kept\n // so a future allowlist change fails as a miss rather than a malformed call.\n throw new ProxyMiss('transport', `method without an api prefix: ${method}`)\n }\n // Never wait longer for the proxy than the caller would for one node.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n Math.min(proxy.timeoutMs, callerTimeoutMs)\n )\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n try {\n let res: Response\n try {\n res = await fetch(proxy.url, {\n method: 'POST',\n body: JSON.stringify({ api: method.slice(0, dot), method: method.slice(dot + 1), params }),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders(), ...proxy.headers },\n signal\n })\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'transport', errorMessage(e))\n }\n if (res.status !== 200) {\n // Release the connection: an unconsumed body pins a pooled socket.\n try {\n await res.body?.cancel()\n } catch {\n // nothing to release\n }\n const relayed = res.status === 502 && (res.headers.get('x-ssr-cache') ?? '').toUpperCase() === 'RPCERROR'\n throw new ProxyMiss(relayed ? 'rpcerror' : 'status', relayed ? 'proxy relayed a node error' : `proxy answered ${res.status}`)\n }\n let result: unknown\n try {\n result = await res.json()\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'parse', errorMessage(e))\n }\n if (validate && !validate(result)) {\n throw new ProxyMiss('validate', 'proxy result rejected by validator')\n }\n return result as T\n } finally {\n cleanupTimeout()\n cleanupMerge()\n }\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 // Server-side read-through proxy, when configured and the method is on its\n // allowlist: one call, and on any miss the node loop below runs unchanged.\n // It runs BEFORE the node deadline is taken, so a slow proxy costs its own\n // timeout and nothing of the failover budget the nodes get today.\n // Snapshot: the binding can be cleared by the host while this call awaits.\n const proxy = serverRpcProxy\n if (proxy && isNodeRuntime && proxy.methodSet.has(method)) {\n if (Date.now() < proxyOpenUntil) {\n rpcProxyStats.skipped++\n } else {\n try {\n const served = await proxyRpcCall(proxy, method, params, ceiling, signal, validate)\n rpcProxyStats.served++\n proxyConsecutiveMisses = 0\n return served\n } catch (e: unknown) {\n if (signal?.aborted) throw e\n rpcProxyStats.fallback++\n const reason: string = e instanceof ProxyMiss ? e.reason : 'transport'\n rpcProxyStats.fallbackByReason[reason] = (rpcProxyStats.fallbackByReason[reason] ?? 0) + 1\n if (reason === 'rpcerror') {\n // A relayed node error is a healthy proxy answer: it closes the\n // count like a served call. Crawler-made feed URLs produce these in\n // runs, and counting them opened the breaker on a working proxy.\n proxyConsecutiveMisses = 0\n } else if (++proxyConsecutiveMisses >= proxy.failureThreshold) {\n proxyOpenUntil = Date.now() + proxy.cooldownMs\n proxyConsecutiveMisses = 0\n }\n }\n }\n }\n\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n\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 setServerRpcProxy as setHiveTxServerRpcProxy,\n rpcProxyStats,\n type ResilienceOptions,\n type ServerRpcProxyOptions,\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 * Route allowlisted server-side RPC reads through a read-through cache in\n * front of the node pool (one cache per host, shared by every renderer\n * process). An optimization, never a dependency: any proxy failure falls\n * straight through to the node loop. No effect outside Node; null switches\n * it off. Delegates to the unified hive-tx `setServerRpcProxy`.\n * @param opts - `{ url, headers, timeoutMs, methods }` or null\n */\n export function setServerRpcProxy(opts: ServerRpcProxyOptions | null) {\n setHiveTxServerRpcProxy(opts);\n }\n\n /**\n * The live counters of that proxy path: `served` (answered by the proxy),\n * `fallback` with a per-reason breakdown (the read went to the node pool\n * after a proxy failure) and `skipped` (breaker open). The same object the\n * call path increments, exposed here because the root build carries its own\n * copy of the hive-tx internals; a consumer importing `rpcProxyStats` from\n * the `/hive` entry would read a different, never-incremented instance.\n * Read-only by contract: the web tier prints it, nothing resets it.\n */\n export function getServerRpcProxyStats(): Readonly {\n return rpcProxyStats;\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 /**\n * Optional: set when this operation edits existing content rather than creating it.\n *\n * A `comment` operation is byte-identical for a create and an update, so only the\n * caller knows which it is. When set, no content activity is recorded. Activity\n * rewards content creation. Without this, an edit of content published elsewhere\n * is credited as content created here. Never broadcast.\n */\n isUpdate?: boolean;\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\n * available, unless the payload sets `isUpdate`\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 */\n/**\n * Resolve which content activity a broadcast earns, or `null` for none.\n *\n * Content activity rewards publishing, so an update earns nothing: the `comment`\n * operation an edit broadcasts is indistinguishable from a create on chain, which\n * leaves the caller as the only party that can tell them apart. Without this, editing\n * a post first published on another frontend is credited here as a post.\n */\nexport function resolveContentActivityType(\n payload: Pick\n): 100 | 110 | null {\n if (payload.isUpdate) {\n return null;\n }\n\n return payload.parentAuthor ? 110 : 100;\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 = resolveContentActivityType(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 (activityType !== null && 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 // No activity is recorded here. Activity rewards creating content. Every\n // broadcast from this mutation edits content that already exists.\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 vote_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 vote_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 { 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 {\n RC_RESOURCE_NAMES,\n type RcCostBreakdown,\n type RcResourceName,\n type RcResourceParams\n} from \"../types/resource-params\";\nimport type { RcStats } from \"../types/stats\";\nimport { computeResourceCost } from \"./estimate-comment-rc-cost\";\n\nexport type RcResourceUsage = Record;\n\nexport interface RcPricedUsage {\n cost: number;\n breakdown: RcCostBreakdown[];\n}\n\n/**\n * Turns per-resource usage into an RC cost.\n *\n * This is the single pricing path. Every RC figure the app shows, the publish\n * warning, the comment warning, the vote warning and the credits tooltip, goes\n * through here, so they cannot disagree with each other or with the chain.\n */\nexport function priceRcUsage(\n usage: RcResourceUsage,\n rcParams: RcResourceParams,\n rcStats: Pick\n): RcPricedUsage {\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 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 leaves the safe-integer range.\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 { cost, breakdown };\n}\n","import { utf8ByteLength, varintByteLength } from \"@/modules/core/utf8\";\nimport type { RcResourceName, RcSizeInfo } from \"../types/resource-params\";\nimport type { RcResourceUsage } from \"./price-rc-usage\";\n\n/**\n * Ports of the per-operation arms of `count_resources`\n * (hive/libraries/chain/rc/resource_count.cpp).\n *\n * Every operation charges three things: the serialized transaction size as\n * history_bytes, a per-operation state footprint, and execution time. Only the\n * middle two differ per operation, which is why they live together here.\n */\n\n/** Fixed header: ref_block_num(2) + ref_block_prefix(4) + expiration(4) + extensions varint(1). */\nexport const TRANSACTION_HEADER_BYTES = 11;\nexport const SIGNATURE_BYTES = 65;\n\nexport const stringFieldBytes = (value: string): number => {\n const length = utf8ByteLength(value);\n return varintByteLength(length) + length;\n};\n\nconst emptyUsage = (): RcResourceUsage => ({\n resource_history_bytes: 0,\n resource_new_accounts: 0,\n resource_market_bytes: 0,\n resource_state_bytes: 0,\n resource_execution_time: 0\n});\n\nexport interface VoteLike {\n voter: string;\n author: string;\n permlink: string;\n}\n\n/** Serialized size of a transaction carrying a single vote. */\nexport function estimateVoteTransactionBytes(op: VoteLike, signatures = 1): number {\n const operationBytes =\n 1 + // operation variant id\n stringFieldBytes(op.voter) +\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n 2; // weight, int16\n\n return (\n TRANSACTION_HEADER_BYTES +\n varintByteLength(1) +\n operationBytes +\n varintByteLength(signatures) +\n SIGNATURE_BYTES * signatures\n );\n}\n\n/**\n * A vote's footprint is fixed: `vote_size` state bytes and `vote_time`\n * execution time, regardless of the post being voted on.\n */\nexport function countVoteResourceUsage(\n { transactionBytes, signatures = 1 }: { transactionBytes: number; signatures?: number },\n sizeInfo: RcSizeInfo\n): RcResourceUsage {\n const state = sizeInfo.resource_state_bytes;\n const exec = sizeInfo.resource_execution_time;\n\n return {\n ...emptyUsage(),\n resource_history_bytes: transactionBytes,\n resource_state_bytes: state.vote_size + state.transaction_base_size,\n resource_execution_time:\n exec.vote_time + exec.transaction_time + exec.verify_authority_time * signatures\n };\n}\n\n/** Resource names, re-exported so callers do not reach into the types module. */\nexport type { RcResourceName };\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\nimport type { RcResourceParams } from \"../types/resource-params\";\nimport { priceRcUsage } from \"./price-rc-usage\";\nimport {\n countVoteResourceUsage,\n estimateVoteTransactionBytes,\n type VoteLike\n} from \"./count-operation-usage\";\nimport {\n countCommentResourceUsage,\n estimateCommentTransactionBytes,\n type CommentLike,\n type CommentOptionsLike\n} from \"./estimate-comment-rc-cost\";\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\n/** The operation about to be broadcast, when the caller has it. */\nexport type RcPrecheckPayload =\n | { kind: \"comment\"; op: CommentLike; options?: CommentOptionsLike }\n | { kind: \"vote\"; op: VoteLike };\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 * From `getRcResourceParamsQueryOptions()`. Required for an exact estimate;\n * without it the result is not ready rather than silently approximate.\n */\n rcParams?: RcResourceParams | null;\n /**\n * The actual operation about to be broadcast. Supplying it is what makes the\n * estimate exact, because cost is dominated by the serialized transaction\n * size. Without it a minimal operation of that type is priced instead, which\n * is a lower bound: it can miss a marginal case but never invents one.\n */\n payload?: RcPrecheckPayload;\n /**\n * What to price when no payload is supplied.\n *\n * - `\"minimal\"` (default) prices the smallest operation of that type. It is\n * a lower bound, so a pre-submit warning is never invented for an\n * operation that would have succeeded.\n * - `\"average\"` prices the network average the chain publishes. Right for\n * \"how many of these can I afford\" displays, where there is no specific\n * operation in hand and the smallest conceivable one would flatter the\n * count.\n */\n fallback?: \"minimal\" | \"average\";\n /**\n * Safety multiplier applied to the 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 /**\n * RC cost of the operation itself.\n *\n * Named `avgCost` for backwards compatibility; it is no longer an average.\n * @deprecated prefer `cost`.\n */\n avgCost: number;\n /** RC cost of the operation, computed the way the chain computes it. */\n cost: number;\n /** Serialized transaction size, the dominant term for a comment. */\n transactionBytes: 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 cost: 0,\n transactionBytes: 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 * Costs are computed the way the chain computes them, from the actual\n * operation, not from the network-wide average. The average is dominated by\n * short replies and badly misleads on posts: it once told an account holding\n * 21.3B RC that it could afford 17 posts, and the next post it tried needed\n * 23.3B.\n *\n * Still a hint, never a hard gate: the buffer covers pool drift between the\n * estimate and the broadcast, and the publish/comment/vote action must stay\n * non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n rcParams,\n operation,\n payload,\n fallback = \"minimal\",\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\n const priced = priceOperation(operation, payload, fallback, rcParams, rcStats);\n if (!priced) {\n // Nothing to price against: reporting \"ready\" here would be a silent\n // all-clear, which is the one answer a pre-check must never invent.\n return { ...EMPTY, currentMana, maxMana };\n }\n\n const { cost, transactionBytes } = priced;\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = cost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost: cost,\n cost,\n transactionBytes,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / cost),\n };\n}\n\n/**\n * Prices whichever operation the caller is about to broadcast.\n *\n * Comments and votes are the two operations whose cost swings with what the\n * user wrote, so they are priced from the payload, and pricing them needs the\n * curve parameters. Every other operation the type advertises (transfer,\n * custom_json, ...) is fixed-shape and takes the network average the chain\n * publishes, which needs nothing else.\n *\n * When no payload is supplied a minimal operation is priced. That is\n * deliberately a lower bound: it can miss a marginal case, but it never warns\n * about one that would have succeeded.\n *\n * Returns null when the answer would have to be invented, so the caller\n * reports \"not ready\" rather than a zero-cost all-clear.\n */\nfunction priceOperation(\n operation: RcPrecheckOperation,\n payload: RcPrecheckPayload | undefined,\n fallback: \"minimal\" | \"average\",\n rcParams: RcResourceParams | null | undefined,\n rcStats: RcStats\n): { cost: number; transactionBytes: number } | null {\n const average = averageCost(rcStats, operation);\n const pricedFromPayload =\n operation === \"comment_operation\" || operation === \"vote_operation\";\n\n // The average is a number the node already returned. It needs no curve\n // parameters, so a caller pricing a transfer must not be blocked waiting on\n // them, which is how every operation outside these two is priced.\n if (!pricedFromPayload || (!payload && fallback === \"average\")) {\n return average;\n }\n\n // Asked to price a real comment or vote without the inputs to do it. The\n // honest answer is \"not ready\": falling back to the average here is exactly\n // what told an account holding 21.3B RC it could afford 17 more posts.\n if (!rcParams?.resource_params || !rcParams.size_info || !rcStats.pool || !rcStats.share) {\n return null;\n }\n\n const stats = { pool: rcStats.pool, regen: rcStats.regen, share: rcStats.share };\n\n if (operation === \"vote_operation\") {\n const op: VoteLike = payload?.kind === \"vote\" ? payload.op : MINIMAL_VOTE;\n const transactionBytes = estimateVoteTransactionBytes(op);\n const usage = countVoteResourceUsage({ transactionBytes }, rcParams.size_info);\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n }\n\n const op: CommentLike = payload?.kind === \"comment\" ? payload.op : MINIMAL_COMMENT;\n const options = payload?.kind === \"comment\" ? payload.options : undefined;\n const transactionBytes = estimateCommentTransactionBytes({ op, options });\n const usage = countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength: op.permlink.length,\n beneficiaries: options?.beneficiaries?.length ?? 0,\n hasCommentOptions: !!options\n },\n rcParams.size_info\n );\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n}\n\n/** The network average the chain publishes for an operation, when it has one. */\nfunction averageCost(\n rcStats: RcStats,\n operation: RcPrecheckOperation\n): { cost: number; transactionBytes: number } | null {\n const cost = rcStats.ops[operation]?.avg_cost;\n return typeof cost === \"number\" && cost > 0 ? { cost, transactionBytes: 0 } : null;\n}\n\n/** Smallest realistic operations, used only when the caller has no payload yet. */\nconst MINIMAL_COMMENT: CommentLike = {\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\",\n parent_author: \"\",\n parent_permlink: \"hive-100000\",\n title: \"\",\n body: \"\",\n json_metadata: \"{}\"\n};\n\nconst MINIMAL_VOTE: VoteLike = {\n voter: \"aaaaaaaaaa\",\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\"\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\n/**\n * POST a single game claim and return the parsed JSON body.\n *\n * A failed post-game comes back from the edge as an HTML gateway page (a 502 was\n * the trail on ECENCY-NEXT-1FCJ), and `response.json()` on that throws a bare\n * `SyntaxError` naming neither the endpoint nor the cause. Check the status and\n * the content type first, then fail with a STABLE, low-cardinality message\n * (content type + status, never the raw body) so these group as a single Sentry\n * issue instead of fragmenting on every distinct error page.\n *\n * Exported for unit testing; the hook below wraps it.\n */\nexport async function gameClaimRequest(\n code: string,\n gameType: \"spin\",\n key: string\n): Promise {\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 // 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 // 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 page.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Games] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Games] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body) as GameClaim;\n } catch {\n throw new Error(\n `[SDK][Games] – malformed JSON response (status ${response.status})`\n );\n }\n}\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 return gameClaimRequest(code, gameType, key);\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","/**\n * Thresholds behind the content moderation treatment. Single source of truth for\n * every client: web and mobile previously carried their own copies, which drifted\n * (mobile flagged downvoted content at -7B rshares and 4 voters where web used\n * -10B and 5), so the same post read differently depending on the app.\n */\n\n/** Sum of rshares below which a post counts as heavily downvoted. */\nexport const HIDDEN_POST_RSHARES_THRESHOLD = -10000000000;\n\n/** Downvoting is only conclusive once enough accounts have voted. */\nexport const HIDDEN_POST_MIN_VOTES = 5;\n\n/**\n * Reputation (human-readable 0-100 scale) below which an author counts as\n * low-trust. New Hive accounts start around 25.\n *\n * NOTE: reputation is the only input. Account age is NOT part of the check, so a\n * years-old account that never earned reputation trips it exactly like a fresh\n * one. User-facing copy must say \"low reputation\", never \"new account\".\n */\nexport const LOW_TRUST_REPUTATION_THRESHOLD = 30;\n","/**\n * Converts Hive's raw reputation to the human-readable 0-100 scale, passing\n * through values that are already on it (the bridge returns both shapes\n * depending on the endpoint).\n */\nconst isHumanReadable = (input: number): boolean =>\n Math.abs(input) > 0 && Math.abs(input) <= 100;\n\nexport function accountReputation(input: string | number): number {\n if (typeof input === \"number\" && isHumanReadable(input)) {\n return Math.floor(input);\n }\n\n if (typeof input === \"string\") {\n input = Number(input);\n\n if (isHumanReadable(input)) {\n return Math.floor(input);\n }\n }\n\n if (input === 0) {\n return 25;\n }\n\n let neg = false;\n\n if (input < 0) {\n neg = true;\n }\n\n let reputationLevel = Math.log10(Math.abs(input as number));\n reputationLevel = Math.max(reputationLevel - 9, 0);\n\n if (reputationLevel < 0) {\n reputationLevel = 0;\n }\n\n if (neg) {\n reputationLevel *= -1;\n }\n\n reputationLevel = reputationLevel * 9 + 25;\n\n return Math.floor(reputationLevel);\n}\n","/**\n * Outbound-link detection for the SEO/backlink-farm signal.\n *\n * A link only counts as outbound promotion when it leaves the Hive/Ecency\n * ecosystem and is not an embedded image, so ordinary on-platform references and\n * post illustrations never trip the check.\n */\n\n// Hosts that are part of the Hive/Ecency ecosystem.\nconst INTERNAL_HOSTS = [\n \"ecency.com\",\n \"ecency.app\",\n \"hive.blog\",\n \"hive.io\",\n \"hiveblocks.com\",\n \"peakd.com\",\n \"snapie.io\",\n \"hivesuite.app\",\n \"leofinance.io\",\n \"inleo.io\",\n \"3speak.tv\",\n \"d.buzz\",\n \"waivio.com\"\n];\n\n// Image/media hosts: an embedded image is content, not a backlink.\nconst IMAGE_HOSTS = [\n \"imgur.com\",\n \"images.hive.blog\",\n \"files.peakd.com\",\n \"i.ecency.com\",\n \"images.ecency.com\",\n \"steemitimages.com\",\n \"cdn.steemitimages.com\",\n \"media.giphy.com\"\n];\n\nconst IMAGE_EXT_RE = /\\.(jpe?g|png|gif|webp|svg|bmp|avif)(\\?|#|$)/i;\n// Match absolute AND protocol-relative URLs (\"//host/...\"), so the check can't be\n// evaded with `[promo](//shop.example)` (the renderer allows protocol-relative hrefs).\nconst URL_RE = /(?:https?:)?\\/\\/[^\\s)<>\"'\\]]+/gi;\n// URLs in prose are commonly followed by punctuation (\"https://ecency.com, and...\");\n// strip it so the host parses correctly and internal links do not false-positive.\nconst TRAILING_PUNCT_RE = /[.,;:!?'\"]+$/;\n\nfunction hostOf(url: string): string {\n const m = /^(?:https?:)?\\/\\/([^/?#]+)/i.exec(url);\n return m ? m[1].toLowerCase().replace(/^www\\./, \"\") : \"\";\n}\n\nfunction isExternalPromoLink(rawUrl: string): boolean {\n const url = rawUrl.replace(TRAILING_PUNCT_RE, \"\");\n if (IMAGE_EXT_RE.test(url)) {\n return false; // embedded image, not a backlink\n }\n const host = hostOf(url);\n if (!host.includes(\".\")) {\n return false; // not a real domain (e.g. a stray \"//something\")\n }\n const matches = (h: string) => host === h || host.endsWith(\".\" + h);\n if (INTERNAL_HOSTS.some(matches) || IMAGE_HOSTS.some(matches)) {\n return false; // Hive/Ecency or image host\n }\n return true;\n}\n\n/** True if the post body contains an outbound (non-Hive, non-image) link. */\nexport function hasExternalLink(body: string | undefined | null): boolean {\n if (!body) {\n return false;\n }\n const matches = body.match(URL_RE);\n if (!matches) {\n return false;\n }\n return matches.some(isExternalPromoLink);\n}\n","import { accountReputation } from \"./account-reputation\";\nimport {\n HIDDEN_POST_MIN_VOTES,\n HIDDEN_POST_RSHARES_THRESHOLD,\n LOW_TRUST_REPUTATION_THRESHOLD\n} from \"./constants\";\nimport { hasExternalLink } from \"./external-links\";\n\n/**\n * Why a piece of content gets the moderation treatment. Clients render their own\n * copy per reason; the rules that pick the reason live here so web and mobile\n * always agree on which one fired.\n */\nexport enum ContentModerationReason {\n /**\n * `stats.gray` / `stats.hide` from hivemind: community moderator mutes, mutes\n * applied by the observer account, and authors hivemind itself grays out.\n */\n MOD_MUTED = \"mod_muted\",\n /** Heavily downvoted by enough distinct accounts to be conclusive. */\n DOWNVOTED = \"downvoted\",\n /** Low-reputation author whose post carries an outbound promotional link. */\n LOW_TRUST = \"low_trust\"\n}\n\n/**\n * The fields of a post or comment the rules read. Deliberately structural: web\n * passes an `Entry`, mobile passes a raw bridge post, and neither has to convert.\n */\nexport interface ModerationCandidate {\n author?: string;\n author_reputation?: string | number;\n body?: string | null;\n net_rshares?: number;\n active_votes?: unknown[] | null;\n stats?: {\n gray?: boolean;\n hide?: boolean;\n total_votes?: number;\n } | null;\n}\n\n/**\n * hivemind's `total_votes` is the authoritative count when present; `active_votes`\n * is the fallback for the feeds that omit stats.\n */\nfunction countVotes(content: ModerationCandidate): number {\n return content?.stats?.total_votes ?? content?.active_votes?.length ?? 0;\n}\n\n/** Heavily downvoted: strongly negative rshares from more than a handful of voters. */\nexport function isHiddenPost(\n netRshares: number | undefined,\n activeVotesLength: number\n): boolean {\n return (\n (netRshares ?? 0) < HIDDEN_POST_RSHARES_THRESHOLD &&\n activeVotesLength >= HIDDEN_POST_MIN_VOTES\n );\n}\n\n/**\n * Content-moderation signal for SEO/backlink-farm abuse: low-reputation accounts\n * publishing an outbound link are the signature of free-faucet SEO spam.\n *\n * Such posts are not blocked, they are de-emphasized and their outbound link is\n * flagged as unverified, so the promotional payoff drops to zero. Low reputation\n * on its own is NOT a moderation signal: plenty of small accounts post ordinary\n * content, and dimming all of them punishes newcomers for existing.\n */\nexport function isLowTrustSeoPost(\n content: Pick\n): boolean {\n const reputation = content?.author_reputation;\n // Some feeds omit reputation entirely. An unknown value is not evidence of\n // anything, so it must not be read as \"brand new account\" (raw 0 scales to 25,\n // which is below the threshold and would flag every post carrying a link).\n if (reputation === undefined || reputation === null) {\n return false;\n }\n return (\n accountReputation(reputation) < LOW_TRUST_REPUTATION_THRESHOLD &&\n hasExternalLink(content?.body)\n );\n}\n\n/** True when the viewer has personally muted this author. */\nexport function isAuthorMuted(\n author: string | undefined,\n mutedAuthors: string[] | undefined | null\n): boolean {\n return !!author && !!mutedAuthors?.includes(author);\n}\n\n/**\n * The reason a post or comment should be de-emphasized, or null when it is fine.\n *\n * Precedence, most authoritative first: an explicit moderation action outranks\n * the vote heuristic, which outranks the spam heuristic. Order matters because a\n * heavily downvoted post usually also has a battered reputation, and labelling\n * that \"low trust\" would hide why the content was actually flagged.\n *\n * A viewer's personal mute list is NOT an input here. Muting an author removes\n * their content from the viewer's lists entirely (see `isAuthorMuted`), rather\n * than labelling it.\n */\nexport function getContentModerationReason(\n content: ModerationCandidate | undefined | null\n): ContentModerationReason | null {\n if (!content) {\n return null;\n }\n if (content.stats?.gray || content.stats?.hide) {\n return ContentModerationReason.MOD_MUTED;\n }\n if (isHiddenPost(content.net_rshares, countVotes(content))) {\n return ContentModerationReason.DOWNVOTED;\n }\n if (isLowTrustSeoPost(content)) {\n return ContentModerationReason.LOW_TRUST;\n }\n return null;\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-comment-rc-cost.ts","../../src/modules/resource-credits/utils/price-rc-usage.ts","../../src/modules/resource-credits/utils/count-operation-usage.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","../../src/modules/moderation/constants.ts","../../src/modules/moderation/account-reputation.ts","../../src/modules/moderation/external-links.ts","../../src/modules/moderation/content-moderation.ts","../../src/modules/newsletter/api.ts","../../src/modules/newsletter/queries/get-digest-subscriptions-query-options.ts","../../src/modules/newsletter/queries/get-newsletter-sender-query-options.ts","../../src/modules/newsletter/queries/get-newsletter-issues-query-options.ts","../../src/modules/newsletter/queries/get-newsletter-posts-query-options.ts","../../src/modules/newsletter/mutations/use-subscribe-digest.ts","../../src/modules/newsletter/mutations/use-leave-digest.ts","../../src/modules/newsletter/mutations/use-unsubscribe-all-digests.ts","../../src/modules/newsletter/mutations/use-send-newsletter-issue.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","DEFAULT_SERVER_RPC_PROXY_METHODS","serverRpcProxy","setServerRpcProxy","opts","url","headers","k","v","timeoutMs","methods","m","pos","fallback","sanitizeNodeList","nodes","n","setNodes","validNodes","setRestNodes","valid","setRestNodesByApi","map","api","list","setUserAgent","ua","setResilience","r","bool","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","rpcProxyStats","ProxyMiss","reason","errorMessage","proxyConsecutiveMisses","proxyOpenUntil","proxyRpcCall","proxy","method","params","callerTimeoutMs","externalSignal","validate","dot","tSignal","cleanupTimeout","createTimeoutSignal","signal","cleanupMerge","mergeSignals","res","e","relayed","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","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","tryRecordHeadBlock","block","createTimeoutReason","err","controller","timer","primary","secondary","onPrimaryAbort","onSecondaryAbort","cleanup","jsonRPCCall","timeout","shouldRetry","body","jitterDelay","hedgedRpcAttempt","hedgePool","explicitTimeout","deadlineAt","onHedgeFired","reject","done","pendingLegs","hedgeFired","primarySettled","lastError","hedgeTimer","primaryStart","controllers","finish","settle","startLeg","isHedge","merged","legTimeout","primaryWindow","delay","live","callRPC","retry","ceiling","served","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","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","timeoutSignal","ac","onAbort","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","getServerRpcProxyStats","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","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","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","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","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","resolveContentActivityType","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","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","EMPTY","estimateCommentRcCost","rcParams","rcStats","usage","regen","cost","breakdown","share","scaled","resourceCost","priceRcUsage","emptyUsage","estimateVoteTransactionBytes","operationBytes","countVoteResourceUsage","estimateRcPrecheck","priced","priceOperation","safeBuffer","estimatedCost","willLikelyFail","average","averageCost","MINIMAL_VOTE","MINIMAL_COMMENT","getGameStatusCheckQueryOptions","gameClaimRequest","contentType","detail","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","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","HIDDEN_POST_RSHARES_THRESHOLD","HIDDEN_POST_MIN_VOTES","LOW_TRUST_REPUTATION_THRESHOLD","isHumanReadable","accountReputation","neg","reputationLevel","INTERNAL_HOSTS","IMAGE_HOSTS","IMAGE_EXT_RE","URL_RE","TRAILING_PUNCT_RE","hostOf","isExternalPromoLink","rawUrl","hasExternalLink","ContentModerationReason","countVotes","isHiddenPost","netRshares","activeVotesLength","isLowTrustSeoPost","reputation","isAuthorMuted","mutedAuthors","getContentModerationReason","NewsletterApiError","NewsletterSendRefusedError","taken","newsletterUrl","parse","subscribeDigestRequest","getDigestSubscriptionsRequest","leaveDigestRequest","unsubscribeAllDigestsRequest","getNewsletterSenderRequest","getNewsletterIssuesRequest","getNewsletterPostsRequest","postSend","request","previewNewsletterSendRequest","sendNewsletterIssueRequest","getDigestSubscriptionsQueryOptions","getNewsletterSenderQueryOptions","getNewsletterIssuesQueryOptions","getNewsletterPostsQueryOptions","useSubscribeDigest","useLeaveDigest","useUnsubscribeAllDigests","usePreviewNewsletterIssue","useSendNewsletterIssue"],"mappings":"whBASA,IAAMA,GAAe,IAAI,WAAA,CAAY,CAAC,CAAA,CAIlCC,EAAAA,CAAqD,IAAA,CACrDC,EAAAA,CAAuD,IAAA,CAE3D,SAASC,IAAgD,CACvD,OAAKF,KACC,OAAO,WAAA,CAAgB,IACzBA,EAAAA,CAAW,IAAI,WAAA,CAEfA,EAAAA,CAAW,CACT,MAAA,CAAOG,EAAuB,CAE5B,IAAMC,EAAiB,EAAC,CACxB,QAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIF,CAAAA,CAAE,MAAA,CAAQE,CAAAA,EAAAA,CAAK,CACjC,IAAIC,CAAAA,CAAIH,EAAE,UAAA,CAAWE,CAAC,EACtB,GAAIC,CAAAA,CAAI,GAAA,CACNF,CAAAA,CAAK,IAAA,CAAKE,CAAC,UACFA,CAAAA,CAAI,IAAA,CACbF,EAAK,IAAA,CAAK,GAAA,CAAQE,GAAK,CAAA,CAAI,GAAA,CAAQA,CAAAA,CAAI,EAAK,CAAA,CAAA,KAAA,GACnCA,CAAAA,EAAK,OAAUA,CAAAA,EAAK,KAAA,EAAUD,EAAI,CAAA,CAAIF,CAAAA,CAAE,OAAQ,CACzD,IAAMI,CAAAA,CAAOJ,CAAAA,CAAE,UAAA,CAAW,EAAEE,CAAC,CAAA,CAC7BC,CAAAA,CAAI,KAAA,EAAA,CAAYA,CAAAA,CAAI,IAAA,GAAU,EAAA,CAAA,EAAOC,EAAO,IAAA,CAAA,CAC5CH,CAAAA,CAAK,IAAA,CAAK,GAAA,CAAQE,CAAAA,EAAK,EAAA,CAAK,IAASA,CAAAA,EAAK,EAAA,CAAM,GAAO,GAAA,CAASA,CAAAA,EAA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AcC,cAAAA,EAAe,CAC7BpU,CAAAA,CAAO3R,GAAU,OAAA,CAAQ,GAAA,CAAK,EAAE,CAAA,CAEtC,OAAOiJ,WAAAA,CAAY,CACjB,WAAA,CAAa,CAAC,YAAA,CAAc,MAAA,CAAQ0I,CAAI,CAAA,CACxC,UAAA,CAAY,MAAO6rC,CAAAA,EAAmC,CACpD,GAAI,CAAC7rC,CAAAA,EAAQ,CAACtb,EACZ,MAAM,IAAI,KAAA,CAAM,uCAAkC,CAAA,CAEpD,OAAOqnD,GAA2BF,CAAAA,CAASnnD,CAAI,CACjD,CAAA,CACA,SAAA,CAAU+4B,CAAAA,CAASouB,EAAS,CAC1B13B,CAAAA,CAAY,iBAAA,CAAkB,CAC5B,QAAA,CAAUrX,CAAAA,CAAU,WAAW,MAAA,CAAO+uC,CAAAA,CAAQ,IAAA,CAAMA,CAAAA,CAAQ,MAAA,CAAQ7rC,CAAI,CAC1E,CAAC,CAAA,CACDmU,CAAAA,CAAY,iBAAA,CAAkB,CAC5B,QAAA,CAAUrX,EAAU,UAAA,CAAW,MAAA,CAAO+uC,CAAAA,CAAQ,IAAA,CAAMA,CAAAA,CAAQ,MAAA,CAAQ7rC,CAAI,CAC1E,CAAC,EACH,CACF,CAAC,CACH","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 * Server-side read-through proxy for RPC reads (see `setServerRpcProxy`).\n * `methods` is the allowlist the proxy serves; a read outside it goes straight\n * to the node pool as before.\n */\nexport interface ServerRpcProxyOptions {\n /** Absolute URL of the proxy endpoint (POST `{api, method, params}`). */\n url: string\n /** Headers sent with every proxy call (the shared internal secret). */\n headers: Record\n /** Per-call timeout in ms; on expiry the read falls back to the node pool. */\n timeoutMs: number\n /** Fully qualified method names (`bridge.get_post`) the proxy may answer;\n * omitted = DEFAULT_SERVER_RPC_PROXY_METHODS. An empty list is ignored. */\n methods?: string[]\n /**\n * After this many consecutive proxy misses the proxy is skipped for\n * `cooldownMs`, so a proxy that is down costs one failed call per cooldown\n * window rather than one per read. Default 3 / 10s. A served call resets it.\n */\n failureThreshold?: number\n cooldownMs?: number\n}\n\n/** Default allowlist: the reads a server render makes and the proxy caches. */\nexport const DEFAULT_SERVER_RPC_PROXY_METHODS: readonly string[] = [\n 'bridge.get_ranked_posts',\n 'bridge.get_account_posts',\n 'bridge.get_post',\n 'bridge.get_discussion',\n 'bridge.get_profile',\n 'bridge.get_profiles',\n 'bridge.get_community',\n 'bridge.list_communities',\n 'condenser_api.get_accounts',\n 'condenser_api.get_content',\n 'condenser_api.get_dynamic_global_properties',\n 'condenser_api.get_trending_tags'\n]\n\n/**\n * Active proxy configuration, or null (the default: every read goes to the node\n * pool). Lives outside `config` so the browser bundle never carries it; it is\n * only ever consulted under Node.\n */\nexport interface ServerRpcProxyState extends Required {\n methodSet: Set\n}\n\nexport let serverRpcProxy: ServerRpcProxyState | null = null\n\n/**\n * Route allowlisted server-side reads through a read-through cache in front\n * of the node pool. One cache per host answers the reads every renderer\n * process used to make on its own; a miss there is one upstream call shared by\n * every concurrent reader. The proxy is an optimization, never a dependency:\n * any failure (non-200, timeout, transport error, a response the caller's\n * validator rejects) falls straight through to the existing node loop, so the\n * worst case is the latency of a failed proxy call on top of what happens\n * today. Has no effect outside Node. Pass null to switch it off.\n */\nexport const setServerRpcProxy = (opts: ServerRpcProxyOptions | null): void => {\n if (opts === null) {\n serverRpcProxy = null\n return\n }\n if (!opts || typeof opts !== 'object') return\n const url = typeof opts.url === 'string' ? opts.url.trim() : ''\n if (!/^https?:\\/\\//i.test(url)) return\n const headers: Record = {}\n if (opts.headers && typeof opts.headers === 'object') {\n for (const [k, v] of Object.entries(opts.headers)) {\n if (typeof v === 'string' && v && !/[\\u0000-\\u001f\\u007f]/.test(v) && !/[\\u0000-\\u001f\\u007f]/.test(k)) {\n headers[k] = v\n }\n }\n }\n const timeoutMs =\n typeof opts.timeoutMs === 'number' && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0\n ? opts.timeoutMs\n : 2_000\n const methods =\n opts.methods === undefined\n ? [...DEFAULT_SERVER_RPC_PROXY_METHODS]\n : Array.isArray(opts.methods)\n ? opts.methods.filter((m): m is string => typeof m === 'string' && m.includes('.'))\n : []\n // Nothing to route through the proxy: keep whatever was configured before.\n if (methods.length === 0) return\n const pos = (v: unknown, fallback: number): number =>\n typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : fallback\n serverRpcProxy = {\n url,\n headers,\n timeoutMs,\n methods,\n failureThreshold: Math.floor(pos(opts.failureThreshold, 3)),\n cooldownMs: pos(opts.cooldownMs, 10_000),\n methodSet: new Set(methods)\n }\n}\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, serverRpcProxy, type ServerRpcProxyState } 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// ── Server-side read-through proxy ──────────────────────────────────────────\n\n/**\n * Counters for the proxy path, readable by a host's diagnostics (the web\n * tier's event-loop monitor prints them). `served` = answered by the proxy,\n * `fallback` = proxy configured and eligible but the read went to the node\n * pool, with the reason.\n */\nexport const rpcProxyStats = {\n served: 0,\n fallback: 0,\n /** Reads that went straight to the nodes because the breaker was open. */\n skipped: 0,\n fallbackByReason: { status: 0, rpcerror: 0, timeout: 0, transport: 0, validate: 0, parse: 0 } as Record\n}\n\n/**\n * `rpcerror` is a 502 tagged `X-Ssr-Cache: RPCERROR`: the proxy reached a node\n * and relayed the node's own error (a tag or post that does not exist, a bad\n * argument). The read still falls back so the caller sees the node's answer\n * unchanged, but the proxy was healthy, so it does not count toward the\n * breaker; the other reasons do.\n */\ntype ProxyMissReason = 'status' | 'rpcerror' | 'timeout' | 'transport' | 'validate' | 'parse'\n\nclass ProxyMiss extends Error {\n constructor(\n public reason: ProxyMissReason,\n message: string\n ) {\n super(message)\n }\n}\n\nconst errorMessage = (e: unknown): string =>\n e instanceof Error ? e.message : typeof e === 'string' ? e : String(e)\n\n// Breaker: consecutive misses open it for the configured cooldown, a served\n// call closes it. Module state, like the health tracker: one per process.\nlet proxyConsecutiveMisses = 0\nlet proxyOpenUntil = 0\n\n/** Test seam: forget breaker state. */\nexport function resetRpcProxyBreaker(): void {\n proxyConsecutiveMisses = 0\n proxyOpenUntil = 0\n}\n\n/**\n * One proxy call for an eligible read. Resolves with the upstream `result` the\n * proxy served, or throws ProxyMiss; the caller then continues with the node\n * loop exactly as if the proxy did not exist. Never throws anything else,\n * except the caller's own abort.\n */\nasync function proxyRpcCall(\n proxy: ServerRpcProxyState,\n method: string,\n params: unknown,\n callerTimeoutMs: number,\n externalSignal: AbortSignal | undefined,\n validate?: (result: unknown) => boolean\n): Promise {\n const dot = method.indexOf('.')\n if (dot <= 0 || dot === method.length - 1) {\n // Unreachable through setServerRpcProxy (it keeps only dotted names), kept\n // so a future allowlist change fails as a miss rather than a malformed call.\n throw new ProxyMiss('transport', `method without an api prefix: ${method}`)\n }\n // Never wait longer for the proxy than the caller would for one node.\n const { signal: tSignal, cleanup: cleanupTimeout } = createTimeoutSignal(\n Math.min(proxy.timeoutMs, callerTimeoutMs)\n )\n const { signal, cleanup: cleanupMerge } = mergeSignals(tSignal, externalSignal)\n try {\n let res: Response\n try {\n res = await fetch(proxy.url, {\n method: 'POST',\n body: JSON.stringify({ api: method.slice(0, dot), method: method.slice(dot + 1), params }),\n headers: { 'Content-Type': 'application/json', ...serverIdentityHeaders(), ...proxy.headers },\n signal\n })\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'transport', errorMessage(e))\n }\n if (res.status !== 200) {\n // Release the connection: an unconsumed body pins a pooled socket.\n try {\n await res.body?.cancel()\n } catch {\n // nothing to release\n }\n const relayed = res.status === 502 && (res.headers.get('x-ssr-cache') ?? '').toUpperCase() === 'RPCERROR'\n throw new ProxyMiss(relayed ? 'rpcerror' : 'status', relayed ? 'proxy relayed a node error' : `proxy answered ${res.status}`)\n }\n let result: unknown\n try {\n result = await res.json()\n } catch (e: unknown) {\n if (externalSignal?.aborted) throw e\n throw new ProxyMiss(tSignal.aborted ? 'timeout' : 'parse', errorMessage(e))\n }\n if (validate && !validate(result)) {\n throw new ProxyMiss('validate', 'proxy result rejected by validator')\n }\n return result as T\n } finally {\n cleanupTimeout()\n cleanupMerge()\n }\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 // Server-side read-through proxy, when configured and the method is on its\n // allowlist: one call, and on any miss the node loop below runs unchanged.\n // It runs BEFORE the node deadline is taken, so a slow proxy costs its own\n // timeout and nothing of the failover budget the nodes get today.\n // Snapshot: the binding can be cleared by the host while this call awaits.\n const proxy = serverRpcProxy\n if (proxy && isNodeRuntime && proxy.methodSet.has(method)) {\n if (Date.now() < proxyOpenUntil) {\n rpcProxyStats.skipped++\n } else {\n try {\n const served = await proxyRpcCall(proxy, method, params, ceiling, signal, validate)\n rpcProxyStats.served++\n proxyConsecutiveMisses = 0\n return served\n } catch (e: unknown) {\n if (signal?.aborted) throw e\n rpcProxyStats.fallback++\n const reason: string = e instanceof ProxyMiss ? e.reason : 'transport'\n rpcProxyStats.fallbackByReason[reason] = (rpcProxyStats.fallbackByReason[reason] ?? 0) + 1\n if (reason === 'rpcerror') {\n // A relayed node error is a healthy proxy answer: it closes the\n // count like a served call. Crawler-made feed URLs produce these in\n // runs, and counting them opened the breaker on a working proxy.\n proxyConsecutiveMisses = 0\n } else if (++proxyConsecutiveMisses >= proxy.failureThreshold) {\n proxyOpenUntil = Date.now() + proxy.cooldownMs\n proxyConsecutiveMisses = 0\n }\n }\n }\n }\n\n const deadline = Date.now() + config.resilience.totalBudgetFactor * ceiling\n\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 setServerRpcProxy as setHiveTxServerRpcProxy,\n rpcProxyStats,\n type ResilienceOptions,\n type ServerRpcProxyOptions,\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 * Route allowlisted server-side RPC reads through a read-through cache in\n * front of the node pool (one cache per host, shared by every renderer\n * process). An optimization, never a dependency: any proxy failure falls\n * straight through to the node loop. No effect outside Node; null switches\n * it off. Delegates to the unified hive-tx `setServerRpcProxy`.\n * @param opts - `{ url, headers, timeoutMs, methods }` or null\n */\n export function setServerRpcProxy(opts: ServerRpcProxyOptions | null) {\n setHiveTxServerRpcProxy(opts);\n }\n\n /**\n * The live counters of that proxy path: `served` (answered by the proxy),\n * `fallback` with a per-reason breakdown (the read went to the node pool\n * after a proxy failure) and `skipped` (breaker open). The same object the\n * call path increments, exposed here because the root build carries its own\n * copy of the hive-tx internals; a consumer importing `rpcProxyStats` from\n * the `/hive` entry would read a different, never-incremented instance.\n * Read-only by contract: the web tier prints it, nothing resets it.\n */\n export function getServerRpcProxyStats(): Readonly {\n return rpcProxyStats;\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 // Newsletter (digest subscriptions + sender API)\n // ===========================================================================\n newsletter: {\n subscriptions: (username: string | undefined) => [\n \"newsletter\",\n \"subscriptions\",\n username,\n ],\n sender: (type: string, target: string, username: string | undefined) => [\n \"newsletter\",\n \"sender\",\n type,\n target,\n username,\n ],\n issues: (type: string, target: string, username: string | undefined) => [\n \"newsletter\",\n \"issues\",\n type,\n target,\n username,\n ],\n posts: (\n type: string,\n target: string,\n username: string | undefined,\n limit: number,\n ) => [\"newsletter\", \"posts\", type, target, username, limit],\n _prefix: [\"newsletter\"],\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 /**\n * The viewing user; exclude authors they currently mute. Ecency's own\n * moderation mutes are applied by esync regardless of this value, so leaving\n * it unset drops the viewer's personal mutes, not the platform ones.\n */\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 /**\n * The viewing user; exclude authors they currently mute. Ecency's own\n * moderation mutes are applied by esync regardless of this value.\n */\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 /**\n * Optional: set when this operation edits existing content rather than creating it.\n *\n * A `comment` operation is byte-identical for a create and an update, so only the\n * caller knows which it is. When set, no content activity is recorded. Activity\n * rewards content creation. Without this, an edit of content published elsewhere\n * is credited as content created here. Never broadcast.\n */\n isUpdate?: boolean;\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\n * available, unless the payload sets `isUpdate`\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 */\n/**\n * Resolve which content activity a broadcast earns, or `null` for none.\n *\n * Content activity rewards publishing, so an update earns nothing: the `comment`\n * operation an edit broadcasts is indistinguishable from a create on chain, which\n * leaves the caller as the only party that can tell them apart. Without this, editing\n * a post first published on another frontend is credited here as a post.\n */\nexport function resolveContentActivityType(\n payload: Pick\n): 100 | 110 | null {\n if (payload.isUpdate) {\n return null;\n }\n\n return payload.parentAuthor ? 110 : 100;\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 = resolveContentActivityType(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 (activityType !== null && 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 // No activity is recorded here. Activity rewards creating content. Every\n // broadcast from this mutation edits content that already exists.\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 vote_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 vote_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 { 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 {\n RC_RESOURCE_NAMES,\n type RcCostBreakdown,\n type RcResourceName,\n type RcResourceParams\n} from \"../types/resource-params\";\nimport type { RcStats } from \"../types/stats\";\nimport { computeResourceCost } from \"./estimate-comment-rc-cost\";\n\nexport type RcResourceUsage = Record;\n\nexport interface RcPricedUsage {\n cost: number;\n breakdown: RcCostBreakdown[];\n}\n\n/**\n * Turns per-resource usage into an RC cost.\n *\n * This is the single pricing path. Every RC figure the app shows, the publish\n * warning, the comment warning, the vote warning and the credits tooltip, goes\n * through here, so they cannot disagree with each other or with the chain.\n */\nexport function priceRcUsage(\n usage: RcResourceUsage,\n rcParams: RcResourceParams,\n rcStats: Pick\n): RcPricedUsage {\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 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 leaves the safe-integer range.\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 { cost, breakdown };\n}\n","import { utf8ByteLength, varintByteLength } from \"@/modules/core/utf8\";\nimport type { RcResourceName, RcSizeInfo } from \"../types/resource-params\";\nimport type { RcResourceUsage } from \"./price-rc-usage\";\n\n/**\n * Ports of the per-operation arms of `count_resources`\n * (hive/libraries/chain/rc/resource_count.cpp).\n *\n * Every operation charges three things: the serialized transaction size as\n * history_bytes, a per-operation state footprint, and execution time. Only the\n * middle two differ per operation, which is why they live together here.\n */\n\n/** Fixed header: ref_block_num(2) + ref_block_prefix(4) + expiration(4) + extensions varint(1). */\nexport const TRANSACTION_HEADER_BYTES = 11;\nexport const SIGNATURE_BYTES = 65;\n\nexport const stringFieldBytes = (value: string): number => {\n const length = utf8ByteLength(value);\n return varintByteLength(length) + length;\n};\n\nconst emptyUsage = (): RcResourceUsage => ({\n resource_history_bytes: 0,\n resource_new_accounts: 0,\n resource_market_bytes: 0,\n resource_state_bytes: 0,\n resource_execution_time: 0\n});\n\nexport interface VoteLike {\n voter: string;\n author: string;\n permlink: string;\n}\n\n/** Serialized size of a transaction carrying a single vote. */\nexport function estimateVoteTransactionBytes(op: VoteLike, signatures = 1): number {\n const operationBytes =\n 1 + // operation variant id\n stringFieldBytes(op.voter) +\n stringFieldBytes(op.author) +\n stringFieldBytes(op.permlink) +\n 2; // weight, int16\n\n return (\n TRANSACTION_HEADER_BYTES +\n varintByteLength(1) +\n operationBytes +\n varintByteLength(signatures) +\n SIGNATURE_BYTES * signatures\n );\n}\n\n/**\n * A vote's footprint is fixed: `vote_size` state bytes and `vote_time`\n * execution time, regardless of the post being voted on.\n */\nexport function countVoteResourceUsage(\n { transactionBytes, signatures = 1 }: { transactionBytes: number; signatures?: number },\n sizeInfo: RcSizeInfo\n): RcResourceUsage {\n const state = sizeInfo.resource_state_bytes;\n const exec = sizeInfo.resource_execution_time;\n\n return {\n ...emptyUsage(),\n resource_history_bytes: transactionBytes,\n resource_state_bytes: state.vote_size + state.transaction_base_size,\n resource_execution_time:\n exec.vote_time + exec.transaction_time + exec.verify_authority_time * signatures\n };\n}\n\n/** Resource names, re-exported so callers do not reach into the types module. */\nexport type { RcResourceName };\n","import { calculateRCMana } from \"@/modules/core/hive-tx\";\nimport type { RCAccount } from \"@/modules/core/hive-tx\";\nimport type { RcStats } from \"../types/stats\";\nimport type { RcResourceParams } from \"../types/resource-params\";\nimport { priceRcUsage } from \"./price-rc-usage\";\nimport {\n countVoteResourceUsage,\n estimateVoteTransactionBytes,\n type VoteLike\n} from \"./count-operation-usage\";\nimport {\n countCommentResourceUsage,\n estimateCommentTransactionBytes,\n type CommentLike,\n type CommentOptionsLike\n} from \"./estimate-comment-rc-cost\";\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\n/** The operation about to be broadcast, when the caller has it. */\nexport type RcPrecheckPayload =\n | { kind: \"comment\"; op: CommentLike; options?: CommentOptionsLike }\n | { kind: \"vote\"; op: VoteLike };\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 * From `getRcResourceParamsQueryOptions()`. Required for an exact estimate;\n * without it the result is not ready rather than silently approximate.\n */\n rcParams?: RcResourceParams | null;\n /**\n * The actual operation about to be broadcast. Supplying it is what makes the\n * estimate exact, because cost is dominated by the serialized transaction\n * size. Without it a minimal operation of that type is priced instead, which\n * is a lower bound: it can miss a marginal case but never invents one.\n */\n payload?: RcPrecheckPayload;\n /**\n * What to price when no payload is supplied.\n *\n * - `\"minimal\"` (default) prices the smallest operation of that type. It is\n * a lower bound, so a pre-submit warning is never invented for an\n * operation that would have succeeded.\n * - `\"average\"` prices the network average the chain publishes. Right for\n * \"how many of these can I afford\" displays, where there is no specific\n * operation in hand and the smallest conceivable one would flatter the\n * count.\n */\n fallback?: \"minimal\" | \"average\";\n /**\n * Safety multiplier applied to the 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 /**\n * RC cost of the operation itself.\n *\n * Named `avgCost` for backwards compatibility; it is no longer an average.\n * @deprecated prefer `cost`.\n */\n avgCost: number;\n /** RC cost of the operation, computed the way the chain computes it. */\n cost: number;\n /** Serialized transaction size, the dominant term for a comment. */\n transactionBytes: 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 cost: 0,\n transactionBytes: 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 * Costs are computed the way the chain computes them, from the actual\n * operation, not from the network-wide average. The average is dominated by\n * short replies and badly misleads on posts: it once told an account holding\n * 21.3B RC that it could afford 17 posts, and the next post it tried needed\n * 23.3B.\n *\n * Still a hint, never a hard gate: the buffer covers pool drift between the\n * estimate and the broadcast, and the publish/comment/vote action must stay\n * non-blocking.\n */\nexport function estimateRcPrecheck({\n rcAccount,\n rcStats,\n rcParams,\n operation,\n payload,\n fallback = \"minimal\",\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\n const priced = priceOperation(operation, payload, fallback, rcParams, rcStats);\n if (!priced) {\n // Nothing to price against: reporting \"ready\" here would be a silent\n // all-clear, which is the one answer a pre-check must never invent.\n return { ...EMPTY, currentMana, maxMana };\n }\n\n const { cost, transactionBytes } = priced;\n const safeBuffer = Number.isFinite(buffer) && buffer > 0 ? buffer : 1.2;\n const estimatedCost = cost * safeBuffer;\n const willLikelyFail = currentMana < estimatedCost;\n\n return {\n ready: true,\n currentMana,\n maxMana,\n avgCost: cost,\n cost,\n transactionBytes,\n estimatedCost,\n willLikelyFail,\n deficit: willLikelyFail ? Math.ceil(estimatedCost - currentMana) : 0,\n remaining: Math.floor(currentMana / cost),\n };\n}\n\n/**\n * Prices whichever operation the caller is about to broadcast.\n *\n * Comments and votes are the two operations whose cost swings with what the\n * user wrote, so they are priced from the payload, and pricing them needs the\n * curve parameters. Every other operation the type advertises (transfer,\n * custom_json, ...) is fixed-shape and takes the network average the chain\n * publishes, which needs nothing else.\n *\n * When no payload is supplied a minimal operation is priced. That is\n * deliberately a lower bound: it can miss a marginal case, but it never warns\n * about one that would have succeeded.\n *\n * Returns null when the answer would have to be invented, so the caller\n * reports \"not ready\" rather than a zero-cost all-clear.\n */\nfunction priceOperation(\n operation: RcPrecheckOperation,\n payload: RcPrecheckPayload | undefined,\n fallback: \"minimal\" | \"average\",\n rcParams: RcResourceParams | null | undefined,\n rcStats: RcStats\n): { cost: number; transactionBytes: number } | null {\n const average = averageCost(rcStats, operation);\n const pricedFromPayload =\n operation === \"comment_operation\" || operation === \"vote_operation\";\n\n // The average is a number the node already returned. It needs no curve\n // parameters, so a caller pricing a transfer must not be blocked waiting on\n // them, which is how every operation outside these two is priced.\n if (!pricedFromPayload || (!payload && fallback === \"average\")) {\n return average;\n }\n\n // Asked to price a real comment or vote without the inputs to do it. The\n // honest answer is \"not ready\": falling back to the average here is exactly\n // what told an account holding 21.3B RC it could afford 17 more posts.\n if (!rcParams?.resource_params || !rcParams.size_info || !rcStats.pool || !rcStats.share) {\n return null;\n }\n\n const stats = { pool: rcStats.pool, regen: rcStats.regen, share: rcStats.share };\n\n if (operation === \"vote_operation\") {\n const op: VoteLike = payload?.kind === \"vote\" ? payload.op : MINIMAL_VOTE;\n const transactionBytes = estimateVoteTransactionBytes(op);\n const usage = countVoteResourceUsage({ transactionBytes }, rcParams.size_info);\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n }\n\n const op: CommentLike = payload?.kind === \"comment\" ? payload.op : MINIMAL_COMMENT;\n const options = payload?.kind === \"comment\" ? payload.options : undefined;\n const transactionBytes = estimateCommentTransactionBytes({ op, options });\n const usage = countCommentResourceUsage(\n {\n transactionBytes,\n permlinkLength: op.permlink.length,\n beneficiaries: options?.beneficiaries?.length ?? 0,\n hasCommentOptions: !!options\n },\n rcParams.size_info\n );\n return { cost: priceRcUsage(usage, rcParams, stats).cost, transactionBytes };\n}\n\n/** The network average the chain publishes for an operation, when it has one. */\nfunction averageCost(\n rcStats: RcStats,\n operation: RcPrecheckOperation\n): { cost: number; transactionBytes: number } | null {\n const cost = rcStats.ops[operation]?.avg_cost;\n return typeof cost === \"number\" && cost > 0 ? { cost, transactionBytes: 0 } : null;\n}\n\n/** Smallest realistic operations, used only when the caller has no payload yet. */\nconst MINIMAL_COMMENT: CommentLike = {\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\",\n parent_author: \"\",\n parent_permlink: \"hive-100000\",\n title: \"\",\n body: \"\",\n json_metadata: \"{}\"\n};\n\nconst MINIMAL_VOTE: VoteLike = {\n voter: \"aaaaaaaaaa\",\n author: \"aaaaaaaaaa\",\n permlink: \"aaaaaaaaaaaaaaaaaaaa\"\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\n/**\n * POST a single game claim and return the parsed JSON body.\n *\n * A failed post-game comes back from the edge as an HTML gateway page (a 502 was\n * the trail on ECENCY-NEXT-1FCJ), and `response.json()` on that throws a bare\n * `SyntaxError` naming neither the endpoint nor the cause. Check the status and\n * the content type first, then fail with a STABLE, low-cardinality message\n * (content type + status, never the raw body) so these group as a single Sentry\n * issue instead of fragmenting on every distinct error page.\n *\n * Exported for unit testing; the hook below wraps it.\n */\nexport async function gameClaimRequest(\n code: string,\n gameType: \"spin\",\n key: string\n): Promise {\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 // 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 // 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 page.\n const detail =\n body && contentType.includes(\"json\") ? `: ${body.slice(0, 200)}` : \"\";\n throw new Error(\n `[SDK][Games] – failed with status ${response.status}${detail}`\n );\n }\n\n if (!contentType.includes(\"json\")) {\n throw new Error(\n `[SDK][Games] – expected JSON but received \"${contentType || \"empty\"}\" response (status ${response.status})`\n );\n }\n\n try {\n return JSON.parse(body) as GameClaim;\n } catch {\n throw new Error(\n `[SDK][Games] – malformed JSON response (status ${response.status})`\n );\n }\n}\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 return gameClaimRequest(code, gameType, key);\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","/**\n * Thresholds behind the content moderation treatment. Single source of truth for\n * every client: web and mobile previously carried their own copies, which drifted\n * (mobile flagged downvoted content at -7B rshares and 4 voters where web used\n * -10B and 5), so the same post read differently depending on the app.\n */\n\n/** Sum of rshares below which a post counts as heavily downvoted. */\nexport const HIDDEN_POST_RSHARES_THRESHOLD = -10000000000;\n\n/** Downvoting is only conclusive once enough accounts have voted. */\nexport const HIDDEN_POST_MIN_VOTES = 5;\n\n/**\n * Reputation (human-readable 0-100 scale) below which an author counts as\n * low-trust. New Hive accounts start around 25.\n *\n * NOTE: reputation is the only input. Account age is NOT part of the check, so a\n * years-old account that never earned reputation trips it exactly like a fresh\n * one. User-facing copy must say \"low reputation\", never \"new account\".\n */\nexport const LOW_TRUST_REPUTATION_THRESHOLD = 30;\n","/**\n * Converts Hive's raw reputation to the human-readable 0-100 scale, passing\n * through values that are already on it (the bridge returns both shapes\n * depending on the endpoint).\n */\nconst isHumanReadable = (input: number): boolean =>\n Math.abs(input) > 0 && Math.abs(input) <= 100;\n\nexport function accountReputation(input: string | number): number {\n if (typeof input === \"number\" && isHumanReadable(input)) {\n return Math.floor(input);\n }\n\n if (typeof input === \"string\") {\n input = Number(input);\n\n if (isHumanReadable(input)) {\n return Math.floor(input);\n }\n }\n\n if (input === 0) {\n return 25;\n }\n\n let neg = false;\n\n if (input < 0) {\n neg = true;\n }\n\n let reputationLevel = Math.log10(Math.abs(input as number));\n reputationLevel = Math.max(reputationLevel - 9, 0);\n\n if (reputationLevel < 0) {\n reputationLevel = 0;\n }\n\n if (neg) {\n reputationLevel *= -1;\n }\n\n reputationLevel = reputationLevel * 9 + 25;\n\n return Math.floor(reputationLevel);\n}\n","/**\n * Outbound-link detection for the SEO/backlink-farm signal.\n *\n * A link only counts as outbound promotion when it leaves the Hive/Ecency\n * ecosystem and is not an embedded image, so ordinary on-platform references and\n * post illustrations never trip the check.\n */\n\n// Hosts that are part of the Hive/Ecency ecosystem.\nconst INTERNAL_HOSTS = [\n \"ecency.com\",\n \"ecency.app\",\n \"hive.blog\",\n \"hive.io\",\n \"hiveblocks.com\",\n \"peakd.com\",\n \"snapie.io\",\n \"hivesuite.app\",\n \"leofinance.io\",\n \"inleo.io\",\n \"3speak.tv\",\n \"d.buzz\",\n \"waivio.com\"\n];\n\n// Image/media hosts: an embedded image is content, not a backlink.\nconst IMAGE_HOSTS = [\n \"imgur.com\",\n \"images.hive.blog\",\n \"files.peakd.com\",\n \"i.ecency.com\",\n \"images.ecency.com\",\n \"steemitimages.com\",\n \"cdn.steemitimages.com\",\n \"media.giphy.com\"\n];\n\nconst IMAGE_EXT_RE = /\\.(jpe?g|png|gif|webp|svg|bmp|avif)(\\?|#|$)/i;\n// Match absolute AND protocol-relative URLs (\"//host/...\"), so the check can't be\n// evaded with `[promo](//shop.example)` (the renderer allows protocol-relative hrefs).\nconst URL_RE = /(?:https?:)?\\/\\/[^\\s)<>\"'\\]]+/gi;\n// URLs in prose are commonly followed by punctuation (\"https://ecency.com, and...\");\n// strip it so the host parses correctly and internal links do not false-positive.\nconst TRAILING_PUNCT_RE = /[.,;:!?'\"]+$/;\n\nfunction hostOf(url: string): string {\n const m = /^(?:https?:)?\\/\\/([^/?#]+)/i.exec(url);\n return m ? m[1].toLowerCase().replace(/^www\\./, \"\") : \"\";\n}\n\nfunction isExternalPromoLink(rawUrl: string): boolean {\n const url = rawUrl.replace(TRAILING_PUNCT_RE, \"\");\n if (IMAGE_EXT_RE.test(url)) {\n return false; // embedded image, not a backlink\n }\n const host = hostOf(url);\n if (!host.includes(\".\")) {\n return false; // not a real domain (e.g. a stray \"//something\")\n }\n const matches = (h: string) => host === h || host.endsWith(\".\" + h);\n if (INTERNAL_HOSTS.some(matches) || IMAGE_HOSTS.some(matches)) {\n return false; // Hive/Ecency or image host\n }\n return true;\n}\n\n/** True if the post body contains an outbound (non-Hive, non-image) link. */\nexport function hasExternalLink(body: string | undefined | null): boolean {\n if (!body) {\n return false;\n }\n const matches = body.match(URL_RE);\n if (!matches) {\n return false;\n }\n return matches.some(isExternalPromoLink);\n}\n","import { accountReputation } from \"./account-reputation\";\nimport {\n HIDDEN_POST_MIN_VOTES,\n HIDDEN_POST_RSHARES_THRESHOLD,\n LOW_TRUST_REPUTATION_THRESHOLD\n} from \"./constants\";\nimport { hasExternalLink } from \"./external-links\";\n\n/**\n * Why a piece of content gets the moderation treatment. Clients render their own\n * copy per reason; the rules that pick the reason live here so web and mobile\n * always agree on which one fired.\n */\nexport enum ContentModerationReason {\n /**\n * `stats.gray` / `stats.hide` from hivemind: community moderator mutes, mutes\n * applied by the observer account, and authors hivemind itself grays out.\n */\n MOD_MUTED = \"mod_muted\",\n /** Heavily downvoted by enough distinct accounts to be conclusive. */\n DOWNVOTED = \"downvoted\",\n /** Low-reputation author whose post carries an outbound promotional link. */\n LOW_TRUST = \"low_trust\"\n}\n\n/**\n * The fields of a post or comment the rules read. Deliberately structural: web\n * passes an `Entry`, mobile passes a raw bridge post, and neither has to convert.\n */\nexport interface ModerationCandidate {\n author?: string;\n author_reputation?: string | number;\n body?: string | null;\n net_rshares?: number;\n active_votes?: unknown[] | null;\n stats?: {\n gray?: boolean;\n hide?: boolean;\n total_votes?: number;\n } | null;\n}\n\n/**\n * hivemind's `total_votes` is the authoritative count when present; `active_votes`\n * is the fallback for the feeds that omit stats.\n */\nfunction countVotes(content: ModerationCandidate): number {\n return content?.stats?.total_votes ?? content?.active_votes?.length ?? 0;\n}\n\n/** Heavily downvoted: strongly negative rshares from more than a handful of voters. */\nexport function isHiddenPost(\n netRshares: number | undefined,\n activeVotesLength: number\n): boolean {\n return (\n (netRshares ?? 0) < HIDDEN_POST_RSHARES_THRESHOLD &&\n activeVotesLength >= HIDDEN_POST_MIN_VOTES\n );\n}\n\n/**\n * Content-moderation signal for SEO/backlink-farm abuse: low-reputation accounts\n * publishing an outbound link are the signature of free-faucet SEO spam.\n *\n * Such posts are not blocked, they are de-emphasized and their outbound link is\n * flagged as unverified, so the promotional payoff drops to zero. Low reputation\n * on its own is NOT a moderation signal: plenty of small accounts post ordinary\n * content, and dimming all of them punishes newcomers for existing.\n */\nexport function isLowTrustSeoPost(\n content: Pick\n): boolean {\n const reputation = content?.author_reputation;\n // Some feeds omit reputation entirely. An unknown value is not evidence of\n // anything, so it must not be read as \"brand new account\" (raw 0 scales to 25,\n // which is below the threshold and would flag every post carrying a link).\n if (reputation === undefined || reputation === null) {\n return false;\n }\n return (\n accountReputation(reputation) < LOW_TRUST_REPUTATION_THRESHOLD &&\n hasExternalLink(content?.body)\n );\n}\n\n/** True when the viewer has personally muted this author. */\nexport function isAuthorMuted(\n author: string | undefined,\n mutedAuthors: string[] | undefined | null\n): boolean {\n return !!author && !!mutedAuthors?.includes(author);\n}\n\n/**\n * The reason a post or comment should be de-emphasized, or null when it is fine.\n *\n * Precedence, most authoritative first: an explicit moderation action outranks\n * the vote heuristic, which outranks the spam heuristic. Order matters because a\n * heavily downvoted post usually also has a battered reputation, and labelling\n * that \"low trust\" would hide why the content was actually flagged.\n *\n * A viewer's personal mute list is NOT an input here. Muting an author removes\n * their content from the viewer's lists entirely (see `isAuthorMuted`), rather\n * than labelling it.\n */\nexport function getContentModerationReason(\n content: ModerationCandidate | undefined | null\n): ContentModerationReason | null {\n if (!content) {\n return null;\n }\n if (content.stats?.gray || content.stats?.hide) {\n return ContentModerationReason.MOD_MUTED;\n }\n if (isHiddenPost(content.net_rshares, countVotes(content))) {\n return ContentModerationReason.DOWNVOTED;\n }\n if (isLowTrustSeoPost(content)) {\n return ContentModerationReason.LOW_TRUST;\n }\n return null;\n}\n","import { CONFIG, getBoundFetch } from \"@/modules/core\";\nimport type {\n DigestSubscribeInput,\n DigestSubscribeResult,\n DigestSubscription,\n NewsletterCandidatePost,\n NewsletterListType,\n NewsletterSendPreview,\n NewsletterSendRequest,\n NewsletterSendResult,\n NewsletterSenderStanding,\n NewsletterSentIssue,\n} from \"./types\";\n\n/**\n * Client for the newsletter relay at {privateApiHost}/api/newsletter/*\n * (Next.js route handlers on ecency.com, which alone hold the news-service\n * credentials — clients never talk to the service directly).\n *\n * Identity is the HiveSigner access token, passed here as the explicit `code`\n * argument. Transport mirrors the deployed web client per route: subscribe and\n * unsubscribe-all carry it in the POST body as `code` (the subscribe route\n * authenticates ONLY from the body — a header alone is treated as anonymous);\n * every other call, the send/preview POSTs included, uses the `X-HS-Token`\n * header. The relay verifies it upstream and derives the account from it, so\n * a stale token 401s — callers are responsible for supplying a fresh one\n * (web: ensureValidToken; mobile: the token-refresh wrapper).\n *\n * The email-token confirm/unsubscribe flows are deliberately absent: those\n * links land on web pages.\n */\nexport class NewsletterApiError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly data?: unknown,\n ) {\n super(message);\n }\n}\n\n/** A refused send, carrying the relay's routing `code` (already_sent, suspended, ...). */\nexport class NewsletterSendRefusedError extends NewsletterApiError {\n constructor(\n message: string,\n status: number,\n public readonly code?: string,\n public readonly taken?: Array<{ cadence: string; period: string; kind: string }>,\n data?: unknown,\n ) {\n super(message, status, data);\n }\n}\n\nfunction newsletterUrl(path: string): string {\n return `${CONFIG.privateApiHost}/api/newsletter${path}`;\n}\n\nasync function parse(response: Response): Promise {\n const data = (await response.json().catch(() => undefined)) as\n | (T & { error?: string })\n | undefined;\n if (!response.ok) {\n throw new NewsletterApiError(\n data?.error || `Request failed (${response.status})`,\n response.status,\n data,\n );\n }\n // A 2xx without a JSON body is not a result; saying so beats returning blanks.\n if (!data || typeof data !== \"object\") {\n throw new NewsletterApiError(\n `Unexpected response (${response.status})`,\n response.status,\n );\n }\n return data;\n}\n\n/**\n * Subscribe an address to a digest. Authenticated callers (code given) skip\n * the captcha; anonymous callers must supply `captchaToken` in the input and\n * get double opt-in. The `own` digest type is always authenticated.\n */\nexport async function subscribeDigestRequest(\n input: DigestSubscribeInput,\n code?: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(\"/subscribe\"), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ ...input, ...(code ? { code } : {}) }),\n });\n return parse(response);\n}\n\n/** Every live digest subscription attributed to the token's account. */\nexport async function getDigestSubscriptionsRequest(\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(\"/subscriptions\"), {\n headers: { \"X-HS-Token\": code },\n });\n const data = await parse<{ subscriptions?: DigestSubscription[] }>(response);\n return data.subscriptions ?? [];\n}\n\n/** Leave one digest by subscription id. */\nexport async function leaveDigestRequest(\n id: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(`/subscriptions/${encodeURIComponent(id)}`),\n { method: \"DELETE\", headers: { \"X-HS-Token\": code } },\n );\n await parse<{ left: boolean }>(response);\n}\n\n/**\n * Suppress ONE address entirely (no Ecency bulk mail to it again). Only that\n * address stops: an account can hold subscriptions under several addresses.\n */\nexport async function unsubscribeAllDigestsRequest(\n email: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(\"/unsubscribe-all\"), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email, code }),\n });\n await parse<{ suppressed: boolean }>(response);\n}\n\n/** Sender standing (status, complaint/bounce stats, subscriber counts) for a list. */\nexport async function getNewsletterSenderRequest(\n type: NewsletterListType,\n target: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(`/sender?type=${type}&target=${encodeURIComponent(target)}`),\n { headers: { \"X-HS-Token\": code } },\n );\n return parse(response);\n}\n\n/** Already-sent issues for a list, newest first. */\nexport async function getNewsletterIssuesRequest(\n type: NewsletterListType,\n target: string,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(`/issues?type=${type}&target=${encodeURIComponent(target)}`),\n { headers: { \"X-HS-Token\": code } },\n );\n const data = await parse<{ issues?: NewsletterSentIssue[] }>(response);\n return data.issues ?? [];\n}\n\n/** Candidate posts for composing a digest issue. */\nexport async function getNewsletterPostsRequest(\n type: NewsletterListType,\n target: string,\n code: string,\n limit = 20,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(\n newsletterUrl(\n `/posts?type=${type}&target=${encodeURIComponent(target)}&limit=${limit}`,\n ),\n { headers: { \"X-HS-Token\": code } },\n );\n const data = await parse<{ posts?: NewsletterCandidatePost[] }>(response);\n return data.posts ?? [];\n}\n\nasync function postSend(\n path: string,\n request: NewsletterSendRequest,\n code: string,\n): Promise {\n const fetchApi = getBoundFetch();\n const response = await fetchApi(newsletterUrl(path), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", \"X-HS-Token\": code },\n body: JSON.stringify(request),\n });\n const data = (await response.json().catch(() => undefined)) as\n | (T & {\n error?: string;\n code?: string;\n taken?: NewsletterSendRefusedError[\"taken\"];\n })\n | undefined;\n if (!response.ok) {\n throw new NewsletterSendRefusedError(\n data?.error || `Request failed (${response.status})`,\n response.status,\n data?.code,\n data?.taken,\n data,\n );\n }\n if (!data || typeof data !== \"object\") {\n throw new NewsletterSendRefusedError(\n `Unexpected response (${response.status})`,\n response.status,\n );\n }\n return data;\n}\n\n/** Render the would-be issue (subject/html/text, counts, taken periods) without sending. */\nexport function previewNewsletterSendRequest(\n request: NewsletterSendRequest,\n code: string,\n): Promise {\n return postSend(\"/send/preview\", request, code);\n}\n\n/** Send a post or composed digest to the list's subscribers. Pro/team gated by the relay. */\nexport function sendNewsletterIssueRequest(\n request: NewsletterSendRequest,\n code: string,\n): Promise {\n return postSend(\"/send\", request, code);\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getDigestSubscriptionsRequest } from \"../api\";\n\n/**\n * The signed-in account's live digest subscriptions. Disabled without a\n * username + token: callers render nothing then, and a request that\n * predictably 401s is noise. `retry: false` because the common failure is a\n * stale token, which a retry with the same token cannot fix.\n */\nexport function getDigestSubscriptionsQueryOptions(\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.subscriptions(name),\n enabled: !!name && !!code,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getDigestSubscriptionsRequest(code);\n },\n staleTime: 60_000,\n retry: false,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getNewsletterSenderRequest } from \"../api\";\nimport type { NewsletterListType } from \"../types\";\n\n/**\n * Sender standing for a creator/community list. View access is the list's\n * owner (creator) or the community team, decided by the relay — enable this\n * only for callers already known to be the sender.\n */\nexport function getNewsletterSenderQueryOptions(\n type: NewsletterListType,\n target: string,\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.sender(type, target, name),\n enabled: !!name && !!code && !!target,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getNewsletterSenderRequest(type, target, code);\n },\n staleTime: 5 * 60_000,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getNewsletterIssuesRequest } from \"../api\";\nimport type { NewsletterListType } from \"../types\";\n\n/** Already-sent issues for a creator/community list (sender-only view). */\nexport function getNewsletterIssuesQueryOptions(\n type: NewsletterListType,\n target: string,\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.issues(type, target, name),\n enabled: !!name && !!code && !!target,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getNewsletterIssuesRequest(type, target, code);\n },\n staleTime: 60_000,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { queryOptions } from \"@tanstack/react-query\";\nimport { getNewsletterPostsRequest } from \"../api\";\nimport type { NewsletterListType } from \"../types\";\n\n/** Candidate posts for composing a digest issue (send-gated by the relay). */\nexport function getNewsletterPostsQueryOptions(\n type: NewsletterListType,\n target: string,\n username: string | undefined,\n code: string | undefined,\n limit = 20,\n) {\n const name = username?.replace(\"@\", \"\");\n return queryOptions({\n queryKey: QueryKeys.newsletter.posts(type, target, name, limit),\n enabled: !!name && !!code && !!target,\n queryFn: async () => {\n if (!code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return getNewsletterPostsRequest(type, target, code, limit);\n },\n staleTime: 60_000,\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { subscribeDigestRequest } from \"../api\";\nimport type { DigestSubscribeInput } from \"../types\";\n\n/**\n * Subscribe to a digest (also re-used to change cadence: same list + address\n * with a new cadence updates the row). Works signed-in (code) and anonymous\n * (input.captchaToken); the signed-in path refreshes the account's\n * subscriptions list on success.\n */\nexport function useSubscribeDigest(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"subscribe\", name],\n mutationFn: (input: DigestSubscribeInput) =>\n subscribeDigestRequest(input, code),\n onSuccess() {\n if (name) {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.newsletter.subscriptions(name),\n });\n }\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { leaveDigestRequest } from \"../api\";\nimport type { DigestSubscription } from \"../types\";\n\n/** Leave one digest by subscription id; drops the row from the cached list. */\nexport function useLeaveDigest(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"leave\", name],\n mutationFn: async (id: string) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return leaveDigestRequest(id, code);\n },\n onSuccess(_result, id) {\n queryClient.setQueryData(\n QueryKeys.newsletter.subscriptions(name),\n (prev) => (prev ?? []).filter((s) => s.id !== id),\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { unsubscribeAllDigestsRequest } from \"../api\";\nimport type { DigestSubscription } from \"../types\";\n\n/**\n * Stop all Ecency mail to ONE address. Only that address's rows leave the\n * cached list: an account can hold subscriptions under more than one address,\n * and those stay visible.\n */\nexport function useUnsubscribeAllDigests(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"unsubscribe-all\", name],\n mutationFn: async (email: string) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return unsubscribeAllDigestsRequest(email, code);\n },\n onSuccess(_result, email) {\n queryClient.setQueryData(\n QueryKeys.newsletter.subscriptions(name),\n (prev) =>\n (prev ?? []).filter(\n (s) => s.email.toLowerCase() !== email.toLowerCase(),\n ),\n );\n },\n });\n}\n","import { QueryKeys } from \"@/modules/core\";\nimport { useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport {\n previewNewsletterSendRequest,\n sendNewsletterIssueRequest,\n} from \"../api\";\nimport type { NewsletterSendRequest } from \"../types\";\n\n/**\n * Preview the would-be issue. No cache side effects: a preview changes\n * nothing server-side.\n */\nexport function usePreviewNewsletterIssue(\n username: string | undefined,\n code: string | undefined,\n) {\n const name = username?.replace(\"@\", \"\");\n return useMutation({\n mutationKey: [\"newsletter\", \"send-preview\", name],\n mutationFn: async (request: NewsletterSendRequest) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return previewNewsletterSendRequest(request, code);\n },\n });\n}\n\n/**\n * Send a post or composed digest to a list. Errors are\n * NewsletterSendRefusedError with the relay's routing `code`\n * (already_sent + taken periods, suspended, post_refused, ...). On success the\n * list's issues + sender standing refresh.\n */\nexport function useSendNewsletterIssue(\n username: string | undefined,\n code: string | undefined,\n) {\n const queryClient = useQueryClient();\n const name = username?.replace(\"@\", \"\");\n\n return useMutation({\n mutationKey: [\"newsletter\", \"send\", name],\n mutationFn: async (request: NewsletterSendRequest) => {\n if (!name || !code) {\n throw new Error(\"[SDK][Newsletter] – missing auth\");\n }\n return sendNewsletterIssueRequest(request, code);\n },\n onSuccess(_result, request) {\n queryClient.invalidateQueries({\n queryKey: QueryKeys.newsletter.issues(request.type, request.target, name),\n });\n queryClient.invalidateQueries({\n queryKey: QueryKeys.newsletter.sender(request.type, request.target, name),\n });\n },\n });\n}\n"]} \ No newline at end of file diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 531b465a46..e31445e318 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -1,7 +1,7 @@ { "name": "@ecency/sdk", "private": false, - "version": "2.3.91", + "version": "2.3.92", "description": "Ecency SDK", "repository": { "type": "git", diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index 4964d85e88..e5088f462e 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -25,3 +25,4 @@ export * from "./modules/hive-engine"; export * from "./modules/bad-actors"; export * from "./modules/polls"; export * from "./modules/moderation"; +export * from "./modules/newsletter"; diff --git a/packages/sdk/src/modules/core/query-keys.ts b/packages/sdk/src/modules/core/query-keys.ts index 07b4b4e4af..0b0fd254a0 100644 --- a/packages/sdk/src/modules/core/query-keys.ts +++ b/packages/sdk/src/modules/core/query-keys.ts @@ -586,6 +586,38 @@ export const QueryKeys = { status: (username: string | undefined) => ["quests", "status", username], }, + // =========================================================================== + // Newsletter (digest subscriptions + sender API) + // =========================================================================== + newsletter: { + subscriptions: (username: string | undefined) => [ + "newsletter", + "subscriptions", + username, + ], + sender: (type: string, target: string, username: string | undefined) => [ + "newsletter", + "sender", + type, + target, + username, + ], + issues: (type: string, target: string, username: string | undefined) => [ + "newsletter", + "issues", + type, + target, + username, + ], + posts: ( + type: string, + target: string, + username: string | undefined, + limit: number, + ) => ["newsletter", "posts", type, target, username, limit], + _prefix: ["newsletter"], + }, + // =========================================================================== // Support Ecency // =========================================================================== diff --git a/packages/sdk/src/modules/newsletter/api.spec.ts b/packages/sdk/src/modules/newsletter/api.spec.ts new file mode 100644 index 0000000000..7f26ba9ded --- /dev/null +++ b/packages/sdk/src/modules/newsletter/api.spec.ts @@ -0,0 +1,279 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + NewsletterApiError, + NewsletterSendRefusedError, + getDigestSubscriptionsRequest, + getNewsletterIssuesRequest, + getNewsletterPostsRequest, + getNewsletterSenderRequest, + leaveDigestRequest, + previewNewsletterSendRequest, + sendNewsletterIssueRequest, + subscribeDigestRequest, + unsubscribeAllDigestsRequest, +} from "./api"; +import type { DigestSubscribeInput } from "./types"; + +const INPUT: DigestSubscribeInput = { + email: "alice@example.com", + type: "creator", + target: "alice", + cadence: "weekly", + source: "mobile-app", +}; + +function okJson(body: unknown) { + return { ok: true, status: 200, json: async () => body }; +} + +function errJson(status: number, body: unknown) { + return { ok: false, status, json: async () => body }; +} + +describe("newsletter api", () => { + // getBoundFetch() caches the bound fetch on first call, so reuse one stable mock + // and reset it per test (a fresh mock each test wouldn't be picked up). + const fetchMock = vi.fn(); + + beforeEach(() => { + fetchMock.mockReset(); + vi.stubGlobal("fetch", fetchMock); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + }); + + describe("subscribeDigestRequest", () => { + it("POSTs to /api/newsletter/subscribe with the input and the code in the BODY", async () => { + fetchMock.mockResolvedValueOnce(okJson({ status: "active" })); + + const result = await subscribeDigestRequest(INPUT, "hs-token"); + + const [url, init] = fetchMock.mock.calls[0]; + expect(String(url)).toContain("/api/newsletter/subscribe"); + expect((init as RequestInit).method).toBe("POST"); + // The subscribe route authenticates ONLY from the body, never the header. + expect((init as RequestInit).headers).not.toHaveProperty("X-HS-Token"); + const payload = JSON.parse((init as RequestInit).body as string); + expect(payload).toEqual({ ...INPUT, code: "hs-token" }); + expect(result).toEqual({ status: "active" }); + }); + + it("omits the code field entirely for anonymous callers", async () => { + fetchMock.mockResolvedValueOnce( + okJson({ status: "pending_confirmation" }), + ); + + await subscribeDigestRequest({ ...INPUT, captchaToken: "tt" }); + + const payload = JSON.parse( + (fetchMock.mock.calls[0][1] as RequestInit).body as string, + ); + expect(payload).not.toHaveProperty("code"); + expect(payload.captchaToken).toBe("tt"); + }); + + it("throws NewsletterApiError with status + data on a non-2xx", async () => { + fetchMock.mockResolvedValueOnce(errJson(403, { error: "Security check failed" })); + + const promise = subscribeDigestRequest(INPUT); + await expect(promise).rejects.toBeInstanceOf(NewsletterApiError); + await expect(promise).rejects.toMatchObject({ + status: 403, + message: "Security check failed", + }); + }); + }); + + describe("getDigestSubscriptionsRequest", () => { + it("GETs /api/newsletter/subscriptions with the X-HS-Token header", async () => { + fetchMock.mockResolvedValueOnce(okJson({ subscriptions: [{ id: "a" }] })); + + const result = await getDigestSubscriptionsRequest("hs-token"); + + const [url, init] = fetchMock.mock.calls[0]; + expect(String(url)).toContain("/api/newsletter/subscriptions"); + expect((init as RequestInit).method).toBeUndefined(); + expect((init as RequestInit).headers).toMatchObject({ + "X-HS-Token": "hs-token", + }); + expect(result).toEqual([{ id: "a" }]); + }); + + it("returns [] when the relay answers without a subscriptions array", async () => { + fetchMock.mockResolvedValueOnce(okJson({})); + expect(await getDigestSubscriptionsRequest("t")).toEqual([]); + }); + }); + + describe("leaveDigestRequest", () => { + it("DELETEs the URL-encoded subscription id with the header token", async () => { + fetchMock.mockResolvedValueOnce(okJson({ left: true })); + + await leaveDigestRequest("id/with slash", "hs-token"); + + const [url, init] = fetchMock.mock.calls[0]; + expect(String(url)).toContain( + "/api/newsletter/subscriptions/id%2Fwith%20slash", + ); + expect((init as RequestInit).method).toBe("DELETE"); + expect((init as RequestInit).headers).toMatchObject({ + "X-HS-Token": "hs-token", + }); + }); + }); + + describe("unsubscribeAllDigestsRequest", () => { + it("POSTs {email, code} to /api/newsletter/unsubscribe-all", async () => { + fetchMock.mockResolvedValueOnce(okJson({ suppressed: true })); + + await unsubscribeAllDigestsRequest("alice@example.com", "hs-token"); + + const [url, init] = fetchMock.mock.calls[0]; + expect(String(url)).toContain("/api/newsletter/unsubscribe-all"); + expect((init as RequestInit).method).toBe("POST"); + expect(JSON.parse((init as RequestInit).body as string)).toEqual({ + email: "alice@example.com", + code: "hs-token", + }); + }); + }); + + describe("getNewsletterSenderRequest", () => { + it("GETs /api/newsletter/sender with type + encoded target and the header token", async () => { + fetchMock.mockResolvedValueOnce(okJson({ status: "active" })); + + await getNewsletterSenderRequest("community", "hive-125125", "hs-token"); + + const [url, init] = fetchMock.mock.calls[0]; + expect(String(url)).toContain( + "/api/newsletter/sender?type=community&target=hive-125125", + ); + expect((init as RequestInit).headers).toMatchObject({ + "X-HS-Token": "hs-token", + }); + }); + + it("keeps the status on an error so callers can branch on 403", async () => { + fetchMock.mockResolvedValueOnce(errJson(403, { error: "Not a sender" })); + await expect( + getNewsletterSenderRequest("creator", "alice", "t"), + ).rejects.toMatchObject({ status: 403 }); + }); + }); + + describe("getNewsletterIssuesRequest", () => { + it("unwraps the issues array, defaulting to []", async () => { + fetchMock.mockResolvedValueOnce(okJson({ issues: [{ id: "i1" }] })); + expect(await getNewsletterIssuesRequest("creator", "alice", "t")).toEqual([ + { id: "i1" }, + ]); + + fetchMock.mockResolvedValueOnce(okJson({})); + expect(await getNewsletterIssuesRequest("creator", "alice", "t")).toEqual( + [], + ); + expect(String(fetchMock.mock.calls[0][0])).toContain( + "/api/newsletter/issues?type=creator&target=alice", + ); + }); + }); + + describe("getNewsletterPostsRequest", () => { + it("passes the limit through and defaults it to 20", async () => { + fetchMock.mockResolvedValue(okJson({ posts: [] })); + + await getNewsletterPostsRequest("creator", "alice", "t"); + expect(String(fetchMock.mock.calls[0][0])).toContain( + "/api/newsletter/posts?type=creator&target=alice&limit=20", + ); + + await getNewsletterPostsRequest("creator", "alice", "t", 40); + expect(String(fetchMock.mock.calls[1][0])).toContain("&limit=40"); + }); + }); + + describe("preview + send", () => { + const SEND = { + type: "creator" as const, + target: "alice", + author: "alice", + permlink: "my-post", + }; + + it("POSTs the preview with the token as X-HS-Token header", async () => { + fetchMock.mockResolvedValueOnce(okJson({ subject: "s" })); + + await previewNewsletterSendRequest(SEND, "hs-token"); + + const [url, init] = fetchMock.mock.calls[0]; + expect(String(url)).toContain("/api/newsletter/send/preview"); + expect((init as RequestInit).method).toBe("POST"); + expect((init as RequestInit).headers).toMatchObject({ + "X-HS-Token": "hs-token", + }); + expect(JSON.parse((init as RequestInit).body as string)).toEqual(SEND); + }); + + it("POSTs the send to /api/newsletter/send with the header token and the request as body", async () => { + fetchMock.mockResolvedValueOnce(okJson({ issues: [] })); + await sendNewsletterIssueRequest(SEND, "hs-token"); + const [url, init] = fetchMock.mock.calls[0]; + expect(String(url)).toContain("/api/newsletter/send"); + expect(String(url)).not.toContain("/send/preview"); + expect((init as RequestInit).method).toBe("POST"); + expect((init as RequestInit).headers).toMatchObject({ + "X-HS-Token": "hs-token", + }); + expect(JSON.parse((init as RequestInit).body as string)).toEqual(SEND); + }); + + it("surfaces a refused send with the relay's code and taken periods", async () => { + fetchMock.mockResolvedValueOnce( + errJson(409, { + error: "Already sent", + code: "already_sent", + taken: [{ cadence: "weekly", period: "2026-W34", kind: "post" }], + }), + ); + + const promise = sendNewsletterIssueRequest(SEND, "t"); + await expect(promise).rejects.toBeInstanceOf(NewsletterSendRefusedError); + await expect(promise).rejects.toMatchObject({ + status: 409, + code: "already_sent", + taken: [{ cadence: "weekly", period: "2026-W34", kind: "post" }], + // The full parsed payload rides along too, so callers handling + // NewsletterApiError uniformly see the same body either way. + data: { error: "Already sent", code: "already_sent" }, + }); + }); + + it("keeps the status when the error body is not JSON", async () => { + fetchMock.mockResolvedValueOnce({ + ok: false, + status: 502, + json: async () => { + throw new Error("not json"); + }, + }); + await expect(sendNewsletterIssueRequest(SEND, "t")).rejects.toMatchObject( + { status: 502 }, + ); + }); + + it("treats a 2xx without a JSON object body as an error, not a blank result", async () => { + fetchMock.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => { + throw new Error("not json"); + }, + }); + await expect( + previewNewsletterSendRequest(SEND, "t"), + ).rejects.toMatchObject({ status: 200 }); + }); + }); +}); diff --git a/packages/sdk/src/modules/newsletter/api.ts b/packages/sdk/src/modules/newsletter/api.ts new file mode 100644 index 0000000000..9d3974c78f --- /dev/null +++ b/packages/sdk/src/modules/newsletter/api.ts @@ -0,0 +1,237 @@ +import { CONFIG, getBoundFetch } from "@/modules/core"; +import type { + DigestSubscribeInput, + DigestSubscribeResult, + DigestSubscription, + NewsletterCandidatePost, + NewsletterListType, + NewsletterSendPreview, + NewsletterSendRequest, + NewsletterSendResult, + NewsletterSenderStanding, + NewsletterSentIssue, +} from "./types"; + +/** + * Client for the newsletter relay at {privateApiHost}/api/newsletter/* + * (Next.js route handlers on ecency.com, which alone hold the news-service + * credentials — clients never talk to the service directly). + * + * Identity is the HiveSigner access token, passed here as the explicit `code` + * argument. Transport mirrors the deployed web client per route: subscribe and + * unsubscribe-all carry it in the POST body as `code` (the subscribe route + * authenticates ONLY from the body — a header alone is treated as anonymous); + * every other call, the send/preview POSTs included, uses the `X-HS-Token` + * header. The relay verifies it upstream and derives the account from it, so + * a stale token 401s — callers are responsible for supplying a fresh one + * (web: ensureValidToken; mobile: the token-refresh wrapper). + * + * The email-token confirm/unsubscribe flows are deliberately absent: those + * links land on web pages. + */ +export class NewsletterApiError extends Error { + constructor( + message: string, + public readonly status: number, + public readonly data?: unknown, + ) { + super(message); + } +} + +/** A refused send, carrying the relay's routing `code` (already_sent, suspended, ...). */ +export class NewsletterSendRefusedError extends NewsletterApiError { + constructor( + message: string, + status: number, + public readonly code?: string, + public readonly taken?: Array<{ cadence: string; period: string; kind: string }>, + data?: unknown, + ) { + super(message, status, data); + } +} + +function newsletterUrl(path: string): string { + return `${CONFIG.privateApiHost}/api/newsletter${path}`; +} + +async function parse(response: Response): Promise { + const data = (await response.json().catch(() => undefined)) as + | (T & { error?: string }) + | undefined; + if (!response.ok) { + throw new NewsletterApiError( + data?.error || `Request failed (${response.status})`, + response.status, + data, + ); + } + // A 2xx without a JSON body is not a result; saying so beats returning blanks. + if (!data || typeof data !== "object") { + throw new NewsletterApiError( + `Unexpected response (${response.status})`, + response.status, + ); + } + return data; +} + +/** + * Subscribe an address to a digest. Authenticated callers (code given) skip + * the captcha; anonymous callers must supply `captchaToken` in the input and + * get double opt-in. The `own` digest type is always authenticated. + */ +export async function subscribeDigestRequest( + input: DigestSubscribeInput, + code?: string, +): Promise { + const fetchApi = getBoundFetch(); + const response = await fetchApi(newsletterUrl("/subscribe"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ ...input, ...(code ? { code } : {}) }), + }); + return parse(response); +} + +/** Every live digest subscription attributed to the token's account. */ +export async function getDigestSubscriptionsRequest( + code: string, +): Promise { + const fetchApi = getBoundFetch(); + const response = await fetchApi(newsletterUrl("/subscriptions"), { + headers: { "X-HS-Token": code }, + }); + const data = await parse<{ subscriptions?: DigestSubscription[] }>(response); + return data.subscriptions ?? []; +} + +/** Leave one digest by subscription id. */ +export async function leaveDigestRequest( + id: string, + code: string, +): Promise { + const fetchApi = getBoundFetch(); + const response = await fetchApi( + newsletterUrl(`/subscriptions/${encodeURIComponent(id)}`), + { method: "DELETE", headers: { "X-HS-Token": code } }, + ); + await parse<{ left: boolean }>(response); +} + +/** + * Suppress ONE address entirely (no Ecency bulk mail to it again). Only that + * address stops: an account can hold subscriptions under several addresses. + */ +export async function unsubscribeAllDigestsRequest( + email: string, + code: string, +): Promise { + const fetchApi = getBoundFetch(); + const response = await fetchApi(newsletterUrl("/unsubscribe-all"), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email, code }), + }); + await parse<{ suppressed: boolean }>(response); +} + +/** Sender standing (status, complaint/bounce stats, subscriber counts) for a list. */ +export async function getNewsletterSenderRequest( + type: NewsletterListType, + target: string, + code: string, +): Promise { + const fetchApi = getBoundFetch(); + const response = await fetchApi( + newsletterUrl(`/sender?type=${type}&target=${encodeURIComponent(target)}`), + { headers: { "X-HS-Token": code } }, + ); + return parse(response); +} + +/** Already-sent issues for a list, newest first. */ +export async function getNewsletterIssuesRequest( + type: NewsletterListType, + target: string, + code: string, +): Promise { + const fetchApi = getBoundFetch(); + const response = await fetchApi( + newsletterUrl(`/issues?type=${type}&target=${encodeURIComponent(target)}`), + { headers: { "X-HS-Token": code } }, + ); + const data = await parse<{ issues?: NewsletterSentIssue[] }>(response); + return data.issues ?? []; +} + +/** Candidate posts for composing a digest issue. */ +export async function getNewsletterPostsRequest( + type: NewsletterListType, + target: string, + code: string, + limit = 20, +): Promise { + const fetchApi = getBoundFetch(); + const response = await fetchApi( + newsletterUrl( + `/posts?type=${type}&target=${encodeURIComponent(target)}&limit=${limit}`, + ), + { headers: { "X-HS-Token": code } }, + ); + const data = await parse<{ posts?: NewsletterCandidatePost[] }>(response); + return data.posts ?? []; +} + +async function postSend( + path: string, + request: NewsletterSendRequest, + code: string, +): Promise { + const fetchApi = getBoundFetch(); + const response = await fetchApi(newsletterUrl(path), { + method: "POST", + headers: { "Content-Type": "application/json", "X-HS-Token": code }, + body: JSON.stringify(request), + }); + const data = (await response.json().catch(() => undefined)) as + | (T & { + error?: string; + code?: string; + taken?: NewsletterSendRefusedError["taken"]; + }) + | undefined; + if (!response.ok) { + throw new NewsletterSendRefusedError( + data?.error || `Request failed (${response.status})`, + response.status, + data?.code, + data?.taken, + data, + ); + } + if (!data || typeof data !== "object") { + throw new NewsletterSendRefusedError( + `Unexpected response (${response.status})`, + response.status, + ); + } + return data; +} + +/** Render the would-be issue (subject/html/text, counts, taken periods) without sending. */ +export function previewNewsletterSendRequest( + request: NewsletterSendRequest, + code: string, +): Promise { + return postSend("/send/preview", request, code); +} + +/** Send a post or composed digest to the list's subscribers. Pro/team gated by the relay. */ +export function sendNewsletterIssueRequest( + request: NewsletterSendRequest, + code: string, +): Promise { + return postSend("/send", request, code); +} diff --git a/packages/sdk/src/modules/newsletter/index.ts b/packages/sdk/src/modules/newsletter/index.ts new file mode 100644 index 0000000000..6f35213308 --- /dev/null +++ b/packages/sdk/src/modules/newsletter/index.ts @@ -0,0 +1,4 @@ +export * from "./api"; +export * from "./types"; +export * from "./queries"; +export * from "./mutations"; diff --git a/packages/sdk/src/modules/newsletter/mutations/index.ts b/packages/sdk/src/modules/newsletter/mutations/index.ts new file mode 100644 index 0000000000..8c48083b63 --- /dev/null +++ b/packages/sdk/src/modules/newsletter/mutations/index.ts @@ -0,0 +1,4 @@ +export * from "./use-subscribe-digest"; +export * from "./use-leave-digest"; +export * from "./use-unsubscribe-all-digests"; +export * from "./use-send-newsletter-issue"; diff --git a/packages/sdk/src/modules/newsletter/mutations/use-leave-digest.ts b/packages/sdk/src/modules/newsletter/mutations/use-leave-digest.ts new file mode 100644 index 0000000000..7ea6395a5f --- /dev/null +++ b/packages/sdk/src/modules/newsletter/mutations/use-leave-digest.ts @@ -0,0 +1,29 @@ +import { QueryKeys } from "@/modules/core"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { leaveDigestRequest } from "../api"; +import type { DigestSubscription } from "../types"; + +/** Leave one digest by subscription id; drops the row from the cached list. */ +export function useLeaveDigest( + username: string | undefined, + code: string | undefined, +) { + const queryClient = useQueryClient(); + const name = username?.replace("@", ""); + + return useMutation({ + mutationKey: ["newsletter", "leave", name], + mutationFn: async (id: string) => { + if (!name || !code) { + throw new Error("[SDK][Newsletter] – missing auth"); + } + return leaveDigestRequest(id, code); + }, + onSuccess(_result, id) { + queryClient.setQueryData( + QueryKeys.newsletter.subscriptions(name), + (prev) => (prev ?? []).filter((s) => s.id !== id), + ); + }, + }); +} diff --git a/packages/sdk/src/modules/newsletter/mutations/use-send-newsletter-issue.ts b/packages/sdk/src/modules/newsletter/mutations/use-send-newsletter-issue.ts new file mode 100644 index 0000000000..ca5e54baa1 --- /dev/null +++ b/packages/sdk/src/modules/newsletter/mutations/use-send-newsletter-issue.ts @@ -0,0 +1,59 @@ +import { QueryKeys } from "@/modules/core"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { + previewNewsletterSendRequest, + sendNewsletterIssueRequest, +} from "../api"; +import type { NewsletterSendRequest } from "../types"; + +/** + * Preview the would-be issue. No cache side effects: a preview changes + * nothing server-side. + */ +export function usePreviewNewsletterIssue( + username: string | undefined, + code: string | undefined, +) { + const name = username?.replace("@", ""); + return useMutation({ + mutationKey: ["newsletter", "send-preview", name], + mutationFn: async (request: NewsletterSendRequest) => { + if (!name || !code) { + throw new Error("[SDK][Newsletter] – missing auth"); + } + return previewNewsletterSendRequest(request, code); + }, + }); +} + +/** + * Send a post or composed digest to a list. Errors are + * NewsletterSendRefusedError with the relay's routing `code` + * (already_sent + taken periods, suspended, post_refused, ...). On success the + * list's issues + sender standing refresh. + */ +export function useSendNewsletterIssue( + username: string | undefined, + code: string | undefined, +) { + const queryClient = useQueryClient(); + const name = username?.replace("@", ""); + + return useMutation({ + mutationKey: ["newsletter", "send", name], + mutationFn: async (request: NewsletterSendRequest) => { + if (!name || !code) { + throw new Error("[SDK][Newsletter] – missing auth"); + } + return sendNewsletterIssueRequest(request, code); + }, + onSuccess(_result, request) { + queryClient.invalidateQueries({ + queryKey: QueryKeys.newsletter.issues(request.type, request.target, name), + }); + queryClient.invalidateQueries({ + queryKey: QueryKeys.newsletter.sender(request.type, request.target, name), + }); + }, + }); +} diff --git a/packages/sdk/src/modules/newsletter/mutations/use-subscribe-digest.ts b/packages/sdk/src/modules/newsletter/mutations/use-subscribe-digest.ts new file mode 100644 index 0000000000..b0c4249689 --- /dev/null +++ b/packages/sdk/src/modules/newsletter/mutations/use-subscribe-digest.ts @@ -0,0 +1,31 @@ +import { QueryKeys } from "@/modules/core"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { subscribeDigestRequest } from "../api"; +import type { DigestSubscribeInput } from "../types"; + +/** + * Subscribe to a digest (also re-used to change cadence: same list + address + * with a new cadence updates the row). Works signed-in (code) and anonymous + * (input.captchaToken); the signed-in path refreshes the account's + * subscriptions list on success. + */ +export function useSubscribeDigest( + username: string | undefined, + code: string | undefined, +) { + const queryClient = useQueryClient(); + const name = username?.replace("@", ""); + + return useMutation({ + mutationKey: ["newsletter", "subscribe", name], + mutationFn: (input: DigestSubscribeInput) => + subscribeDigestRequest(input, code), + onSuccess() { + if (name) { + queryClient.invalidateQueries({ + queryKey: QueryKeys.newsletter.subscriptions(name), + }); + } + }, + }); +} diff --git a/packages/sdk/src/modules/newsletter/mutations/use-unsubscribe-all-digests.ts b/packages/sdk/src/modules/newsletter/mutations/use-unsubscribe-all-digests.ts new file mode 100644 index 0000000000..ff4c6f5974 --- /dev/null +++ b/packages/sdk/src/modules/newsletter/mutations/use-unsubscribe-all-digests.ts @@ -0,0 +1,36 @@ +import { QueryKeys } from "@/modules/core"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { unsubscribeAllDigestsRequest } from "../api"; +import type { DigestSubscription } from "../types"; + +/** + * Stop all Ecency mail to ONE address. Only that address's rows leave the + * cached list: an account can hold subscriptions under more than one address, + * and those stay visible. + */ +export function useUnsubscribeAllDigests( + username: string | undefined, + code: string | undefined, +) { + const queryClient = useQueryClient(); + const name = username?.replace("@", ""); + + return useMutation({ + mutationKey: ["newsletter", "unsubscribe-all", name], + mutationFn: async (email: string) => { + if (!name || !code) { + throw new Error("[SDK][Newsletter] – missing auth"); + } + return unsubscribeAllDigestsRequest(email, code); + }, + onSuccess(_result, email) { + queryClient.setQueryData( + QueryKeys.newsletter.subscriptions(name), + (prev) => + (prev ?? []).filter( + (s) => s.email.toLowerCase() !== email.toLowerCase(), + ), + ); + }, + }); +} diff --git a/packages/sdk/src/modules/newsletter/queries/get-digest-subscriptions-query-options.ts b/packages/sdk/src/modules/newsletter/queries/get-digest-subscriptions-query-options.ts new file mode 100644 index 0000000000..3bf92635f0 --- /dev/null +++ b/packages/sdk/src/modules/newsletter/queries/get-digest-subscriptions-query-options.ts @@ -0,0 +1,28 @@ +import { QueryKeys } from "@/modules/core"; +import { queryOptions } from "@tanstack/react-query"; +import { getDigestSubscriptionsRequest } from "../api"; + +/** + * The signed-in account's live digest subscriptions. Disabled without a + * username + token: callers render nothing then, and a request that + * predictably 401s is noise. `retry: false` because the common failure is a + * stale token, which a retry with the same token cannot fix. + */ +export function getDigestSubscriptionsQueryOptions( + username: string | undefined, + code: string | undefined, +) { + const name = username?.replace("@", ""); + return queryOptions({ + queryKey: QueryKeys.newsletter.subscriptions(name), + enabled: !!name && !!code, + queryFn: async () => { + if (!code) { + throw new Error("[SDK][Newsletter] – missing auth"); + } + return getDigestSubscriptionsRequest(code); + }, + staleTime: 60_000, + retry: false, + }); +} diff --git a/packages/sdk/src/modules/newsletter/queries/get-newsletter-issues-query-options.ts b/packages/sdk/src/modules/newsletter/queries/get-newsletter-issues-query-options.ts new file mode 100644 index 0000000000..dffb5869ca --- /dev/null +++ b/packages/sdk/src/modules/newsletter/queries/get-newsletter-issues-query-options.ts @@ -0,0 +1,25 @@ +import { QueryKeys } from "@/modules/core"; +import { queryOptions } from "@tanstack/react-query"; +import { getNewsletterIssuesRequest } from "../api"; +import type { NewsletterListType } from "../types"; + +/** Already-sent issues for a creator/community list (sender-only view). */ +export function getNewsletterIssuesQueryOptions( + type: NewsletterListType, + target: string, + username: string | undefined, + code: string | undefined, +) { + const name = username?.replace("@", ""); + return queryOptions({ + queryKey: QueryKeys.newsletter.issues(type, target, name), + enabled: !!name && !!code && !!target, + queryFn: async () => { + if (!code) { + throw new Error("[SDK][Newsletter] – missing auth"); + } + return getNewsletterIssuesRequest(type, target, code); + }, + staleTime: 60_000, + }); +} diff --git a/packages/sdk/src/modules/newsletter/queries/get-newsletter-posts-query-options.ts b/packages/sdk/src/modules/newsletter/queries/get-newsletter-posts-query-options.ts new file mode 100644 index 0000000000..9f7899266b --- /dev/null +++ b/packages/sdk/src/modules/newsletter/queries/get-newsletter-posts-query-options.ts @@ -0,0 +1,26 @@ +import { QueryKeys } from "@/modules/core"; +import { queryOptions } from "@tanstack/react-query"; +import { getNewsletterPostsRequest } from "../api"; +import type { NewsletterListType } from "../types"; + +/** Candidate posts for composing a digest issue (send-gated by the relay). */ +export function getNewsletterPostsQueryOptions( + type: NewsletterListType, + target: string, + username: string | undefined, + code: string | undefined, + limit = 20, +) { + const name = username?.replace("@", ""); + return queryOptions({ + queryKey: QueryKeys.newsletter.posts(type, target, name, limit), + enabled: !!name && !!code && !!target, + queryFn: async () => { + if (!code) { + throw new Error("[SDK][Newsletter] – missing auth"); + } + return getNewsletterPostsRequest(type, target, code, limit); + }, + staleTime: 60_000, + }); +} diff --git a/packages/sdk/src/modules/newsletter/queries/get-newsletter-sender-query-options.ts b/packages/sdk/src/modules/newsletter/queries/get-newsletter-sender-query-options.ts new file mode 100644 index 0000000000..d0d663cf76 --- /dev/null +++ b/packages/sdk/src/modules/newsletter/queries/get-newsletter-sender-query-options.ts @@ -0,0 +1,29 @@ +import { QueryKeys } from "@/modules/core"; +import { queryOptions } from "@tanstack/react-query"; +import { getNewsletterSenderRequest } from "../api"; +import type { NewsletterListType } from "../types"; + +/** + * Sender standing for a creator/community list. View access is the list's + * owner (creator) or the community team, decided by the relay — enable this + * only for callers already known to be the sender. + */ +export function getNewsletterSenderQueryOptions( + type: NewsletterListType, + target: string, + username: string | undefined, + code: string | undefined, +) { + const name = username?.replace("@", ""); + return queryOptions({ + queryKey: QueryKeys.newsletter.sender(type, target, name), + enabled: !!name && !!code && !!target, + queryFn: async () => { + if (!code) { + throw new Error("[SDK][Newsletter] – missing auth"); + } + return getNewsletterSenderRequest(type, target, code); + }, + staleTime: 5 * 60_000, + }); +} diff --git a/packages/sdk/src/modules/newsletter/queries/index.ts b/packages/sdk/src/modules/newsletter/queries/index.ts new file mode 100644 index 0000000000..011a80972c --- /dev/null +++ b/packages/sdk/src/modules/newsletter/queries/index.ts @@ -0,0 +1,4 @@ +export * from "./get-digest-subscriptions-query-options"; +export * from "./get-newsletter-sender-query-options"; +export * from "./get-newsletter-issues-query-options"; +export * from "./get-newsletter-posts-query-options"; diff --git a/packages/sdk/src/modules/newsletter/types/index.ts b/packages/sdk/src/modules/newsletter/types/index.ts new file mode 100644 index 0000000000..fa11bf497a --- /dev/null +++ b/packages/sdk/src/modules/newsletter/types/index.ts @@ -0,0 +1 @@ +export * from "./newsletter"; diff --git a/packages/sdk/src/modules/newsletter/types/newsletter.ts b/packages/sdk/src/modules/newsletter/types/newsletter.ts new file mode 100644 index 0000000000..1f5443b681 --- /dev/null +++ b/packages/sdk/src/modules/newsletter/types/newsletter.ts @@ -0,0 +1,137 @@ +export type DigestType = "own" | "community" | "creator" | "site"; +export type DigestCadence = "weekly" | "monthly"; +export type DigestStatus = "active" | "pending_confirmation" | "suppressed" | "ended"; + +/** The two list types that have a sender side (own/site digests are system-sent). */ +export type NewsletterListType = "creator" | "community"; + +export interface DigestSubscription { + id: string; + email: string; + account: string | null; + type: DigestType; + target: string; + cadence: DigestCadence; + status: DigestStatus; + created_at: string; +} + +/** + * Where the subscribe request originated. The relay keeps a closed allowlist + * (apps/web/src/app/api/newsletter/subscribe/route.ts SOURCES) — a value the + * route does not accept is a silent 400, so additions land there first. + */ +export type DigestSubscribeSource = + | "community-page" + | "creator-page" + | "settings" + | "landing-page" + | "publish-prompt" + | "post-page" + | "self-hosted-blog" + | "mobile-app"; + +export interface DigestSubscribeInput { + email: string; + type: DigestType; + target: string; + cadence: DigestCadence; + source: DigestSubscribeSource; + /** + * Cloudflare Turnstile token. Required by the relay whenever the caller has + * no verified account; ignored for authenticated callers, whose account is + * the proof. + */ + captchaToken?: string; +} + +export interface DigestSubscribeResult { + status: "active" | "pending_confirmation" | "refused"; + /** Proven (authenticated or already-confirmed) callers only. */ + subscription?: DigestSubscription; + created?: boolean; + confirmationSent?: boolean; + reason?: "suppressed"; +} + +export interface NewsletterPostRef { + author: string; + permlink: string; +} + +/** One post, the post being the issue. */ +export interface NewsletterSendRef extends NewsletterPostRef { + type: NewsletterListType; + target: string; +} + +/** Several posts with a subject and an intro. */ +export interface NewsletterComposeRequest { + type: NewsletterListType; + target: string; + posts: NewsletterPostRef[]; + subject?: string; + intro?: string; +} + +export type NewsletterSendRequest = NewsletterSendRef | NewsletterComposeRequest; + +export interface NewsletterCandidatePost extends NewsletterPostRef { + title: string; + created: string; + featured: boolean; +} + +export interface NewsletterSendPreview { + subject: string; + html: string; + text: string; + post: { author: string; permlink: string; title: string }; + posts: Array<{ author: string; permlink: string; title: string }>; + subscribers: { weekly: number; monthly: number }; + alreadySent: DigestCadence[]; +} + +export interface NewsletterSendResult { + issues: Array<{ + issueId: string; + cadence: DigestCadence; + period: string; + send: { recipients: number; sent: number; pending: number }; + }>; +} + +export interface NewsletterSentIssue { + id: string; + cadence: DigestCadence; + kind: "digest" | "post"; + period_start: string; + subject: string; + status: string; + post_author: string | null; + post_permlink: string | null; + requested_by: string | null; + created_at: string; + delivered: number; + bounced: number; + rejected: number; +} + +export interface NewsletterSenderStanding { + type: DigestType; + target: string; + status: "active" | "suspended"; + reason: string | null; + since: string | null; + stats: { + delivered: number; + bounced: number; + rejected: number; + complaints: number; + unsubscribed: number; + complaintRate: number; + bounceRate: number; + }; + /** Live, mailable subscribers per cadence. */ + subscribers?: { weekly: number; monthly: number }; +} diff --git a/packages/wallets/CHANGELOG.md b/packages/wallets/CHANGELOG.md index 4018a18110..50b44908eb 100644 --- a/packages/wallets/CHANGELOG.md +++ b/packages/wallets/CHANGELOG.md @@ -1,5 +1,12 @@ # @ecency/wallets +## 5.0.92 + +### Patch Changes + +- Updated dependencies []: + - @ecency/sdk@2.3.92 + ## 5.0.91 ### Patch Changes diff --git a/packages/wallets/package.json b/packages/wallets/package.json index cd392c5b46..157631dd9f 100644 --- a/packages/wallets/package.json +++ b/packages/wallets/package.json @@ -1,7 +1,7 @@ { "name": "@ecency/wallets", "private": false, - "version": "5.0.91", + "version": "5.0.92", "description": "Ecency wallets", "repository": { "type": "git",