feat: @polymarket/react hooks SDK - #220
Draft
cesarenaldi wants to merge 12 commits into
Draft
Conversation
…s, and discovery hooks
Add createBaseSecureClient to restore an authenticated client from existing session credentials without running an authentication workflow, promote beginAuthentication to the public API, export the workflow request vocabulary types from the root entry point, and add fetchDepositWallet, extracting the default Deposit Wallet resolution from createSecureClient.
Add the signature-only WorkflowHandler contract with cancellation unified onto CancelledSigningError, useAuthentication with handler-driven authenticate/logout, serializable Session with synchronous initialSession restore and 401 invalidation, internal read primitives renamed to the public/secure families with secure gating, useOpenOrders, and the @polymarket/react/viem entry point with useWorkflowHandler and WalletClientUnavailableError. Only dedicated hooks and usePolymarketClient are exported; action primitives stay internal.
Capture the session-derivation model, signature-only handler ownership at wallet entry points, error-surface decisions, entry-point isolation as a review-enforced guideline, and the client tree-shaking follow-up.
…eError Map the balance/allowance 400 rejection to a typed error at the order posting boundary so consumers can branch on it without string-matching the rejection message. Added to the PostOrderError, PostOrdersError, PlaceMarketOrderError, and PlaceLimitOrderError unions; the internal allowance-recovery detection now checks the typed error directly.
Add usePlaceMarketOrder and usePlaceLimitOrder driving the order posting workflows through the workflow handler with per-hook step narrowing and no automatic allowance recovery, useSetupTradingApprovals as the account-readiness and allowance-recovery path over the gasless relayer, useCancelOrder, and the internal useSecureWrite primitive with UnauthenticatedError, 401 session invalidation, reset, and stale-execution discarding.
Add usePositions, useClosedPositions, usePortfolioValue, and useActivity over public per-address data with the user defaulting to the session wallet (paused while unauthenticated, explicit user works without a session), useBalance, useNotifications, useOrder, and useTradingRestriction for session-bound account state, and useDropNotifications as the notification dismissal write.
Add the market-order execution preview over estimateMarketPrice, pairing with the placement hooks' slippage bounds. Skip pausing covers empty amount inputs; the estimate is refreshed explicitly via refetch.
Add discovery and trading-form reads (useEvent, usePriceHistory, useMidpoint, useLastTradePrice, useSearch, useTags, useRelatedTags, useComments, usePublicProfile, useMarketHolders, useTraderLeaderboard) and gasless lifecycle writes resolving at transaction confirmation (useRedeemPositions, useSplitPosition, useMergePositions, useTransfer). Generalize the gasless workflow step vocabulary into GaslessStep/asGaslessWorkflow shared across the gasless write hooks.
Add useIsWalletDeployed reading the session wallet's deployment status and useDeployWallet deploying the Deposit Wallet signature-free through the gasless relayer, resolving at transaction confirmation. Deployment stays an explicit onboarding step; ordering with trading approvals is documented on both hooks.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Introduces
@polymarket/react, the React hooks SDK built on@polymarket/client, covering the full end-user trading-hub loop: discover, authenticate, onboard, trade, and monitor. Design direction and settled decisions are recorded indocs/react-sdk-direction.md.Architecture
Sessionis a serializable object apps persist themselves; the secure client is a memoized derivation of(config, session).initialSessionrestores synchronously at mount with no logged-out flash; revoked sessions surface as 401s that end the session.WorkflowHandler(single interception point over the client's workflow generators). EOA accounts are rejected by invariant, which keeps the handler vocabulary signature-only: no transaction sending, no gas.@polymarket/react/viemships first (useWorkflowHandler, works with anything producing a viemWalletClient).refetch, withskippausing and TanStack-compatible result naming so a cache layer can be adopted later without breakage.[execute, { status, step, data, error, reset }], with per-hook narrowing of both handler request kinds and step kinds. Order placement has no automatic allowance recovery: rejections surface as the new typedInsufficientAllowanceErrorand integrators route users through the approvals hook.Client package additions
createBaseClient/createBaseSecureClient: construction without bound actions, including restoring an authenticated client from session credentials without running an authentication workflow.beginAuthenticationpromoted to public API; workflow request vocabulary types exported.fetchDepositWallet: the default account-wallet resolution extracted fromcreateSecureClient.InsufficientAllowanceError: the balance/allowance order rejection typed at the posting boundary instead of a string-matched message.Hook surface
Setup
createConfig/PolymarketProvider· authuseAuthentication· onboardinguseIsWalletDeployed/useDeployWallet/useSetupTradingApprovals· discoveryuseMarkets/useMarket/useEvents/useEvent/useSearch/useTags/useRelatedTags/useComments/usePublicProfile/useMarketHolders/useTraderLeaderboard· trading formuseOrderBook/useMidpoint/useLastTradePrice/usePriceHistory/useEstimatedMarketPrice/usePlaceMarketOrder/usePlaceLimitOrder/useCancelOrder· portfoliousePositions/useClosedPositions/usePortfolioValue/useActivity/useBalance/useOpenOrders/useOrder/useNotifications/useDropNotifications/useTradingRestriction· lifecycleuseRedeemPositions/useSplitPosition/useMergePositions/useTransfer· escape hatchusePolymarketClient.Per-address portfolio reads default
userto the session wallet and pause while unauthenticated; an explicituserworks without a session. The roster is deliberately curated for end-user hubs (not market-maker/builder dashboards); skipped actions and reasons are documented in the direction doc.Verification
@ts-expect-errorrejections)pnpm lint,pnpm typecheck,pnpm buildgreen throughoutOut of scope / follow-ups
useSubscriptionsover the unifiedsubscribetopics + dedicated live order book / user channel hooks)listMarketHoldersreturns a direct array despite thelist*prefix; rename candidateauthenticate()does not deployment-check explicitly passed Safe/Proxy wallets the waycreateSecureClientdoesChangesets included:
@polymarket/reactminor (initial beta) and@polymarket/clientpatches.