@polymarket/client 0.0.0-canary-20260421120448

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/account.ts","../src/input.ts","../src/pagination.ts","../src/response.ts","../src/actions/params.ts","../src/actions/account.ts","../src/actions/activity.ts","../src/abis.ts","../src/types.ts","../src/workflow.ts","../src/actions/gasless.ts","../src/actions/approvals.ts","../src/actions/auth.ts","../src/actions/builders.ts","../src/actions/clob.ts","../src/actions/comments.ts","../src/actions/events.ts","../src/actions/leaderboards.ts","../src/actions/markets.ts","../src/actions/orders/cancel.ts","../src/actions/orders/estimate.ts","../src/actions/orders/post.ts","../src/actions/orders/allowance.ts","../src/actions/orders/context.ts","../src/actions/orders/math.ts","../src/actions/orders/limit.ts","../src/actions/orders/market.ts","../src/actions/orders/orders.ts","../src/actions/orders/typed-data.ts","../src/actions/orders/types.ts","../src/actions/orders/prepare.ts","../src/actions/portfolio.ts","../src/actions/positions.ts","../src/actions/profiles.ts","../src/actions/search.ts","../src/actions/series.ts","../src/actions/sports.ts","../src/actions/tags.ts","../src/actions/teams.ts","../src/actions/transfers.ts"],"names":["resolveAccountIdentity","environment","signer","wallet","classifyWalletType","toSignatureType","walletType","WalletType","SignatureType","PROXY_BYTECODE_TEMPLATE","proxyWalletBytecodeHash","config","bytecode","expectHexString","Hash","deriveProxyWalletAddress","expectEvmAddress","ContractAddress","AbiParameters","deriveSafeWalletAddress","sameAddress","left","right","never","parseUserInput","input","schema","result","UserInputError","PageSizeSchema","z","OffsetCursorStateSchema","paginate","fetchPage","initialCursor","createEmptyPaginator","createPaginator","cursor","unwrap","nextCursor","currentCursor","page","encodeOffsetCursor","state","toPaginationCursor","decodeOffsetCursor","pageSize","error","validateWith","response","ResultAsync","UnexpectedResponseError","payload","parseResponse","readBlob","endpoint","ok","err","toSearchParams","params","mappings","isSnakeCaseSearchParamMappings","toSnakeCaseSearchParams","searchParams","paramKey","searchParamKey","value","isSearchParamArray","item","toSearchParamValue","snakeCase","exceptions","toDataSearchParams","key","toSnakeCase","character","fetchClosedOnlyMode","client","ClosedOnlyModeSchema","ListOpenOrdersRequestSchema","PaginationCursorSchema","listOpenOrders","request","OpenOrdersPageSchema","END_CURSOR","FetchOrderRequestSchema","fetchOrder","OpenOrderSchema","ListAccountTradesRequestFields","ListAccountTradesRequestSchema","listAccountTrades","ClobTradesPageSchema","DropNotificationsRequestSchema","fetchNotifications","signatureType","NotificationsResponseSchema","dropNotifications","FetchBalanceAllowanceRequestSchema","AssetTypeSchema","fetchBalanceAllowance","BalanceAllowanceResponseSchema","UpdateBalanceAllowanceRequestSchema","updateBalanceAllowance","FetchOrderScoringRequestSchema","fetchOrderScoring","OrderScoringResponseSchema","FetchOrdersScoringRequestSchema","fetchOrdersScoring","body","OrdersScoringResponseSchema","ListUserEarningsForDayRequestSchema","listUserEarningsForDay","UserEarningsPageSchema","fetchTotalEarningsForUserForDay","TotalUserEarningsResponseSchema","ListUserEarningsAndMarketsConfigRequestSchema","listUserEarningsAndMarketsConfig","UserRewardsEarningsPageSchema","fetchRewardPercentages","RewardsPercentagesSchema","ActivitySortBySchema","SortDirectionSchema","TradeFilterTypeSchema","ListTradesRequestSchema","SideSchema","ListActivityRequestSchema","ActivityTypeSchema","listTrades","decoded","ListTradesResponseSchema","trades","hasMore","listActivity","ListActivityResponseSchema","activity","ZERO_BYTES32","ERC20_APPROVE_FUNCTION","AbiFunction","ERC20_TRANSFER_FUNCTION","ERC1155_SET_APPROVAL_FOR_ALL_FUNCTION","CTF_SPLIT_POSITION_FUNCTION","CTF_MERGE_POSITIONS_FUNCTION","CTF_REDEEM_POSITIONS_FUNCTION","NEG_RISK_REDEEM_POSITIONS_FUNCTION","SAFE_MULTISEND_FUNCTION","BINARY_OUTCOME_PARTITION","BINARY_OUTCOME_INDEX_SETS","MAX_UINT256","erc20ApprovalCall","tokenAddress","spender","amount","encodeErc20ApproveCall","erc1155ApprovalForAllCall","operator","approved","encodeErc1155SetApprovalForAllCall","erc20TransferCall","recipient","encodeErc20TransferCall","splitPositionCall","targetAddress","collateralTokenAddress","conditionId","negRisk","encodeSplitPositionCall","mergePositionsCall","encodeMergePositionsCall","ctfRedeemPositionsCall","conditionalTokensAddress","encodeCtfRedeemPositionsCall","negRiskRedeemPositionsCall","negRiskAdapterAddress","amounts","encodeNegRiskRedeemPositionsCall","invariant","expectUint256","label","encodeSafeMultisendCall","calls","encodedTransactions","call","encodeSafeMultisendTransaction","expectTransactionHandle","message","requestAddress","signerTransactionRequest","chainId","EIP712_DOMAIN","SAFE_FACTORY_NAME","SAFE_CREATE","SAFE_TRANSACTION","FetchExecuteParamsRequestSchema","RelayerTransactionType","fetchExecuteParams","RelayerExecuteParamsSchema","FetchGaslessTransactionRequestSchema","TransactionIdSchema","IsGaslessReadyRequestSchema","EvmAddressSchema","isGaslessReady","RelayerDeployedResponseSchema","deployed","prepareGaslessWallet","safeWallet","signature","expectEvmSignature","signGaslessTypedData","createSafeCreateTypedDataPayload","handle","executeGasless","ZERO_ADDRESS","GaslessWalletHandle","fetchTransaction","GaslessTransactionSchema","TransactionCallSchema","isHexString","GaslessTransactionMetadataSchema","PrepareGaslessTransactionRequestSchema","val","expectNonEmptyArray","prepareGaslessTransaction","executeParams","transaction","aggregateSafeTransactionCalls","signGaslessMessage","createSafeTypedDataPayload","packSafeSignature","createSafeSignatureParams","RelayerExecuteRequestSchema","RelayerExecuteResponseSchema","GaslessTransactionHandle","safeMultisend","operation","prefixlessSignature","v","packedV","#client","pollCount","RelayerTransactionState","transactionHash","TransactionFailedError","delay","TimeoutError","#wallet","#transaction","PrepareErc20ApprovalRequestSchema","prepareErc20Approval","sendErc20ApprovalTransaction","PrepareErc1155ApprovalForAllRequestSchema","prepareErc1155ApprovalForAll","sendErc1155ApprovalForAllTransaction","prepareTradingApprovals","createApiKey","toL1Headers","ApiKeyCredsSchema","deriveApiKey","createOrDeriveApiKey","RequestRejectedError","fetchApiKeys","ApiKeysResponseSchema","deleteApiKey","createBuilderApiKey","BuilderApiKeyCredsSchema","fetchBuilderApiKeys","BuilderApiKeysResponseSchema","revokeBuilderApiKey","auth","ListBuilderTradesRequestSchema","listBuilderTrades","PaginatedBuilderTradesSchema","FetchMidpointRequestSchema","fetchMidpoint","MidpointSchema","FetchMidpointsRequestSchema","fetchMidpoints","toTokenRequestPayload","MidpointsSchema","FetchTickSizeRequestSchema","fetchTickSize","FetchTickSizeResponseSchema","FetchNegRiskRequestSchema","fetchNegRisk","FetchNegRiskResponseSchema","FetchFeeRateRequestSchema","fetchFeeRate","FetchFeeRateResponseSchema","FetchPriceRequestSchema","OrderSideSchema","fetchPrice","PriceSchema","FetchPricesRequestSchema","fetchPrices","toTokenWithSideRequestPayload","PricesSchema","FetchOrderBookRequestSchema","fetchOrderBook","FetchOrderBookResponseSchema","FetchOrderBooksRequestSchema","fetchOrderBooks","OrderBooksSchema","FetchSpreadRequestSchema","fetchSpread","SpreadSchema","FetchSpreadsRequestSchema","fetchSpreads","SpreadsSchema","FetchLastTradePriceRequestSchema","fetchLastTradePrice","LastTradePriceSchema","FetchLastTradePricesRequestSchema","fetchLastTradePrices","LastTradePricesSchema","ListPriceHistoryRequestSchema","PriceHistoryIntervalSchema","fetchPriceHistory","PriceHistorySchema","ListCurrentRewardsRequestSchema","listCurrentRewards","PaginatedCurrentRewardsSchema","ListMarketRewardsRequestSchema","ConditionIdSchema","listMarketRewards","PaginatedMarketRewardsSchema","tokenId","side","ListCommentsRequestSchema","EventIdSchema","SeriesIdSchema","FetchCommentsByIdRequestSchema","CommentIdSchema","ListCommentsByUserAddressRequestSchema","listComments","ListCommentsResponseSchema","comments","fetchCommentsById","listCommentsByUserAddress","address","ListEventsRequestSchema","ISODateStringSchema","ISOCalendarDateSchema","FetchEventRequestSchema","FetchEventTagsRequestSchema","FetchEventLiveVolumeRequestSchema","listEvents","toEventsSearchParams","ListEventsKeysetResponseSchema","fetchEvent","toFetchEventByIdSearchParams","EventSchema","toFetchEventBySlugSearchParams","fetchEventTags","FetchEventTagsResponseSchema","fetchEventLiveVolume","FetchEventLiveVolumeResponseSchema","ListBuilderLeaderboardRequestSchema","TimePeriodSchema","ListBuilderVolumeRequestSchema","ListTraderLeaderboardRequestSchema","LeaderboardCategorySchema","LeaderboardOrderBySchema","listBuilderLeaderboard","ListBuilderLeaderboardResponseSchema","builders","fetchBuilderVolume","ListBuilderVolumeResponseSchema","listTraderLeaderboard","ListTraderLeaderboardResponseSchema","traders","ListMarketsRequestSchema","FetchMarketByIdRequestSchema","FetchMarketBySlugRequestSchema","FetchMarketRequestSchema","FetchMarketTagsRequestSchema","ListMarketHoldersRequestSchema","ListOpenInterestRequestSchema","MarketPositionStatusSchema","MarketPositionSortBySchema","MarketPositionSortDirectionSchema","ListMarketPositionsRequestSchema","listMarkets","toMarketsSearchParams","ListMarketsKeysetResponseSchema","fetchMarket","fetchMarketById","fetchMarketBySlug","fetchMarketTags","FetchMarketTagsResponseSchema","listMarketHolders","ListMarketHoldersResponseSchema","listOpenInterest","ListOpenInterestResponseSchema","listMarketPositions","ListMarketPositionsResponseSchema","positions","MarketSchema","CancelOrderRequestSchema","CancelOrdersRequestSchema","CancelMarketOrdersRequestSchema","cancelOrder","cancel","cancelOrders","cancelAll","cancelMarketOrders","path","CancelOrdersResponseSchema","EstimateMarketPriceRequestSchema","OrderType","estimateMarketPrice","tickSize","resolveEstimatedMarketPrice","orderBook","price","OrderSide","calculateBuyMarketPrice","calculateSellMarketPrice","isValidPrice","amountToMatch","orderType","InsufficientLiquidityError","sum","index","position","bestPosition","PostOrdersRequestSchema","postOrder","order","createSendOrderPayload","OrderResponseSchema","postOrders","orders","OrderResponsesSchema","resolveCurrentAllowance","assetType","AssetType","allowances","resolveAllowanceAmount","resolveRoundingConfig","resolveFeeRateBps","resolveExchangeAddress","parseAmount","roundDown","decimals","decimalPlaces","roundUp","roundNormal","parts","PrepareLimitOrderParamsSchema","TokenIdSchema","context","minimumExpiration","prepareLimitOrderDraft","resolveLimitOrderContext","computeLimitOrderAmounts","account","feeRateBps","resolvePrice","roundConfig","rawPrice","rawTakerAmount","rawMakerAmount","PrepareMarketOrderParamsSchema","prepareMarketOrderDraft","resolveMarketOrderContext","computeMarketOrderAmounts","createUnsignedOrder","generateOrderSalt","createSignedOrder","_chainId","_exchangeAddress","signedFields","ORDER_STRUCTURE","PROTOCOL_NAME","PROTOCOL_VERSION","createOrderTypedDataPayload","createOrderTypedDataMessage","encodeOrderSide","signOrder","prepareMarketOrder","draft","ensureOrderApproval","unsignedOrder","prepareLimitOrder","prepareMarketOrderPosting","createOrderPostingWorkflow","prepareLimitOrderPosting","workflowPromise","workflow","PositionSortBySchema","PositionSortDirectionSchema","ClosedPositionSortBySchema","ListPositionsRequestSchema","ListClosedPositionsRequestSchema","FetchPortfolioValueRequestSchema","FetchTradedMarketCountRequestSchema","DownloadAccountingSnapshotRequestSchema","listPositions","ListPositionsResponseSchema","listClosedPositions","ListClosedPositionsResponseSchema","fetchPortfolioValue","FetchPortfolioValueResponseSchema","fetchTradedMarketCount","TradedSchema","downloadAccountingSnapshot","PrepareSplitPositionRequestSchema","PrepareMergePositionsRequestSchema","PrepareRedeemPositionsRequestSchema","prepareSplitPosition","negativeRisk","resolveMarketNegativeRiskFlag","resolveSplitTargetAddress","sendSplitPositionTransaction","prepareMergePositions","binaryPositions","expectBinaryPositions","expectNegativeRiskFlag","resolveMergeAmount","resolveMergeTargetAddress","sendMergePositionsTransaction","prepareRedeemPositions","deriveNegRiskRedeemAmounts","sendRedeemPositionsTransaction","markets","market","isPresent","yesPosition","noPosition","toPositionAmount","first","requestedAmount","maxAmount","calculateMaxMergeAmount","yesAmount","noAmount","expectedOutcomeIndex","isNullish","toTokenBaseUnits","size","FetchPublicProfileRequestSchema","fetchPublicProfile","PublicProfileSchema","SearchRequestSchema","search","PublicSearchResponseSchema","ListSeriesRequestSchema","FetchSeriesRequestSchema","listSeries","ListSeriesResponseSchema","series","fetchSeries","SeriesSchema","listSports","ListSportsMetadataResponseSchema","fetchSportsMarketTypes","SportsMarketTypesResponseSchema","ListTagsRequestSchema","FetchTagRequestSchema","RelatedTagsByIdRequestSchema","RelatedTagsBySlugRequestSchema","RelatedTagResourcesByIdRequestSchema","RelatedTagResourcesBySlugRequestSchema","listTags","ListTagsResponseSchema","tags","fetchTag","TagSchema","fetchRelatedTags","ListRelatedTagsResponseSchema","fetchRelatedTagResources","ListRelatedTagResourcesResponseSchema","ListTeamsRequestSchema","listTeams","ListTeamsResponseSchema","teams","PrepareErc20TransferRequestSchema","prepareErc20Transfer","sendErc20TransferTransaction"],"mappings":"2wFAmBO,SAASA,GACdC,CAAAA,CACAC,CAAAA,CACAC,EAAqBD,CAAAA,CACJ,CACjB,OAAO,CACL,MAAA,CAAAA,EACA,MAAA,CAAAC,CAAAA,CACA,WAAYC,EAAAA,CAAmBH,CAAAA,CAAaC,EAAQC,CAAM,CAC5D,CACF,CAGO,SAASE,EAAgBC,CAAAA,CAAuC,CACrE,OAAQA,CAAAA,EACN,KAAKC,WAAW,GAAA,CACd,OAAOC,cAAc,GAAA,CACvB,KAAKD,WAAW,UAAA,CACd,OAAOC,cAAc,UAAA,CACvB,KAAKD,WAAW,gBAAA,CACd,OAAOC,cAAc,gBACzB,CACF,CAEA,IAAMC,EAAAA,CACJ,qQAEF,SAASC,EAAAA,CAAwBC,EAA2C,CAC1E,IAAMC,EAAWH,EAAAA,CAAwB,OAAA,CACvC,KACAE,CAAAA,CAAO,YAAA,CAAa,MAAM,CAAC,CAAA,CAAE,aAC/B,CAAA,CAAE,QAAQ,IAAA,CAAMA,CAAAA,CAAO,oBAAoB,KAAA,CAAM,CAAC,CAAA,CAAE,WAAA,EAAa,CAAA,CAEjE,OAAOE,eAAAA,CAAgBC,IAAAA,CAAK,UAAU,CAAA,EAAA,EAAKF,CAAQ,EAAE,CAAC,CACxD,CAEA,SAASG,EAAAA,CACPb,EACAS,CAAAA,CACY,CACZ,OAAOK,gBAAAA,CACLC,eAAAA,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,CAAM,8BAAA,CACN,OAAA,CAAAA,CACF,CACF","file":"chunk-VQMBZJB5.js","sourcesContent":["import { SignatureType } from '@polymarket/bindings/clob';\nimport { WalletType } from '@polymarket/bindings/gamma';\nimport type { HexString } from '@polymarket/types';\nimport {\n type EvmAddress,\n expectEvmAddress,\n expectHexString,\n never,\n} from '@polymarket/types';\nimport { AbiParameters, ContractAddress, Hash } from 'ox';\nimport type { EnvironmentConfig, WalletDerivationConfig } from './environments';\n\nexport type AccountIdentity = {\n signer: EvmAddress;\n wallet: EvmAddress;\n walletType: WalletType;\n};\n\n/** @internal */\nexport function resolveAccountIdentity(\n environment: EnvironmentConfig,\n signer: EvmAddress,\n wallet: EvmAddress = signer,\n): AccountIdentity {\n return {\n signer,\n wallet,\n walletType: classifyWalletType(environment, signer, wallet),\n };\n}\n\n/** @internal */\nexport function toSignatureType(walletType: WalletType): SignatureType {\n switch (walletType) {\n case WalletType.EOA:\n return SignatureType.EOA;\n case WalletType.POLY_PROXY:\n return SignatureType.POLY_PROXY;\n case WalletType.POLY_GNOSIS_SAFE:\n return SignatureType.POLY_GNOSIS_SAFE;\n }\n}\n\nconst PROXY_BYTECODE_TEMPLATE =\n '3d3d606380380380913d393d73%s5af4602a57600080fd5b602d8060366000396000f3363d3d373d3d3d363d73%s5af43d82803e903d91602b57fd5bf352e831dd00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000';\n\nfunction proxyWalletBytecodeHash(config: WalletDerivationConfig): HexString {\n const bytecode = PROXY_BYTECODE_TEMPLATE.replace(\n '%s',\n config.proxyFactory.slice(2).toLowerCase(),\n ).replace('%s', config.proxyImplementation.slice(2).toLowerCase());\n\n return expectHexString(Hash.keccak256(`0x${bytecode}`));\n}\n\nfunction deriveProxyWalletAddress(\n signer: EvmAddress,\n config: WalletDerivationConfig,\n): EvmAddress {\n return expectEvmAddress(\n ContractAddress.fromCreate2({\n bytecodeHash: proxyWalletBytecodeHash(config),\n from: config.proxyFactory,\n salt: Hash.keccak256(AbiParameters.encodePacked(['address'], [signer])),\n }),\n );\n}\n\n/** @internal */\nexport function deriveSafeWalletAddress(\n signer: EvmAddress,\n config: WalletDerivationConfig,\n): EvmAddress {\n return expectEvmAddress(\n ContractAddress.fromCreate2({\n bytecodeHash: config.safeInitCodeHash,\n from: config.safeFactory,\n salt: Hash.keccak256(\n AbiParameters.encode([{ name: 'address', type: 'address' }], [signer]),\n ),\n }),\n );\n}\n\nfunction sameAddress(left: EvmAddress, right: EvmAddress): boolean {\n return left.toLowerCase() === right.toLowerCase();\n}\n\nfunction classifyWalletType(\n environment: EnvironmentConfig,\n signer: EvmAddress,\n wallet: EvmAddress,\n): WalletType {\n if (sameAddress(wallet, signer)) {\n return WalletType.EOA;\n }\n\n const config = environment.walletDerivation;\n\n if (sameAddress(wallet, deriveProxyWalletAddress(signer, config))) {\n return WalletType.POLY_PROXY;\n }\n\n if (sameAddress(wallet, deriveSafeWalletAddress(signer, config))) {\n return WalletType.POLY_GNOSIS_SAFE;\n }\n\n never(\n `Wallet ${wallet} does not match the signer ${signer} or any supported deterministic wallet address.`,\n );\n}\n","import type { z } from 'zod';\nimport { UserInputError } from './errors';\n\n/**\n * Parses consumer input and throws `UserInputError` when validation fails.\n */\nexport function parseUserInput<TOutput>(\n input: unknown,\n schema: z.ZodType<TOutput>,\n): TOutput {\n const result = schema.safeParse(input);\n\n if (result.success) {\n return result.data;\n }\n\n throw UserInputError.fromZodError(result.error);\n}\n","import {\n type PaginationCursor,\n toPaginationCursor,\n} from '@polymarket/bindings';\nimport { type ResultAsync, unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport { UserInputError } from './errors';\n\nexport const PageSizeSchema = z.number().int().positive();\n\nexport type Page<T> = {\n items: T[];\n hasMore: boolean;\n nextCursor?: PaginationCursor;\n totalCount?: number;\n};\n\nexport type Paginated<T> = AsyncIterable<Page<T>> & {\n firstPage(): Promise<Page<T>>;\n from(cursor?: PaginationCursor): Paginated<T>;\n};\n\n/** @internal */\ntype OffsetCursorState = {\n offset: number;\n pageSize: number;\n};\n\n/** @internal */\nconst OffsetCursorStateSchema = z.object({\n offset: z.number().int().min(0),\n pageSize: PageSizeSchema,\n});\n\n/** @internal */\nexport function paginate<T, TError>(\n fetchPage: (cursor?: PaginationCursor) => ResultAsync<Page<T>, TError>,\n initialCursor?: PaginationCursor,\n): Paginated<T> {\n function createEmptyPaginator(): Paginated<T> {\n return {\n async firstPage() {\n return {\n items: [],\n hasMore: false,\n };\n },\n from() {\n return createEmptyPaginator();\n },\n async *[Symbol.asyncIterator]() {},\n };\n }\n\n function createPaginator(cursor = initialCursor): Paginated<T> {\n return {\n firstPage() {\n return unwrap(fetchPage(cursor));\n },\n from(nextCursor) {\n if (nextCursor === undefined) {\n return createEmptyPaginator();\n }\n\n return createPaginator(nextCursor);\n },\n async *[Symbol.asyncIterator]() {\n let currentCursor = cursor;\n\n while (true) {\n const page = await unwrap(fetchPage(currentCursor));\n\n yield page;\n\n if (!page.hasMore) {\n return;\n }\n\n currentCursor = page.nextCursor;\n }\n },\n };\n }\n\n return createPaginator();\n}\n\n/** @internal */\nexport function encodeOffsetCursor(state: OffsetCursorState): PaginationCursor {\n return toPaginationCursor(\n btoa(JSON.stringify(OffsetCursorStateSchema.parse(state))),\n );\n}\n\n/** @internal */\nexport function decodeOffsetCursor(\n cursor: PaginationCursor | undefined,\n pageSize: number,\n): OffsetCursorState {\n if (cursor === undefined) {\n return {\n offset: 0,\n pageSize,\n };\n }\n\n try {\n return OffsetCursorStateSchema.parse(JSON.parse(atob(cursor)));\n } catch (error) {\n throw new UserInputError('Invalid pagination cursor', { cause: error });\n }\n}\n","import { err, ok, type Result, ResultAsync } from '@polymarket/types';\nimport type { z } from 'zod';\nimport { UnexpectedResponseError } from './errors';\n\nexport function validateWith<TReturnType>(schema: z.ZodType<TReturnType>) {\n return function validateResponse(\n response: Response,\n ): ResultAsync<TReturnType, UnexpectedResponseError> {\n return ResultAsync.fromPromise(\n response.json(),\n () =>\n new UnexpectedResponseError(\n `Received non-JSON response from ${response.url}`,\n ),\n ).andThen((payload) => parseResponse(response.url, schema, payload));\n };\n}\n\nexport function readBlob(\n response: Response,\n): ResultAsync<Blob, UnexpectedResponseError> {\n return ResultAsync.fromPromise(\n response.blob(),\n () =>\n new UnexpectedResponseError(\n `Received unreadable binary response from ${response.url}`,\n ),\n );\n}\n\nfunction parseResponse<TReturnType>(\n endpoint: string,\n schema: z.ZodType<TReturnType>,\n response: unknown,\n): Result<TReturnType, UnexpectedResponseError> {\n const result = schema.safeParse(response);\n\n if (result.success) {\n return ok(result.data);\n }\n\n return err(UnexpectedResponseError.fromZodError(result.error, { endpoint }));\n}\n","export type SearchParamPrimitive = boolean | number | string;\n\nexport type SearchParamValue =\n | SearchParamPrimitive\n | readonly SearchParamPrimitive[];\n\nexport type SearchParamsInput = Record<string, SearchParamValue | undefined>;\n\nexport type SearchParamMappings<TParams extends SearchParamsInput> = {\n [TKey in keyof TParams]: string;\n};\n\ntype SnakeCaseSearchParamMappings = {\n format: 'snake_case';\n exceptions: Record<string, string | undefined>;\n};\n\nexport function toSearchParams<TParams extends SearchParamsInput>(\n params: TParams,\n mappings: SearchParamMappings<TParams> | SnakeCaseSearchParamMappings,\n): URLSearchParams {\n if (isSnakeCaseSearchParamMappings(mappings)) {\n return toSnakeCaseSearchParams(params, mappings.exceptions);\n }\n\n const searchParams = new URLSearchParams();\n\n for (const [paramKey, searchParamKey] of Object.entries(mappings) as Array<\n readonly [keyof TParams, string]\n >) {\n const value = params[paramKey];\n\n if (value === undefined) {\n continue;\n }\n\n if (isSearchParamArray(value)) {\n for (const item of value) {\n searchParams.append(searchParamKey, toSearchParamValue(item));\n }\n\n continue;\n }\n\n searchParams.append(searchParamKey, toSearchParamValue(value));\n }\n\n return searchParams;\n}\n\nexport function snakeCase<TParams extends SearchParamsInput>(\n exceptions: Partial<SearchParamMappings<TParams>> = {},\n): SnakeCaseSearchParamMappings {\n return {\n format: 'snake_case',\n exceptions,\n };\n}\n\n/**\n * Data endpoints use camelCase query keys and comma-separated arrays.\n */\nexport function toDataSearchParams<TParams extends SearchParamsInput>(\n params: TParams,\n): URLSearchParams {\n const searchParams = new URLSearchParams();\n\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) {\n continue;\n }\n\n if (Array.isArray(value)) {\n searchParams.append(key, value.map(toSearchParamValue).join(','));\n continue;\n }\n\n searchParams.append(key, toSearchParamValue(value as SearchParamPrimitive));\n }\n\n return searchParams;\n}\n\nfunction isSnakeCaseSearchParamMappings(\n mappings:\n | SearchParamMappings<SearchParamsInput>\n | SnakeCaseSearchParamMappings,\n): mappings is SnakeCaseSearchParamMappings {\n return 'format' in mappings;\n}\n\nfunction toSnakeCaseSearchParams<TParams extends SearchParamsInput>(\n params: TParams,\n exceptions: Record<string, string | undefined>,\n): URLSearchParams {\n const searchParams = new URLSearchParams();\n\n for (const [paramKey, value] of Object.entries(params) as Array<\n readonly [string, SearchParamValue]\n >) {\n if (value === undefined) {\n continue;\n }\n\n const searchParamKey = exceptions[paramKey] ?? toSnakeCase(paramKey);\n\n if (isSearchParamArray(value)) {\n for (const item of value) {\n searchParams.append(searchParamKey, toSearchParamValue(item));\n }\n\n continue;\n }\n\n searchParams.append(searchParamKey, toSearchParamValue(value));\n }\n\n return searchParams;\n}\n\nfunction isSearchParamArray(\n value: SearchParamValue,\n): value is readonly SearchParamPrimitive[] {\n return Array.isArray(value);\n}\n\nfunction toSnakeCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `_${character.toLowerCase()}`);\n}\n\nexport function toSearchParamValue(value: SearchParamPrimitive): string {\n return String(value);\n}\n","import {\n PaginationCursorSchema,\n toPaginationCursor,\n} from '@polymarket/bindings';\nimport {\n AssetTypeSchema,\n type BalanceAllowanceResponse,\n BalanceAllowanceResponseSchema,\n type ClobTrade,\n ClobTradesPageSchema,\n ClosedOnlyModeSchema,\n END_CURSOR,\n type NotificationsResponse,\n NotificationsResponseSchema,\n type OpenOrder,\n OpenOrderSchema,\n OpenOrdersPageSchema,\n OrderScoringResponseSchema,\n type OrdersScoringResponse,\n OrdersScoringResponseSchema,\n type RewardsPercentages,\n RewardsPercentagesSchema,\n type TotalUserEarning,\n TotalUserEarningsResponseSchema,\n type UserEarning,\n UserEarningsPageSchema,\n type UserRewardsEarning,\n UserRewardsEarningsPageSchema,\n} from '@polymarket/bindings/clob';\nimport { unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport { toSignatureType } from '../account';\nimport type { BaseSecureClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n SigningError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport { PageSizeSchema, type Paginated, paginate } from '../pagination';\nimport { validateWith } from '../response';\nimport { snakeCase, toSearchParams } from './params';\n\nexport type FetchClosedOnlyModeError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Fetches whether the account is restricted to closed-only trading.\n *\n * @throws {@link FetchClosedOnlyModeError}\n *\n * @example\n * ```ts\n * const closedOnly = await fetchClosedOnlyMode(client);\n * ```\n */\nexport async function fetchClosedOnlyMode(\n client: BaseSecureClient,\n): Promise<boolean> {\n const response = await unwrap(\n client.secureClob\n .get('/auth/ban-status/closed-only')\n .andThen(validateWith(ClosedOnlyModeSchema)),\n );\n\n return response.closed_only;\n}\n\nconst ListOpenOrdersRequestSchema = z\n .object({\n assetId: z.string().optional(),\n cursor: PaginationCursorSchema.optional(),\n id: z.string().optional(),\n market: z.string().optional(),\n })\n .default({});\n\nexport type ListOpenOrdersRequest = z.input<typeof ListOpenOrdersRequestSchema>;\nexport type ListOpenOrdersError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists open orders for the authenticated account across all pages.\n *\n * @throws {@link ListOpenOrdersError}\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listOpenOrders(client, {\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: OpenOrder[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listOpenOrders(client, {\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * for await (const page of result) {\n * // page.items: OpenOrder[]\n * }\n * ```\n */\nexport function listOpenOrders(\n client: BaseSecureClient,\n request?: ListOpenOrdersRequest,\n): Paginated<OpenOrder> {\n const { cursor, ...params } = parseUserInput(\n request,\n ListOpenOrdersRequestSchema,\n );\n\n return paginate(\n (nextCursor) =>\n client.secureClob\n .get('/data/orders', {\n params: toSearchParams({ ...params, nextCursor }, snakeCase()),\n })\n .andThen(validateWith(OpenOrdersPageSchema))\n .map((response) => ({\n items: response.data,\n hasMore: response.next_cursor !== END_CURSOR,\n nextCursor:\n response.next_cursor === END_CURSOR\n ? undefined\n : toPaginationCursor(response.next_cursor),\n totalCount: response.count,\n })),\n cursor,\n );\n}\n\nconst FetchOrderRequestSchema = z.object({\n orderId: z.string(),\n});\n\nexport type FetchOrderRequest = z.input<typeof FetchOrderRequestSchema>;\nexport type FetchOrderError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches a single order for the authenticated account.\n *\n * @throws {@link FetchOrderError}\n *\n * @example\n * ```ts\n * const order = await fetchOrder(client, {\n * orderId: '123',\n * });\n * ```\n */\nexport async function fetchOrder(\n client: BaseSecureClient,\n request: FetchOrderRequest,\n): Promise<OpenOrder> {\n const params = parseUserInput(request, FetchOrderRequestSchema);\n\n return unwrap(\n client.secureClob\n .get(`/data/order/${params.orderId}`)\n .andThen(validateWith(OpenOrderSchema)),\n );\n}\n\nconst ListAccountTradesRequestFields = {\n after: z.string().optional(),\n assetId: z.string().optional(),\n before: z.string().optional(),\n cursor: PaginationCursorSchema.optional(),\n id: z.string().optional(),\n makerAddress: z.string().optional(),\n market: z.string().optional(),\n};\n\nconst ListAccountTradesRequestSchema = z\n .object(ListAccountTradesRequestFields)\n .default({});\n\nexport type ListAccountTradesRequest = z.input<\n typeof ListAccountTradesRequestSchema\n>;\nexport type ListAccountTradesError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists trades for the authenticated account across all pages.\n *\n * @throws {@link ListAccountTradesError}\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listAccountTrades(client, {\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: ClobTrade[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listAccountTrades(client, {\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * for await (const page of result) {\n * // page.items: ClobTrade[]\n * }\n * ```\n */\nexport function listAccountTrades(\n client: BaseSecureClient,\n request?: ListAccountTradesRequest,\n): Paginated<ClobTrade> {\n const { cursor, ...params } = parseUserInput(\n request,\n ListAccountTradesRequestSchema,\n );\n\n return paginate(\n (nextCursor) =>\n client.secureClob\n .get('/data/trades', {\n params: toSearchParams({ ...params, nextCursor }, snakeCase()),\n })\n .andThen(validateWith(ClobTradesPageSchema))\n .map((response) => ({\n items: response.data,\n hasMore: response.next_cursor !== END_CURSOR,\n nextCursor:\n response.next_cursor === END_CURSOR\n ? undefined\n : toPaginationCursor(response.next_cursor),\n totalCount: response.count,\n })),\n cursor,\n );\n}\n\nexport type FetchNotificationsError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError;\n\nconst DropNotificationsRequestSchema = z.object({\n ids: z.array(z.string()).min(1),\n});\n\nexport type DropNotificationsRequest = z.input<\n typeof DropNotificationsRequestSchema\n>;\n\n/**\n * Fetches notifications for the authenticated account.\n *\n * @throws {@link FetchNotificationsError}\n *\n * @example\n * ```ts\n * const notifications = await fetchNotifications(client);\n * ```\n */\nexport async function fetchNotifications(\n client: BaseSecureClient,\n): Promise<NotificationsResponse> {\n const signatureType = toSignatureType(client.account.walletType);\n\n return unwrap(\n client.secureClob\n .get('/notifications', {\n params: toSearchParams({ signatureType }, snakeCase()),\n })\n .andThen(validateWith(NotificationsResponseSchema)),\n );\n}\n\nexport type DropNotificationsError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Drops notifications for the authenticated account.\n *\n * @throws {@link DropNotificationsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * await dropNotifications(client, {\n * ids: ['1', '2'],\n * });\n * ```\n */\nexport async function dropNotifications(\n client: BaseSecureClient,\n request: DropNotificationsRequest,\n): Promise<void> {\n const params = parseUserInput(request, DropNotificationsRequestSchema);\n const signatureType = toSignatureType(client.account.walletType);\n const searchParams = toSearchParams(\n {\n ids: params.ids.join(','),\n signatureType,\n },\n snakeCase(),\n );\n\n await unwrap(\n client.secureClob.del('/notifications', {\n params: searchParams,\n }),\n );\n}\n\nconst FetchBalanceAllowanceRequestSchema = z.object({\n assetType: AssetTypeSchema,\n tokenId: z.string().optional(),\n});\n\nexport type FetchBalanceAllowanceRequest = z.input<\n typeof FetchBalanceAllowanceRequestSchema\n>;\n\nexport type FetchBalanceAllowanceError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches balance and allowance for the authenticated account.\n *\n * @remarks\n * This is a low-level action that most SDK consumers will not need.\n *\n * @throws {@link FetchBalanceAllowanceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const balanceAllowance = await fetchBalanceAllowance(client, {\n * assetType: AssetType.COLLATERAL,\n * });\n * ```\n */\nexport async function fetchBalanceAllowance(\n client: BaseSecureClient,\n request: FetchBalanceAllowanceRequest,\n): Promise<BalanceAllowanceResponse> {\n const params = parseUserInput(request, FetchBalanceAllowanceRequestSchema);\n const signatureType = toSignatureType(client.account.walletType);\n\n return unwrap(\n client.secureClob\n .get('/balance-allowance', {\n params: toSearchParams(\n {\n ...params,\n signatureType,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(BalanceAllowanceResponseSchema)),\n );\n}\n\nconst UpdateBalanceAllowanceRequestSchema = z.object({\n assetType: AssetTypeSchema,\n tokenId: z.string().optional(),\n});\n\nexport type UpdateBalanceAllowanceRequest = z.input<\n typeof UpdateBalanceAllowanceRequestSchema\n>;\n\nexport type UpdateBalanceAllowanceError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Refreshes balance and allowance for the authenticated account.\n *\n * @remarks\n * This is a low-level action that most SDK consumers will not need.\n *\n * @throws {@link UpdateBalanceAllowanceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const balanceAllowance = await updateBalanceAllowance(client, {\n * assetType: AssetType.COLLATERAL,\n * });\n * ```\n */\nexport async function updateBalanceAllowance(\n client: BaseSecureClient,\n request: UpdateBalanceAllowanceRequest,\n): Promise<BalanceAllowanceResponse> {\n const params = parseUserInput(request, UpdateBalanceAllowanceRequestSchema);\n const signatureType = toSignatureType(client.account.walletType);\n const searchParams = toSearchParams(\n {\n ...params,\n signatureType,\n },\n snakeCase(),\n );\n\n await unwrap(\n client.secureClob.get('/balance-allowance/update', {\n params: searchParams,\n }),\n );\n\n return fetchBalanceAllowance(client, params);\n}\n\nconst FetchOrderScoringRequestSchema = z.object({\n orderId: z.string(),\n});\n\nexport type FetchOrderScoringRequest = z.input<\n typeof FetchOrderScoringRequestSchema\n>;\nexport type FetchOrderScoringError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches whether a single order is currently scoring.\n *\n * @throws {@link FetchOrderScoringError}\n *\n * @example\n * ```ts\n * const scoring = await fetchOrderScoring(client, {\n * orderId: '123',\n * });\n * ```\n */\nexport async function fetchOrderScoring(\n client: BaseSecureClient,\n request: FetchOrderScoringRequest,\n): Promise<boolean> {\n const params = parseUserInput(request, FetchOrderScoringRequestSchema);\n const response = await unwrap(\n client.secureClob\n .get('/order-scoring', {\n params: toSearchParams(params, snakeCase()),\n })\n .andThen(validateWith(OrderScoringResponseSchema)),\n );\n\n return response.scoring;\n}\n\nconst FetchOrdersScoringRequestSchema = z.object({\n orderIds: z.array(z.string()),\n});\n\nexport type FetchOrdersScoringRequest = z.input<\n typeof FetchOrdersScoringRequestSchema\n>;\nexport type FetchOrdersScoringError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches scoring state for multiple orders.\n *\n * @throws {@link FetchOrdersScoringError}\n *\n * @example\n * ```ts\n * const scoring = await fetchOrdersScoring(client, {\n * orderIds: ['1', '2'],\n * });\n * ```\n */\nexport async function fetchOrdersScoring(\n client: BaseSecureClient,\n request: FetchOrdersScoringRequest,\n): Promise<OrdersScoringResponse> {\n const params = parseUserInput(request, FetchOrdersScoringRequestSchema);\n const body = params.orderIds;\n\n return unwrap(\n client.secureClob\n .post('/orders-scoring', {\n json: body,\n })\n .andThen(validateWith(OrdersScoringResponseSchema)),\n );\n}\n\nconst ListUserEarningsForDayRequestSchema = z.object({\n cursor: PaginationCursorSchema.optional(),\n date: z.string(),\n});\n\nexport type ListUserEarningsForDayRequest = z.input<\n typeof ListUserEarningsForDayRequestSchema\n>;\nexport type ListUserEarningsForDayError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists per-market earnings for the authenticated account on a given day.\n *\n * @throws {@link ListUserEarningsForDayError}\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listUserEarningsForDay(client, {\n * date: '2026-04-16',\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: UserEarning[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listUserEarningsForDay(client, {\n * date: '2026-04-16',\n * });\n *\n * for await (const page of result) {\n * // page.items: UserEarning[]\n * }\n * ```\n */\nexport function listUserEarningsForDay(\n client: BaseSecureClient,\n request: ListUserEarningsForDayRequest,\n): Paginated<UserEarning> {\n const { cursor, ...params } = parseUserInput(\n request,\n ListUserEarningsForDayRequestSchema,\n );\n const signatureType = toSignatureType(client.account.walletType);\n\n return paginate(\n (nextCursor) =>\n client.secureClob\n .get('/rewards/user', {\n params: toSearchParams(\n {\n ...params,\n nextCursor,\n signatureType,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(UserEarningsPageSchema))\n .map((response) => ({\n items: response.data,\n hasMore: response.next_cursor !== END_CURSOR,\n nextCursor:\n response.next_cursor === END_CURSOR\n ? undefined\n : toPaginationCursor(response.next_cursor),\n totalCount: response.count,\n })),\n cursor,\n );\n}\n\nexport type FetchTotalEarningsForUserForDayRequest = z.input<\n typeof ListUserEarningsForDayRequestSchema\n>;\nexport type FetchTotalEarningsForUserForDayError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches total earnings for the authenticated account on a given day.\n *\n * @throws {@link FetchTotalEarningsForUserForDayError}\n *\n * @example\n * ```ts\n * const earnings = await fetchTotalEarningsForUserForDay(client, {\n * date: '2026-04-16',\n * });\n * ```\n */\nexport async function fetchTotalEarningsForUserForDay(\n client: BaseSecureClient,\n request: FetchTotalEarningsForUserForDayRequest,\n): Promise<TotalUserEarning[]> {\n const params = parseUserInput(request, ListUserEarningsForDayRequestSchema);\n const signatureType = toSignatureType(client.account.walletType);\n\n return unwrap(\n client.secureClob\n .get('/rewards/user/total', {\n params: toSearchParams(\n {\n ...params,\n signatureType,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(TotalUserEarningsResponseSchema)),\n );\n}\n\nconst ListUserEarningsAndMarketsConfigRequestSchema = z.object({\n cursor: PaginationCursorSchema.optional(),\n date: z.string(),\n noCompetition: z.boolean().optional(),\n orderBy: z.string().optional(),\n pageSize: PageSizeSchema.max(500).default(100),\n position: z.string().optional(),\n});\n\nexport type ListUserEarningsAndMarketsConfigRequest = z.input<\n typeof ListUserEarningsAndMarketsConfigRequestSchema\n>;\nexport type ListUserEarningsAndMarketsConfigError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists market reward configuration and earnings for the authenticated account on a given day.\n *\n * @throws {@link ListUserEarningsAndMarketsConfigError}\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listUserEarningsAndMarketsConfig(client, {\n * date: '2026-04-16',\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: UserRewardsEarning[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listUserEarningsAndMarketsConfig(client, {\n * date: '2026-04-16',\n * });\n *\n * for await (const page of result) {\n * // page.items: UserRewardsEarning[]\n * }\n * ```\n */\nexport function listUserEarningsAndMarketsConfig(\n client: BaseSecureClient,\n request: ListUserEarningsAndMarketsConfigRequest,\n): Paginated<UserRewardsEarning> {\n const { cursor, ...params } = parseUserInput(\n request,\n ListUserEarningsAndMarketsConfigRequestSchema,\n );\n const signatureType = toSignatureType(client.account.walletType);\n\n return paginate(\n (nextCursor) =>\n client.secureClob\n .get('/rewards/user/markets', {\n params: toSearchParams(\n {\n ...params,\n nextCursor,\n signatureType,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(UserRewardsEarningsPageSchema))\n .map((response) => ({\n items: response.data,\n hasMore: response.next_cursor !== END_CURSOR,\n nextCursor:\n response.next_cursor === END_CURSOR\n ? undefined\n : toPaginationCursor(response.next_cursor),\n totalCount: response.count,\n })),\n cursor,\n );\n}\n\nexport type FetchRewardPercentagesError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Fetches reward percentages for the authenticated account.\n *\n * @throws {@link FetchRewardPercentagesError}\n *\n * @example\n * ```ts\n * const percentages = await fetchRewardPercentages(client);\n * ```\n */\nexport async function fetchRewardPercentages(\n client: BaseSecureClient,\n): Promise<RewardsPercentages> {\n const signatureType = toSignatureType(client.account.walletType);\n\n return unwrap(\n client.secureClob\n .get('/rewards/user/percentages', {\n params: toSearchParams({ signatureType }, snakeCase()),\n })\n .andThen(validateWith(RewardsPercentagesSchema)),\n );\n}\n","import { PaginationCursorSchema } from '@polymarket/bindings';\nimport {\n type Activity,\n ActivityTypeSchema,\n ListActivityResponseSchema,\n ListTradesResponseSchema,\n SideSchema,\n type Trade,\n} from '@polymarket/bindings/data';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport {\n decodeOffsetCursor,\n encodeOffsetCursor,\n PageSizeSchema,\n type Paginated,\n paginate,\n} from '../pagination';\nimport { validateWith } from '../response';\nimport { toDataSearchParams } from './params';\n\nconst ActivitySortBySchema = z.enum(['TIMESTAMP', 'TOKENS', 'CASH']);\nconst SortDirectionSchema = z.enum(['ASC', 'DESC']);\nconst TradeFilterTypeSchema = z.enum(['CASH', 'TOKENS']);\n\nconst ListTradesRequestSchema = z\n .object({\n cursor: PaginationCursorSchema.optional(),\n pageSize: PageSizeSchema.default(20),\n takerOnly: z.boolean().optional(),\n filterType: TradeFilterTypeSchema.optional(),\n filterAmount: z.number().optional(),\n market: z.array(z.string()).optional(),\n eventId: z.array(z.number().int()).optional(),\n user: z.string().optional(),\n side: SideSchema.optional(),\n })\n .refine((value) => !(value.market && value.eventId), {\n message: 'Provide market or eventId, not both',\n path: ['eventId'],\n })\n .refine(\n (value) =>\n (value.filterType === undefined) === (value.filterAmount === undefined),\n {\n message: 'Provide filterType and filterAmount together',\n path: ['filterAmount'],\n },\n );\n\nconst ListActivityRequestSchema = z\n .object({\n cursor: PaginationCursorSchema.optional(),\n pageSize: PageSizeSchema.default(20),\n user: z.string(),\n market: z.array(z.string()).optional(),\n eventId: z.array(z.number().int()).optional(),\n type: z.array(ActivityTypeSchema).optional(),\n start: z.number().int().optional(),\n end: z.number().int().optional(),\n sortBy: ActivitySortBySchema.optional(),\n sortDirection: SortDirectionSchema.optional(),\n side: SideSchema.optional(),\n })\n .refine((value) => !(value.market && value.eventId), {\n message: 'Provide market or eventId, not both',\n path: ['eventId'],\n });\n\nexport type ListTradesRequest = z.input<typeof ListTradesRequestSchema>;\nexport type ListActivityRequest = z.input<typeof ListActivityRequestSchema>;\n\nexport type ListTradesError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists trades for a wallet, market, or event.\n *\n * @throws {@link ListTradesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listTrades(client, {\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: Trade[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listTrades(client, {\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * for await (const page of result) {\n * // page.items: Trade[]\n * }\n * ```\n */\nexport function listTrades(\n client: BaseClient,\n request: ListTradesRequest = {},\n): Paginated<Trade> {\n const { cursor, pageSize, ...params } = parseUserInput(\n request,\n ListTradesRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.data\n .get('/trades', {\n params: toDataSearchParams({\n ...params,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n }),\n })\n .andThen(validateWith(ListTradesResponseSchema))\n .map((trades) => {\n const hasMore = trades.length > decoded.pageSize;\n\n return {\n items: trades.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n\nexport type ListActivityError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists wallet activity.\n *\n * @throws {@link ListActivityError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listActivity(client, {\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: Activity[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listActivity(client, {\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * for await (const page of result) {\n * // page.items: Activity[]\n * }\n * ```\n */\nexport function listActivity(\n client: BaseClient,\n request: ListActivityRequest,\n): Paginated<Activity> {\n const { cursor, pageSize, ...params } = parseUserInput(\n request,\n ListActivityRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.data\n .get('/activity', {\n params: toDataSearchParams({\n ...params,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n }),\n })\n .andThen(validateWith(ListActivityResponseSchema))\n .map((activity) => {\n const hasMore = activity.length > decoded.pageSize;\n\n return {\n items: activity.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n","import type { ConditionId } from '@polymarket/bindings';\nimport { type EvmAddress, type HexString, invariant } from '@polymarket/types';\nimport { AbiFunction, AbiParameters } from 'ox';\nimport { UserInputError } from './errors';\nimport type { TransactionCall } from './types';\n\nconst ZERO_BYTES32 =\n '0x0000000000000000000000000000000000000000000000000000000000000000';\nconst ERC20_APPROVE_FUNCTION = AbiFunction.from(\n 'function approve(address spender, uint256 amount)',\n);\nconst ERC20_TRANSFER_FUNCTION = AbiFunction.from(\n 'function transfer(address recipient, uint256 amount)',\n);\nconst ERC1155_SET_APPROVAL_FOR_ALL_FUNCTION = AbiFunction.from(\n 'function setApprovalForAll(address operator, bool approved)',\n);\nconst CTF_SPLIT_POSITION_FUNCTION = AbiFunction.from(\n 'function splitPosition(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)',\n);\nconst CTF_MERGE_POSITIONS_FUNCTION = AbiFunction.from(\n 'function mergePositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] partition, uint256 amount)',\n);\nconst CTF_REDEEM_POSITIONS_FUNCTION = AbiFunction.from(\n 'function redeemPositions(address collateralToken, bytes32 parentCollectionId, bytes32 conditionId, uint256[] indexSets)',\n);\nconst NEG_RISK_REDEEM_POSITIONS_FUNCTION = AbiFunction.from(\n 'function redeemPositions(bytes32 _conditionId, uint256[] _amounts)',\n);\nconst SAFE_MULTISEND_FUNCTION = AbiFunction.from('function multiSend(bytes)');\nconst BINARY_OUTCOME_PARTITION = [1n, 2n] as const;\nconst BINARY_OUTCOME_INDEX_SETS = [1n, 2n] as const;\n\n/** @internal */\nexport const MAX_UINT256 = (1n << 256n) - 1n;\n\nexport type Erc20ApprovalCallError = UserInputError;\n\n/**\n * Creates a transaction call for `approve(address,uint256)` on an ERC-20 token.\n *\n * @throws {@link Erc20ApprovalCallError}\n * Thrown when the approval amount is invalid.\n */\nexport function erc20ApprovalCall(\n tokenAddress: EvmAddress,\n spender: EvmAddress,\n amount: bigint,\n): TransactionCall {\n if (amount < 0n) {\n throw new UserInputError('Approval amount must be non-negative');\n }\n\n if (amount > MAX_UINT256) {\n throw new UserInputError('Approval amount exceeds uint256 range');\n }\n\n return {\n data: encodeErc20ApproveCall(spender, amount),\n to: tokenAddress,\n };\n}\n\n/**\n * Creates a transaction call for `setApprovalForAll(address,bool)` on an ERC-1155 token.\n */\nexport function erc1155ApprovalForAllCall(\n tokenAddress: EvmAddress,\n operator: EvmAddress,\n approved: boolean,\n): TransactionCall {\n return {\n data: encodeErc1155SetApprovalForAllCall(operator, approved),\n to: tokenAddress,\n };\n}\n\nexport type Erc20TransferCallError = UserInputError;\n\n/**\n * Creates a transaction call for `transfer(address,uint256)` on an ERC-20 token.\n *\n * @throws {@link Erc20TransferCallError}\n * Thrown when the transfer amount is invalid.\n */\nexport function erc20TransferCall(\n tokenAddress: EvmAddress,\n recipient: EvmAddress,\n amount: bigint,\n): TransactionCall {\n if (amount < 0n) {\n throw new UserInputError('Transfer amount must be non-negative');\n }\n\n if (amount > MAX_UINT256) {\n throw new UserInputError('Transfer amount exceeds uint256 range');\n }\n\n return {\n data: encodeErc20TransferCall(recipient, amount),\n to: tokenAddress,\n };\n}\n\nexport type CtfRedeemPositionsCallError = UserInputError;\n\nexport type SplitPositionCallError = UserInputError;\n\n/**\n * Creates a transaction call for `splitPosition(address,bytes32,bytes32,uint256[],uint256)`.\n * Works with both the Conditional Tokens contract and the neg-risk adapter.\n *\n * @remarks\n * This is a low-level transaction builder that most SDK consumers will not need.\n *\n * @throws {@link SplitPositionCallError}\n * Thrown when the amount is invalid.\n */\nexport function splitPositionCall(\n targetAddress: EvmAddress,\n collateralTokenAddress: EvmAddress,\n conditionId: ConditionId,\n amount: bigint,\n negRisk = false,\n): TransactionCall {\n return {\n data: encodeSplitPositionCall(\n collateralTokenAddress,\n conditionId,\n amount,\n negRisk,\n ),\n to: targetAddress,\n };\n}\n\nexport type MergePositionsCallError = UserInputError;\n\n/**\n * Creates a transaction call for `mergePositions(address,bytes32,bytes32,uint256[],uint256)`.\n * Works with both the Conditional Tokens contract and the neg-risk adapter.\n *\n * @remarks\n * This is a low-level transaction builder that most SDK consumers will not need.\n *\n * @throws {@link MergePositionsCallError}\n * Thrown when the amount is invalid.\n */\nexport function mergePositionsCall(\n targetAddress: EvmAddress,\n collateralTokenAddress: EvmAddress,\n conditionId: ConditionId,\n amount: bigint,\n negRisk = false,\n): TransactionCall {\n return {\n data: encodeMergePositionsCall(\n collateralTokenAddress,\n conditionId,\n amount,\n negRisk,\n ),\n to: targetAddress,\n };\n}\n\n/**\n * Creates a transaction call for `redeemPositions(address,bytes32,bytes32,uint256[])`\n * on the Conditional Tokens contract.\n *\n * @remarks\n * This is a low-level transaction builder that most SDK consumers will not need.\n *\n * @throws {@link CtfRedeemPositionsCallError}\n * Thrown when the condition is invalid.\n */\nexport function ctfRedeemPositionsCall(\n conditionalTokensAddress: EvmAddress,\n collateralTokenAddress: EvmAddress,\n conditionId: ConditionId,\n): TransactionCall {\n return {\n data: encodeCtfRedeemPositionsCall(collateralTokenAddress, conditionId),\n to: conditionalTokensAddress,\n };\n}\n\nexport type NegRiskRedeemPositionsCallError = UserInputError;\n\n/**\n * Creates a transaction call for `redeemPositions(bytes32,uint256[])` on the\n * negative-risk adapter contract.\n *\n * @remarks\n * This is a low-level transaction builder that most SDK consumers will not need.\n *\n * @throws {@link NegRiskRedeemPositionsCallError}\n * Thrown when the condition or redeem amounts are invalid.\n */\nexport function negRiskRedeemPositionsCall(\n negRiskAdapterAddress: EvmAddress,\n conditionId: ConditionId,\n amounts: readonly [bigint, bigint],\n): TransactionCall {\n return {\n data: encodeNegRiskRedeemPositionsCall(conditionId, amounts),\n to: negRiskAdapterAddress,\n };\n}\n\nfunction encodeErc20ApproveCall(\n spender: EvmAddress,\n amount: bigint,\n): HexString {\n invariant(amount >= 0n, 'Approval amount must be non-negative');\n\n return AbiFunction.encodeData(ERC20_APPROVE_FUNCTION, [spender, amount]);\n}\n\nfunction encodeErc1155SetApprovalForAllCall(\n operator: EvmAddress,\n approved: boolean,\n): HexString {\n return AbiFunction.encodeData(ERC1155_SET_APPROVAL_FOR_ALL_FUNCTION, [\n operator,\n approved,\n ]);\n}\n\nfunction encodeErc20TransferCall(\n recipient: EvmAddress,\n amount: bigint,\n): HexString {\n return AbiFunction.encodeData(ERC20_TRANSFER_FUNCTION, [recipient, amount]);\n}\n\nfunction encodeSplitPositionCall(\n collateralTokenAddress: EvmAddress,\n conditionId: ConditionId,\n amount: bigint,\n negRisk: boolean,\n): HexString {\n return AbiFunction.encodeData(CTF_SPLIT_POSITION_FUNCTION, [\n collateralTokenAddress,\n ZERO_BYTES32,\n conditionId,\n negRisk ? [] : BINARY_OUTCOME_PARTITION,\n expectUint256(amount, 'Split amount'),\n ]);\n}\n\nfunction encodeMergePositionsCall(\n collateralTokenAddress: EvmAddress,\n conditionId: ConditionId,\n amount: bigint,\n negRisk: boolean,\n): HexString {\n return AbiFunction.encodeData(CTF_MERGE_POSITIONS_FUNCTION, [\n collateralTokenAddress,\n ZERO_BYTES32,\n conditionId,\n negRisk ? [] : BINARY_OUTCOME_PARTITION,\n expectUint256(amount, 'Merge amount'),\n ]);\n}\n\nfunction encodeCtfRedeemPositionsCall(\n collateralTokenAddress: EvmAddress,\n conditionId: ConditionId,\n): HexString {\n return AbiFunction.encodeData(CTF_REDEEM_POSITIONS_FUNCTION, [\n collateralTokenAddress,\n ZERO_BYTES32,\n conditionId,\n BINARY_OUTCOME_INDEX_SETS,\n ]);\n}\n\nfunction encodeNegRiskRedeemPositionsCall(\n conditionId: ConditionId,\n amounts: readonly [bigint, bigint],\n): HexString {\n return AbiFunction.encodeData(NEG_RISK_REDEEM_POSITIONS_FUNCTION, [\n conditionId,\n amounts.map((amount) => expectUint256(amount, 'Redeem amount')),\n ]);\n}\n\nfunction expectUint256(value: bigint, label: string): bigint {\n if (value < 0n) {\n throw new UserInputError(`${label} must be non-negative`);\n }\n\n if (value > MAX_UINT256) {\n throw new UserInputError(`${label} exceeds uint256 range`);\n }\n\n return value;\n}\n\n/** @internal */\nexport function encodeSafeMultisendCall(\n calls: readonly TransactionCall[],\n): HexString {\n const encodedTransactions = calls.map((call) =>\n encodeSafeMultisendTransaction(call),\n );\n\n return AbiFunction.encodeData(SAFE_MULTISEND_FUNCTION, [\n encodedTransactions.length === 0\n ? '0x'\n : AbiParameters.encodePacked(\n Array.from({ length: encodedTransactions.length }, () => 'bytes'),\n encodedTransactions,\n ),\n ]);\n}\n\nfunction encodeSafeMultisendTransaction(call: TransactionCall): HexString {\n const value = call.value ?? 0n;\n\n return AbiParameters.encodePacked(\n ['uint8', 'address', 'uint256', 'uint256', 'bytes'],\n [0, call.to, value, BigInt((call.data.length - 2) / 2), call.data],\n );\n}\n","import type { TransactionId } from '@polymarket/bindings';\nimport {\n type EvmAddress,\n type HexString,\n invariant,\n type TxHash,\n} from '@polymarket/types';\nimport type { WaitForGaslessTransactionError } from './actions';\n\nexport type TypedDataField = {\n name: string;\n type: string;\n};\n\nexport type TypedData = Record<string, readonly TypedDataField[]>;\n\nexport type TypedDataDomain = {\n chainId?: number;\n name?: string;\n salt?: HexString;\n verifyingContract?: EvmAddress;\n version?: string;\n};\n\nexport type TypedDataPayload = {\n domain: TypedDataDomain;\n message: Record<string, unknown>;\n primaryType: string;\n types: TypedData;\n};\n\nexport type TransactionCall = {\n data: HexString;\n to: EvmAddress;\n value?: bigint;\n};\n\n/** @internal */\nexport type ApiKeyAuthorizationRequest = {\n method: 'DELETE' | 'GET' | 'POST';\n path: string;\n body?: string;\n};\n\nexport interface ApiKeyAuthorization {\n /** @internal */\n get isBuilderKey(): boolean;\n\n /** @internal */\n get supportGasless(): boolean;\n\n /** @internal */\n authorize(request: ApiKeyAuthorizationRequest): Promise<HeadersInit>;\n}\n\nexport type TransactionOutcome = {\n /**\n * The hash of the settled transaction.\n */\n transactionHash: TxHash;\n /**\n * The unique identifier of the settled transaction when submitted through the Polymarket API,\n * or null if the transaction was submitted directly to the blockchain.\n */\n transactionId: TransactionId | null;\n};\n\nexport type WaitForTransactionError = WaitForGaslessTransactionError;\n\nexport interface TransactionHandle {\n /**\n * The hash of the submitted transaction, or null if the transaction is pending submission.\n */\n readonly transactionHash: TxHash | null;\n /**\n * The unique identifier of the submitted transaction when submitted through the Polymarket API,\n * or null if the transaction was submitted directly to the blockchain.\n */\n readonly transactionId: TransactionId | null;\n /**\n * Waits for the submitted transaction to settle.\n *\n * @throws {@link WaitForTransactionError}\n * Thrown when polling times out, the transaction reaches a terminal failure state, or a later read returns an unexpected response.\n */\n wait(): Promise<TransactionOutcome>;\n}\n\nexport interface DeployTransactionHandle extends TransactionHandle {\n /**\n * The deterministic address of the Safe wallet being deployed by this transaction.\n */\n readonly wallet: EvmAddress;\n}\n\n/** @internal */\nexport function expectTransactionHandle(\n value: unknown,\n message = 'Expected a TransactionHandle',\n): TransactionHandle {\n invariant(\n typeof value === 'object' &&\n value !== null &&\n 'transactionHash' in value &&\n 'transactionId' in value &&\n 'wait' in value &&\n typeof value.wait === 'function',\n message,\n );\n return value as TransactionHandle;\n}\n","import type { EvmAddress, EvmSignature, HexString } from '@polymarket/types';\nimport type { CancelledSigningError, SigningError } from './errors';\nimport type {\n TransactionCall,\n TransactionHandle,\n TypedDataPayload,\n} from './types';\n\nexport type SignerTransactionRequest = {\n chainId: number;\n data?: HexString;\n to: EvmAddress;\n value?: bigint;\n};\n\nexport type RequestAddressRequest = {\n kind: 'requestAddress';\n};\n\nexport type SignAuthMessageRequest = {\n kind: 'signAuthMessage';\n payload: TypedDataPayload;\n};\n\nexport type SendErc20ApprovalTransactionRequest = {\n kind: 'sendErc20ApprovalTransaction';\n request: SignerTransactionRequest;\n};\n\nexport type SendErc1155ApprovalForAllTransactionRequest = {\n kind: 'sendErc1155ApprovalForAllTransaction';\n request: SignerTransactionRequest;\n};\n\nexport type SendErc20TransferTransactionRequest = {\n kind: 'sendErc20TransferTransaction';\n request: SignerTransactionRequest;\n};\n\nexport type SignGaslessTypedDataRequest = {\n kind: 'signGaslessTypedData';\n payload: TypedDataPayload;\n};\n\nexport type SignGaslessMessageRequest = {\n kind: 'signGaslessMessage';\n payload: TypedDataPayload;\n};\n\nexport type SendSplitPositionTransactionRequest = {\n kind: 'sendSplitPositionTransaction';\n request: SignerTransactionRequest;\n};\n\nexport type SendMergePositionsTransactionRequest = {\n kind: 'sendMergePositionsTransaction';\n request: SignerTransactionRequest;\n};\n\nexport type SendRedeemPositionsTransactionRequest = {\n kind: 'sendRedeemPositionsTransaction';\n request: SignerTransactionRequest;\n};\n\nexport type SignOrderRequest = {\n kind: 'signOrder';\n payload: TypedDataPayload;\n};\n\nexport type AuthenticationWorkflowRequest =\n | RequestAddressRequest\n | SignAuthMessageRequest;\n\nexport type AuthenticationWorkflow<TReturn> = AsyncGenerator<\n AuthenticationWorkflowRequest,\n TReturn,\n EvmAddress | EvmSignature\n>;\n\nexport type AuthenticateWith = <TReturn>(\n workflow: AuthenticationWorkflow<TReturn>,\n) => Promise<TReturn>;\n\nexport type AuthenticateWithError = CancelledSigningError | SigningError;\nexport type CompleteWithError = CancelledSigningError | SigningError;\n\nexport type CompleteWorkflowRequest =\n | RequestAddressRequest\n | SendErc20ApprovalTransactionRequest\n | SendErc1155ApprovalForAllTransactionRequest\n | SendErc20TransferTransactionRequest\n | SignGaslessTypedDataRequest\n | SignGaslessMessageRequest\n | SendSplitPositionTransactionRequest\n | SendMergePositionsTransactionRequest\n | SendRedeemPositionsTransactionRequest\n | SignOrderRequest;\n\nexport type CompleteWorkflowNext =\n | EvmAddress\n | EvmSignature\n | TransactionHandle;\n\nexport type CompleteWith = <TRequest extends CompleteWorkflowRequest, TReturn>(\n workflow: AsyncGenerator<TRequest, TReturn, CompleteWorkflowNext>,\n) => Promise<TReturn>;\n\nexport function requestAddress(): RequestAddressRequest {\n return {\n kind: 'requestAddress',\n };\n}\n\nexport function signerTransactionRequest(\n chainId: number,\n call: TransactionCall,\n): SignerTransactionRequest {\n return {\n chainId,\n ...call,\n };\n}\n","import { EvmAddressSchema, TransactionIdSchema } from '@polymarket/bindings';\nimport { WalletType } from '@polymarket/bindings/gamma';\nimport {\n type GaslessTransaction,\n GaslessTransactionSchema,\n RelayerDeployedResponseSchema,\n type RelayerExecuteParams,\n RelayerExecuteParamsSchema,\n type RelayerExecuteRequest,\n RelayerExecuteRequestSchema,\n type RelayerExecuteResponse,\n RelayerExecuteResponseSchema,\n RelayerTransactionState,\n RelayerTransactionType,\n} from '@polymarket/bindings/relayer';\nimport {\n delay,\n type EvmAddress,\n type EvmSignature,\n expectEvmAddress,\n expectEvmSignature,\n expectHexString,\n expectNonEmptyArray,\n type HexString,\n invariant,\n isHexString,\n type NonEmptyArray,\n unwrap,\n ZERO_ADDRESS,\n} from '@polymarket/types';\nimport { z } from 'zod';\nimport { encodeSafeMultisendCall } from '../abis';\nimport { deriveSafeWalletAddress } from '../account';\nimport type { BaseClient, BaseSecureClient } from '../clients';\nimport {\n type RateLimitError,\n type RequestRejectedError,\n TimeoutError,\n TransactionFailedError,\n type TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport { validateWith } from '../response';\nimport type {\n DeployTransactionHandle,\n TransactionCall,\n TransactionHandle,\n TransactionOutcome,\n TypedDataField,\n TypedDataPayload,\n} from '../types';\nimport {\n type RequestAddressRequest,\n requestAddress,\n type SignGaslessMessageRequest,\n type SignGaslessTypedDataRequest,\n} from '../workflow';\n\nconst EIP712_DOMAIN: readonly TypedDataField[] = [\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n];\n\nconst SAFE_FACTORY_NAME = 'Polymarket Contract Proxy Factory';\n\nconst SAFE_CREATE: readonly TypedDataField[] = [\n { name: 'paymentToken', type: 'address' },\n { name: 'payment', type: 'uint256' },\n { name: 'paymentReceiver', type: 'address' },\n];\n\nconst SAFE_TRANSACTION: readonly TypedDataField[] = [\n { name: 'to', type: 'address' },\n { name: 'value', type: 'uint256' },\n { name: 'data', type: 'bytes' },\n { name: 'operation', type: 'uint8' },\n { name: 'safeTxGas', type: 'uint256' },\n { name: 'baseGas', type: 'uint256' },\n { name: 'gasPrice', type: 'uint256' },\n { name: 'gasToken', type: 'address' },\n { name: 'refundReceiver', type: 'address' },\n { name: 'nonce', type: 'uint256' },\n];\n\nconst FetchExecuteParamsRequestSchema = z.object({\n address: z.string(),\n type: z.enum(RelayerTransactionType),\n});\n\nexport type FetchExecuteParamsRequest = z.input<\n typeof FetchExecuteParamsRequestSchema\n>;\n\nexport type FetchExecuteParamsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches the parameters needed to prepare a low-level transaction submission.\n *\n * @remarks\n * This is a low-level action that most SDK consumers will not need.\n *\n * @throws {@link FetchExecuteParamsError}\n * Thrown on failure.\n */\nexport async function fetchExecuteParams(\n client: BaseClient,\n request: FetchExecuteParamsRequest,\n): Promise<RelayerExecuteParams> {\n const params = parseUserInput(request, FetchExecuteParamsRequestSchema);\n\n return unwrap(\n client.relayer\n .get('/v1/account/transactions/params', {\n params: new URLSearchParams({\n address: params.address,\n type: params.type,\n }),\n })\n .andThen(validateWith(RelayerExecuteParamsSchema)),\n );\n}\n\nconst FetchGaslessTransactionRequestSchema = z.object({\n transactionId: TransactionIdSchema,\n});\n\nexport type FetchGaslessTransactionRequest = z.input<\n typeof FetchGaslessTransactionRequestSchema\n>;\n\nconst IsGaslessReadyRequestSchema = z.object({\n wallet: EvmAddressSchema,\n});\n\nexport type IsGaslessReadyRequest = z.input<typeof IsGaslessReadyRequestSchema>;\n\nexport type IsGaslessReadyError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Checks whether a wallet is ready for gasless transactions.\n *\n * @throws {@link IsGaslessReadyError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const ready = await isGaslessReady(client, {\n * wallet: '0x1234...',\n * });\n * ```\n */\nexport async function isGaslessReady(\n client: BaseClient,\n request: IsGaslessReadyRequest,\n): Promise<boolean> {\n const params = parseUserInput(request, IsGaslessReadyRequestSchema);\n\n return unwrap(\n client.relayer\n .get('/deployed', {\n params: new URLSearchParams({\n address: params.wallet,\n }),\n })\n .andThen(validateWith(RelayerDeployedResponseSchema))\n .map(({ deployed }) => deployed),\n );\n}\n\nexport type GaslessWalletWorkflowRequest =\n | RequestAddressRequest\n | SignGaslessTypedDataRequest;\n\nexport type GaslessWalletWorkflow = AsyncGenerator<\n GaslessWalletWorkflowRequest,\n DeployTransactionHandle,\n EvmAddress | EvmSignature | TransactionHandle\n>;\n\nexport type PrepareGaslessWalletError =\n | ExecuteGaslessError\n | IsGaslessReadyError\n | UserInputError;\n\n/**\n * Starts preparing the wallet for gasless transactions.\n *\n * @throws {@link PrepareGaslessWalletError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const handle = await prepareGaslessWallet(client).then(completeWith(wallet));\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n */\nexport async function prepareGaslessWallet(\n client: BaseClient,\n): Promise<GaslessWalletWorkflow> {\n invariant(\n client.supportsGasless,\n 'Client does not support gasless transactions',\n );\n\n return async function* (): GaslessWalletWorkflow {\n const signer = expectEvmAddress(yield requestAddress());\n\n const safeWallet = deriveSafeWalletAddress(\n signer,\n client.environment.walletDerivation,\n );\n\n if (await isGaslessReady(client, { wallet: safeWallet })) {\n throw new UserInputError(\n 'Wallet is already ready for gasless transactions',\n );\n }\n\n if (client.isSecureClient()) {\n invariant(\n signer === client.account.signer,\n 'Wallet client address does not match the authenticated signer',\n );\n }\n\n const signature = expectEvmSignature(\n yield signGaslessTypedData(\n createSafeCreateTypedDataPayload({\n chainId: client.environment.chainId,\n safeFactory: client.environment.walletDerivation.safeFactory,\n }),\n ),\n );\n\n const handle = await executeGasless(client, {\n data: '0x',\n from: signer,\n proxyWallet: safeWallet,\n signature,\n signatureParams: {\n payment: '0',\n paymentReceiver: ZERO_ADDRESS,\n paymentToken: ZERO_ADDRESS,\n },\n to: client.environment.walletDerivation.safeFactory,\n type: RelayerTransactionType.SAFE_CREATE,\n });\n\n return new GaslessWalletHandle(safeWallet, handle);\n }.call(null);\n}\n\n/**\n * Fetches a submitted transaction.\n *\n * @remarks\n * This is a low-level action that most SDK consumers will not need.\n *\n * @throws {@link FetchGaslessTransactionError}\n * Thrown on failure.\n */\nexport async function fetchTransaction(\n client: BaseClient,\n request: FetchGaslessTransactionRequest,\n): Promise<GaslessTransaction> {\n const params = parseUserInput(request, FetchGaslessTransactionRequestSchema);\n\n return unwrap(\n client.relayer\n .get(`/v1/account/transactions/${params.transactionId}`)\n .andThen(validateWith(GaslessTransactionSchema)),\n );\n}\n\nconst TransactionCallSchema = z.object({\n data: z.custom<HexString>(isHexString),\n to: EvmAddressSchema,\n value: z.bigint().optional(),\n});\n\nexport const GaslessTransactionMetadataSchema = z.string().max(500);\n\nconst PrepareGaslessTransactionRequestSchema = z.object({\n calls: z\n .array(TransactionCallSchema)\n .min(1)\n .transform((val) => expectNonEmptyArray(val)),\n metadata: GaslessTransactionMetadataSchema,\n});\n\nexport type PrepareGaslessTransactionRequest = z.input<\n typeof PrepareGaslessTransactionRequestSchema\n>;\n\nexport type GaslessWorkflowRequest =\n | RequestAddressRequest\n | SignGaslessMessageRequest;\n\nexport type GaslessWorkflow = AsyncGenerator<\n GaslessWorkflowRequest,\n TransactionHandle,\n EvmAddress | EvmSignature | TransactionHandle\n>;\n\nexport type PrepareGaslessTransactionError =\n | ExecuteGaslessError\n | FetchExecuteParamsError\n | UserInputError;\n\n/**\n * Starts preparing a low-level transaction workflow from one or more calls.\n *\n * @remarks\n * This is a low-level action that most SDK consumers will not need.\n *\n * @throws {@link PrepareGaslessTransactionError}\n * Thrown on failure.\n */\nexport async function prepareGaslessTransaction(\n client: BaseSecureClient,\n request: PrepareGaslessTransactionRequest,\n): Promise<GaslessWorkflow> {\n const params = parseUserInput(\n request,\n PrepareGaslessTransactionRequestSchema,\n );\n\n invariant(\n client.supportsGasless,\n 'Gasless transactions require a Relayer API Key or Builder API Key in the client configuration.',\n );\n invariant(\n client.account.walletType === WalletType.POLY_GNOSIS_SAFE,\n 'Gasless transaction preparation currently supports Safe-backed accounts only',\n );\n\n return async function* (): GaslessWorkflow {\n const signer = expectEvmAddress(yield requestAddress());\n\n invariant(\n signer === client.account.signer,\n 'Wallet client address does not match the authenticated signer',\n );\n\n const executeParams = await fetchExecuteParams(client, {\n address: client.account.signer,\n type: RelayerTransactionType.SAFE,\n });\n const transaction = aggregateSafeTransactionCalls(\n params.calls,\n client.environment.safeMultisend,\n );\n\n const signature = expectEvmSignature(\n yield signGaslessMessage(\n createSafeTypedDataPayload({\n chainId: client.environment.chainId,\n data: transaction.data,\n nonce: executeParams.nonce,\n operation: transaction.operation,\n safeAddress: client.account.wallet,\n to: transaction.to,\n value: transaction.value,\n }),\n ),\n );\n\n return executeGasless(client, {\n data: transaction.data,\n from: client.account.signer,\n metadata: params.metadata,\n nonce: executeParams.nonce,\n proxyWallet: client.account.wallet,\n signature: packSafeSignature(signature),\n signatureParams: createSafeSignatureParams(transaction.operation),\n to: transaction.to,\n type: RelayerTransactionType.SAFE,\n value: transaction.value > 0n ? `${transaction.value}` : undefined,\n });\n }.call(null);\n}\n\ntype ExecuteGaslessRequest = RelayerExecuteRequest;\n\ntype ExecuteGaslessError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\nasync function executeGasless(\n client: BaseClient,\n request: ExecuteGaslessRequest,\n): Promise<GaslessTransactionHandle> {\n const payload = parseUserInput(request, RelayerExecuteRequestSchema);\n\n const response = await unwrap(\n client.relayer\n .post('/submit', {\n json: payload,\n })\n .andThen(validateWith(RelayerExecuteResponseSchema)),\n );\n\n return new GaslessTransactionHandle(client, response);\n}\n\ntype SafeTransaction = {\n data: HexString;\n operation: 0 | 1;\n to: EvmAddress;\n value: bigint;\n};\n\ntype CreateSafeTypedDataPayloadRequest = {\n chainId: number;\n data: HexString;\n nonce: string;\n operation: 0 | 1;\n safeAddress: EvmAddress;\n to: EvmAddress;\n value: bigint;\n};\n\nfunction aggregateSafeTransactionCalls(\n calls: NonEmptyArray<TransactionCall>,\n safeMultisend: EvmAddress,\n): SafeTransaction {\n if (calls.length === 1) {\n const [call] = calls;\n\n return {\n data: call.data,\n operation: 0,\n to: call.to,\n value: call.value ?? 0n,\n };\n }\n\n return {\n data: encodeSafeMultisendCall(calls),\n operation: 1,\n to: safeMultisend,\n value: 0n,\n };\n}\n\nfunction createSafeSignatureParams(operation: 0 | 1) {\n return {\n baseGas: '0',\n gasPrice: '0',\n gasToken: ZERO_ADDRESS,\n operation: `${operation}`,\n refundReceiver: ZERO_ADDRESS,\n safeTxnGas: '0',\n };\n}\n\nfunction createSafeTypedDataPayload(\n request: CreateSafeTypedDataPayloadRequest,\n): TypedDataPayload {\n return {\n domain: {\n chainId: request.chainId,\n verifyingContract: request.safeAddress,\n },\n message: {\n baseGas: 0n,\n data: request.data,\n gasPrice: 0n,\n gasToken: ZERO_ADDRESS,\n nonce: BigInt(request.nonce),\n operation: request.operation,\n refundReceiver: ZERO_ADDRESS,\n safeTxGas: 0n,\n to: request.to,\n value: request.value,\n },\n primaryType: 'SafeTx',\n types: {\n EIP712Domain: EIP712_DOMAIN,\n SafeTx: SAFE_TRANSACTION,\n },\n };\n}\n\ntype CreateSafeCreateTypedDataPayloadRequest = {\n chainId: number;\n safeFactory: EvmAddress;\n};\n\nfunction createSafeCreateTypedDataPayload(\n request: CreateSafeCreateTypedDataPayloadRequest,\n): TypedDataPayload {\n return {\n domain: {\n chainId: request.chainId,\n name: SAFE_FACTORY_NAME,\n verifyingContract: request.safeFactory,\n },\n message: {\n payment: 0n,\n paymentReceiver: ZERO_ADDRESS,\n paymentToken: ZERO_ADDRESS,\n },\n primaryType: 'CreateProxy',\n types: {\n CreateProxy: SAFE_CREATE,\n },\n };\n}\n\nfunction signGaslessTypedData(\n payload: TypedDataPayload,\n): SignGaslessTypedDataRequest {\n return {\n kind: 'signGaslessTypedData',\n payload,\n };\n}\n\nfunction signGaslessMessage(\n payload: TypedDataPayload,\n): SignGaslessMessageRequest {\n return {\n kind: 'signGaslessMessage',\n payload,\n };\n}\n\nfunction packSafeSignature(signature: EvmSignature): HexString {\n const prefixlessSignature = signature.slice(2);\n const v = Number.parseInt(prefixlessSignature.slice(128, 130), 16);\n\n const packedV =\n v === 0 || v === 1 ? v + 31 : v === 27 || v === 28 ? v + 4 : v;\n\n return expectHexString(\n `0x${prefixlessSignature.slice(0, 128)}${packedV.toString(16).padStart(2, '0')}`,\n );\n}\n\nexport type WaitForGaslessTransactionError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError\n | TimeoutError\n | TransactionFailedError;\n\nclass GaslessTransactionHandle implements TransactionHandle {\n readonly #client: BaseClient;\n\n readonly transactionHash;\n readonly transactionId;\n\n constructor(client: BaseClient, response: RelayerExecuteResponse) {\n this.#client = client;\n this.transactionHash = response.transactionHash;\n this.transactionId = response.transactionId;\n }\n\n async wait(): Promise<TransactionOutcome> {\n let pollCount = 0;\n\n while (pollCount < this.#client.environment.relayerMaxPolls) {\n const transaction = await fetchTransaction(this.#client, {\n transactionId: this.transactionId,\n });\n\n if (\n transaction.state === RelayerTransactionState.STATE_MINED ||\n transaction.state === RelayerTransactionState.STATE_CONFIRMED\n ) {\n const transactionHash =\n transaction.transactionHash ?? this.transactionHash;\n\n if (transactionHash === null) {\n throw new UnexpectedResponseError(\n 'Expected submitted transaction to have a transaction hash once settled',\n );\n }\n\n return {\n transactionHash,\n transactionId: transaction.transactionId,\n };\n }\n\n if (\n transaction.state === RelayerTransactionState.STATE_FAILED ||\n transaction.state === RelayerTransactionState.STATE_INVALID\n ) {\n throw new TransactionFailedError(\n transaction.errorMsg ??\n `Transaction ${transaction.transactionId} reached terminal state ${transaction.state}`,\n );\n }\n\n pollCount += 1;\n await delay(this.#client.environment.relayerPollFrequencyMs);\n }\n\n throw new TimeoutError(\n `Timed out waiting for transaction ${this.transactionId} to settle`,\n );\n }\n}\n\nclass GaslessWalletHandle implements DeployTransactionHandle {\n readonly #wallet: EvmAddress;\n readonly #transaction: TransactionHandle;\n\n constructor(wallet: EvmAddress, transaction: TransactionHandle) {\n this.#wallet = wallet;\n this.#transaction = transaction;\n }\n\n get wallet() {\n return this.#wallet;\n }\n\n get transactionHash() {\n return this.#transaction.transactionHash;\n }\n\n get transactionId() {\n return this.#transaction.transactionId;\n }\n\n wait() {\n return this.#transaction.wait();\n }\n}\n","import { type EvmAddress, EvmAddressSchema } from '@polymarket/bindings';\nimport { WalletType } from '@polymarket/bindings/gamma';\nimport type { EvmSignature } from '@polymarket/types';\nimport { z } from 'zod';\nimport {\n erc20ApprovalCall,\n erc1155ApprovalForAllCall,\n MAX_UINT256,\n} from '../abis';\nimport type { BaseSecureClient } from '../clients';\nimport type { UserInputError } from '../errors';\nimport { parseUserInput } from '../input';\nimport { expectTransactionHandle, type TransactionHandle } from '../types';\nimport type { SignerTransactionRequest } from '../workflow';\nimport {\n type SendErc20ApprovalTransactionRequest,\n type SendErc1155ApprovalForAllTransactionRequest,\n signerTransactionRequest,\n} from '../workflow';\nimport {\n GaslessTransactionMetadataSchema,\n type GaslessWorkflowRequest,\n prepareGaslessTransaction,\n} from './gasless';\n\nexport type Erc20ApprovalWorkflowRequest =\n | GaslessWorkflowRequest\n | SendErc20ApprovalTransactionRequest;\n\nexport type Erc20ApprovalWorkflow = AsyncGenerator<\n Erc20ApprovalWorkflowRequest,\n TransactionHandle,\n EvmAddress | EvmSignature | TransactionHandle\n>;\n\nconst PrepareErc20ApprovalRequestSchema = z.object({\n amount: z.union([z.bigint(), z.literal('max')]),\n metadata: GaslessTransactionMetadataSchema.optional(),\n spenderAddress: EvmAddressSchema,\n tokenAddress: EvmAddressSchema,\n});\n\nexport type PrepareErc20ApprovalRequest = z.input<\n typeof PrepareErc20ApprovalRequestSchema\n>;\n\nexport type PrepareErc20ApprovalError = UserInputError;\n\n/**\n * Starts an ERC-20 approval workflow.\n *\n * @example\n * ```ts\n * const handle = await prepareErc20Approval(client, {\n * amount: 'max',\n * spenderAddress: '0x1234…',\n * tokenAddress: '0x5678…',\n * }).then(completeWith(wallet));\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @throws {@link PrepareErc20ApprovalError}\n * Thrown on failure.\n */\nexport async function prepareErc20Approval(\n client: BaseSecureClient,\n request: PrepareErc20ApprovalRequest,\n): Promise<Erc20ApprovalWorkflow> {\n const params = parseUserInput(request, PrepareErc20ApprovalRequestSchema);\n const amount = params.amount === 'max' ? MAX_UINT256 : params.amount;\n\n return async function* (): Erc20ApprovalWorkflow {\n if (client.account.walletType === WalletType.EOA) {\n return expectTransactionHandle(\n yield sendErc20ApprovalTransaction(\n signerTransactionRequest(\n client.environment.chainId,\n erc20ApprovalCall(\n params.tokenAddress,\n params.spenderAddress,\n amount,\n ),\n ),\n ),\n );\n }\n\n return yield* await prepareGaslessTransaction(client, {\n calls: [\n erc20ApprovalCall(params.tokenAddress, params.spenderAddress, amount),\n ],\n metadata:\n params.metadata ??\n `Approve ${params.amount} of ${params.tokenAddress} to ${params.spenderAddress}`,\n });\n }.call(null);\n}\n\nexport type Erc1155ApprovalForAllWorkflowRequest =\n | GaslessWorkflowRequest\n | SendErc1155ApprovalForAllTransactionRequest;\n\nexport type Erc1155ApprovalForAllWorkflow = AsyncGenerator<\n Erc1155ApprovalForAllWorkflowRequest,\n TransactionHandle,\n EvmAddress | EvmSignature | TransactionHandle\n>;\n\nconst PrepareErc1155ApprovalForAllRequestSchema = z.object({\n approved: z.boolean().default(true),\n metadata: GaslessTransactionMetadataSchema.optional(),\n operatorAddress: EvmAddressSchema,\n tokenAddress: EvmAddressSchema,\n});\n\nexport type PrepareErc1155ApprovalForAllRequest = z.input<\n typeof PrepareErc1155ApprovalForAllRequestSchema\n>;\n\nexport type PrepareErc1155ApprovalForAllError = UserInputError;\n\n/**\n * Starts an ERC-1155 approval-for-all workflow.\n *\n * @example\n * ```ts\n * const handle = await prepareErc1155ApprovalForAll(client, {\n * operatorAddress: '0x1234…',\n * tokenAddress: '0x5678…',\n * }).then(completeWith(wallet));\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @throws {@link PrepareErc1155ApprovalForAllError}\n * Thrown on failure.\n */\nexport async function prepareErc1155ApprovalForAll(\n client: BaseSecureClient,\n request: PrepareErc1155ApprovalForAllRequest,\n): Promise<Erc1155ApprovalForAllWorkflow> {\n const params = parseUserInput(\n request,\n PrepareErc1155ApprovalForAllRequestSchema,\n );\n\n return async function* (): Erc1155ApprovalForAllWorkflow {\n if (client.account.walletType === WalletType.EOA) {\n return expectTransactionHandle(\n yield sendErc1155ApprovalForAllTransaction(\n signerTransactionRequest(\n client.environment.chainId,\n erc1155ApprovalForAllCall(\n params.tokenAddress,\n params.operatorAddress,\n params.approved,\n ),\n ),\n ),\n );\n }\n\n return yield* await prepareGaslessTransaction(client, {\n calls: [\n erc1155ApprovalForAllCall(\n params.tokenAddress,\n params.operatorAddress,\n params.approved,\n ),\n ],\n metadata:\n params.metadata ??\n `${params.approved ? 'Approve' : 'Revoke'} ${params.operatorAddress} on ${params.tokenAddress}`,\n });\n }.call(null);\n}\n\nexport type TradingApprovalsWorkflowRequest =\n | GaslessWorkflowRequest\n | SendErc20ApprovalTransactionRequest\n | SendErc1155ApprovalForAllTransactionRequest;\n\nexport type TradingApprovalsWorkflow = AsyncGenerator<\n TradingApprovalsWorkflowRequest,\n TransactionHandle,\n EvmAddress | EvmSignature | TransactionHandle\n>;\n\nexport type PrepareTradingApprovalsError = UserInputError;\n\n/**\n * Starts a trading-setup approval workflow.\n *\n * Prepares all approvals required for trading, including collateral and\n * position token approvals for both standard and neg-risk market flows.\n * The neg-risk adapter approvals cover split, merge, and redemption workflows\n * on neg-risk markets.\n *\n * @example\n * ```ts\n * const handle = await prepareTradingApprovals(client).then(completeWith(wallet));\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @throws {@link PrepareTradingApprovalsError}\n * Thrown on failure.\n */\nexport async function prepareTradingApprovals(\n client: BaseSecureClient,\n): Promise<TradingApprovalsWorkflow> {\n const calls = [\n erc20ApprovalCall(\n client.environment.collateralToken,\n client.environment.standardExchange,\n MAX_UINT256,\n ),\n erc20ApprovalCall(\n client.environment.collateralToken,\n client.environment.negRiskExchange,\n MAX_UINT256,\n ),\n erc20ApprovalCall(\n client.environment.collateralToken,\n client.environment.negRiskAdapter,\n MAX_UINT256,\n ),\n erc1155ApprovalForAllCall(\n client.environment.conditionalTokens,\n client.environment.standardExchange,\n true,\n ),\n erc1155ApprovalForAllCall(\n client.environment.conditionalTokens,\n client.environment.negRiskExchange,\n true,\n ),\n erc1155ApprovalForAllCall(\n client.environment.conditionalTokens,\n client.environment.negRiskAdapter,\n true,\n ),\n ] as const;\n\n return async function* (): TradingApprovalsWorkflow {\n if (client.account.walletType === WalletType.EOA) {\n const collateralStandardApproval = expectTransactionHandle(\n yield sendErc20ApprovalTransaction(\n signerTransactionRequest(client.environment.chainId, calls[0]),\n ),\n );\n await collateralStandardApproval.wait();\n\n const collateralNegRiskApproval = expectTransactionHandle(\n yield sendErc20ApprovalTransaction(\n signerTransactionRequest(client.environment.chainId, calls[1]),\n ),\n );\n await collateralNegRiskApproval.wait();\n\n const collateralNegRiskAdapterApproval = expectTransactionHandle(\n yield sendErc20ApprovalTransaction(\n signerTransactionRequest(client.environment.chainId, calls[2]),\n ),\n );\n await collateralNegRiskAdapterApproval.wait();\n\n const conditionalStandardApproval = expectTransactionHandle(\n yield sendErc1155ApprovalForAllTransaction(\n signerTransactionRequest(client.environment.chainId, calls[3]),\n ),\n );\n await conditionalStandardApproval.wait();\n\n const conditionalNegRiskApproval = expectTransactionHandle(\n yield sendErc1155ApprovalForAllTransaction(\n signerTransactionRequest(client.environment.chainId, calls[4]),\n ),\n );\n await conditionalNegRiskApproval.wait();\n\n return expectTransactionHandle(\n yield sendErc1155ApprovalForAllTransaction(\n signerTransactionRequest(client.environment.chainId, calls[5]),\n ),\n );\n }\n\n return yield* await prepareGaslessTransaction(client, {\n calls: [...calls],\n metadata: 'Trading setup approvals',\n });\n }.call(null);\n}\n\nfunction sendErc20ApprovalTransaction(\n request: SignerTransactionRequest,\n): SendErc20ApprovalTransactionRequest {\n return {\n kind: 'sendErc20ApprovalTransaction',\n request,\n };\n}\n\nfunction sendErc1155ApprovalForAllTransaction(\n request: SignerTransactionRequest,\n): SendErc1155ApprovalForAllTransactionRequest {\n return {\n kind: 'sendErc1155ApprovalForAllTransaction',\n request,\n };\n}\n","import type { ApiKey } from '@polymarket/bindings';\nimport {\n type ApiKeyCreds,\n ApiKeyCredsSchema,\n ApiKeysResponseSchema,\n type BuilderApiKey,\n type BuilderApiKeyCreds,\n BuilderApiKeyCredsSchema,\n BuilderApiKeysResponseSchema,\n} from '@polymarket/bindings/clob';\nimport { type EvmAddress, type EvmSignature, unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient, BaseSecureClient } from '../clients';\nimport {\n type RateLimitError,\n RequestRejectedError,\n type SigningError,\n type TransportError,\n type UnexpectedResponseError,\n} from '../errors';\nimport { validateWith } from '../response';\n\nexport type ApiKeyAuthRequest = {\n address: EvmAddress;\n nonce: number;\n signature: EvmSignature;\n timestamp: number;\n};\n\nexport type CreateApiKeyError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Creates a new API key from a signed L1 auth payload.\n *\n * @remarks\n * This is a low-level auth action that most SDK consumers will not need.\n *\n * @example\n * ```ts\n * const creds = await createApiKey(client, request);\n * ```\n *\n * @throws {@link CreateApiKeyError}\n * Thrown on failure.\n */\nexport async function createApiKey(\n client: BaseClient,\n request: ApiKeyAuthRequest,\n): Promise<ApiKeyCreds> {\n return unwrap(\n client.clob\n .post('auth/api-key', {\n headers: toL1Headers(request),\n })\n .andThen(validateWith(ApiKeyCredsSchema)),\n );\n}\n\nexport type DeriveApiKeyError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Derives an existing API key from a signed L1 auth payload.\n *\n * @remarks\n * This is a low-level auth action that most SDK consumers will not need.\n *\n * @example\n * ```ts\n * const creds = await deriveApiKey(client, request);\n * ```\n *\n * @throws {@link DeriveApiKeyError}\n * Thrown on failure.\n */\nexport async function deriveApiKey(\n client: BaseClient,\n request: ApiKeyAuthRequest,\n): Promise<ApiKeyCreds> {\n return unwrap(\n client.clob\n .get('/auth/derive-api-key', {\n headers: toL1Headers(request),\n })\n .andThen(validateWith(ApiKeyCredsSchema)),\n );\n}\n\nexport type CreateOrDeriveApiKeyError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Creates an API key and falls back to derivation when it already exists.\n *\n * @remarks\n * This is a low-level auth action that most SDK consumers will not need.\n *\n * @example\n * ```ts\n * const creds = await createOrDeriveApiKey(client, request);\n * ```\n *\n * @throws {@link CreateOrDeriveApiKeyError}\n * Thrown on failure.\n */\nexport async function createOrDeriveApiKey(\n client: BaseClient,\n request: ApiKeyAuthRequest,\n): Promise<ApiKeyCreds> {\n try {\n return await createApiKey(client, request);\n } catch (error) {\n if (!(error instanceof RequestRejectedError) || error.status !== 400) {\n throw error;\n }\n }\n\n return deriveApiKey(client, request);\n}\n\nexport type FetchApiKeysError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Fetches all API keys associated with the authenticated client.\n *\n * @remarks\n * This is a low-level auth action that most SDK consumers will not need.\n *\n * @example\n * ```ts\n * const apiKeys = await fetchApiKeys(client);\n * ```\n *\n * @throws {@link FetchApiKeysError}\n * Thrown on failure.\n */\nexport async function fetchApiKeys(\n client: BaseSecureClient,\n): Promise<ApiKey[]> {\n const response = await unwrap(\n client.secureClob\n .get('/auth/api-keys')\n .andThen(validateWith(ApiKeysResponseSchema)),\n );\n\n return response.apiKeys;\n}\n\nexport type DeleteApiKeyError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Deletes the authenticated API key.\n *\n * @remarks\n * This is a low-level auth action that most SDK consumers will not need.\n *\n * @example\n * ```ts\n * await deleteApiKey(client);\n * ```\n *\n * @throws {@link DeleteApiKeyError}\n * Thrown when request signing fails, or the request is rejected, rate limited,\n * interrupted by transport issues, or returns an unexpected response.\n */\nexport async function deleteApiKey(client: BaseSecureClient): Promise<void> {\n await unwrap(\n client.secureClob\n .del('/auth/api-key')\n .andThen(validateWith(z.literal('OK'))),\n );\n}\n\nexport type CreateBuilderApiKeyError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Creates a new builder API key for the authenticated client.\n *\n * @remarks\n * This is a low-level auth action that most SDK consumers will not need.\n *\n * @example\n * ```ts\n * const builderApiKey = await createBuilderApiKey(client);\n * ```\n *\n * @throws {@link CreateBuilderApiKeyError}\n * Thrown when request signing fails, or the request is rejected, rate limited,\n * interrupted by transport issues, or returns an unexpected response.\n */\nexport async function createBuilderApiKey(\n client: BaseSecureClient,\n): Promise<BuilderApiKeyCreds> {\n return unwrap(\n client.secureClob\n .post('/auth/builder-api-key')\n .andThen(validateWith(BuilderApiKeyCredsSchema)),\n );\n}\n\nexport type FetchBuilderApiKeysError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Fetches builder API keys associated with the authenticated client.\n *\n * @remarks\n * This is a low-level auth action that most SDK consumers will not need.\n *\n * @example\n * ```ts\n * const builderApiKeys = await fetchBuilderApiKeys(client);\n * ```\n *\n * @throws {@link FetchBuilderApiKeysError}\n * Thrown when request signing fails, or the request is rejected, rate limited,\n * interrupted by transport issues, or returns an unexpected response.\n */\nexport async function fetchBuilderApiKeys(\n client: BaseSecureClient,\n): Promise<BuilderApiKey[]> {\n return unwrap(\n client.secureClob\n .get('/auth/builder-api-key')\n .andThen(validateWith(BuilderApiKeysResponseSchema)),\n );\n}\n\nexport type RevokeBuilderApiKeyError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Revokes a builder API key.\n *\n * @remarks\n * This is a low-level auth action that most SDK consumers will not need.\n *\n * @example\n * ```ts\n * await revokeBuilderApiKey(client);\n * ```\n *\n * @throws {@link RevokeBuilderApiKeyError}\n * Thrown when request signing fails, or the request is rejected, rate limited,\n * interrupted by transport issues, or returns an unexpected response.\n */\nexport async function revokeBuilderApiKey(client: BaseClient): Promise<void> {\n await unwrap(\n client.clob\n .del('/auth/builder-api-key')\n .andThen(validateWith(z.literal('OK'))),\n );\n}\n\nfunction toL1Headers(auth: ApiKeyAuthRequest): HeadersInit {\n return {\n POLY_ADDRESS: auth.address,\n POLY_NONCE: `${auth.nonce}`,\n POLY_SIGNATURE: auth.signature,\n POLY_TIMESTAMP: `${auth.timestamp}`,\n };\n}\n","import {\n PaginationCursorSchema,\n toPaginationCursor,\n} from '@polymarket/bindings';\nimport {\n type BuilderTrade,\n END_CURSOR,\n PaginatedBuilderTradesSchema,\n} from '@polymarket/bindings/clob';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport { type Paginated, paginate } from '../pagination';\nimport { validateWith } from '../response';\nimport { snakeCase, toSearchParams } from './params';\n\nconst ListBuilderTradesRequestSchema = z.object({\n after: z.string().optional(),\n before: z.string().optional(),\n builder: z.string().optional(),\n cursor: PaginationCursorSchema.optional(),\n id: z.string().optional(),\n market: z.string().optional(),\n tokenId: z.string().optional(),\n});\n\nexport type ListBuilderTradesRequest = z.input<\n typeof ListBuilderTradesRequestSchema\n>;\n\nexport type ListBuilderTradesError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists builder-attributed trades.\n *\n * @throws {@link ListBuilderTradesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listBuilderTrades(client);\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: BuilderTrade[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listBuilderTrades(client);\n *\n * for await (const page of result) {\n * // page.items: BuilderTrade[]\n * }\n * ```\n */\nexport function listBuilderTrades(\n client: BaseClient,\n request: ListBuilderTradesRequest = {},\n): Paginated<BuilderTrade> {\n const { cursor, ...params } = parseUserInput(\n request,\n ListBuilderTradesRequestSchema,\n );\n\n return paginate(\n (nextCursor) =>\n client.clob\n .get('/builder/trades', {\n params: toSearchParams(\n { ...params, nextCursor },\n snakeCase({\n tokenId: 'asset_id',\n }),\n ),\n })\n .andThen(validateWith(PaginatedBuilderTradesSchema))\n .map((response) => ({\n items: response.data,\n hasMore: response.next_cursor !== END_CURSOR,\n nextCursor:\n response.next_cursor === END_CURSOR\n ? undefined\n : toPaginationCursor(response.next_cursor),\n totalCount: response.count,\n })),\n cursor,\n );\n}\n","import {\n ConditionIdSchema,\n PaginationCursorSchema,\n type TickSizeValue,\n toPaginationCursor,\n} from '@polymarket/bindings';\nimport {\n type CurrentReward,\n END_CURSOR,\n FetchFeeRateResponseSchema,\n FetchNegRiskResponseSchema,\n FetchOrderBookResponseSchema,\n FetchTickSizeResponseSchema,\n type LastTradePrice,\n type LastTradePriceForToken,\n LastTradePriceSchema,\n LastTradePricesSchema,\n type MarketReward,\n MidpointSchema,\n MidpointsSchema,\n type OrderBook,\n OrderBooksSchema,\n OrderSideSchema,\n PaginatedCurrentRewardsSchema,\n PaginatedMarketRewardsSchema,\n PriceHistoryIntervalSchema,\n type PriceHistoryPoint,\n PriceHistorySchema,\n PriceSchema,\n type Prices,\n PricesSchema,\n SpreadSchema,\n SpreadsSchema,\n} from '@polymarket/bindings/clob';\nimport { unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport { type Paginated, paginate } from '../pagination';\nimport { validateWith } from '../response';\nimport { snakeCase, toSearchParams } from './params';\n\nconst FetchMidpointRequestSchema = z.object({\n tokenId: z.string(),\n});\n\nexport type FetchMidpointRequest = z.input<typeof FetchMidpointRequestSchema>;\n\nexport type FetchMidpointError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches the midpoint price for a token.\n *\n * @throws {@link FetchMidpointError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoint = await fetchMidpoint(client, {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * });\n *\n * // midpoint === '0.53'\n * ```\n *\n */\nexport async function fetchMidpoint(\n client: BaseClient,\n request: FetchMidpointRequest,\n): Promise<string> {\n const params = parseUserInput(request, FetchMidpointRequestSchema);\n const response = await unwrap(\n client.clob\n .get('/midpoint', {\n params: toSearchParams(params, snakeCase()),\n })\n .andThen(validateWith(MidpointSchema)),\n );\n\n return response.mid;\n}\n\nconst FetchMidpointsRequestSchema = z\n .array(\n z.object({\n tokenId: z.string(),\n }),\n )\n .min(1);\n\nexport type FetchMidpointsRequest = z.input<typeof FetchMidpointsRequestSchema>;\n\nexport type FetchMidpointsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches midpoint prices for multiple tokens.\n *\n * @throws {@link FetchMidpointsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const midpoints = await fetchMidpoints(client, [\n * {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * },\n * ]);\n *\n * // midpoints[tokenId] === '0.53'\n * ```\n *\n */\nexport async function fetchMidpoints(\n client: BaseClient,\n request: FetchMidpointsRequest,\n): Promise<Record<string, string>> {\n const params = parseUserInput(request, FetchMidpointsRequestSchema);\n\n return unwrap(\n client.clob\n .post('midpoints', {\n json: toTokenRequestPayload(params),\n })\n .andThen(validateWith(MidpointsSchema)),\n );\n}\n\nconst FetchTickSizeRequestSchema = z.object({\n tokenId: z.string(),\n});\n\nexport type FetchTickSizeRequest = z.input<typeof FetchTickSizeRequestSchema>;\n\nexport type FetchTickSizeError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches the minimum price tick size for a token's order book.\n *\n * @remarks\n * This is a low-level market action that most SDK consumers will not need.\n *\n * @throws {@link FetchTickSizeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const tickSize = await fetchTickSize(client, {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * });\n *\n * // tickSize === 0.01\n * ```\n */\nexport async function fetchTickSize(\n client: BaseClient,\n request: FetchTickSizeRequest,\n): Promise<TickSizeValue> {\n const params = parseUserInput(request, FetchTickSizeRequestSchema);\n const response = await unwrap(\n client.clob\n .get('/tick-size', {\n params: toSearchParams(params, snakeCase()),\n })\n .andThen(validateWith(FetchTickSizeResponseSchema)),\n );\n\n return response.minimum_tick_size;\n}\n\nconst FetchNegRiskRequestSchema = z.object({\n tokenId: z.string(),\n});\n\nexport type FetchNegRiskRequest = z.input<typeof FetchNegRiskRequestSchema>;\n\nexport type FetchNegRiskError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches whether a token is in a negative-risk market.\n *\n * @remarks\n * This is a low-level market action that most SDK consumers will not need.\n *\n * @throws {@link FetchNegRiskError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const negRisk = await fetchNegRisk(client, {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * });\n *\n * // negRisk === false\n * ```\n */\nexport async function fetchNegRisk(\n client: BaseClient,\n request: FetchNegRiskRequest,\n): Promise<boolean> {\n const params = parseUserInput(request, FetchNegRiskRequestSchema);\n const response = await unwrap(\n client.clob\n .get('/neg-risk', {\n params: toSearchParams(params, snakeCase()),\n })\n .andThen(validateWith(FetchNegRiskResponseSchema)),\n );\n\n return response.neg_risk;\n}\n\nconst FetchFeeRateRequestSchema = z.object({\n tokenId: z.string(),\n});\n\nexport type FetchFeeRateRequest = z.input<typeof FetchFeeRateRequestSchema>;\n\nexport type FetchFeeRateError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches the base fee rate, in basis points, for a token's order book.\n *\n * @remarks\n * This is a low-level market action that most SDK consumers will not need.\n *\n * @throws {@link FetchFeeRateError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const feeRate = await fetchFeeRate(client, {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * });\n *\n * // feeRate === 0\n * ```\n */\nexport async function fetchFeeRate(\n client: BaseClient,\n request: FetchFeeRateRequest,\n): Promise<number> {\n const params = parseUserInput(request, FetchFeeRateRequestSchema);\n const response = await unwrap(\n client.clob\n .get('/fee-rate', {\n params: toSearchParams(params, snakeCase()),\n })\n .andThen(validateWith(FetchFeeRateResponseSchema)),\n );\n\n return response.base_fee;\n}\n\nconst FetchPriceRequestSchema = z.object({\n tokenId: z.string(),\n side: OrderSideSchema,\n});\n\nexport type FetchPriceRequest = z.input<typeof FetchPriceRequestSchema>;\n\nexport type FetchPriceError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches the current quoted price for a token and side.\n *\n * @throws {@link FetchPriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const price = await fetchPrice(client, {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * side: OrderSide.BUY,\n * });\n *\n * // price === '0.52'\n * ```\n *\n */\nexport async function fetchPrice(\n client: BaseClient,\n request: FetchPriceRequest,\n): Promise<string> {\n const params = parseUserInput(request, FetchPriceRequestSchema);\n const response = await unwrap(\n client.clob\n .get('/price', {\n params: toSearchParams(params, snakeCase()),\n })\n .andThen(validateWith(PriceSchema)),\n );\n\n return response.price;\n}\n\nconst FetchPricesRequestSchema = z\n .array(\n z.object({\n tokenId: z.string(),\n side: OrderSideSchema,\n }),\n )\n .min(1);\n\nexport type FetchPricesRequest = z.input<typeof FetchPricesRequestSchema>;\n\nexport type FetchPricesError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches quoted prices for multiple tokens.\n *\n * @throws {@link FetchPricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const prices = await fetchPrices(client, [\n * {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * side: OrderSide.BUY,\n * },\n * ]);\n *\n * // prices[tokenId]?.BUY === '0.52'\n * ```\n *\n */\nexport async function fetchPrices(\n client: BaseClient,\n request: FetchPricesRequest,\n): Promise<Prices> {\n const params = parseUserInput(request, FetchPricesRequestSchema);\n\n return unwrap(\n client.clob\n .post('prices', {\n json: toTokenWithSideRequestPayload(params),\n })\n .andThen(validateWith(PricesSchema)),\n );\n}\n\nconst FetchOrderBookRequestSchema = z.object({\n tokenId: z.string(),\n});\n\nexport type FetchOrderBookRequest = z.input<typeof FetchOrderBookRequestSchema>;\n\nexport type FetchOrderBookError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches the current order book for a token.\n *\n * @throws {@link FetchOrderBookError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const orderBook = await fetchOrderBook(client, {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * });\n *\n * // orderBook.bids / orderBook.asks\n * ```\n */\nexport async function fetchOrderBook(\n client: BaseClient,\n request: FetchOrderBookRequest,\n): Promise<OrderBook> {\n const params = parseUserInput(request, FetchOrderBookRequestSchema);\n\n return unwrap(\n client.clob\n .get('/book', {\n params: toSearchParams(params, snakeCase()),\n })\n .andThen(validateWith(FetchOrderBookResponseSchema)),\n );\n}\n\nconst FetchOrderBooksRequestSchema = z\n .array(\n z.object({\n tokenId: z.string(),\n }),\n )\n .min(1);\n\nexport type FetchOrderBooksRequest = z.input<\n typeof FetchOrderBooksRequestSchema\n>;\n\nexport type FetchOrderBooksError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches order books for multiple tokens.\n *\n * @throws {@link FetchOrderBooksError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const books = await fetchOrderBooks(client, [\n * {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * },\n * ])\n *\n * // books: OrderBook[]\n * ```\n */\nexport async function fetchOrderBooks(\n client: BaseClient,\n request: FetchOrderBooksRequest,\n): Promise<OrderBook[]> {\n const params = parseUserInput(request, FetchOrderBooksRequestSchema);\n\n return unwrap(\n client.clob\n .post('books', {\n json: toTokenRequestPayload(params),\n })\n .andThen(validateWith(OrderBooksSchema)),\n );\n}\n\nconst FetchSpreadRequestSchema = z.object({\n tokenId: z.string(),\n});\n\nexport type FetchSpreadRequest = z.input<typeof FetchSpreadRequestSchema>;\n\nexport type FetchSpreadError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches the spread for a token.\n *\n * @throws {@link FetchSpreadError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spread = await fetchSpread(client, {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * });\n *\n * // spread === '0.02'\n * ```\n *\n */\nexport async function fetchSpread(\n client: BaseClient,\n request: FetchSpreadRequest,\n): Promise<string> {\n const params = parseUserInput(request, FetchSpreadRequestSchema);\n const response = await unwrap(\n client.clob\n .get('/spread', {\n params: toSearchParams(params, snakeCase()),\n })\n .andThen(validateWith(SpreadSchema)),\n );\n\n return response.spread;\n}\n\nconst FetchSpreadsRequestSchema = z\n .array(\n z.object({\n tokenId: z.string(),\n }),\n )\n .min(1);\n\nexport type FetchSpreadsRequest = z.input<typeof FetchSpreadsRequestSchema>;\n\nexport type FetchSpreadsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches spreads for multiple tokens.\n *\n * @throws {@link FetchSpreadsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const spreads = await fetchSpreads(client, [\n * {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * },\n * ]);\n *\n * // spreads[tokenId] === '0.02'\n * ```\n *\n */\nexport async function fetchSpreads(\n client: BaseClient,\n request: FetchSpreadsRequest,\n): Promise<Record<string, string>> {\n const params = parseUserInput(request, FetchSpreadsRequestSchema);\n\n return unwrap(\n client.clob\n .post('spreads', {\n json: toTokenRequestPayload(params),\n })\n .andThen(validateWith(SpreadsSchema)),\n );\n}\n\nconst FetchLastTradePriceRequestSchema = z.object({\n tokenId: z.string(),\n});\n\nexport type FetchLastTradePriceRequest = z.input<\n typeof FetchLastTradePriceRequestSchema\n>;\n\nexport type FetchLastTradePriceError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches the last traded price for a token.\n *\n * @throws {@link FetchLastTradePriceError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const trade = await fetchLastTradePrice(client, {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * });\n *\n * // trade === { price: '0.53', side: OrderSide.BUY }\n * ```\n *\n */\nexport async function fetchLastTradePrice(\n client: BaseClient,\n request: FetchLastTradePriceRequest,\n): Promise<LastTradePrice> {\n const params = parseUserInput(request, FetchLastTradePriceRequestSchema);\n\n return unwrap(\n client.clob\n .get('/last-trade-price', {\n params: toSearchParams(params, snakeCase()),\n })\n .andThen(validateWith(LastTradePriceSchema)),\n );\n}\n\nconst FetchLastTradePricesRequestSchema = z\n .array(\n z.object({\n tokenId: z.string(),\n }),\n )\n .min(1);\n\nexport type FetchLastTradePricesRequest = z.input<\n typeof FetchLastTradePricesRequestSchema\n>;\n\nexport type FetchLastTradePricesError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches last traded prices for multiple tokens.\n *\n * @throws {@link FetchLastTradePricesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const trades = await fetchLastTradePrices(client, [\n * {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * },\n * ]);\n *\n * // trades[0] === { tokenId, price: '0.53', side: OrderSide.BUY }\n * ```\n *\n */\nexport async function fetchLastTradePrices(\n client: BaseClient,\n request: FetchLastTradePricesRequest,\n): Promise<LastTradePriceForToken[]> {\n const params = parseUserInput(request, FetchLastTradePricesRequestSchema);\n\n return unwrap(\n client.clob\n .post('last-trades-prices', {\n json: toTokenRequestPayload(params),\n })\n .andThen(validateWith(LastTradePricesSchema)),\n );\n}\n\nconst ListPriceHistoryRequestSchema = z.object({\n tokenId: z.string(),\n startTs: z.number().int().optional(),\n endTs: z.number().int().optional(),\n fidelity: z.number().int().positive().optional(),\n interval: PriceHistoryIntervalSchema.optional(),\n});\n\nexport type FetchPriceHistoryRequest = z.input<\n typeof ListPriceHistoryRequestSchema\n>;\n\nexport type FetchPriceHistoryError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches historical price points for a token.\n *\n * @throws {@link FetchPriceHistoryError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const history = await fetchPriceHistory(client, {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * interval: PriceHistoryInterval.ONE_DAY,\n * fidelity: 60,\n * });\n *\n * // history === PriceHistoryPoint[]\n * ```\n *\n */\nexport async function fetchPriceHistory(\n client: BaseClient,\n request: FetchPriceHistoryRequest,\n): Promise<PriceHistoryPoint[]> {\n const params = parseUserInput(request, ListPriceHistoryRequestSchema);\n const response = await unwrap(\n client.clob\n .get('/prices-history', {\n params: toSearchParams(params, {\n tokenId: 'market',\n startTs: 'startTs',\n endTs: 'endTs',\n fidelity: 'fidelity',\n interval: 'interval',\n }),\n })\n .andThen(validateWith(PriceHistorySchema)),\n );\n\n return response.history;\n}\n\nconst ListCurrentRewardsRequestSchema = z\n .object({\n cursor: PaginationCursorSchema.optional(),\n sponsored: z.boolean().optional(),\n })\n .default({});\n\nexport type ListCurrentRewardsRequest = z.input<\n typeof ListCurrentRewardsRequestSchema\n>;\n\nexport type ListCurrentRewardsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists current active market rewards.\n *\n * @throws {@link ListCurrentRewardsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listCurrentRewards(client);\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: CurrentReward[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listCurrentRewards(client);\n *\n * for await (const page of result) {\n * // page.items: CurrentReward[]\n * }\n * ```\n */\nexport function listCurrentRewards(\n client: BaseClient,\n request: ListCurrentRewardsRequest = {},\n): Paginated<CurrentReward> {\n const { cursor, ...params } = parseUserInput(\n request,\n ListCurrentRewardsRequestSchema,\n );\n\n return paginate(\n (nextCursor) =>\n client.clob\n .get('/rewards/markets/current', {\n params: toSearchParams(\n {\n ...params,\n nextCursor,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(PaginatedCurrentRewardsSchema))\n .map((response) => ({\n items: response.data,\n hasMore: response.next_cursor !== END_CURSOR,\n nextCursor:\n response.next_cursor === END_CURSOR\n ? undefined\n : toPaginationCursor(response.next_cursor),\n totalCount: response.count,\n })),\n cursor,\n );\n}\n\nconst ListMarketRewardsRequestSchema = z.object({\n conditionId: ConditionIdSchema,\n cursor: PaginationCursorSchema.optional(),\n sponsored: z.boolean().optional(),\n});\n\nexport type ListMarketRewardsRequest = z.input<\n typeof ListMarketRewardsRequestSchema\n>;\n\nexport type ListMarketRewardsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists reward configurations for a market.\n *\n * @throws {@link ListMarketRewardsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listMarketRewards(client, {\n * conditionId:\n * '0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af',\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: MarketReward[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listMarketRewards(client, {\n * conditionId:\n * '0xbd31dc8a20211944f6b70f31557f1001557b59905b7738480ca09bd4532f84af',\n * });\n *\n * for await (const page of result) {\n * // page.items: MarketReward[]\n * }\n * ```\n */\nexport function listMarketRewards(\n client: BaseClient,\n request: ListMarketRewardsRequest,\n): Paginated<MarketReward> {\n const { cursor, ...params } = parseUserInput(\n request,\n ListMarketRewardsRequestSchema,\n );\n\n return paginate(\n (nextCursor) =>\n client.clob\n .get(`rewards/markets/${params.conditionId}`, {\n params: toSearchParams(\n {\n nextCursor,\n sponsored: params.sponsored,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(PaginatedMarketRewardsSchema))\n .map((response) => ({\n items: response.data,\n hasMore: response.next_cursor !== END_CURSOR,\n nextCursor:\n response.next_cursor === END_CURSOR\n ? undefined\n : toPaginationCursor(response.next_cursor),\n totalCount: response.count,\n })),\n cursor,\n );\n}\n\nfunction toTokenRequestPayload(\n params: Array<{\n tokenId: string;\n }>,\n) {\n return params.map(({ tokenId }) => ({\n token_id: tokenId,\n }));\n}\n\nfunction toTokenWithSideRequestPayload(\n params: Array<{\n tokenId: string;\n side: z.infer<typeof OrderSideSchema>;\n }>,\n) {\n return params.map(({ tokenId, side }) => ({\n token_id: tokenId,\n side,\n }));\n}\n","import {\n CommentIdSchema,\n EventIdSchema,\n PaginationCursorSchema,\n} from '@polymarket/bindings';\nimport {\n type Comment,\n ListCommentsResponseSchema,\n SeriesIdSchema,\n} from '@polymarket/bindings/gamma';\nimport { unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport {\n decodeOffsetCursor,\n encodeOffsetCursor,\n PageSizeSchema,\n type Paginated,\n paginate,\n} from '../pagination';\nimport { validateWith } from '../response';\nimport { snakeCase, toSearchParams } from './params';\n\nconst ListCommentsRequestSchema = z.object({\n ascending: z.boolean().optional(),\n cursor: PaginationCursorSchema.optional(),\n pageSize: PageSizeSchema.default(20),\n getPositions: z.boolean().optional(),\n holdersOnly: z.boolean().optional(),\n order: z.string().optional(),\n parentEntityId: z.union([EventIdSchema, SeriesIdSchema]),\n parentEntityType: z.enum(['Event', 'Series']),\n});\n\nconst FetchCommentsByIdRequestSchema = z.object({\n getPositions: z.boolean().optional(),\n id: CommentIdSchema,\n});\n\nconst ListCommentsByUserAddressRequestSchema = z.object({\n address: z.string(),\n ascending: z.boolean().optional(),\n cursor: PaginationCursorSchema.optional(),\n order: z.string().optional(),\n pageSize: PageSizeSchema.default(20),\n});\n\nexport type ListCommentsRequest = z.input<typeof ListCommentsRequestSchema>;\nexport type FetchCommentsByIdRequest = z.input<\n typeof FetchCommentsByIdRequestSchema\n>;\nexport type ListCommentsByUserAddressRequest = z.input<\n typeof ListCommentsByUserAddressRequestSchema\n>;\n\nexport type ListCommentsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists comments for an event or series.\n *\n * @throws {@link ListCommentsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listComments(client, {\n * parentEntityId: '123',\n * parentEntityType: 'Event',\n * pageSize: 20,\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: Comment[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listComments(client, {\n * parentEntityId: '123',\n * parentEntityType: 'Event',\n * pageSize: 20,\n * });\n *\n * for await (const page of result) {\n * // page.items: Comment[]\n * }\n * ```\n */\nexport function listComments(\n client: BaseClient,\n request: ListCommentsRequest,\n): Paginated<Comment> {\n const { cursor, pageSize, ...params } = parseUserInput(\n request,\n ListCommentsRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.gamma\n .get('/comments', {\n params: toSearchParams(\n {\n ascending: params.ascending,\n getPositions: params.getPositions,\n holdersOnly: params.holdersOnly,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n order: params.order,\n parentEntityId: params.parentEntityId,\n parentEntityType: params.parentEntityType,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(ListCommentsResponseSchema))\n .map((comments) => {\n const hasMore = comments.length > decoded.pageSize;\n\n return {\n items: comments.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n\nexport type FetchCommentsByIdError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches a comment thread by comment id.\n *\n * @throws {@link FetchCommentsByIdError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const thread = await fetchCommentsById(client, {\n * id: '456',\n * getPositions: true,\n * });\n *\n * // thread: Comment[]\n * ```\n */\nexport async function fetchCommentsById(\n client: BaseClient,\n request: FetchCommentsByIdRequest,\n): Promise<Comment[]> {\n const params = parseUserInput(request, FetchCommentsByIdRequestSchema);\n\n return unwrap(\n client.gamma\n .get(`comments/${params.id}`, {\n params: toSearchParams(\n {\n getPositions: params.getPositions,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(ListCommentsResponseSchema)),\n );\n}\n\nexport type ListCommentsByUserAddressError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists comments written by a wallet address.\n *\n * @throws {@link ListCommentsByUserAddressError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listCommentsByUserAddress(client, {\n * address: '0x1234...',\n * pageSize: 10,\n * order: 'DESC',\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: Comment[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listCommentsByUserAddress(client, {\n * address: '0x1234...',\n * pageSize: 10,\n * order: 'DESC',\n * });\n *\n * for await (const page of result) {\n * // page.items: Comment[]\n * }\n * ```\n */\nexport function listCommentsByUserAddress(\n client: BaseClient,\n request: ListCommentsByUserAddressRequest,\n): Paginated<Comment> {\n const { address, cursor, pageSize, ...params } = parseUserInput(\n request,\n ListCommentsByUserAddressRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.gamma\n .get(`comments/user_address/${address}`, {\n params: toSearchParams(\n {\n ascending: params.ascending,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n order: params.order,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(ListCommentsResponseSchema))\n .map((comments) => {\n const hasMore = comments.length > decoded.pageSize;\n\n return {\n items: comments.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n","import {\n ISOCalendarDateSchema,\n ISODateStringSchema,\n PaginationCursorSchema,\n} from '@polymarket/bindings';\nimport {\n FetchEventLiveVolumeResponseSchema,\n type LiveVolume,\n} from '@polymarket/bindings/data';\nimport {\n type Event,\n EventSchema,\n FetchEventTagsResponseSchema,\n ListEventsKeysetResponseSchema,\n type TagReference,\n} from '@polymarket/bindings/gamma';\nimport { unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport { PageSizeSchema, type Paginated, paginate } from '../pagination';\nimport { validateWith } from '../response';\nimport { snakeCase, toDataSearchParams, toSearchParams } from './params';\n\nconst ListEventsRequestSchema = z.object({\n ascending: z.boolean().optional(),\n closed: z.boolean().optional(),\n cursor: PaginationCursorSchema.optional(),\n pageSize: PageSizeSchema.optional(),\n cyom: z.boolean().optional(),\n endDateMax: ISODateStringSchema.optional(),\n endDateMin: ISODateStringSchema.optional(),\n ended: z.boolean().optional(),\n eventDate: ISOCalendarDateSchema.optional(),\n eventWeek: z.number().int().optional(),\n excludeTagIds: z.array(z.number().int()).optional(),\n featured: z.boolean().optional(),\n featuredOrder: z.boolean().optional(),\n gameIds: z.array(z.number().int()).optional(),\n ids: z.array(z.number().int()).optional(),\n includeBestLines: z.boolean().optional(),\n includeChat: z.boolean().optional(),\n includeChildren: z.boolean().optional(),\n includeTemplate: z.boolean().optional(),\n liquidityMax: z.number().optional(),\n liquidityMin: z.number().optional(),\n live: z.boolean().optional(),\n locale: z.string().optional(),\n order: z.string().optional(),\n parentEventId: z.number().int().optional(),\n partnerSlug: z.string().optional(),\n recurrence: z.enum(['daily', 'weekly', 'monthly']).optional(),\n relatedTags: z.boolean().optional(),\n seriesIds: z.array(z.number().int()).optional(),\n slug: z.array(z.string()).optional(),\n startDateMax: ISODateStringSchema.optional(),\n startDateMin: ISODateStringSchema.optional(),\n startTimeMax: ISODateStringSchema.optional(),\n startTimeMin: ISODateStringSchema.optional(),\n tagIds: z.array(z.number().int()).optional(),\n tagMatch: z.enum(['any', 'all']).optional(),\n tagSlug: z.string().optional(),\n titleSearch: z.string().optional(),\n volumeMax: z.number().optional(),\n volumeMin: z.number().optional(),\n});\n\nexport type ListEventsRequest = z.input<typeof ListEventsRequestSchema>;\n\nconst FetchEventRequestSchema = z.union([\n z.object({\n id: z.string(),\n includeBestLines: z.boolean().optional(),\n includeChat: z.boolean().optional(),\n includeTemplate: z.boolean().optional(),\n locale: z.string().optional(),\n }),\n z.object({\n slug: z.string(),\n includeBestLines: z.boolean().optional(),\n includeChat: z.boolean().optional(),\n includeTemplate: z.boolean().optional(),\n locale: z.string().optional(),\n }),\n]);\n\nexport type FetchEventRequest = z.input<typeof FetchEventRequestSchema>;\n\nconst FetchEventTagsRequestSchema = z.object({\n id: z.string(),\n});\n\nexport type FetchEventTagsRequest = z.input<typeof FetchEventTagsRequestSchema>;\n\nconst FetchEventLiveVolumeRequestSchema = z.object({\n id: z.string(),\n});\n\nexport type FetchEventLiveVolumeRequest = z.input<\n typeof FetchEventLiveVolumeRequestSchema\n>;\n\ntype ListEventsParams = z.output<typeof ListEventsRequestSchema>;\n\nexport type ListEventsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists events.\n *\n * @throws {@link ListEventsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listEvents(client, {\n * closed: false,\n * pageSize: 10,\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: Event[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listEvents(client, {\n * closed: false,\n * pageSize: 10,\n * });\n *\n * for await (const page of result) {\n * // page.items: Event[]\n * }\n * ```\n */\nexport function listEvents(\n client: BaseClient,\n request: ListEventsRequest = {},\n): Paginated<Event> {\n const params = parseUserInput(request, ListEventsRequestSchema);\n\n return paginate(\n (cursor) =>\n client.gamma\n .get('/events/keyset', {\n params: toEventsSearchParams({\n ...params,\n cursor: cursor ?? params.cursor,\n }),\n })\n .andThen(validateWith(ListEventsKeysetResponseSchema))\n .map((response) => ({\n items: response.items,\n hasMore: response.next_cursor !== undefined,\n nextCursor: response.next_cursor,\n })),\n params.cursor,\n );\n}\n\nexport type FetchEventError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches an event.\n *\n * @throws {@link FetchEventError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const event = await fetchEvent(client, {\n * id: '12345',\n * });\n *\n * // event === Event\n * ```\n */\nexport async function fetchEvent(\n client: BaseClient,\n request: FetchEventRequest,\n): Promise<Event> {\n const params = parseUserInput(request, FetchEventRequestSchema);\n\n if ('id' in params) {\n return unwrap(\n client.gamma\n .get(`events/${params.id}`, {\n params: toFetchEventByIdSearchParams(params),\n })\n .andThen(validateWith(EventSchema)),\n );\n }\n\n return unwrap(\n client.gamma\n .get(`events/slug/${params.slug}`, {\n params: toFetchEventBySlugSearchParams(params),\n })\n .andThen(validateWith(EventSchema)),\n );\n}\n\nexport type FetchEventTagsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches an event's tags.\n *\n * @throws {@link FetchEventTagsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const tags = await fetchEventTags(client, {\n * id: '12345',\n * });\n *\n * // tags: TagReference[]\n * ```\n */\nexport async function fetchEventTags(\n client: BaseClient,\n request: FetchEventTagsRequest,\n): Promise<TagReference[]> {\n const params = parseUserInput(request, FetchEventTagsRequestSchema);\n\n return unwrap(\n client.gamma\n .get(`events/${params.id}/tags`)\n .andThen(validateWith(FetchEventTagsResponseSchema)),\n );\n}\n\nexport type FetchEventLiveVolumeError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches live volume for an event.\n *\n * @throws {@link FetchEventLiveVolumeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const volume = await fetchEventLiveVolume(client, {\n * id: '160707',\n * });\n *\n * // volume: LiveVolume[]\n * ```\n */\nexport async function fetchEventLiveVolume(\n client: BaseClient,\n request: FetchEventLiveVolumeRequest,\n): Promise<LiveVolume[]> {\n const params = parseUserInput(request, FetchEventLiveVolumeRequestSchema);\n\n return unwrap(\n client.data\n .get('/live-volume', {\n params: toDataSearchParams(params),\n })\n .andThen(validateWith(FetchEventLiveVolumeResponseSchema)),\n );\n}\n\nfunction toEventsSearchParams(params: ListEventsParams): URLSearchParams {\n return toSearchParams(\n params,\n snakeCase<ListEventsParams>({\n cursor: 'after_cursor',\n excludeTagIds: 'exclude_tag_id',\n gameIds: 'game_id',\n ids: 'id',\n pageSize: 'limit',\n seriesIds: 'series_id',\n tagIds: 'tag_id',\n }),\n );\n}\n\nfunction toFetchEventByIdSearchParams(\n params: Extract<z.output<typeof FetchEventRequestSchema>, { id: string }>,\n): URLSearchParams {\n return toSearchParams(\n {\n includeBestLines: params.includeBestLines,\n includeChat: params.includeChat,\n includeTemplate: params.includeTemplate,\n locale: params.locale,\n },\n snakeCase(),\n );\n}\n\nfunction toFetchEventBySlugSearchParams(\n params: Extract<z.output<typeof FetchEventRequestSchema>, { slug: string }>,\n): URLSearchParams {\n return toSearchParams(\n {\n includeBestLines: params.includeBestLines,\n includeChat: params.includeChat,\n includeTemplate: params.includeTemplate,\n locale: params.locale,\n },\n snakeCase(),\n );\n}\n","import { PaginationCursorSchema } from '@polymarket/bindings';\nimport {\n type BuilderVolumeEntry,\n LeaderboardCategorySchema,\n type LeaderboardEntry,\n LeaderboardOrderBySchema,\n ListBuilderLeaderboardResponseSchema,\n ListBuilderVolumeResponseSchema,\n ListTraderLeaderboardResponseSchema,\n TimePeriodSchema,\n type TraderLeaderboardEntry,\n} from '@polymarket/bindings/data';\nimport { unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport {\n decodeOffsetCursor,\n encodeOffsetCursor,\n PageSizeSchema,\n type Paginated,\n paginate,\n} from '../pagination';\nimport { validateWith } from '../response';\nimport { toDataSearchParams } from './params';\n\nconst ListBuilderLeaderboardRequestSchema = z.object({\n cursor: PaginationCursorSchema.optional(),\n pageSize: PageSizeSchema.default(20),\n timePeriod: TimePeriodSchema.optional(),\n});\n\nconst ListBuilderVolumeRequestSchema = z.object({\n timePeriod: TimePeriodSchema.optional(),\n});\n\nconst ListTraderLeaderboardRequestSchema = z.object({\n category: LeaderboardCategorySchema.optional(),\n cursor: PaginationCursorSchema.optional(),\n pageSize: PageSizeSchema.default(20),\n timePeriod: TimePeriodSchema.optional(),\n orderBy: LeaderboardOrderBySchema.optional(),\n user: z.string().optional(),\n userName: z.string().optional(),\n});\n\nexport type ListBuilderLeaderboardRequest = z.input<\n typeof ListBuilderLeaderboardRequestSchema\n>;\nexport type ListBuilderVolumeRequest = z.input<\n typeof ListBuilderVolumeRequestSchema\n>;\nexport type ListTraderLeaderboardRequest = z.input<\n typeof ListTraderLeaderboardRequestSchema\n>;\n\nexport type ListBuilderLeaderboardError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists builder leaderboard rankings.\n *\n * @throws {@link ListBuilderLeaderboardError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listBuilderLeaderboard(client, {\n * pageSize: 10,\n * timePeriod: 'DAY',\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: LeaderboardEntry[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listBuilderLeaderboard(client, {\n * pageSize: 10,\n * timePeriod: 'DAY',\n * });\n *\n * for await (const page of result) {\n * // page.items: LeaderboardEntry[]\n * }\n * ```\n */\nexport function listBuilderLeaderboard(\n client: BaseClient,\n request: ListBuilderLeaderboardRequest = {},\n): Paginated<LeaderboardEntry> {\n const { cursor, pageSize, ...params } = parseUserInput(\n request,\n ListBuilderLeaderboardRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.data\n .get('/v1/builders/leaderboard', {\n params: toDataSearchParams({\n ...params,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n }),\n })\n .andThen(validateWith(ListBuilderLeaderboardResponseSchema))\n .map((builders) => {\n const hasMore = builders.length > decoded.pageSize;\n\n return {\n items: builders.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n\nexport type ListBuilderVolumeError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists daily builder volume entries.\n *\n * @throws {@link ListBuilderVolumeError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const volume = await fetchBuilderVolume(client, {\n * timePeriod: 'DAY',\n * });\n *\n * // volume: BuilderVolumeEntry[]\n * ```\n */\nexport async function fetchBuilderVolume(\n client: BaseClient,\n request: ListBuilderVolumeRequest = {},\n): Promise<BuilderVolumeEntry[]> {\n const params = parseUserInput(request, ListBuilderVolumeRequestSchema);\n\n return unwrap(\n client.data\n .get('/v1/builders/volume', {\n params: toDataSearchParams(params),\n })\n .andThen(validateWith(ListBuilderVolumeResponseSchema)),\n );\n}\n\nexport type ListTraderLeaderboardError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists trader leaderboard rankings.\n *\n * @throws {@link ListTraderLeaderboardError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listTraderLeaderboard(client, {\n * orderBy: 'PNL',\n * pageSize: 10,\n * timePeriod: 'DAY',\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: TraderLeaderboardEntry[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listTraderLeaderboard(client, {\n * orderBy: 'PNL',\n * pageSize: 10,\n * timePeriod: 'DAY',\n * });\n *\n * for await (const page of result) {\n * // page.items: TraderLeaderboardEntry[]\n * }\n * ```\n */\nexport function listTraderLeaderboard(\n client: BaseClient,\n request: ListTraderLeaderboardRequest = {},\n): Paginated<TraderLeaderboardEntry> {\n const { cursor, pageSize, ...params } = parseUserInput(\n request,\n ListTraderLeaderboardRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.data\n .get('/v1/leaderboard', {\n params: toDataSearchParams({\n ...params,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n }),\n })\n .andThen(validateWith(ListTraderLeaderboardResponseSchema))\n .map((traders) => {\n const hasMore = traders.length > decoded.pageSize;\n\n return {\n items: traders.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n","import {\n ISODateStringSchema,\n PaginationCursorSchema,\n} from '@polymarket/bindings';\nimport {\n ListMarketHoldersResponseSchema,\n ListMarketPositionsResponseSchema,\n ListOpenInterestResponseSchema,\n type MetaHolder,\n type MetaMarketPositionV1,\n type OpenInterest,\n} from '@polymarket/bindings/data';\nimport {\n FetchMarketTagsResponseSchema,\n ListMarketsKeysetResponseSchema,\n type Market,\n MarketSchema,\n type TagReference,\n} from '@polymarket/bindings/gamma';\nimport { unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport {\n decodeOffsetCursor,\n encodeOffsetCursor,\n PageSizeSchema,\n type Paginated,\n paginate,\n} from '../pagination';\nimport { validateWith } from '../response';\nimport { snakeCase, toDataSearchParams, toSearchParams } from './params';\n\n// The public markets endpoint forces active=true and archived=false server-side.\nconst ListMarketsRequestSchema = z.object({\n ascending: z.boolean().optional(),\n closed: z.boolean().optional(),\n clobTokenIds: z.array(z.string()).optional(),\n cursor: PaginationCursorSchema.optional(),\n pageSize: PageSizeSchema.optional(),\n conditionIds: z.array(z.string()).optional(),\n cyom: z.boolean().optional(),\n decimalized: z.boolean().optional(),\n endDateMax: ISODateStringSchema.optional(),\n endDateMin: ISODateStringSchema.optional(),\n gameId: z.string().optional(),\n ids: z.array(z.number().int()).optional(),\n includeTag: z.boolean().optional(),\n liquidityNumMax: z.number().optional(),\n liquidityNumMin: z.number().optional(),\n locale: z.string().optional(),\n marketMakerAddresses: z.array(z.string()).optional(),\n order: z.string().optional(),\n questionIds: z.array(z.string()).optional(),\n relatedTags: z.boolean().optional(),\n rfqEnabled: z.boolean().optional(),\n rewardsMinSize: z.number().optional(),\n slug: z.array(z.string()).optional(),\n sportsMarketTypes: z.array(z.string()).optional(),\n startDateMax: ISODateStringSchema.optional(),\n startDateMin: ISODateStringSchema.optional(),\n tagId: z.number().int().optional(),\n tagMatch: z.enum(['any', 'all']).optional(),\n umaResolutionStatus: z.string().optional(),\n volumeNumMax: z.number().optional(),\n volumeNumMin: z.number().optional(),\n});\n\nexport type ListMarketsRequest = z.input<typeof ListMarketsRequestSchema>;\n\nconst FetchMarketByIdRequestSchema = z.object({\n id: z.string(),\n includeTag: z.boolean().optional(),\n locale: z.string().optional(),\n});\n\nconst FetchMarketBySlugRequestSchema = z.object({\n slug: z.string(),\n includeTag: z.boolean().optional(),\n locale: z.string().optional(),\n});\n\nconst FetchMarketRequestSchema = z.union([\n FetchMarketByIdRequestSchema,\n FetchMarketBySlugRequestSchema,\n]);\n\nexport type FetchMarketRequest = z.input<typeof FetchMarketRequestSchema>;\n\nconst FetchMarketTagsRequestSchema = z.object({\n id: z.string(),\n});\n\nexport type FetchMarketTagsRequest = z.input<\n typeof FetchMarketTagsRequestSchema\n>;\n\nconst ListMarketHoldersRequestSchema = z.object({\n limit: z.number().int().optional(),\n market: z.array(z.string()),\n minBalance: z.number().int().optional(),\n});\n\nconst ListOpenInterestRequestSchema = z.object({\n market: z.array(z.string()).optional(),\n});\n\nconst MarketPositionStatusSchema = z.enum(['OPEN', 'CLOSED', 'ALL']);\nconst MarketPositionSortBySchema = z.enum([\n 'TOKENS',\n 'CASH_PNL',\n 'REALIZED_PNL',\n 'TOTAL_PNL',\n]);\nconst MarketPositionSortDirectionSchema = z.enum(['ASC', 'DESC']);\n\nconst ListMarketPositionsRequestSchema = z.object({\n cursor: PaginationCursorSchema.optional(),\n market: z.string(),\n pageSize: PageSizeSchema.default(20),\n user: z.string().optional(),\n status: MarketPositionStatusSchema.optional(),\n sortBy: MarketPositionSortBySchema.optional(),\n sortDirection: MarketPositionSortDirectionSchema.optional(),\n});\n\nexport type ListMarketHoldersRequest = z.input<\n typeof ListMarketHoldersRequestSchema\n>;\nexport type ListOpenInterestRequest = z.input<\n typeof ListOpenInterestRequestSchema\n>;\nexport type ListMarketPositionsRequest = z.input<\n typeof ListMarketPositionsRequestSchema\n>;\n\ntype ListMarketsParams = z.output<typeof ListMarketsRequestSchema>;\n\nexport type ListMarketsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists markets.\n *\n * @throws {@link ListMarketsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listMarkets(client, {\n * closed: false,\n * pageSize: 10,\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: Market[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listMarkets(client, {\n * closed: false,\n * pageSize: 10,\n * });\n *\n * for await (const page of result) {\n * // page.items: Market[]\n * }\n * ```\n */\nexport function listMarkets(\n client: BaseClient,\n request: ListMarketsRequest = {},\n): Paginated<Market> {\n const params = parseUserInput(request, ListMarketsRequestSchema);\n\n return paginate(\n (cursor) =>\n client.gamma\n .get('/markets/keyset', {\n params: toMarketsSearchParams({\n ...params,\n cursor: cursor ?? params.cursor,\n }),\n })\n .andThen(validateWith(ListMarketsKeysetResponseSchema))\n .map((response) => ({\n items: response.items,\n hasMore: response.next_cursor !== undefined,\n nextCursor: response.next_cursor,\n })),\n params.cursor,\n );\n}\n\nexport type FetchMarketError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches a market.\n *\n * @throws {@link FetchMarketError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const market = await fetchMarket(client, {\n * id: '12345',\n * });\n *\n * // market === Market\n * ```\n */\nexport async function fetchMarket(\n client: BaseClient,\n request: FetchMarketRequest,\n): Promise<Market> {\n const params = parseUserInput(request, FetchMarketRequestSchema);\n\n if ('id' in params) {\n return fetchMarketById(client, params);\n }\n\n return fetchMarketBySlug(client, params);\n}\n\nexport type FetchMarketTagsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches a market's tags.\n *\n * @throws {@link FetchMarketTagsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const tags = await fetchMarketTags(client, {\n * id: '12345',\n * });\n *\n * // tags: TagReference[]\n * ```\n */\nexport async function fetchMarketTags(\n client: BaseClient,\n request: FetchMarketTagsRequest,\n): Promise<TagReference[]> {\n const params = parseUserInput(request, FetchMarketTagsRequestSchema);\n\n return unwrap(\n client.gamma\n .get(`markets/${params.id}/tags`)\n .andThen(validateWith(FetchMarketTagsResponseSchema)),\n );\n}\n\nexport type ListMarketHoldersError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists the top holders for one or more markets.\n *\n * @throws {@link ListMarketHoldersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const holders = await listMarketHolders(client, {\n * market: ['0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093'],\n * limit: 5,\n * });\n *\n * // holders: MetaHolder[]\n * ```\n */\nexport async function listMarketHolders(\n client: BaseClient,\n request: ListMarketHoldersRequest,\n): Promise<MetaHolder[]> {\n const params = parseUserInput(request, ListMarketHoldersRequestSchema);\n\n return unwrap(\n client.data\n .get('/holders', {\n params: toDataSearchParams(params),\n })\n .andThen(validateWith(ListMarketHoldersResponseSchema)),\n );\n}\n\nexport type ListOpenInterestError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists open interest for one or more markets.\n *\n * @throws {@link ListOpenInterestError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const openInterest = await listOpenInterest(client, {\n * market: ['0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093'],\n * });\n *\n * // openInterest: OpenInterest[]\n * ```\n */\nexport async function listOpenInterest(\n client: BaseClient,\n request: ListOpenInterestRequest = {},\n): Promise<OpenInterest[]> {\n const params = parseUserInput(request, ListOpenInterestRequestSchema);\n\n return unwrap(\n client.data\n .get('/oi', {\n params: toDataSearchParams(params),\n })\n .andThen(validateWith(ListOpenInterestResponseSchema)),\n );\n}\n\nexport type ListMarketPositionsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists positions for a market.\n *\n * @throws {@link ListMarketPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listMarketPositions(client, {\n * market: '0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093',\n * pageSize: 10,\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: MetaMarketPositionV1[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listMarketPositions(client, {\n * market: '0xe546672750517f62c45a5a00067481981e62b9c20fa8220203232c9dc8fd2093',\n * pageSize: 10,\n * });\n *\n * for await (const page of result) {\n * // page.items: MetaMarketPositionV1[]\n * }\n * ```\n */\nexport function listMarketPositions(\n client: BaseClient,\n request: ListMarketPositionsRequest,\n): Paginated<MetaMarketPositionV1> {\n const { cursor, pageSize, ...params } = parseUserInput(\n request,\n ListMarketPositionsRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.data\n .get('/v1/market-positions', {\n params: toDataSearchParams({\n ...params,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n }),\n })\n .andThen(validateWith(ListMarketPositionsResponseSchema))\n .map((positions) => {\n const hasMore = positions.length > decoded.pageSize;\n\n return {\n items: positions.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n\nfunction toMarketsSearchParams(params: ListMarketsParams): URLSearchParams {\n return toSearchParams(\n params,\n snakeCase<ListMarketsParams>({\n cursor: 'after_cursor',\n ids: 'id',\n marketMakerAddresses: 'market_maker_address',\n pageSize: 'limit',\n }),\n );\n}\n\nasync function fetchMarketBySlug(\n client: BaseClient,\n params: z.output<typeof FetchMarketBySlugRequestSchema>,\n): Promise<Market> {\n return unwrap(\n client.gamma\n .get(`markets/slug/${params.slug}`, {\n params: toSearchParams(\n {\n includeTag: params.includeTag,\n locale: params.locale,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(MarketSchema)),\n );\n}\n\nasync function fetchMarketById(\n client: BaseClient,\n params: z.output<typeof FetchMarketByIdRequestSchema>,\n): Promise<Market> {\n return unwrap(\n client.gamma\n .get(`markets/${params.id}`, {\n params: toSearchParams(\n {\n includeTag: params.includeTag,\n locale: params.locale,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(MarketSchema)),\n );\n}\n","import {\n type CancelOrdersResponse,\n CancelOrdersResponseSchema,\n} from '@polymarket/bindings/clob';\nimport { unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseSecureClient } from '../../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n SigningError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../../errors';\nimport { parseUserInput } from '../../input';\nimport { validateWith } from '../../response';\n\nconst CancelOrderRequestSchema = z.object({\n orderId: z.string(),\n});\n\nconst CancelOrdersRequestSchema = z.object({\n orderIds: z.array(z.string()).min(1).max(3000),\n});\n\nconst CancelMarketOrdersRequestSchema = z\n .object({\n assetId: z.string().optional(),\n market: z.string().optional(),\n })\n .refine(\n (request) => request.market !== undefined || request.assetId !== undefined,\n {\n message: 'At least one of market or assetId is required.',\n path: ['market'],\n },\n );\n\nexport type CancelOrderRequest = z.input<typeof CancelOrderRequestSchema>;\n\nexport type CancelOrderError =\n | RequestRejectedError\n | RateLimitError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Cancels a single open order for the authenticated account.\n *\n * @throws {@link CancelOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await cancelOrder(client, {\n * orderId: '123',\n * });\n *\n * // response.canceled: string[]\n * ```\n */\nexport async function cancelOrder(\n client: BaseSecureClient,\n request: CancelOrderRequest,\n): Promise<CancelOrdersResponse> {\n const params = parseUserInput(request, CancelOrderRequestSchema);\n\n return cancel(client, '/order', {\n orderID: params.orderId,\n });\n}\n\nexport type CancelOrdersRequest = z.input<typeof CancelOrdersRequestSchema>;\nexport type CancelOrdersError =\n | RequestRejectedError\n | RateLimitError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Cancels multiple open orders for the authenticated account.\n *\n * @throws {@link CancelOrdersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await cancelOrders(client, {\n * orderIds: ['1', '2'],\n * });\n *\n * // response.canceled: string[]\n * ```\n */\nexport async function cancelOrders(\n client: BaseSecureClient,\n request: CancelOrdersRequest,\n): Promise<CancelOrdersResponse> {\n const params = parseUserInput(request, CancelOrdersRequestSchema);\n\n return cancel(client, '/orders', params.orderIds);\n}\n\nexport type CancelAllError =\n | RequestRejectedError\n | RateLimitError\n | SigningError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Cancels all open orders for the authenticated account.\n *\n * @throws {@link CancelAllError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await cancelAll(client);\n *\n * // response.canceled: string[]\n * ```\n */\nexport async function cancelAll(\n client: BaseSecureClient,\n): Promise<CancelOrdersResponse> {\n return cancel(client, '/cancel-all');\n}\n\nexport type CancelMarketOrdersRequest = z.input<\n typeof CancelMarketOrdersRequestSchema\n>;\nexport type CancelMarketOrdersError =\n | RequestRejectedError\n | RateLimitError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Cancels all open orders for the authenticated account that match the market\n * or asset filter.\n *\n * @throws {@link CancelMarketOrdersError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await cancelMarketOrders(client, {\n * market: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * });\n *\n * // response.canceled: string[]\n * ```\n */\nexport async function cancelMarketOrders(\n client: BaseSecureClient,\n request: CancelMarketOrdersRequest,\n): Promise<CancelOrdersResponse> {\n const params = parseUserInput(request, CancelMarketOrdersRequestSchema);\n\n return cancel(client, '/cancel-market-orders', {\n asset_id: params.assetId,\n market: params.market,\n });\n}\n\nasync function cancel(\n client: BaseSecureClient,\n path: string,\n payload?: unknown,\n): Promise<CancelOrdersResponse> {\n return unwrap(\n client.secureClob\n .del(path, {\n json: payload,\n })\n .andThen(validateWith(CancelOrdersResponseSchema)),\n );\n}\n","import type { TickSizeValue } from '@polymarket/bindings';\nimport {\n type OrderBookLevel,\n OrderSide,\n OrderSideSchema,\n OrderType,\n} from '@polymarket/bindings/clob';\nimport { invariant } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient } from '../../clients';\nimport {\n InsufficientLiquidityError,\n type RateLimitError,\n type RequestRejectedError,\n type TransportError,\n type UnexpectedResponseError,\n type UserInputError,\n} from '../../errors';\nimport { parseUserInput } from '../../input';\nimport { fetchOrderBook, fetchTickSize } from '../clob';\n\nconst EstimateMarketPriceRequestSchema = z.object({\n tokenId: z.string(),\n amount: z.number().positive(),\n side: OrderSideSchema,\n orderType: z\n .union([z.literal(OrderType.FAK), z.literal(OrderType.FOK)])\n .default(OrderType.FOK),\n});\n\nexport type EstimateMarketPriceRequest = z.input<\n typeof EstimateMarketPriceRequestSchema\n>;\n\nexport type EstimateMarketPriceError =\n | InsufficientLiquidityError\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Estimates the price level a market order would cross at current book depth.\n *\n * For BUY orders, `amount` is the amount of collateral to spend. For SELL orders,\n * `amount` is the number of shares to sell.\n *\n * When `orderType` is `FOK`, this estimate requires enough resting liquidity to\n * satisfy the full requested amount and throws if the book is too thin. When\n * `orderType` is `FAK`, the estimate may fall back to the best currently\n * available price level even if the full requested amount cannot fill, so it\n * should be treated as a partial-fill execution estimate rather than a full-fill\n * guarantee.\n *\n * @example\n * ```ts\n * const price = await estimateMarketPrice(client, {\n * tokenId:\n * '8501497159083948713316135768103773293754490207922884688769443031624417212426',\n * side: OrderSide.BUY,\n * amount: 10,\n * });\n *\n * // price === 0.53\n * ```\n *\n * @throws {@link EstimateMarketPriceError}\n * Thrown on failure.\n */\nexport async function estimateMarketPrice(\n client: BaseClient,\n request: EstimateMarketPriceRequest,\n): Promise<number> {\n const params = parseUserInput(request, EstimateMarketPriceRequestSchema);\n const tickSize = await fetchTickSize(client, {\n tokenId: params.tokenId,\n });\n\n return resolveEstimatedMarketPrice(client, {\n amount: params.amount,\n orderType: params.orderType,\n side: params.side,\n tickSize,\n tokenId: params.tokenId,\n });\n}\n\n/** @internal */\nexport async function resolveEstimatedMarketPrice(\n client: BaseClient,\n params: {\n amount: number;\n orderType: OrderType;\n side: OrderSide;\n tokenId: string;\n tickSize: TickSizeValue;\n },\n): Promise<number> {\n const orderBook = await fetchOrderBook(client, {\n tokenId: params.tokenId,\n });\n\n const price =\n params.side === OrderSide.BUY\n ? calculateBuyMarketPrice(orderBook.asks, params.amount, params.orderType)\n : calculateSellMarketPrice(\n orderBook.bids,\n params.amount,\n params.orderType,\n );\n\n invariant(\n isValidPrice(price, params.tickSize),\n `Resolved market price fell outside the valid range for tick size ${params.tickSize}.`,\n );\n\n return price;\n}\n\nfunction isValidPrice(price: number, tickSize: TickSizeValue): boolean {\n return price >= tickSize && price <= 1 - tickSize;\n}\n\nfunction calculateBuyMarketPrice(\n positions: OrderBookLevel[],\n amountToMatch: number,\n orderType: OrderType,\n): number {\n if (positions.length === 0) {\n throw new InsufficientLiquidityError('No resting liquidity.');\n }\n\n let sum = 0;\n\n for (let index = positions.length - 1; index >= 0; index -= 1) {\n const position = positions[index];\n\n if (position === undefined) {\n continue;\n }\n\n sum += Number.parseFloat(position.size) * Number.parseFloat(position.price);\n\n if (sum >= amountToMatch) {\n return Number.parseFloat(position.price);\n }\n }\n\n if (orderType === OrderType.FOK) {\n throw new InsufficientLiquidityError(\n 'Insufficient liquidity for full fill.',\n );\n }\n\n // biome-ignore lint/style/noNonNullAssertion: Checked for emptiness above.\n const bestPosition = positions[0]!;\n\n return Number.parseFloat(bestPosition.price);\n}\n\nfunction calculateSellMarketPrice(\n positions: OrderBookLevel[],\n amountToMatch: number,\n orderType: OrderType,\n): number {\n if (positions.length === 0) {\n throw new InsufficientLiquidityError('No resting liquidity.');\n }\n\n let sum = 0;\n\n for (let index = positions.length - 1; index >= 0; index -= 1) {\n const position = positions[index];\n\n if (position === undefined) {\n continue;\n }\n\n sum += Number.parseFloat(position.size);\n\n if (sum >= amountToMatch) {\n return Number.parseFloat(position.price);\n }\n }\n\n if (orderType === OrderType.FOK) {\n throw new InsufficientLiquidityError(\n 'Insufficient liquidity for full fill.',\n );\n }\n\n // biome-ignore lint/style/noNonNullAssertion: Checked for emptiness above.\n const bestPosition = positions[0]!;\n\n return Number.parseFloat(bestPosition.price);\n}\n","import {\n type OrderResponse,\n OrderResponseSchema,\n type OrderResponses,\n OrderResponsesSchema,\n OrderType,\n} from '@polymarket/bindings/clob';\nimport { invariant, unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseSecureClient } from '../../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n SigningError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../../errors';\nimport { parseUserInput } from '../../input';\nimport { validateWith } from '../../response';\nimport type { SignedOrder } from './types';\n\nconst PostOrdersRequestSchema = z.array(z.custom<SignedOrder>()).min(1).max(15);\n\nexport type PostOrdersRequest = z.input<typeof PostOrdersRequestSchema>;\n\nexport type PostOrderError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError;\n\nexport type PostOrdersError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Posts a signed order for the authenticated account.\n *\n * @example\n * ```ts\n * const response = await prepareMarketOrder(client, {\n * amount: 10,\n * side: OrderSide.BUY,\n * tokenId: '123',\n * })\n * .then(completeWith(wallet))\n * .then(postOrder(client));\n * ```\n *\n * @throws {@link PostOrderError}\n * Thrown on failure.\n */\nexport function postOrder(\n client: BaseSecureClient,\n): (order: SignedOrder) => Promise<OrderResponse> {\n return async function postSignedOrder(order: SignedOrder) {\n const payload = createSendOrderPayload(client, order);\n\n return unwrap(\n client.secureClob\n .post('/order', {\n json: payload,\n })\n .andThen(validateWith(OrderResponseSchema)),\n );\n };\n}\n\n/**\n * Posts multiple signed orders for the authenticated account.\n *\n * @remarks\n * Accepts between 1 and 15 orders, matching the current service limit.\n *\n * @example\n * ```ts\n * const responses = await postOrders(client)([firstSignedOrder, secondSignedOrder]);\n * ```\n *\n * @throws {@link PostOrdersError}\n * Thrown on failure.\n */\nexport function postOrders(\n client: BaseSecureClient,\n): (orders: PostOrdersRequest) => Promise<OrderResponses>;\nexport function postOrders(\n client: BaseSecureClient,\n): (orders: PostOrdersRequest) => Promise<OrderResponses> {\n return async function postSignedOrders(orders: PostOrdersRequest) {\n const validatedOrders = parseUserInput(orders, PostOrdersRequestSchema);\n const payload = validatedOrders.map((order) =>\n createSendOrderPayload(client, order),\n );\n\n return unwrap(\n client.secureClob\n .post('/orders', {\n json: payload,\n })\n .andThen(validateWith(OrderResponsesSchema)),\n );\n };\n}\n\nfunction createSendOrderPayload(client: BaseSecureClient, order: SignedOrder) {\n invariant(\n order.postOnly !== true ||\n order.orderType === OrderType.GTC ||\n order.orderType === OrderType.GTD,\n 'Post-only orders are only supported for GTC and GTD order types.',\n );\n\n return {\n deferExec: false,\n order: {\n expiration: `${order.expiration}`,\n feeRateBps: `${order.feeRateBps}`,\n maker: order.maker,\n makerAmount: order.makerAmount,\n nonce: `${order.nonce}`,\n salt: Number.parseInt(order.salt, 10),\n side: order.side,\n signature: order.signature,\n signatureType: order.signatureType,\n signer: order.signer,\n taker: order.taker,\n takerAmount: order.takerAmount,\n tokenId: order.tokenId,\n },\n orderType: order.orderType,\n owner: client.credentials.key,\n ...(order.postOnly === true ? { postOnly: true } : {}),\n };\n}\n","import type { TokenId } from '@polymarket/bindings';\nimport { AssetType, OrderSide } from '@polymarket/bindings/clob';\nimport type { EvmAddress } from '@polymarket/types';\nimport type { BaseSecureClient } from '../../clients';\nimport { fetchBalanceAllowance } from '../account';\n\nexport type ResolveCurrentAllowanceParams = {\n spenderAddress: EvmAddress;\n side: OrderSide;\n tokenId: TokenId;\n};\n\n/* @internal */\nexport async function resolveCurrentAllowance(\n client: BaseSecureClient,\n params: ResolveCurrentAllowanceParams,\n): Promise<bigint> {\n const assetType =\n params.side === OrderSide.BUY\n ? AssetType.COLLATERAL\n : AssetType.CONDITIONAL;\n const { allowances } = await fetchBalanceAllowance(\n client,\n params.side === OrderSide.BUY\n ? {\n assetType,\n }\n : {\n assetType,\n tokenId: params.tokenId,\n },\n );\n\n return resolveAllowanceAmount(allowances, params.spenderAddress);\n}\n\nfunction resolveAllowanceAmount(\n allowances: Record<EvmAddress, bigint>,\n spender: EvmAddress,\n): bigint {\n const match = Object.entries(allowances).find(\n ([key]) => key.toLowerCase() === spender.toLowerCase(),\n );\n\n return match?.[1] ?? 0n;\n}\n","import type { TickSizeValue } from '@polymarket/bindings';\nimport type { EvmAddress } from '@polymarket/types';\nimport { invariant } from '@polymarket/types';\nimport type { BaseSecureClient } from '../../clients';\nimport { fetchFeeRate } from '../clob';\n\nexport type RoundingConfig = {\n amount: number;\n price: number;\n size: number;\n};\n\nexport function resolveRoundingConfig(tickSize: TickSizeValue): RoundingConfig {\n switch (tickSize) {\n case 0.1:\n return { amount: 3, price: 1, size: 2 };\n case 0.01:\n return { amount: 4, price: 2, size: 2 };\n case 0.001:\n return { amount: 5, price: 3, size: 2 };\n case 0.0001:\n return { amount: 6, price: 4, size: 2 };\n }\n\n invariant(false, `Unsupported tick size: ${tickSize}`);\n}\n\nexport async function resolveFeeRateBps(\n client: BaseSecureClient,\n tokenId: string,\n): Promise<number> {\n return fetchFeeRate(client, {\n tokenId,\n });\n}\n\nexport function resolveExchangeAddress(\n client: BaseSecureClient,\n negRisk: boolean,\n): EvmAddress {\n return negRisk\n ? client.environment.negRiskExchange\n : client.environment.standardExchange;\n}\n","const COLLATERAL_TOKEN_DECIMALS = 6;\n\nexport function parseAmount(value: number): bigint {\n return BigInt(Math.round(value * 10 ** COLLATERAL_TOKEN_DECIMALS));\n}\n\nexport function roundDown(value: number, decimals: number): number {\n if (decimalPlaces(value) <= decimals) {\n return value;\n }\n\n return Math.floor(value * 10 ** decimals) / 10 ** decimals;\n}\n\nexport function roundUp(value: number, decimals: number): number {\n if (decimalPlaces(value) <= decimals) {\n return value;\n }\n\n return Math.ceil(value * 10 ** decimals) / 10 ** decimals;\n}\n\nexport function roundNormal(value: number, decimals: number): number {\n if (decimalPlaces(value) <= decimals) {\n return value;\n }\n\n return Math.round(value * 10 ** decimals) / 10 ** decimals;\n}\n\nexport function decimalPlaces(value: number): number {\n if (Number.isInteger(value)) {\n return 0;\n }\n\n const parts = value.toString().split('.');\n\n return parts.length <= 1 ? 0 : (parts[1]?.length ?? 0);\n}\n","import {\n EvmAddressSchema,\n type TickSizeValue,\n TokenIdSchema,\n} from '@polymarket/bindings';\nimport {\n OrderSide,\n OrderSideSchema,\n OrderType,\n} from '@polymarket/bindings/clob';\nimport type { EvmAddress } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseSecureClient } from '../../clients';\nimport { UserInputError } from '../../errors';\nimport { fetchNegRisk, fetchTickSize } from '../clob';\nimport {\n resolveExchangeAddress,\n resolveFeeRateBps,\n resolveRoundingConfig,\n} from './context';\nimport {\n decimalPlaces,\n parseAmount,\n roundDown,\n roundNormal,\n roundUp,\n} from './math';\nimport type { OrderDraft, PrepareLimitOrderRequest } from './types';\n\nexport const PrepareLimitOrderParamsSchema = z\n .strictObject({\n tokenId: TokenIdSchema,\n price: z.number().positive(),\n size: z.number().positive(),\n side: OrderSideSchema,\n taker: EvmAddressSchema.optional(),\n postOnly: z.boolean().default(false),\n expiration: z.number().int().nonnegative().optional(),\n })\n .superRefine((params, context) => {\n if (params.expiration !== undefined) {\n const minimumExpiration = Math.floor(Date.now() / 1000) + 60;\n\n if (params.expiration <= minimumExpiration) {\n context.addIssue({\n code: 'custom',\n message: 'Expiration must be at least 60 seconds in the future.',\n path: ['expiration'],\n });\n }\n }\n }) satisfies z.ZodType<PrepareLimitOrderRequest>;\n\nexport type PrepareLimitOrderDraftParams = z.output<\n typeof PrepareLimitOrderParamsSchema\n>;\n\ntype ResolveLimitOrderContextParams = {\n price: number;\n tokenId: string;\n};\n\nexport async function prepareLimitOrderDraft(\n client: BaseSecureClient,\n params: PrepareLimitOrderDraftParams,\n): Promise<OrderDraft> {\n const context = await resolveLimitOrderContext(client, {\n price: params.price,\n tokenId: params.tokenId,\n });\n const amounts = computeLimitOrderAmounts({\n price: context.price,\n side: params.side,\n size: params.size,\n tickSize: context.tickSize,\n });\n\n return {\n chainId: client.environment.chainId,\n exchangeAddress: context.exchangeAddress,\n expiration: params.expiration ?? 0,\n feeRateBps: context.feeRateBps,\n funderAddress: context.funderAddress,\n offeredAmount: amounts.offeredAmount,\n orderType: params.expiration === undefined ? OrderType.GTC : OrderType.GTD,\n side: params.side,\n signer: context.signerAddress,\n allowedTaker: params.taker,\n requestedAmount: amounts.requestedAmount,\n tokenId: params.tokenId,\n };\n}\n\ntype LimitOrderContext = {\n exchangeAddress: EvmAddress;\n feeRateBps: number;\n funderAddress: EvmAddress;\n negRisk: boolean;\n price: number;\n signerAddress: EvmAddress;\n tickSize: TickSizeValue;\n};\n\nasync function resolveLimitOrderContext(\n client: BaseSecureClient,\n params: ResolveLimitOrderContextParams,\n): Promise<LimitOrderContext> {\n const account = client.account;\n const tickSize = await fetchTickSize(client, {\n tokenId: params.tokenId,\n });\n const feeRateBps = await resolveFeeRateBps(client, params.tokenId);\n const negRisk = await fetchNegRisk(client, {\n tokenId: params.tokenId,\n });\n\n return {\n exchangeAddress: resolveExchangeAddress(client, negRisk),\n feeRateBps,\n funderAddress: account.wallet,\n negRisk,\n price: resolvePrice(params.price, tickSize),\n signerAddress: account.signer,\n tickSize,\n };\n}\n\nfunction computeLimitOrderAmounts(params: {\n price: number;\n side: OrderSide;\n size: number;\n tickSize: TickSizeValue;\n}): {\n offeredAmount: bigint;\n requestedAmount: bigint;\n} {\n const roundConfig = resolveRoundingConfig(params.tickSize);\n const rawPrice = roundNormal(params.price, roundConfig.price);\n\n if (params.side === OrderSide.BUY) {\n const rawTakerAmount = roundDown(params.size, roundConfig.size);\n let rawMakerAmount = rawTakerAmount * rawPrice;\n\n if (decimalPlaces(rawMakerAmount) > roundConfig.amount) {\n rawMakerAmount = roundUp(rawMakerAmount, roundConfig.amount + 4);\n\n if (decimalPlaces(rawMakerAmount) > roundConfig.amount) {\n rawMakerAmount = roundDown(rawMakerAmount, roundConfig.amount);\n }\n }\n\n return {\n offeredAmount: parseAmount(rawMakerAmount),\n requestedAmount: parseAmount(rawTakerAmount),\n };\n }\n\n const rawMakerAmount = roundDown(params.size, roundConfig.size);\n let rawTakerAmount = rawMakerAmount * rawPrice;\n\n if (decimalPlaces(rawTakerAmount) > roundConfig.amount) {\n rawTakerAmount = roundUp(rawTakerAmount, roundConfig.amount + 4);\n\n if (decimalPlaces(rawTakerAmount) > roundConfig.amount) {\n rawTakerAmount = roundDown(rawTakerAmount, roundConfig.amount);\n }\n }\n\n return {\n offeredAmount: parseAmount(rawMakerAmount),\n requestedAmount: parseAmount(rawTakerAmount),\n };\n}\n\nfunction resolvePrice(price: number, tickSize: TickSizeValue): number {\n const roundConfig = resolveRoundingConfig(tickSize);\n\n if (price < tickSize || price > 1 - tickSize) {\n throw new UserInputError(\n `Price must be between ${tickSize} and ${1 - tickSize} for tick size ${tickSize}.`,\n );\n }\n\n if (decimalPlaces(price) > roundConfig.price) {\n throw new UserInputError(\n `Price must conform to tick size ${tickSize} with at most ${roundConfig.price} decimal places.`,\n );\n }\n\n return roundNormal(price, roundConfig.price);\n}\n","import {\n EvmAddressSchema,\n type TickSizeValue,\n TokenIdSchema,\n} from '@polymarket/bindings';\nimport {\n OrderSide,\n OrderSideSchema,\n OrderType,\n} from '@polymarket/bindings/clob';\nimport type { EvmAddress } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseSecureClient } from '../../clients';\nimport { fetchNegRisk, fetchTickSize } from '../clob';\nimport {\n resolveExchangeAddress,\n resolveFeeRateBps,\n resolveRoundingConfig,\n} from './context';\nimport { resolveEstimatedMarketPrice } from './estimate';\nimport { decimalPlaces, parseAmount, roundDown, roundUp } from './math';\nimport type { OrderDraft, PrepareMarketOrderRequest } from './types';\n\nexport const PrepareMarketOrderParamsSchema = z.object({\n tokenId: TokenIdSchema,\n amount: z.number().positive(),\n side: OrderSideSchema,\n taker: EvmAddressSchema.optional(),\n orderType: z\n .union([z.literal(OrderType.FAK), z.literal(OrderType.FOK)])\n .default(OrderType.FAK),\n}) satisfies z.ZodType<PrepareMarketOrderRequest>;\n\nexport type PrepareMarketOrderDraftParams = z.output<\n typeof PrepareMarketOrderParamsSchema\n>;\n\nexport async function prepareMarketOrderDraft(\n client: BaseSecureClient,\n params: PrepareMarketOrderDraftParams,\n): Promise<OrderDraft> {\n const context = await resolveMarketOrderContext(client, params);\n const amounts = computeMarketOrderAmounts({\n amount: params.amount,\n price: context.price,\n side: params.side,\n tickSize: context.tickSize,\n });\n\n return {\n chainId: client.environment.chainId,\n exchangeAddress: context.exchangeAddress,\n expiration: 0,\n feeRateBps: context.feeRateBps,\n funderAddress: context.funderAddress,\n offeredAmount: amounts.offeredAmount,\n orderType: params.orderType,\n side: params.side,\n signer: context.signerAddress,\n allowedTaker: params.taker,\n requestedAmount: amounts.requestedAmount,\n tokenId: params.tokenId,\n };\n}\n\ntype ResolveMarketOrderContextParams = {\n amount: number;\n orderType: OrderType;\n side: OrderSide;\n tokenId: string;\n};\n\ntype MarketOrderContext = {\n exchangeAddress: EvmAddress;\n feeRateBps: number;\n funderAddress: EvmAddress;\n negRisk: boolean;\n price: number;\n signerAddress: EvmAddress;\n tickSize: TickSizeValue;\n};\n\nasync function resolveMarketOrderContext(\n client: BaseSecureClient,\n params: ResolveMarketOrderContextParams,\n): Promise<MarketOrderContext> {\n const account = client.account;\n const tickSize = await fetchTickSize(client, {\n tokenId: params.tokenId,\n });\n const feeRateBps = await resolveFeeRateBps(client, params.tokenId);\n const price = await resolveEstimatedMarketPrice(client, {\n amount: params.amount,\n orderType: params.orderType,\n side: params.side,\n tickSize,\n tokenId: params.tokenId,\n });\n const negRisk = await fetchNegRisk(client, {\n tokenId: params.tokenId,\n });\n\n return {\n exchangeAddress: resolveExchangeAddress(client, negRisk),\n feeRateBps,\n funderAddress: account.wallet,\n negRisk,\n price,\n signerAddress: account.signer,\n tickSize,\n };\n}\n\nfunction computeMarketOrderAmounts(params: {\n amount: number;\n price: number;\n side: OrderSide;\n tickSize: TickSizeValue;\n}): {\n offeredAmount: bigint;\n requestedAmount: bigint;\n} {\n const roundConfig = resolveRoundingConfig(params.tickSize);\n const rawPrice = roundDown(params.price, roundConfig.price);\n const rawMakerAmount = roundDown(params.amount, roundConfig.size);\n\n if (params.side === OrderSide.BUY) {\n let rawTakerAmount = rawMakerAmount / rawPrice;\n\n if (decimalPlaces(rawTakerAmount) > roundConfig.amount) {\n rawTakerAmount = roundUp(rawTakerAmount, roundConfig.amount + 4);\n\n if (decimalPlaces(rawTakerAmount) > roundConfig.amount) {\n rawTakerAmount = roundDown(rawTakerAmount, roundConfig.amount);\n }\n }\n\n return {\n offeredAmount: parseAmount(rawMakerAmount),\n requestedAmount: parseAmount(rawTakerAmount),\n };\n }\n\n let rawTakerAmount = rawMakerAmount * rawPrice;\n\n if (decimalPlaces(rawTakerAmount) > roundConfig.amount) {\n rawTakerAmount = roundUp(rawTakerAmount, roundConfig.amount + 4);\n\n if (decimalPlaces(rawTakerAmount) > roundConfig.amount) {\n rawTakerAmount = roundDown(rawTakerAmount, roundConfig.amount);\n }\n }\n\n return {\n offeredAmount: parseAmount(rawMakerAmount),\n requestedAmount: parseAmount(rawTakerAmount),\n };\n}\n","import { ZERO_ADDRESS } from '@polymarket/types';\nimport type { AccountIdentity } from '../../account';\nimport { toSignatureType } from '../../account';\nimport type { OrderDraft, SignedOrder, UnsignedOrder } from './types';\n\nexport function createUnsignedOrder(\n order: OrderDraft,\n account: AccountIdentity,\n): UnsignedOrder {\n return {\n chainId: order.chainId,\n exchangeAddress: order.exchangeAddress,\n expiration: order.expiration,\n feeRateBps: order.feeRateBps,\n maker: order.funderAddress,\n makerAmount: order.offeredAmount.toString(),\n // CLOB v1 still requires a nonce on the order, even though it is expected to disappear in v2.\n nonce: 0,\n orderType: order.orderType,\n salt: generateOrderSalt().toString(),\n side: order.side,\n signatureType: toSignatureType(account.walletType),\n signer: order.signer,\n taker: order.allowedTaker ?? ZERO_ADDRESS,\n takerAmount: order.requestedAmount.toString(),\n tokenId: order.tokenId,\n };\n}\n\nexport function createSignedOrder(\n order: UnsignedOrder,\n signature: SignedOrder['signature'],\n): SignedOrder {\n const {\n chainId: _chainId,\n exchangeAddress: _exchangeAddress,\n ...signedFields\n } = order;\n\n return {\n ...signedFields,\n signature,\n };\n}\n\nfunction generateOrderSalt(): bigint {\n return BigInt(Math.round(Math.random() * Date.now()));\n}\n","import { OrderSide } from '@polymarket/bindings/clob';\nimport type { EvmAddress } from '@polymarket/types';\nimport type { TypedDataField, TypedDataPayload } from '../../types';\nimport type { UnsignedOrder } from './types';\n\nconst EIP712_DOMAIN: readonly TypedDataField[] = [\n { name: 'name', type: 'string' },\n { name: 'version', type: 'string' },\n { name: 'chainId', type: 'uint256' },\n { name: 'verifyingContract', type: 'address' },\n];\n\nconst ORDER_STRUCTURE: readonly TypedDataField[] = [\n { name: 'salt', type: 'uint256' },\n { name: 'maker', type: 'address' },\n { name: 'signer', type: 'address' },\n { name: 'taker', type: 'address' },\n { name: 'tokenId', type: 'uint256' },\n { name: 'makerAmount', type: 'uint256' },\n { name: 'takerAmount', type: 'uint256' },\n { name: 'expiration', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n { name: 'feeRateBps', type: 'uint256' },\n { name: 'side', type: 'uint8' },\n { name: 'signatureType', type: 'uint8' },\n];\n\nconst PROTOCOL_NAME = 'Polymarket CTF Exchange';\nconst PROTOCOL_VERSION = '1';\n\ntype OrderTypedDataMessage = {\n expiration: bigint;\n feeRateBps: bigint;\n maker: EvmAddress;\n makerAmount: bigint;\n nonce: bigint;\n salt: bigint;\n side: number;\n signatureType: UnsignedOrder['signatureType'];\n signer: EvmAddress;\n taker: EvmAddress;\n takerAmount: bigint;\n tokenId: bigint;\n};\n\nexport function createOrderTypedDataPayload(\n order: UnsignedOrder,\n): TypedDataPayload {\n return {\n domain: {\n chainId: order.chainId,\n name: PROTOCOL_NAME,\n verifyingContract: order.exchangeAddress,\n version: PROTOCOL_VERSION,\n },\n message: createOrderTypedDataMessage(order),\n primaryType: 'Order',\n types: {\n EIP712Domain: EIP712_DOMAIN,\n Order: ORDER_STRUCTURE,\n },\n };\n}\n\nfunction createOrderTypedDataMessage(\n order: UnsignedOrder,\n): OrderTypedDataMessage {\n return {\n expiration: BigInt(order.expiration),\n feeRateBps: BigInt(order.feeRateBps),\n maker: order.maker,\n makerAmount: BigInt(order.makerAmount),\n // CLOB v1 still signs nonce, even though it is expected to disappear in v2.\n nonce: BigInt(order.nonce),\n salt: BigInt(order.salt),\n side: encodeOrderSide(order.side),\n signatureType: order.signatureType,\n signer: order.signer,\n taker: order.taker,\n takerAmount: BigInt(order.takerAmount),\n tokenId: BigInt(order.tokenId),\n };\n}\n\nfunction encodeOrderSide(side: OrderSide): number {\n return side === OrderSide.BUY ? 0 : 1;\n}\n","import type { TokenId } from '@polymarket/bindings';\nimport type {\n OrderResponse,\n OrderSide,\n OrderType,\n SignatureType,\n} from '@polymarket/bindings/clob';\nimport type { EvmAddress, EvmSignature } from '@polymarket/types';\nimport type { TransactionHandle, TypedDataPayload } from '../../types';\nimport type { SignOrderRequest } from '../../workflow';\nimport type {\n Erc20ApprovalWorkflowRequest,\n Erc1155ApprovalForAllWorkflowRequest,\n} from '../approvals';\n\nexport type PrepareMarketOrderRequest = {\n /** TokenID of the Conditional token asset being traded */\n tokenId: string;\n\n /**\n * BUY orders: dollar amount to spend\n * SELL orders: number of shares to sell\n */\n amount: number;\n\n /** Side of the order */\n side: OrderSide;\n\n /** Taker address. Omit for public orders (zero address is equivalent). */\n taker?: string;\n\n /**\n * Specifies the type of order execution.\n * - FOK (Fill or Kill): must be filled entirely or not at all\n * - FAK (Fill and Kill): partially fills, cancels any unfilled remainder\n *\n * @defaultValue OrderType.FAK\n */\n orderType?: OrderType.FAK | OrderType.FOK;\n};\n\nexport type PrepareLimitOrderRequest = {\n /** TokenID of the Conditional token asset being traded */\n tokenId: string;\n\n /** Price used to create the order */\n price: number;\n\n /** Size in terms of the conditional token */\n size: number;\n\n /** Side of the order */\n side: OrderSide;\n\n /** Taker address. Omit for public orders (zero address is equivalent). */\n taker?: string;\n\n /**\n * Posts the prepared order as post-only when submitted.\n *\n * @defaultValue false\n */\n postOnly?: boolean;\n\n /**\n * Unix timestamp in seconds after which the order expires.\n *\n * When provided, the SDK prepares a Good-Til-Date (GTD) limit order that\n * expires at the given timestamp.\n *\n * When omitted, the SDK prepares a Good-Til-Cancelled (GTC) limit order.\n */\n expiration?: number;\n};\n\nexport type OrderDraft = {\n chainId: number;\n exchangeAddress: EvmAddress;\n expiration: number;\n feeRateBps: number;\n funderAddress: EvmAddress;\n offeredAmount: bigint;\n orderType: OrderType;\n side: OrderSide;\n signer: EvmAddress;\n allowedTaker?: EvmAddress;\n requestedAmount: bigint;\n tokenId: TokenId;\n};\n\n/**\n * @internal\n */\nexport type UnsignedOrder = {\n chainId: number;\n exchangeAddress: EvmAddress;\n expiration: number;\n feeRateBps: number;\n maker: EvmAddress;\n makerAmount: string;\n nonce: number;\n orderType: OrderType;\n salt: string;\n side: OrderSide;\n signatureType: SignatureType;\n signer: EvmAddress;\n taker: EvmAddress;\n takerAmount: string;\n tokenId: TokenId;\n};\n\nexport type SignedOrder = {\n expiration: number;\n feeRateBps: number;\n maker: EvmAddress;\n makerAmount: string;\n nonce: number;\n orderType: OrderType;\n salt: string;\n side: OrderSide;\n signatureType: SignatureType;\n signer: EvmAddress;\n taker: EvmAddress;\n takerAmount: string;\n tokenId: TokenId;\n signature: EvmSignature;\n postOnly?: boolean;\n};\n\nexport type OrderWorkflowRequest =\n | Erc20ApprovalWorkflowRequest\n | Erc1155ApprovalForAllWorkflowRequest\n | SignOrderRequest;\n\nexport type OrderWorkflow = AsyncGenerator<\n OrderWorkflowRequest,\n SignedOrder,\n EvmAddress | EvmSignature | TransactionHandle\n>;\n\nexport type OrderPostingWorkflow = AsyncGenerator<\n OrderWorkflowRequest,\n OrderResponse,\n EvmAddress | EvmSignature | TransactionHandle\n>;\n\n/** @internal */\nexport function signOrder(payload: TypedDataPayload): SignOrderRequest {\n return {\n kind: 'signOrder',\n payload,\n };\n}\n","import { AssetType, OrderSide } from '@polymarket/bindings/clob';\nimport {\n type EvmAddress,\n type EvmSignature,\n expectEvmSignature,\n} from '@polymarket/types';\nimport type { BaseSecureClient } from '../../clients';\nimport type {\n InsufficientLiquidityError,\n RateLimitError,\n RequestRejectedError,\n SigningError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../../errors';\nimport { parseUserInput } from '../../input';\nimport type { TransactionHandle } from '../../types';\nimport { updateBalanceAllowance } from '../account';\nimport {\n type Erc20ApprovalWorkflowRequest,\n type Erc1155ApprovalForAllWorkflowRequest,\n prepareErc20Approval,\n prepareErc1155ApprovalForAll,\n} from '../approvals';\nimport { resolveCurrentAllowance } from './allowance';\nimport { PrepareLimitOrderParamsSchema, prepareLimitOrderDraft } from './limit';\nimport {\n PrepareMarketOrderParamsSchema,\n prepareMarketOrderDraft,\n} from './market';\nimport { createSignedOrder, createUnsignedOrder } from './orders';\nimport { postOrder } from './post';\nimport { createOrderTypedDataPayload } from './typed-data';\nimport {\n type OrderDraft,\n type OrderPostingWorkflow,\n type OrderWorkflow,\n type PrepareLimitOrderRequest,\n type PrepareMarketOrderRequest,\n signOrder,\n} from './types';\n\nexport type PrepareMarketOrderError =\n | InsufficientLiquidityError\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Starts the market-order workflow.\n *\n * @throws {@link PrepareMarketOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await prepareMarketOrder(client, {\n * amount: 10,\n * side: OrderSide.BUY,\n * tokenId: '123',\n * })\n * .then(completeWith(wallet))\n * .then(postOrder(client));\n *\n * // response: OrderResponse\n * ```\n */\nexport async function prepareMarketOrder(\n client: BaseSecureClient,\n request: PrepareMarketOrderRequest,\n): Promise<OrderWorkflow> {\n const params = parseUserInput(request, PrepareMarketOrderParamsSchema);\n\n return async function* (): OrderWorkflow {\n const draft = await prepareMarketOrderDraft(client, params);\n\n yield* ensureOrderApproval(client, draft);\n\n const unsignedOrder = createUnsignedOrder(draft, client.account);\n\n const signature = expectEvmSignature(\n yield signOrder(createOrderTypedDataPayload(unsignedOrder)),\n );\n\n return createSignedOrder(unsignedOrder, signature);\n }.call(null);\n}\n\nexport type PrepareLimitOrderError =\n | RateLimitError\n | RequestRejectedError\n | SigningError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Starts the limit-order workflow.\n *\n * @throws {@link PrepareLimitOrderError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const order = await prepareLimitOrder(client, {\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * tokenId: '123',\n * }).then(completeWith(wallet))\n * .then(postOrder(client));\n *\n * // response: OrderResponse\n * ```\n */\nexport async function prepareLimitOrder(\n client: BaseSecureClient,\n request: PrepareLimitOrderRequest,\n): Promise<OrderWorkflow> {\n const params = parseUserInput(request, PrepareLimitOrderParamsSchema);\n\n return async function* (): OrderWorkflow {\n const draft = await prepareLimitOrderDraft(client, params);\n\n yield* ensureOrderApproval(client, draft);\n\n const unsignedOrder = createUnsignedOrder(draft, client.account);\n\n const signature = expectEvmSignature(\n yield signOrder(createOrderTypedDataPayload(unsignedOrder)),\n );\n\n const order = createSignedOrder(unsignedOrder, signature);\n\n return params.postOnly === true ? { ...order, postOnly: true } : order;\n }.call(null);\n}\n\nexport type PrepareMarketOrderPostingError = PrepareMarketOrderError;\n\n/**\n * Starts and posts a market-order workflow.\n *\n * @throws {@link PrepareMarketOrderPostingError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await prepareMarketOrderPosting(client, {\n * amount: 10,\n * side: OrderSide.BUY,\n * tokenId: '123',\n * }).then(completeWith(wallet));\n *\n * // response: OrderResponse\n * ```\n */\nexport async function prepareMarketOrderPosting(\n client: BaseSecureClient,\n request: PrepareMarketOrderRequest,\n): Promise<OrderPostingWorkflow> {\n return createOrderPostingWorkflow(\n client,\n prepareMarketOrder(client, request),\n );\n}\n\nexport type PrepareLimitOrderPostingError = PrepareLimitOrderError;\n\n/**\n * Starts and posts a limit-order workflow.\n *\n * @throws {@link PrepareLimitOrderPostingError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const response = await prepareLimitOrderPosting(client, {\n * postOnly: true,\n * price: 0.52,\n * side: OrderSide.BUY,\n * size: 10,\n * tokenId: '123',\n * }).then(completeWith(wallet));\n *\n * // response: OrderResponse\n * ```\n */\nexport async function prepareLimitOrderPosting(\n client: BaseSecureClient,\n request: PrepareLimitOrderRequest,\n): Promise<OrderPostingWorkflow> {\n return createOrderPostingWorkflow(client, prepareLimitOrder(client, request));\n}\n\nasync function createOrderPostingWorkflow(\n client: BaseSecureClient,\n workflowPromise: Promise<OrderWorkflow>,\n): Promise<OrderPostingWorkflow> {\n const workflow = await workflowPromise;\n\n return async function* (): OrderPostingWorkflow {\n const order = yield* workflow;\n\n return postOrder(client)(order);\n }.call(null);\n}\n\nasync function* ensureOrderApproval(\n client: BaseSecureClient,\n draft: OrderDraft,\n): AsyncGenerator<\n Erc20ApprovalWorkflowRequest | Erc1155ApprovalForAllWorkflowRequest,\n void,\n EvmAddress | EvmSignature | TransactionHandle\n> {\n const currentAllowance = await resolveCurrentAllowance(client, {\n spenderAddress: draft.exchangeAddress,\n side: draft.side,\n tokenId: draft.tokenId,\n });\n\n if (currentAllowance >= draft.offeredAmount) {\n return;\n }\n\n const handle =\n draft.side === OrderSide.BUY\n ? yield* await prepareErc20Approval(client, {\n amount: 'max',\n spenderAddress: draft.exchangeAddress,\n tokenAddress: client.environment.collateralToken,\n })\n : yield* await prepareErc1155ApprovalForAll(client, {\n operatorAddress: draft.exchangeAddress,\n tokenAddress: client.environment.conditionalTokens,\n });\n\n await handle.wait();\n\n await updateBalanceAllowance(client, {\n assetType:\n draft.side === OrderSide.BUY\n ? AssetType.COLLATERAL\n : AssetType.CONDITIONAL,\n tokenId: draft.side === OrderSide.SELL ? draft.tokenId : undefined,\n });\n}\n","import { PaginationCursorSchema } from '@polymarket/bindings';\nimport {\n type ClosedPosition,\n FetchPortfolioValueResponseSchema,\n ListClosedPositionsResponseSchema,\n ListPositionsResponseSchema,\n type Position,\n type Traded,\n TradedSchema,\n type Value,\n} from '@polymarket/bindings/data';\nimport { unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport {\n decodeOffsetCursor,\n encodeOffsetCursor,\n PageSizeSchema,\n type Paginated,\n paginate,\n} from '../pagination';\nimport { readBlob, validateWith } from '../response';\nimport { toDataSearchParams } from './params';\n\nconst PositionSortBySchema = z.enum([\n 'CURRENT',\n 'INITIAL',\n 'TOKENS',\n 'CASHPNL',\n 'PERCENTPNL',\n 'TITLE',\n 'RESOLVING',\n 'PRICE',\n 'AVGPRICE',\n]);\n\nconst PositionSortDirectionSchema = z.enum(['ASC', 'DESC']);\n\nconst ClosedPositionSortBySchema = z.enum([\n 'REALIZEDPNL',\n 'TITLE',\n 'PRICE',\n 'AVGPRICE',\n 'TIMESTAMP',\n]);\n\nconst ListPositionsRequestSchema = z\n .object({\n cursor: PaginationCursorSchema.optional(),\n user: z.string(),\n market: z.array(z.string()).optional(),\n eventId: z.array(z.number().int()).optional(),\n sizeThreshold: z.number().optional(),\n redeemable: z.boolean().optional(),\n mergeable: z.boolean().optional(),\n pageSize: PageSizeSchema.default(20),\n sortBy: PositionSortBySchema.optional(),\n sortDirection: PositionSortDirectionSchema.optional(),\n title: z.string().max(100).optional(),\n })\n .refine((value) => !(value.market && value.eventId), {\n message: 'Provide market or eventId, not both',\n path: ['eventId'],\n });\n\nconst ListClosedPositionsRequestSchema = z\n .object({\n cursor: PaginationCursorSchema.optional(),\n user: z.string(),\n market: z.array(z.string()).optional(),\n title: z.string().max(100).optional(),\n eventId: z.array(z.number().int()).optional(),\n pageSize: PageSizeSchema.default(20),\n sortBy: ClosedPositionSortBySchema.optional(),\n sortDirection: PositionSortDirectionSchema.optional(),\n })\n .refine((value) => !(value.market && value.eventId), {\n message: 'Provide market or eventId, not both',\n path: ['eventId'],\n });\n\nconst FetchPortfolioValueRequestSchema = z.object({\n user: z.string(),\n market: z.array(z.string()).optional(),\n});\n\nconst FetchTradedMarketCountRequestSchema = z.object({\n user: z.string(),\n});\n\nconst DownloadAccountingSnapshotRequestSchema = z.object({\n user: z.string(),\n});\n\nexport type ListPositionsRequest = z.input<typeof ListPositionsRequestSchema>;\nexport type ListClosedPositionsRequest = z.input<\n typeof ListClosedPositionsRequestSchema\n>;\nexport type FetchPortfolioValueRequest = z.input<\n typeof FetchPortfolioValueRequestSchema\n>;\nexport type FetchTradedMarketCountRequest = z.input<\n typeof FetchTradedMarketCountRequestSchema\n>;\nexport type DownloadAccountingSnapshotRequest = z.input<\n typeof DownloadAccountingSnapshotRequestSchema\n>;\n\nexport type ListPositionsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists current positions for a wallet.\n *\n * @throws {@link ListPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listPositions(client, {\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: Position[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listPositions(client, {\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * for await (const page of result) {\n * // page.items: Position[]\n * }\n * ```\n */\nexport function listPositions(\n client: BaseClient,\n request: ListPositionsRequest,\n): Paginated<Position> {\n const { cursor, pageSize, ...params } = parseUserInput(\n request,\n ListPositionsRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.data\n .get('/positions', {\n params: toDataSearchParams({\n ...params,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n }),\n })\n .andThen(validateWith(ListPositionsResponseSchema))\n .map((positions) => {\n const hasMore = positions.length > decoded.pageSize;\n\n return {\n items: positions.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n\nexport type ListClosedPositionsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists closed positions for a wallet.\n *\n * @throws {@link ListClosedPositionsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listClosedPositions(client, {\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: ClosedPosition[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listClosedPositions(client, {\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * pageSize: 10,\n * });\n *\n * for await (const page of result) {\n * // page.items: ClosedPosition[]\n * }\n * ```\n */\nexport function listClosedPositions(\n client: BaseClient,\n request: ListClosedPositionsRequest,\n): Paginated<ClosedPosition> {\n const { cursor, pageSize, ...params } = parseUserInput(\n request,\n ListClosedPositionsRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.data\n .get('/closed-positions', {\n params: toDataSearchParams({\n ...params,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n }),\n })\n .andThen(validateWith(ListClosedPositionsResponseSchema))\n .map((positions) => {\n const hasMore = positions.length > decoded.pageSize;\n\n return {\n items: positions.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n\nexport type FetchPortfolioValueError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches the total value for a wallet's positions.\n *\n * @throws {@link FetchPortfolioValueError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const value = await fetchPortfolioValue(client, {\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * });\n *\n * // value: Value[]\n * ```\n */\nexport async function fetchPortfolioValue(\n client: BaseClient,\n request: FetchPortfolioValueRequest,\n): Promise<Value[]> {\n const params = parseUserInput(request, FetchPortfolioValueRequestSchema);\n\n return unwrap(\n client.data\n .get('/value', {\n params: toDataSearchParams(params),\n })\n .andThen(validateWith(FetchPortfolioValueResponseSchema)),\n );\n}\n\nexport type FetchTradedMarketCountError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches the total number of markets a wallet has traded.\n *\n * @throws {@link FetchTradedMarketCountError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const traded = await fetchTradedMarketCount(client, {\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * });\n *\n * // traded === Traded\n * ```\n */\nexport async function fetchTradedMarketCount(\n client: BaseClient,\n request: FetchTradedMarketCountRequest,\n): Promise<Traded> {\n const params = parseUserInput(request, FetchTradedMarketCountRequestSchema);\n\n return unwrap(\n client.data\n .get('/traded', {\n params: toDataSearchParams(params),\n })\n .andThen(validateWith(TradedSchema)),\n );\n}\n\nexport type DownloadAccountingSnapshotError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Downloads an accounting snapshot archive for a wallet.\n *\n * @throws {@link DownloadAccountingSnapshotError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const snapshot = await downloadAccountingSnapshot(client, {\n * user: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * });\n *\n * // snapshot === Blob\n * ```\n */\nexport async function downloadAccountingSnapshot(\n client: BaseClient,\n request: DownloadAccountingSnapshotRequest,\n): Promise<Blob> {\n const params = parseUserInput(\n request,\n DownloadAccountingSnapshotRequestSchema,\n );\n\n return unwrap(\n client.data\n .get('/v1/accounting/snapshot', {\n params: toDataSearchParams(params),\n })\n .andThen(readBlob),\n );\n}\n","import type { ConditionId } from '@polymarket/bindings';\nimport { ConditionIdSchema } from '@polymarket/bindings';\nimport type { Position } from '@polymarket/bindings/data';\nimport { WalletType } from '@polymarket/bindings/gamma';\nimport {\n type EvmAddress,\n type EvmSignature,\n invariant,\n isNullish,\n isPresent,\n} from '@polymarket/types';\nimport { z } from 'zod';\nimport {\n ctfRedeemPositionsCall,\n mergePositionsCall,\n negRiskRedeemPositionsCall,\n splitPositionCall,\n} from '../abis';\nimport type { BaseSecureClient } from '../clients';\nimport {\n type RateLimitError,\n type RequestRejectedError,\n type TransportError,\n type UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport { expectTransactionHandle, type TransactionHandle } from '../types';\nimport type { SignerTransactionRequest } from '../workflow';\nimport {\n type SendMergePositionsTransactionRequest,\n type SendRedeemPositionsTransactionRequest,\n type SendSplitPositionTransactionRequest,\n signerTransactionRequest,\n} from '../workflow';\nimport {\n GaslessTransactionMetadataSchema,\n type GaslessWorkflowRequest,\n prepareGaslessTransaction,\n} from './gasless';\nimport { listMarkets } from './markets';\nimport { listPositions } from './portfolio';\n\ntype BinaryPositions = readonly [\n yes: Position | undefined,\n no: Position | undefined,\n];\n\ntype PositiveAmount = bigint;\n\nconst PrepareSplitPositionRequestSchema = z.object({\n amount: z.bigint().min(0n),\n conditionId: ConditionIdSchema,\n metadata: GaslessTransactionMetadataSchema.optional(),\n});\n\nconst PrepareMergePositionsRequestSchema = z.object({\n amount: z.union([z.bigint().positive(), z.literal('max')]),\n conditionId: ConditionIdSchema,\n metadata: GaslessTransactionMetadataSchema.optional(),\n});\n\nconst PrepareRedeemPositionsRequestSchema = z.object({\n conditionId: ConditionIdSchema,\n metadata: GaslessTransactionMetadataSchema.optional(),\n});\n\nexport type SplitPositionWorkflowRequest =\n | GaslessWorkflowRequest\n | SendSplitPositionTransactionRequest;\n\nexport type MergePositionsWorkflowRequest =\n | GaslessWorkflowRequest\n | SendMergePositionsTransactionRequest;\n\nexport type RedeemPositionsWorkflowRequest =\n | GaslessWorkflowRequest\n | SendRedeemPositionsTransactionRequest;\n\nexport type SplitPositionWorkflow = AsyncGenerator<\n SplitPositionWorkflowRequest,\n TransactionHandle,\n EvmAddress | EvmSignature | TransactionHandle\n>;\n\nexport type MergePositionsWorkflow = AsyncGenerator<\n MergePositionsWorkflowRequest,\n TransactionHandle,\n EvmAddress | EvmSignature | TransactionHandle\n>;\n\nexport type RedeemPositionsWorkflow = AsyncGenerator<\n RedeemPositionsWorkflowRequest,\n TransactionHandle,\n EvmAddress | EvmSignature | TransactionHandle\n>;\n\nexport type PrepareSplitPositionRequest = z.input<\n typeof PrepareSplitPositionRequestSchema\n>;\n\nexport type PrepareMergePositionsRequest = z.input<\n typeof PrepareMergePositionsRequestSchema\n>;\n\nexport type PrepareRedeemPositionsRequest = z.input<\n typeof PrepareRedeemPositionsRequestSchema\n>;\n\nexport type PrepareSplitPositionError = UserInputError;\nexport type PrepareMergePositionsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\nexport type PrepareRedeemPositionsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Starts a split workflow for a market condition.\n *\n * @example\n * ```ts\n * const handle = await prepareSplitPosition(client, {\n * amount: 1n,\n * conditionId:\n * '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',\n * }).then(completeWith(wallet));\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @throws {@link PrepareSplitPositionError}\n * Thrown on failure.\n */\nexport async function prepareSplitPosition(\n client: BaseSecureClient,\n request: PrepareSplitPositionRequest,\n): Promise<SplitPositionWorkflow> {\n const params = parseUserInput(request, PrepareSplitPositionRequestSchema);\n const negativeRisk = await resolveMarketNegativeRiskFlag(\n client,\n params.conditionId,\n );\n const call = splitPositionCall(\n resolveSplitTargetAddress(client, negativeRisk),\n client.environment.collateralToken,\n params.conditionId,\n params.amount,\n negativeRisk,\n );\n\n return async function* (): SplitPositionWorkflow {\n if (client.account.walletType === WalletType.EOA) {\n return expectTransactionHandle(\n yield sendSplitPositionTransaction(\n signerTransactionRequest(client.environment.chainId, call),\n ),\n );\n }\n\n return yield* await prepareGaslessTransaction(client, {\n calls: [call],\n metadata:\n params.metadata ??\n `Split ${params.amount} positions for condition ${params.conditionId}`,\n });\n }.call(null);\n}\n\n/**\n * Starts a workflow to merge complementary positions in a market back into collateral.\n *\n * @example\n * ```ts\n * const handle = await prepareMergePositions(client, {\n * amount: 'max',\n * conditionId:\n * '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',\n * }).then(completeWith(wallet));\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @throws {@link PrepareMergePositionsError}\n * Thrown on failure.\n */\nexport async function prepareMergePositions(\n client: BaseSecureClient,\n request: PrepareMergePositionsRequest,\n): Promise<MergePositionsWorkflow> {\n const params = parseUserInput(request, PrepareMergePositionsRequestSchema);\n const positions = await listPositions(client, {\n user: client.account.wallet,\n market: [params.conditionId],\n sizeThreshold: 0,\n })\n .firstPage()\n .then((page) => page.items);\n const binaryPositions = expectBinaryPositions(params.conditionId, positions);\n const negativeRisk = expectNegativeRiskFlag(\n params.conditionId,\n binaryPositions,\n );\n const amount = resolveMergeAmount(\n params.conditionId,\n binaryPositions,\n params.amount,\n );\n const call = mergePositionsCall(\n resolveMergeTargetAddress(client, negativeRisk),\n client.environment.collateralToken,\n params.conditionId,\n amount,\n negativeRisk,\n );\n\n return async function* (): MergePositionsWorkflow {\n if (client.account.walletType === WalletType.EOA) {\n return expectTransactionHandle(\n yield sendMergePositionsTransaction(\n signerTransactionRequest(client.environment.chainId, call),\n ),\n );\n }\n\n return yield* await prepareGaslessTransaction(client, {\n calls: [call],\n metadata:\n params.metadata ??\n `Merge ${amount} positions for condition ${params.conditionId}`,\n });\n }.call(null);\n}\n\n/**\n * Starts a redemption workflow for resolved positions.\n *\n * @example\n * ```ts\n * const handle = await prepareRedeemPositions(client, {\n * conditionId:\n * '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',\n * }).then(completeWith(wallet));\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @throws {@link PrepareRedeemPositionsError}\n * Thrown on failure.\n */\nexport async function prepareRedeemPositions(\n client: BaseSecureClient,\n request: PrepareRedeemPositionsRequest,\n): Promise<RedeemPositionsWorkflow> {\n const params = parseUserInput(request, PrepareRedeemPositionsRequestSchema);\n const positions = await listPositions(client, {\n user: client.account.wallet,\n market: [params.conditionId],\n sizeThreshold: 0,\n })\n .firstPage()\n .then((page) => page.items);\n const binaryPositions = expectBinaryPositions(params.conditionId, positions);\n const negativeRisk = expectNegativeRiskFlag(\n params.conditionId,\n binaryPositions,\n );\n const call = negativeRisk\n ? negRiskRedeemPositionsCall(\n client.environment.negRiskAdapter,\n params.conditionId,\n deriveNegRiskRedeemAmounts(binaryPositions),\n )\n : ctfRedeemPositionsCall(\n client.environment.conditionalTokens,\n client.environment.collateralToken,\n params.conditionId,\n );\n\n return async function* (): RedeemPositionsWorkflow {\n if (client.account.walletType === WalletType.EOA) {\n return expectTransactionHandle(\n yield sendRedeemPositionsTransaction(\n signerTransactionRequest(client.environment.chainId, call),\n ),\n );\n }\n\n return yield* await prepareGaslessTransaction(client, {\n calls: [call],\n metadata:\n params.metadata ??\n `Redeem positions for condition ${params.conditionId}`,\n });\n }.call(null);\n}\n\nfunction sendSplitPositionTransaction(\n request: SignerTransactionRequest,\n): SendSplitPositionTransactionRequest {\n return {\n kind: 'sendSplitPositionTransaction',\n request,\n };\n}\n\nfunction sendMergePositionsTransaction(\n request: SignerTransactionRequest,\n): SendMergePositionsTransactionRequest {\n return {\n kind: 'sendMergePositionsTransaction',\n request,\n };\n}\n\nfunction sendRedeemPositionsTransaction(\n request: SignerTransactionRequest,\n): SendRedeemPositionsTransactionRequest {\n return {\n kind: 'sendRedeemPositionsTransaction',\n request,\n };\n}\n\nfunction resolveSplitTargetAddress(client: BaseSecureClient, negRisk: boolean) {\n return negRisk\n ? client.environment.negRiskAdapter\n : client.environment.conditionalTokens;\n}\n\nasync function resolveMarketNegativeRiskFlag(\n client: BaseSecureClient,\n conditionId: ConditionId,\n): Promise<boolean> {\n const page = await listMarkets(client, {\n conditionIds: [conditionId],\n pageSize: 2,\n }).firstPage();\n const markets = page.items;\n\n invariant(\n markets.length === 1,\n `Expected exactly one market for condition ${conditionId}`,\n );\n\n const market = markets[0];\n\n invariant(\n market !== undefined,\n `No market found for condition ${conditionId}`,\n );\n invariant(\n isPresent(market.negRisk),\n `Missing negRisk flag for condition ${conditionId}`,\n );\n\n return market.negRisk;\n}\n\nfunction resolveMergeTargetAddress(client: BaseSecureClient, negRisk: boolean) {\n return negRisk\n ? client.environment.negRiskAdapter\n : client.environment.conditionalTokens;\n}\n\nfunction deriveNegRiskRedeemAmounts([\n yesPosition,\n noPosition,\n]: BinaryPositions): readonly [bigint, bigint] {\n return [toPositionAmount(yesPosition, 0), toPositionAmount(noPosition, 1)];\n}\n\nfunction expectNegativeRiskFlag(\n conditionId: ConditionId,\n [yesPosition, noPosition]: BinaryPositions,\n): boolean {\n const first = yesPosition ?? noPosition;\n\n invariant(\n first !== undefined,\n `You have no positions for condition ${conditionId}`,\n );\n invariant(\n isPresent(first.negativeRisk),\n `Missing negativeRisk flag for condition ${conditionId}`,\n );\n\n if (yesPosition !== undefined && noPosition !== undefined) {\n invariant(\n isPresent(yesPosition.negativeRisk),\n `Missing negativeRisk flag for condition ${conditionId}`,\n );\n invariant(\n isPresent(noPosition.negativeRisk),\n `Missing negativeRisk flag for condition ${conditionId}`,\n );\n invariant(\n yesPosition.negativeRisk === noPosition.negativeRisk,\n `Mixed negativeRisk flags for condition ${conditionId}`,\n );\n }\n\n return first.negativeRisk;\n}\n\nfunction expectBinaryPositions(\n conditionId: ConditionId,\n positions: readonly Position[],\n): BinaryPositions {\n if (positions.length === 0) {\n throw new UserInputError(\n `You have no positions for condition ${conditionId}`,\n );\n }\n\n invariant(\n positions.length <= 2,\n `Expected at most two positions for condition ${conditionId}`,\n );\n\n let yesPosition: Position | undefined;\n let noPosition: Position | undefined;\n\n for (const position of positions) {\n invariant(\n position.outcomeIndex === 0 || position.outcomeIndex === 1,\n `Unexpected outcomeIndex ${position.outcomeIndex} for condition ${conditionId}`,\n );\n\n if (position.outcomeIndex === 0) {\n invariant(\n yesPosition === undefined,\n `Duplicate YES position for condition ${conditionId}`,\n );\n yesPosition = position;\n continue;\n }\n\n invariant(\n noPosition === undefined,\n `Duplicate NO position for condition ${conditionId}`,\n );\n noPosition = position;\n }\n\n return [yesPosition, noPosition];\n}\n\nfunction resolveMergeAmount(\n conditionId: ConditionId,\n positions: BinaryPositions,\n requestedAmount: bigint | 'max',\n): PositiveAmount {\n const maxAmount = calculateMaxMergeAmount(positions);\n\n if (maxAmount === 0n) {\n throw new UserInputError(\n `You have no complementary positions to merge for condition ${conditionId}`,\n );\n }\n\n if (requestedAmount === 'max') {\n return maxAmount;\n }\n\n if (requestedAmount > maxAmount) {\n throw new UserInputError(\n `Requested merge amount ${requestedAmount} exceeds the maximum mergeable amount ${maxAmount} for condition ${conditionId}`,\n );\n }\n\n return requestedAmount;\n}\n\nfunction calculateMaxMergeAmount([\n yesPosition,\n noPosition,\n]: BinaryPositions): bigint {\n const yesAmount = toPositionAmount(yesPosition, 0);\n const noAmount = toPositionAmount(noPosition, 1);\n\n return yesAmount < noAmount ? yesAmount : noAmount;\n}\n\nfunction toPositionAmount(\n position: Position | undefined,\n expectedOutcomeIndex: 0 | 1,\n): bigint {\n if (position === undefined) {\n return 0n;\n }\n\n invariant(\n position.outcomeIndex === expectedOutcomeIndex,\n `Expected outcomeIndex ${expectedOutcomeIndex}`,\n );\n\n if (isNullish(position.size)) {\n return 0n;\n }\n\n return toTokenBaseUnits(position.size);\n}\n\nfunction toTokenBaseUnits(size: number): bigint {\n if (!Number.isFinite(size) || size < 0) {\n throw new UserInputError(\n 'Position size must be a non-negative finite number',\n );\n }\n\n return BigInt(Math.floor(size * 1e6));\n}\n","import {\n type PublicProfile,\n PublicProfileSchema,\n} from '@polymarket/bindings/gamma';\nimport { err, ok, unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport {\n type RateLimitError,\n RequestRejectedError,\n type TransportError,\n type UnexpectedResponseError,\n type UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport { validateWith } from '../response';\nimport { snakeCase, toSearchParams } from './params';\n\nconst FetchPublicProfileRequestSchema = z.object({\n address: z.string(),\n});\n\nexport type FetchPublicProfileRequest = z.input<\n typeof FetchPublicProfileRequestSchema\n>;\n\nexport type FetchPublicProfileError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches a public profile by wallet address.\n *\n * @throws {@link FetchPublicProfileError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const profile = await fetchPublicProfile(client, {\n * address: '0x7c3db723f1d4d8cb9c550095203b686cb11e5c6b',\n * });\n *\n * // profile === PublicProfile | null\n * ```\n */\nexport async function fetchPublicProfile(\n client: BaseClient,\n request: FetchPublicProfileRequest,\n): Promise<PublicProfile | null> {\n const params = parseUserInput(request, FetchPublicProfileRequestSchema);\n\n return unwrap(\n client.gamma\n .get('/public-profile', {\n params: toSearchParams(params, snakeCase()),\n })\n .andThen(validateWith(PublicProfileSchema))\n .orElse((error) => {\n if (error instanceof RequestRejectedError && error.status === 404) {\n return ok(null);\n }\n\n return err(error);\n }),\n );\n}\n","import {\n type PublicSearchResponse,\n PublicSearchResponseSchema,\n} from '@polymarket/bindings/gamma';\nimport { unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport { validateWith } from '../response';\nimport { snakeCase, toSearchParams } from './params';\n\nconst SearchRequestSchema = z.object({\n q: z.string().min(1),\n ascending: z.boolean().optional(),\n cache: z.boolean().optional(),\n eventsStatus: z.string().min(1).optional(),\n eventsTag: z.array(z.string()).optional(),\n excludeTagIds: z.array(z.number().int()).optional(),\n keepClosedMarkets: z.number().int().optional(),\n limitPerType: z.number().int().optional(),\n optimized: z.boolean().optional(),\n page: z.number().int().optional(),\n presets: z.array(z.string()).optional(),\n recurrence: z.enum(['daily', 'weekly', 'monthly']).optional(),\n searchProfiles: z.boolean().optional(),\n searchTags: z.boolean().optional(),\n sort: z.string().min(1).optional(),\n});\n\nexport type SearchRequest = z.input<typeof SearchRequestSchema>;\n\ntype SearchParams = z.output<typeof SearchRequestSchema>;\n\nexport type SearchError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Runs a public full-text search.\n *\n * @throws {@link SearchError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const result = await search(client, {\n * q: 'trump',\n * limitPerType: 3,\n * });\n *\n * // result === PublicSearchResponse\n * ```\n */\nexport async function search(\n client: BaseClient,\n request: SearchRequest,\n): Promise<PublicSearchResponse> {\n const params = parseUserInput(request, SearchRequestSchema);\n\n return unwrap(\n client.gamma\n .get('/public-search', {\n params: toSearchParams(\n params,\n snakeCase<SearchParams>({\n excludeTagIds: 'exclude_tag_id',\n }),\n ),\n })\n .andThen(validateWith(PublicSearchResponseSchema)),\n );\n}\n","import { PaginationCursorSchema } from '@polymarket/bindings';\nimport {\n ListSeriesResponseSchema,\n type Series,\n SeriesSchema,\n} from '@polymarket/bindings/gamma';\nimport { unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport {\n decodeOffsetCursor,\n encodeOffsetCursor,\n PageSizeSchema,\n type Paginated,\n paginate,\n} from '../pagination';\nimport { validateWith } from '../response';\nimport { snakeCase, toSearchParams } from './params';\n\nconst ListSeriesRequestSchema = z.object({\n ascending: z.boolean().optional(),\n categoriesIds: z.array(z.number().int()).optional(),\n categoriesLabels: z.array(z.string()).optional(),\n closed: z.boolean().optional(),\n cursor: PaginationCursorSchema.optional(),\n excludeEvents: z.boolean().optional(),\n includeChat: z.boolean().optional(),\n locale: z.string().optional(),\n order: z.string().optional(),\n pageSize: PageSizeSchema.default(20),\n recurrence: z.enum(['daily', 'weekly', 'monthly']).optional(),\n slug: z.array(z.string()).optional(),\n});\n\nconst FetchSeriesRequestSchema = z.object({\n id: z.string(),\n includeChat: z.boolean().optional(),\n locale: z.string().optional(),\n});\n\nexport type ListSeriesRequest = z.input<typeof ListSeriesRequestSchema>;\nexport type FetchSeriesRequest = z.input<typeof FetchSeriesRequestSchema>;\ntype ListSeriesParams = z.output<typeof ListSeriesRequestSchema>;\n\nexport type ListSeriesError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists series.\n *\n * @throws {@link ListSeriesError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listSeries(client, {\n * closed: false,\n * pageSize: 10,\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: Series[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listSeries(client, {\n * closed: false,\n * pageSize: 10,\n * });\n *\n * for await (const page of result) {\n * // page.items: Series[]\n * }\n * ```\n */\nexport function listSeries(\n client: BaseClient,\n request: ListSeriesRequest = {},\n): Paginated<Series> {\n const { cursor, pageSize, ...params } = parseUserInput(\n request,\n ListSeriesRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.gamma\n .get('/series', {\n params: toSearchParams(\n {\n ...params,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n },\n snakeCase<ListSeriesParams>({\n categoriesIds: 'categories_ids',\n categoriesLabels: 'categories_labels',\n }),\n ),\n })\n .andThen(validateWith(ListSeriesResponseSchema))\n .map((series) => {\n const hasMore = series.length > decoded.pageSize;\n\n return {\n items: series.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n\nexport type FetchSeriesError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches a series.\n *\n * @throws {@link FetchSeriesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const series = await fetchSeries(client, {\n * id: 'fed-daily-series',\n * includeChat: true,\n * });\n *\n * // series === Series\n * ```\n */\nexport async function fetchSeries(\n client: BaseClient,\n request: FetchSeriesRequest,\n): Promise<Series> {\n const params = parseUserInput(request, FetchSeriesRequestSchema);\n\n return unwrap(\n client.gamma\n .get(`series/${params.id}`, {\n params: toSearchParams(\n {\n includeChat: params.includeChat,\n locale: params.locale,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(SeriesSchema)),\n );\n}\n","import {\n ListSportsMetadataResponseSchema,\n type SportsMarketTypesResponse,\n SportsMarketTypesResponseSchema,\n type SportsMetadata,\n} from '@polymarket/bindings/gamma';\nimport { unwrap } from '@polymarket/types';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n} from '../errors';\nimport { validateWith } from '../response';\n\nexport type ListSportsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Lists available sports metadata.\n *\n * @throws {@link ListSportsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const sports = await listSports(client);\n *\n * // sports: SportsMetadata[]\n * ```\n */\nexport async function listSports(\n client: BaseClient,\n): Promise<SportsMetadata[]> {\n return unwrap(\n client.gamma\n .get('/sports')\n .andThen(validateWith(ListSportsMetadataResponseSchema)),\n );\n}\n\nexport type FetchSportsMarketTypesError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError;\n\n/**\n * Fetches the available market types grouped by sport.\n *\n * @throws {@link FetchSportsMarketTypesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const marketTypes = await fetchSportsMarketTypes(client);\n *\n * // marketTypes === SportsMarketTypesResponse\n * ```\n */\nexport async function fetchSportsMarketTypes(\n client: BaseClient,\n): Promise<SportsMarketTypesResponse> {\n return unwrap(\n client.gamma\n .get('/sports/market-types')\n .andThen(validateWith(SportsMarketTypesResponseSchema)),\n );\n}\n","import { PaginationCursorSchema } from '@polymarket/bindings';\nimport {\n ListRelatedTagResourcesResponseSchema,\n ListRelatedTagsResponseSchema,\n ListTagsResponseSchema,\n type RelatedTag,\n type Tag,\n TagSchema,\n} from '@polymarket/bindings/gamma';\nimport { unwrap } from '@polymarket/types';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport {\n decodeOffsetCursor,\n encodeOffsetCursor,\n PageSizeSchema,\n type Paginated,\n paginate,\n} from '../pagination';\nimport { validateWith } from '../response';\nimport { snakeCase, toSearchParams } from './params';\n\nconst ListTagsRequestSchema = z.object({\n ascending: z.boolean().optional(),\n cursor: PaginationCursorSchema.optional(),\n includeChat: z.boolean().optional(),\n includeTemplate: z.boolean().optional(),\n isCarousel: z.boolean().optional(),\n locale: z.string().optional(),\n order: z.string().optional(),\n pageSize: PageSizeSchema.default(20),\n});\n\nconst FetchTagRequestSchema = z.union([\n z.object({\n id: z.string(),\n includeChat: z.boolean().optional(),\n includeTemplate: z.boolean().optional(),\n locale: z.string().optional(),\n }),\n z.object({\n slug: z.string(),\n locale: z.string().optional(),\n }),\n]);\n\nconst RelatedTagsByIdRequestSchema = z.object({\n id: z.string(),\n omitEmpty: z.boolean().optional(),\n status: z.enum(['active', 'closed', 'all']).optional(),\n});\n\nconst RelatedTagsBySlugRequestSchema = z.object({\n slug: z.string(),\n});\n\nconst RelatedTagResourcesByIdRequestSchema = z.object({\n id: z.string(),\n locale: z.string().optional(),\n omitEmpty: z.boolean().optional(),\n status: z.enum(['active', 'closed', 'all']).optional(),\n});\n\nconst RelatedTagResourcesBySlugRequestSchema = z.object({\n locale: z.string().optional(),\n slug: z.string(),\n omitEmpty: z.boolean().optional(),\n status: z.enum(['active', 'closed', 'all']).optional(),\n});\n\nexport type ListTagsRequest = z.input<typeof ListTagsRequestSchema>;\nexport type FetchTagRequest = z.input<typeof FetchTagRequestSchema>;\nexport type FetchRelatedTagsRequest =\n | z.input<typeof RelatedTagsByIdRequestSchema>\n | z.input<typeof RelatedTagsBySlugRequestSchema>;\nexport type FetchRelatedTagResourcesRequest =\n | z.input<typeof RelatedTagResourcesByIdRequestSchema>\n | z.input<typeof RelatedTagResourcesBySlugRequestSchema>;\n\nexport type ListTagsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists tags.\n *\n * @throws {@link ListTagsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listTags(client, {\n * includeTemplate: true,\n * pageSize: 12,\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: Tag[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listTags(client, {\n * includeTemplate: true,\n * pageSize: 12,\n * });\n *\n * for await (const page of result) {\n * // page.items: Tag[]\n * }\n * ```\n */\nexport function listTags(\n client: BaseClient,\n request: ListTagsRequest = {},\n): Paginated<Tag> {\n const { cursor, pageSize, ...params } = parseUserInput(\n request,\n ListTagsRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.gamma\n .get('/tags', {\n params: toSearchParams(\n {\n ...params,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(ListTagsResponseSchema))\n .map((tags) => {\n const hasMore = tags.length > decoded.pageSize;\n\n return {\n items: tags.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n\nexport type FetchTagError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches a tag by id or slug.\n *\n * @throws {@link FetchTagError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const tag = await fetchTag(client, {\n * slug: 'politics',\n * locale: 'en',\n * });\n *\n * // tag === Tag\n * ```\n */\nexport async function fetchTag(\n client: BaseClient,\n request: FetchTagRequest,\n): Promise<Tag> {\n const params = parseUserInput(request, FetchTagRequestSchema);\n\n if ('id' in params) {\n return unwrap(\n client.gamma\n .get(`tags/${params.id}`, {\n params: toSearchParams(\n {\n includeChat: params.includeChat,\n includeTemplate: params.includeTemplate,\n locale: params.locale,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(TagSchema)),\n );\n }\n\n return unwrap(\n client.gamma\n .get(`tags/slug/${params.slug}`, {\n params: toSearchParams(\n {\n locale: params.locale,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(TagSchema)),\n );\n}\n\nexport type FetchRelatedTagsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches related tag relationships by id or slug.\n *\n * @throws {@link FetchRelatedTagsError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const relatedTags = await fetchRelatedTags(client, {\n * id: '42',\n * status: 'active',\n * omitEmpty: true,\n * });\n *\n * // relatedTags: RelatedTag[]\n * ```\n */\nexport async function fetchRelatedTags(\n client: BaseClient,\n request: FetchRelatedTagsRequest,\n): Promise<RelatedTag[]> {\n if ('id' in request) {\n const params = parseUserInput(request, RelatedTagsByIdRequestSchema);\n\n return unwrap(\n client.gamma\n .get(`tags/${params.id}/related-tags`, {\n params: toSearchParams(\n {\n omitEmpty: params.omitEmpty,\n status: params.status,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(ListRelatedTagsResponseSchema)),\n );\n }\n\n const params = parseUserInput(request, RelatedTagsBySlugRequestSchema);\n\n return unwrap(\n client.gamma\n .get(`tags/slug/${params.slug}/related-tags`)\n .andThen(validateWith(ListRelatedTagsResponseSchema)),\n );\n}\n\nexport type FetchRelatedTagResourcesError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Fetches resources linked from related tag relationships by id or slug.\n *\n * @throws {@link FetchRelatedTagResourcesError}\n * Thrown on failure.\n *\n * @example\n * ```ts\n * const relatedResources = await fetchRelatedTagResources(client, {\n * slug: 'election',\n * status: 'active',\n * omitEmpty: true,\n * });\n *\n * // relatedResources: Tag[]\n * ```\n */\nexport async function fetchRelatedTagResources(\n client: BaseClient,\n request: FetchRelatedTagResourcesRequest,\n): Promise<Tag[]> {\n if ('id' in request) {\n const params = parseUserInput(\n request,\n RelatedTagResourcesByIdRequestSchema,\n );\n\n return unwrap(\n client.gamma\n .get(`tags/${params.id}/related-tags/tags`, {\n params: toSearchParams(\n {\n locale: params.locale,\n omitEmpty: params.omitEmpty,\n status: params.status,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(ListRelatedTagResourcesResponseSchema)),\n );\n }\n\n const params = parseUserInput(\n request,\n RelatedTagResourcesBySlugRequestSchema,\n );\n\n return unwrap(\n client.gamma\n .get(`tags/slug/${params.slug}/related-tags/tags`, {\n params: toSearchParams(\n {\n locale: params.locale,\n omitEmpty: params.omitEmpty,\n status: params.status,\n },\n snakeCase(),\n ),\n })\n .andThen(validateWith(ListRelatedTagResourcesResponseSchema)),\n );\n}\n","import { PaginationCursorSchema } from '@polymarket/bindings';\nimport { ListTeamsResponseSchema, type Team } from '@polymarket/bindings/gamma';\nimport { z } from 'zod';\nimport type { BaseClient } from '../clients';\nimport type {\n RateLimitError,\n RequestRejectedError,\n TransportError,\n UnexpectedResponseError,\n UserInputError,\n} from '../errors';\nimport { parseUserInput } from '../input';\nimport {\n decodeOffsetCursor,\n encodeOffsetCursor,\n PageSizeSchema,\n type Paginated,\n paginate,\n} from '../pagination';\nimport { validateWith } from '../response';\nimport { snakeCase, toSearchParams } from './params';\n\nconst ListTeamsRequestSchema = z.object({\n abbreviation: z.array(z.string()).optional(),\n ascending: z.boolean().optional(),\n cursor: PaginationCursorSchema.optional(),\n league: z.array(z.string()).optional(),\n name: z.array(z.string()).optional(),\n order: z.string().optional(),\n pageSize: PageSizeSchema.default(20),\n providerId: z.array(z.number().int()).optional(),\n});\n\nexport type ListTeamsRequest = z.input<typeof ListTeamsRequestSchema>;\n\nexport type ListTeamsError =\n | RateLimitError\n | RequestRejectedError\n | TransportError\n | UnexpectedResponseError\n | UserInputError;\n\n/**\n * Lists teams.\n *\n * @throws {@link ListTeamsError}\n * Thrown on failure.\n *\n * @example\n * Fetch the first page of results:\n * ```ts\n * const result = listTeams(client, {\n * league: ['NBA'],\n * pageSize: 10,\n * });\n *\n * const firstPage = await result.firstPage();\n *\n * // Optionally, fetch additional pages:\n * for await (const page of result.from(firstPage.nextCursor)) {\n * // page.items: Team[]\n * }\n * ```\n *\n * @example\n * Loop through all pages with `for await`:\n * ```ts\n * const result = listTeams(client, {\n * league: ['NBA'],\n * pageSize: 10,\n * });\n *\n * for await (const page of result) {\n * // page.items: Team[]\n * }\n * ```\n */\nexport function listTeams(\n client: BaseClient,\n request: ListTeamsRequest = {},\n): Paginated<Team> {\n const { cursor, pageSize, ...params } = parseUserInput(\n request,\n ListTeamsRequestSchema,\n );\n\n return paginate((cursor) => {\n const decoded = decodeOffsetCursor(cursor, pageSize);\n\n return client.gamma\n .get('/teams', {\n params: toSearchParams(\n {\n ...params,\n limit: decoded.pageSize + 1,\n offset: decoded.offset,\n },\n snakeCase({ providerId: 'provider_id' }),\n ),\n })\n .andThen(validateWith(ListTeamsResponseSchema))\n .map((teams) => {\n const hasMore = teams.length > decoded.pageSize;\n\n return {\n items: teams.slice(0, decoded.pageSize),\n hasMore,\n nextCursor: hasMore\n ? encodeOffsetCursor({\n offset: decoded.offset + decoded.pageSize,\n pageSize: decoded.pageSize,\n })\n : undefined,\n };\n });\n }, cursor);\n}\n","import { type EvmAddress, EvmAddressSchema } from '@polymarket/bindings';\nimport { WalletType } from '@polymarket/bindings/gamma';\nimport type { EvmSignature } from '@polymarket/types';\nimport { z } from 'zod';\nimport { erc20TransferCall } from '../abis';\nimport type { BaseSecureClient } from '../clients';\nimport type { UserInputError } from '../errors';\nimport { parseUserInput } from '../input';\nimport { expectTransactionHandle, type TransactionHandle } from '../types';\nimport type { SignerTransactionRequest } from '../workflow';\nimport {\n type SendErc20TransferTransactionRequest,\n signerTransactionRequest,\n} from '../workflow';\nimport {\n GaslessTransactionMetadataSchema,\n type GaslessWorkflowRequest,\n prepareGaslessTransaction,\n} from './gasless';\n\nexport type Erc20TransferWorkflowRequest =\n | GaslessWorkflowRequest\n | SendErc20TransferTransactionRequest;\n\nexport type Erc20TransferWorkflow = AsyncGenerator<\n Erc20TransferWorkflowRequest,\n TransactionHandle,\n EvmAddress | EvmSignature | TransactionHandle\n>;\n\nconst PrepareErc20TransferRequestSchema = z.object({\n amount: z.bigint(),\n metadata: GaslessTransactionMetadataSchema.optional(),\n recipientAddress: EvmAddressSchema,\n tokenAddress: EvmAddressSchema,\n});\n\nexport type PrepareErc20TransferRequest = z.input<\n typeof PrepareErc20TransferRequestSchema\n>;\n\nexport type PrepareErc20TransferError = UserInputError;\n\n/**\n * Starts an ERC-20 transfer workflow.\n *\n * @example\n * ```ts\n * const handle = await prepareErc20Transfer(client, {\n * amount: 1n,\n * recipientAddress: client.account.signer,\n * tokenAddress: client.environment.collateralToken,\n * }).then(completeWith(wallet));\n *\n * const outcome = await handle.wait();\n *\n * // outcome.transactionHash: TxHash\n * ```\n *\n * @throws {@link PrepareErc20TransferError}\n * Thrown on failure.\n */\nexport async function prepareErc20Transfer(\n client: BaseSecureClient,\n request: PrepareErc20TransferRequest,\n): Promise<Erc20TransferWorkflow> {\n const params = parseUserInput(request, PrepareErc20TransferRequestSchema);\n\n return async function* (): Erc20TransferWorkflow {\n if (client.account.walletType === WalletType.EOA) {\n return expectTransactionHandle(\n yield sendErc20TransferTransaction(\n signerTransactionRequest(\n client.environment.chainId,\n erc20TransferCall(\n params.tokenAddress,\n params.recipientAddress,\n params.amount,\n ),\n ),\n ),\n );\n }\n\n return yield* await prepareGaslessTransaction(client, {\n calls: [\n erc20TransferCall(\n params.tokenAddress,\n params.recipientAddress,\n params.amount,\n ),\n ],\n metadata:\n params.metadata ??\n `Transfer ${params.amount} of ${params.tokenAddress} to ${params.recipientAddress}`,\n });\n }.call(null);\n}\n\nfunction sendErc20TransferTransaction(\n request: SignerTransactionRequest,\n): SendErc20TransferTransactionRequest {\n return {\n kind: 'sendErc20TransferTransaction',\n request,\n };\n}\n"]}