@polymarket/client 0.1.0-beta.7 → 0.1.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions/index.d.ts +14 -13
- package/dist/actions/index.js +1 -1
- package/dist/chunk-GZWA532J.js +2 -0
- package/dist/chunk-GZWA532J.js.map +1 -0
- package/dist/ethers-v5.d.ts +2 -1
- package/dist/index.d.ts +23 -7
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/{sports-DNQLB2c4.d.ts → sports-_kLx9-gD.d.ts} +11 -11
- package/dist/{types-C9xs0MNQ.d.ts → types-5uGoLhNm.d.ts} +957 -116
- package/dist/viem.d.ts +2 -1
- package/package.json +3 -2
- package/dist/chunk-UBQO5URS.js +0 -2
- package/dist/chunk-UBQO5URS.js.map +0 -1
package/dist/ethers-v5.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ethers } from 'ethers-v5';
|
|
2
|
-
import { T as TypedDataPayload, a as TypedData, S as Signer } from './types-
|
|
2
|
+
import { T as TypedDataPayload, a as TypedData, S as Signer } from './types-5uGoLhNm.js';
|
|
3
3
|
import '@polymarket/bindings';
|
|
4
4
|
import '@polymarket/types';
|
|
5
5
|
import '@polymarket/bindings/gamma';
|
|
@@ -8,6 +8,7 @@ import 'zod';
|
|
|
8
8
|
import '@polymarket/bindings/clob';
|
|
9
9
|
import '@polymarket/bindings/data';
|
|
10
10
|
import '@polymarket/bindings/rfq';
|
|
11
|
+
import '@polymarket/bindings/perps';
|
|
11
12
|
import '@polymarket/bindings/subscriptions';
|
|
12
13
|
import 'ox';
|
|
13
14
|
|
package/dist/index.d.ts
CHANGED
|
@@ -7,16 +7,21 @@ export * from '@polymarket/bindings/data';
|
|
|
7
7
|
export { ActivityType, ComboPositionStatus } from '@polymarket/bindings/data';
|
|
8
8
|
export * from '@polymarket/bindings/gamma';
|
|
9
9
|
export { WalletType } from '@polymarket/bindings/gamma';
|
|
10
|
+
export * from '@polymarket/bindings/perps';
|
|
11
|
+
export { PerpsDepositStatus, PerpsInstrumentCategory, PerpsInstrumentType, PerpsInternalTransferDirection, PerpsKlineInterval, PerpsSide, PerpsTimeInForce, PerpsWithdrawalStatus } from '@polymarket/bindings/perps';
|
|
10
12
|
export * from '@polymarket/bindings/relayer';
|
|
11
|
-
import {
|
|
12
|
-
import { U as UserInputError, b as TransactionCall, A as ApiKeyAuthorization } from './types-
|
|
13
|
-
export { c as AccountIdentity, d as AnalyticsActions, e as ApproveErc1155ForAllError, f as ApproveErc20Error, B as BaseClient, g as BasePublicClient, h as BaseSecureClient, i as BeginAuthenticationRequest, C as CancelAllError, j as CancelMarketOrdersError, k as CancelOrderError, l as CancelOrdersError, m as CancelledSigningError, n as Client, o as ClientActions, p as ClientDecorator, q as CreateSecureClientError, D as DataActions,
|
|
14
|
-
export { C as CreateLimitOrderError, a as CreateMarketOrderError, F as FetchSportsMarketTypesError, L as ListSportsError, P as PlaceLimitOrderError, b as PlaceMarketOrderError } from './sports-
|
|
15
|
-
export {
|
|
13
|
+
import { EvmAddress } from '@polymarket/types';
|
|
14
|
+
import { U as UserInputError, b as TransactionCall, A as ApiKeyAuthorization } from './types-5uGoLhNm.js';
|
|
15
|
+
export { c as AccountIdentity, d as AnalyticsActions, e as ApproveErc1155ForAllError, f as ApproveErc20Error, B as BaseClient, g as BasePublicClient, h as BaseSecureClient, i as BeginAuthenticationRequest, C as CancelAllError, j as CancelMarketOrdersError, k as CancelOrderError, l as CancelOrdersError, m as CancelledSigningError, n as Client, o as ClientActions, p as ClientDecorator, q as ClobEndpoints, r as CreateSecureClientError, D as DataActions, s as DiscoveryActions, t as DownloadAccountingSnapshotError, u as DropNotificationsError, E as EnvironmentConfig, v as EnvironmentConfigFork, w as EnvironmentContracts, x as EstimateMarketPriceError, F as FetchClosedOnlyModeError, y as FetchCommentsByIdError, z as FetchEventError, G as FetchEventLiveVolumeError, H as FetchEventTagsError, I as FetchLastTradePriceError, J as FetchLastTradePricesError, K as FetchMarketError, L as FetchMarketTagsError, M as FetchMidpointError, N as FetchMidpointsError, O as FetchNotificationsError, P as FetchOrderBookError, Q as FetchOrderBooksError, R as FetchOrderError, V as FetchOrderScoringError, W as FetchOrdersScoringError, X as FetchPortfolioValueError, Y as FetchPriceError, Z as FetchPriceHistoryError, _ as FetchPricesError, $ as FetchPublicProfileError, a0 as FetchRelatedTagResourcesError, a1 as FetchRelatedTagsError, a2 as FetchRewardPercentagesError, a3 as FetchSeriesError, a4 as FetchSpreadError, a5 as FetchSpreadsError, a6 as FetchTagError, a7 as FetchTotalEarningsForUserForDayError, a8 as FetchTradedMarketCountError, a9 as InsufficientLiquidityError, aa as ListAccountTradesError, ab as ListActivityError, ac as ListBuilderLeaderboardError, ad as ListBuilderTradesError, ae as ListBuilderVolumeError, af as ListClosedPositionsError, ag as ListComboMarketsError, ah as ListComboPositionsError, ai as ListCommentsByUserAddressError, aj as ListCommentsError, ak as ListCurrentRewardsError, al as ListEventsError, am as ListMarketHoldersError, an as ListMarketPositionsError, ao as ListMarketRewardsError, ap as ListMarketsError, aq as ListOpenInterestError, ar as ListOpenOrdersError, as as ListPositionsError, at as ListSeriesError, au as ListTagsError, av as ListTeamsError, aw as ListTraderLeaderboardError, ax as ListTradesError, ay as ListUserEarningsAndMarketsConfigError, az as ListUserEarningsForDayError, aA as MergePositionsError, aB as OpenRfqSessionError, aC as Page, aD as PageSizeSchema, aE as Paginated, aF as PerpsActions, aG as PerpsEndpoints, aH as PerpsSession, aI as PostOrderError, aJ as PostOrdersError, aK as PublicAccountActions, aL as PublicActions, aM as PublicClient, aN as PublicClientOptions, aO as PublicPerpsActions, aP as PublicRewardsActions, aQ as PublicSubscriptionsActions, aR as RateLimitError, aS as RedeemPositionsError, aT as RequestRejectedError, aU as RequestRejectedErrorOptions, aV as RestEndpoint, aW as RfqCancelQuoteAck, aX as RfqCancelQuoteError, aY as RfqCancelQuoteRejectedError, aZ as RfqCancelQuoteRejectedErrorOptions, a_ as RfqConfirmationAck, a$ as RfqConfirmationError, b0 as RfqConfirmationRejectedError, b1 as RfqConfirmationRequestEvent, b2 as RfqEndpoints, b3 as RfqEvent, b4 as RfqQuoteError, b5 as RfqQuoteReference, b6 as RfqQuoteRejectedError, b7 as RfqQuoteRejectedErrorOptions, b8 as RfqQuoteRequestEvent, b9 as RfqQuoteResponse, ba as RfqQuoteSource, bb as RfqSession, bc as RfqTradeEvent, bd as SearchError, be as SecureAccountActions, bf as SecureActions, bg as SecureClient, bh as SecureClientOptions, bi as SecureDownloadAccountingSnapshotRequest, bj as SecureFetchPortfolioValueRequest, bk as SecureFetchTradedMarketCountRequest, bl as SecureListActivityRequest, bm as SecureListClosedPositionsRequest, bn as SecureListComboPositionsRequest, bo as SecureListPositionsRequest, bp as SecurePerpsActions, bq as SecureRewardsActions, br as SecureRfqActions, bs as SecureSubscriptionsActions, bt as SecureTradingActions, bu as SecureWalletActions, bv as SetupGaslessWalletError, bw as SetupTradingApprovalsError, S as Signer, bx as SignerTransactionRequest, by as SigningError, bz as SplitPositionError, bA as TimeoutError, bB as TransactionFailedError, bC as TransactionHandle, bD as TransactionOutcome, bE as TransferErc20Error, bF as TransportError, a as TypedData, bG as TypedDataDomain, bH as TypedDataField, T as TypedDataPayload, bI as UnexpectedResponseError, bJ as WaitForTransactionError, bK as WalletDerivationConfig, bL as WebSocketEndpoint, bM as accountActions, bN as allActions, bO as analyticsActions, bP as createPublicClient, bQ as createSecureClient, bR as dataActions, bS as discoveryActions, bT as forkEnvironmentConfig, bU as makeErrorGuard, bV as perpsActions, bW as production, bX as rewardsActions, bY as rfqActions, bZ as subscriptionsActions, b_ as tradingActions, b$ as walletActions } from './types-5uGoLhNm.js';
|
|
16
|
+
export { C as CreateLimitOrderError, a as CreateMarketOrderError, F as FetchSportsMarketTypesError, L as ListSportsError, P as PlaceLimitOrderError, b as PlaceMarketOrderError } from './sports-_kLx9-gD.js';
|
|
17
|
+
export { PerpsSessionEvent } from '@polymarket/bindings/subscriptions';
|
|
18
|
+
export { RfqConfirmationDecision, RfqConfirmationRequest, RfqDirection, RfqErrorCode, RfqExecutionStatus, RfqExecutionUpdate, RfqId, RfqQuoteId, RfqQuoteRequest, RfqRequestedSize, RfqRequestedSizeUnit, RfqRequestorPublicId, RfqSide, RfqTrade } from '@polymarket/bindings/rfq';
|
|
16
19
|
import 'zod';
|
|
17
|
-
import '@polymarket/bindings/subscriptions';
|
|
18
20
|
import 'ox';
|
|
19
21
|
|
|
22
|
+
type Tagged<T, Tag extends string> = T & {
|
|
23
|
+
readonly __tag: Tag;
|
|
24
|
+
};
|
|
20
25
|
type CanonicalComboLegs = Tagged<readonly bigint[], 'CanonicalComboLegs'>;
|
|
21
26
|
|
|
22
27
|
type Erc20ApprovalCallError = UserInputError;
|
|
@@ -45,6 +50,17 @@ declare const Erc20TransferCallError: {
|
|
|
45
50
|
* Thrown when the transfer amount is invalid.
|
|
46
51
|
*/
|
|
47
52
|
declare function erc20TransferCall(tokenAddress: EvmAddress, recipient: EvmAddress, amount: bigint): TransactionCall;
|
|
53
|
+
type PerpsDepositCallError = UserInputError;
|
|
54
|
+
declare const PerpsDepositCallError: {
|
|
55
|
+
isError(error: unknown): error is UserInputError;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Creates a transaction call for Perps `deposit(address,uint256,address)`.
|
|
59
|
+
*
|
|
60
|
+
* @throws {@link PerpsDepositCallError}
|
|
61
|
+
* Thrown when the deposit amount is invalid.
|
|
62
|
+
*/
|
|
63
|
+
declare function perpsDepositCall(depositContractAddress: EvmAddress, tokenAddress: EvmAddress, amount: bigint, to: EvmAddress): TransactionCall;
|
|
48
64
|
type CtfRedeemPositionsCallError = UserInputError;
|
|
49
65
|
declare const CtfRedeemPositionsCallError: {
|
|
50
66
|
isError(error: unknown): error is UserInputError;
|
|
@@ -202,4 +218,4 @@ declare function relayerApiKey(config: RelayerApiKeyConfig): ApiKeyAuthorization
|
|
|
202
218
|
*/
|
|
203
219
|
declare function buildHmacSignature(secret: string, timestamp: number, method: string, requestPath: string, body?: string): Promise<string>;
|
|
204
220
|
|
|
205
|
-
export { ApiKeyAuthorization, CombinatorialPrepareConditionCallError, CtfRedeemPositionsCallError, Erc20ApprovalCallError, Erc20TransferCallError, MergePositionsCallError, MergeV2CallError, RedeemV2CallError, type RelayerApiKeyConfig, type RemoteBuilderSigningConfig, SplitPositionCallError, SplitV2CallError, TransactionCall, UserInputError, buildHmacSignature, combinatorialPrepareConditionCall, ctfRedeemPositionsCall, erc1155ApprovalForAllCall, erc20ApprovalCall, erc20TransferCall, mergePositionsCall, mergeV2Call, redeemV2Call, relayerApiKey, remoteBuilderSigning, splitPositionCall, splitV2Call };
|
|
221
|
+
export { ApiKeyAuthorization, CombinatorialPrepareConditionCallError, CtfRedeemPositionsCallError, Erc20ApprovalCallError, Erc20TransferCallError, MergePositionsCallError, MergeV2CallError, PerpsDepositCallError, RedeemV2CallError, type RelayerApiKeyConfig, type RemoteBuilderSigningConfig, SplitPositionCallError, SplitV2CallError, TransactionCall, UserInputError, buildHmacSignature, combinatorialPrepareConditionCall, ctfRedeemPositionsCall, erc1155ApprovalForAllCall, erc20ApprovalCall, erc20TransferCall, mergePositionsCall, mergeV2Call, perpsDepositCall, redeemV2Call, relayerApiKey, remoteBuilderSigning, splitPositionCall, splitV2Call };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {la,va,ta,ra,Pa,ld,jd,hd,fd,ed,bd,fc,dc,bc,db,Na,pc,rc,Dc,Jb,Hb,Fb,Db,Bb,zb,xb,vb,tb,hb,fb,$b,Tb,Rb,Pb,Ud,Be,qe,oe as oe$1,ie as ie$1,ze,xe,ve,te,me,ke,nc,lc,jc,hc as hc$1,Zb,Xb,Vb,La,Ja,Ha,Fa,Da,Ba,ae as ae$1,re,pa,na,Bc,zc,xc,vc,Ic,Hc,$c,Zc,Xc,Vc,Sd,Nd,Ed,Fe,Za,Va,bb,Z,ca,Y,fa,tc,Nb,Lb,V,U as U$1,_ as _$1,W as W$1,L,J,N,Vd,Xd,Zd,X,Jc,Kc}from'./chunk-UBQO5URS.js';export{Ya as ApproveErc1155ForAllError,Ua as ApproveErc20Error,yc as CancelAllError,Ac as CancelMarketOrdersError,uc as CancelOrderError,wc as CancelOrdersError,A as CombinatorialPrepareConditionCallError,md as ComboPositionStatus,Yc as CreateLimitOrderError,Uc as CreateMarketOrderError,o as CtfRedeemPositionsCallError,kd as DownloadAccountingSnapshotError,ua as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,Cc as EstimateMarketPriceError,ka as FetchClosedOnlyModeError,Qb as FetchCommentsByIdError,Wb as FetchEventError,_b as FetchEventLiveVolumeError,Yb as FetchEventTagsError,Eb as FetchLastTradePriceError,Gb as FetchLastTradePricesError,kc as FetchMarketError,mc as FetchMarketTagsError,eb as FetchMidpointError,gb as FetchMidpointsError,sa as FetchNotificationsError,wb as FetchOrderBookError,yb as FetchOrderBooksError,oa as FetchOrderError,Aa as FetchOrderScoringError,Ca as FetchOrdersScoringError,gd as FetchPortfolioValueError,sb as FetchPriceError,Ib as FetchPriceHistoryError,ub as FetchPricesError,Td as FetchPublicProfileError,ye as FetchRelatedTagResourcesError,we as FetchRelatedTagsError,Ka as FetchRewardPercentagesError,le as FetchSeriesError,pe as FetchSportsMarketTypesError,Ab as FetchSpreadError,Cb as FetchSpreadsError,ue as FetchTagError,Ga as FetchTotalEarningsForUserForDayError,id as FetchTradedMarketCountError,qa as ListAccountTradesError,Oa as ListActivityError,ac as ListBuilderLeaderboardError,cb as ListBuilderTradesError,cc as ListBuilderVolumeError,cd as ListClosedPositionsError,ic as ListComboMarketsError,dd as ListComboPositionsError,Sb as ListCommentsByUserAddressError,Ob as ListCommentsError,Kb as ListCurrentRewardsError,Ub as ListEventsError,oc as ListMarketHoldersError,sc as ListMarketPositionsError,Mb as ListMarketRewardsError,gc as ListMarketsError,qc as ListOpenInterestError,ma as ListOpenOrdersError,ad as ListPositionsError,je as ListSeriesError,ne as ListSportsError,se as ListTagsError,Ae as ListTeamsError,ec as ListTraderLeaderboardError,Ma as ListTradesError,Ia as ListUserEarningsAndMarketsConfigError,Ea as ListUserEarningsForDayError,a as MAX_UINT256,r as MergePositionsCallError,Id as MergePositionsError,w as MergeV2CallError,$d as OpenRfqSessionError,_c as PlaceLimitOrderError,Wc as PlaceMarketOrderError,Fc as PostOrderError,Gc as PostOrdersError,Rd as RedeemPositionsError,y as RedeemV2CallError,Yd as RfqCancelQuoteError,Xd as RfqCancelQuoteRejectedError,be as RfqConfirmationDecision,_d as RfqConfirmationError,Zd as RfqConfirmationRejectedError,ce as RfqDirection,de as RfqErrorCode,ee as RfqExecutionStatus,Wd as RfqQuoteError,Vd as RfqQuoteRejectedError,fe as RfqRequestedSizeUnit,ge as RfqSide,he as SearchError,ab as SetupTradingApprovalsError,p as SplitPositionCallError,zd as SplitPositionError,u as SplitV2CallError,Ee as TransferErc20Error,Qa as WaitForTransactionError,B as combinatorialPrepareConditionCall,t as ctfRedeemPositionsCall,l as decodeErc1155BalanceOfBatchResult,j as decodeErc1155BalanceOfResult,h as decodeErc1155IsApprovedForAllResult,e as decodeErc20AllowanceResult,C as encodeProxyCall,D as encodeSafeMultisendCall,f as erc1155ApprovalForAllCall,k as erc1155BalanceOfBatchCall,i as erc1155BalanceOfCall,g as erc1155IsApprovedForAllCall,d as erc20AllowanceCall,c as erc20ApprovalCall,n as erc20TransferCall,Ra as expectTransactionHandle,s as mergePositionsCall,x as mergeV2Call,z as redeemV2Call,q as splitPositionCall,v as splitV2Call}from'./chunk-UBQO5URS.js';import {a,k,h,e,d as d$1,j,f,g,c,b}from'./chunk-E2CLUN5M.js';export{h as CancelledSigningError,i as InsufficientLiquidityError,e as RateLimitError,d as RequestRejectedError,j as SigningError,f as TimeoutError,g as TransactionFailedError,c as TransportError,b as UnexpectedResponseError,a as UserInputError,k as makeErrorGuard}from'./chunk-E2CLUN5M.js';import {DecimalishSchema,ApiKeySchema,EvmAddressSchema,toBaseUnits,OrderSide}from'@polymarket/bindings';export{OrderSide,OrderType}from'@polymarket/bindings';export{SignatureType}from'@polymarket/bindings/clob';export{ActivityType}from'@polymarket/bindings/data';import {WalletType}from'@polymarket/bindings/gamma';export{WalletType}from'@polymarket/bindings/gamma';import {z}from'zod';import {expectEvmAddress,isSameEvmAddress,expectEvmSignature,ResultAsync,invariant,setNonBlockingInterval,setNonBlockingTimeout}from'@polymarket/types';import Ls from'ky';import {RealtimeEventSchema,SportsResultEventSchema,MarketEventSchema,UserEventSchema}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import {RfqKnownInboundMessageSchema,RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/rfq';var Cs=z.object({POLY_BUILDER_API_KEY:z.string().min(1),POLY_BUILDER_TIMESTAMP:z.string().min(1),POLY_BUILDER_PASSPHRASE:z.string().min(1),POLY_BUILDER_SIGNATURE:z.string().min(1)});function Es(t){return new ne(t)}function ks(t){return new se(t)}var ne=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return true}get supportGasless(){return true}async authorize(e){try{return await this.#r(e)}catch(r){throw j.fromError(r,"Could not authorize the builder-authenticated request")}}async#t(){let e=this.#e.headers,r=typeof e=="function"?await e():e,n=new Headers(r);return n.set("content-type","application/json"),n}async#r(e){let r=await fetch(this.#e.url,{body:JSON.stringify({body:e.body,method:e.method,path:e.path}),credentials:this.#e.credentials,headers:await this.#t(),method:"POST",mode:"cors"});if(!r.ok)throw new Error(`Remote signer rejected request with status ${r.status}`);return Cs.parse(await r.json())}},se=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return false}get supportGasless(){return true}authorize(){return Promise.resolve({RELAYER_API_KEY:this.#e.key,RELAYER_API_KEY_ADDRESS:this.#e.address})}};function tr(t){return {domain:{chainId:t.chainId,name:"ClobAuthDomain",version:"1"},message:{address:t.address,message:"This message attests that I control the given wallet",nonce:t.nonce??0,timestamp:`${t.timestamp}`},primaryType:"ClobAuth",types:{ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function Ts(t){return {listPositions:bd.bind(null,t),listClosedPositions:ed.bind(null,t),listComboPositions:fd.bind(null,t),fetchPortfolioValue:hd.bind(null,t),fetchTradedMarketCount:jd.bind(null,t),downloadAccountingSnapshot:ld.bind(null,t),listMarketPositions:tc.bind(null,t),listActivity:Pa.bind(null,t)}}function y(t,e={}){return {...e,user:e.user??t.account.wallet}}function ie(t){let e=Ts(t);return t.isPublicClient()?e:{...e,listPositions:r=>bd(t,y(t,r)),listClosedPositions:r=>ed(t,y(t,r)),listComboPositions:r=>fd(t,y(t,r)),fetchPortfolioValue:r=>hd(t,y(t,r)),fetchTradedMarketCount:r=>jd(t,y(t,r)),downloadAccountingSnapshot:r=>ld(t,y(t,r)),listActivity:r=>Pa(t,y(t,r)),listAccountTrades:ra.bind(null,t),fetchNotifications:ta.bind(null,t),dropNotifications:va.bind(null,t),fetchClosedOnlyMode:la.bind(null,t)}}function oe(t){return {listBuilderTrades:db.bind(null,t),listBuilderLeaderboard:bc.bind(null,t),fetchBuilderVolume:dc.bind(null,t),listTraderLeaderboard:fc.bind(null,t)}}function ce(t){return {fetchEventLiveVolume:$b.bind(null,t),fetchMidpoint:fb.bind(null,t),fetchMidpoints:hb.bind(null,t),fetchPrice:tb.bind(null,t),fetchPrices:vb.bind(null,t),fetchOrderBook:xb.bind(null,t),fetchOrderBooks:zb.bind(null,t),fetchSpread:Bb.bind(null,t),fetchSpreads:Db.bind(null,t),fetchLastTradePrice:Fb.bind(null,t),fetchLastTradePrices:Hb.bind(null,t),fetchPriceHistory:Jb.bind(null,t),estimateMarketPrice:Dc.bind(null,t),listOpenInterest:rc.bind(null,t),listMarketHolders:pc.bind(null,t),listTrades:Na.bind(null,t)}}function ae(t){return {listEvents:Vb.bind(null,t),fetchEvent:Xb.bind(null,t),fetchEventTags:Zb.bind(null,t),listMarkets:hc$1.bind(null,t),listComboMarkets:jc.bind(null,t),fetchMarket:lc.bind(null,t),fetchMarketTags:nc.bind(null,t),listSeries:ke.bind(null,t),fetchSeries:me.bind(null,t),listTags:te.bind(null,t),fetchTag:ve.bind(null,t),fetchRelatedTags:xe.bind(null,t),fetchRelatedTagResources:ze.bind(null,t),search:ie$1.bind(null,t),listSports:oe$1.bind(null,t),fetchSportsMarketTypes:qe.bind(null,t),listTeams:Be.bind(null,t),fetchPublicProfile:Ud.bind(null,t),listComments:Pb.bind(null,t),fetchCommentsById:Rb.bind(null,t),listCommentsByUserAddress:Tb.bind(null,t)}}function ws(t){return {listCurrentRewards:Lb.bind(null,t),listMarketRewards:Nb.bind(null,t)}}function ue(t){let e=ws(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:Ba.bind(null,t),fetchOrdersScoring:Da.bind(null,t),listUserEarningsForDay:Fa.bind(null,t),fetchTotalEarningsForUserForDay:Ha.bind(null,t),listUserEarningsAndMarketsConfig:Ja.bind(null,t),fetchRewardPercentages:La.bind(null,t)}}function rr(t){return {openRfqSession(){return ae$1(t)}}}function de(t){return t.isSecureClient()?{subscribe(e){return re(t,e)}}:{subscribe(e){return re(t,e)}}}function nr(t){return {createMarketOrder:Vc.bind(null,t),placeMarketOrder:Xc.bind(null,t),createLimitOrder:Zc.bind(null,t),placeLimitOrder:$c.bind(null,t),postOrder:Hc(t),postOrders:Ic(t),cancelOrder:vc.bind(null,t),cancelOrders:xc.bind(null,t),cancelAll:zc.bind(null,t),cancelMarketOrders:Bc.bind(null,t),listOpenOrders:na.bind(null,t),fetchOrder:pa.bind(null,t)}}function sr(t){return {isGaslessReady:()=>Promise.resolve(true),setupTradingApprovals:bb.bind(null,t),approveErc20:Va.bind(null,t),approveErc1155ForAll:Za.bind(null,t),transferErc20:Fe.bind(null,t),splitPosition:Ed.bind(null,t),mergePositions:Nd.bind(null,t),redeemPositions:Sd.bind(null,t)}}function ir(t){return t.isSecureClient()?{...ie(t),...oe(t),...ce(t),...ae(t),...ue(t),...rr(t),...de(t),...nr(t),...sr(t)}:{...ie(t),...oe(t),...ce(t),...ae(t),...ue(t),...de(t)}}var le={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:expectEvmAddress("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:expectEvmAddress("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:expectEvmAddress("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:expectEvmAddress("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:expectEvmAddress("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:expectEvmAddress("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},collateralToken:expectEvmAddress("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:expectEvmAddress("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:expectEvmAddress("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:expectEvmAddress("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:expectEvmAddress("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:expectEvmAddress("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:expectEvmAddress("0xe2222d279d744050d28e00520010520000310F59"),exchangeV3:expectEvmAddress("0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"),protocolV2Router:expectEvmAddress("0x12121212006e4CD160D18e3f00711DA5c3372600"),combinatorialModule:expectEvmAddress("0x30000034706c7d8e12009dab006be20000c031a8"),positionManager:expectEvmAddress("0x006F54F7f9A22e0000CC2AB60031000000ae9fEF"),autoRedeemOperator:expectEvmAddress("0xa1200000d0002264C9a1698e001292D00E1b00af"),safeMultisend:expectEvmAddress("0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761"),relayHub:expectEvmAddress("0xD216153c06E857cD7f72665E0aF1d7D82172F494"),clob:"https://clob.polymarket.com",clobMarketWs:"wss://ws-subscriptions-clob.polymarket.com/ws/market",clobUserWs:"wss://ws-subscriptions-clob.polymarket.com/ws/user",relayer:"https://relayer-v2.polymarket.com",gamma:"https://gamma-api.polymarket.com",data:"https://data-api.polymarket.com",rfq:"https://combos-rfq-api.polymarket.com",rtdsWs:"wss://ws-live-data.polymarket.com",rfqQuoterWs:"wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq",sportsWs:"wss://sports-api.polymarket.com/ws",relayerMaxPolls:100,relayerPollFrequencyMs:2e3},hc={...le,name:"preproduction",clob:"https://clob-preprod-int-v2.polymarket.com",data:"https://data-api-preprod-int.polymarket.com",gamma:"https://gamma-api-preprod-int.polymarket.com",relayer:"https://relayer-v2-preprod-int.polymarket.com"};async function or(t,e,r,n,s){let i=`${e}${r}${n}`;s!==void 0&&(i+=s);let o=await globalThis.crypto.subtle.importKey("raw",xs(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),b=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(i));return Os(Ms(b))}function xs(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(e),n=new Uint8Array(r.length);for(let s=0;s<r.length;s+=1)n[s]=r.charCodeAt(s);return n.buffer}function Ms(t){let e=new Uint8Array(t),r="";for(let n of e)r+=String.fromCharCode(n);return btoa(r)}function Os(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}var u=class{#e;#t;constructor({root:e,resolveHeaders:r}){this.#e=Ls.create({prefixUrl:e,throwHttpErrors:false}),this.#t=r;}get(e,r={}){return this.#s("GET",e,r)}post(e,r={}){return this.#s("POST",e,r)}del(e,r={}){return this.#s("DELETE",e,r)}#r(e){return e.startsWith("/")?e.slice(1):e}#s(e,r,n){return this.#o(this.#n(e,r,n))}async#n(e,r,n){let s=this.#a(e,r,n),i=await this.#t?.(s),o=this.#c(s.headers,i);return s.body!==void 0&&!o.has("content-type")&&o.set("content-type","application/json"),this.#e(this.#r(r),{body:s.body,headers:o,method:e,searchParams:s.params})}#a(e,r,n){return {body:"json"in n?this.#d(n.json):void 0,headers:n.headers,json:"json"in n?n.json:void 0,method:e,params:"params"in n?n.params:void 0,path:r}}#d(e){if(e!==void 0)return JSON.stringify(e)}#c(...e){let r=new Headers;for(let n of e)if(n!==void 0)for(let[s,i]of new Headers(n).entries())r.set(s,i);return r}#o(e$1){return ResultAsync.fromPromise(e$1.then(async r=>{if(r.ok)return r;if(r.status===429)throw new e(`Request to ${r.url} was rate limited`);let n=await this.#i(r);throw new d$1(n,{status:r.status})}),r=>r instanceof e||r instanceof d$1?r:c.fromError(r))}async#i(e){let r=e.headers.get("content-type")?.toLowerCase();if(r?.includes("application/json")){let{error:s}=await e.clone().json().catch(()=>({}));if(s)return `${String(s)} (${e.url})`}if(r?.includes("text/plain")){let s=await e.clone().text().then(i=>i.trim(),()=>"");if(s)return `${s} (${e.url})`}return e.headers.get("server")?.toLowerCase()?.includes("cloudflare")?`Request to ${e.url} was blocked by Cloudflare with status ${e.status}`:r?.includes("text/html")||r?.includes("application/xhtml+xml")?`Request to ${e.url} failed with status ${e.status} and an unexpected HTML response body`:`Request to ${e.url} failed with status ${e.status} and unreadable response body`}};function m(t,e){let r;return {close:()=>(r===void 0&&(r=Promise.resolve(t.return()).then(()=>e())),r),[Symbol.asyncIterator](){return t[Symbol.asyncIterator]()}}}var Fs=1e4,Bs=3e4,Ds=5e3,Ws=10*6e4,Qs=3e4,A=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},Fs);}handleMessage(e){return e!=="PONG"?false:(this.#e=Date.now(),true)}isStale(e){return e-this.#e>Bs}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},F=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},Ds);}handleMessage(){return this.#e=Date.now(),false}isStale(e){return e-this.#e>Ws}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},B=class{#e=0;#t;start(e){this.#e=Date.now(),this.#t=e;}stop(){this.#t=void 0;}handleMessage(e){return e!=="ping"?false:(this.#e=Date.now(),this.#t?.("pong"),true)}isStale(e){return e-this.#e>Qs}};var Hs=5e3,Ks=250,js=3e4,l=class{#e;#t=0;schedule(e){if(this.#e!==void 0||!e.shouldReconnect())return;let r=Vs(this.#t,{baseMs:Ks,maxMs:js});this.#t+=1,this.#e=setNonBlockingTimeout(()=>{this.#e=void 0,this.#r(e);},r);}stop(){this.#e!==void 0&&(clearTimeout(this.#e),this.#e=void 0);}resetBackoff(){this.#t=0,this.stop();}async#r(e){if(e.shouldReconnect())try{await e.reconnect();}catch{this.schedule(e);}}},d=class{#e;#t;#r;#s;constructor(e={}){this.#e=e.heartbeat;}connect(e){if(this.#t?.readyState===WebSocket.OPEN)return Promise.resolve({reusedOpenSocket:true});if(this.#c(),this.#r!==void 0)return this.#r;let n=this.#a(e).then(()=>({reusedOpenSocket:false})).catch(s=>{throw this.#r===n&&(this.#r=void 0),s});return this.#r=n,n}send(e){return this.#n(JSON.stringify(e))}#n(e){return this.#t?.readyState!==WebSocket.OPEN?false:(this.#t.send(e),true)}async close(){let e=await this.#u();this.#i(),!(e===void 0||e.readyState===WebSocket.CLOSED)&&await new Promise(r=>{e.addEventListener("close",()=>r(),{once:true}),e.readyState!==WebSocket.CLOSING&&e.close();});}async#a(e){let r=await e.prepare?.();return new Promise((n,s)=>{let i=Ns(e.url,e.headers),o=()=>{i.removeEventListener("error",b),this.#d(i),this.#o(),e.onOpen(r),n(i);},b=R=>{i.removeEventListener("open",o),s(new c(`WebSocket connection failed: ${e.url}`,{cause:R}));};i.addEventListener("open",o,{once:true}),i.addEventListener("error",b,{once:true}),i.addEventListener("message",R=>{if(this.#t!==i)return;let x=String(R.data);if(this.#e?.handleMessage(x))return;let M;try{M=JSON.parse(x);}catch{return}e.onMessage(M);}),i.addEventListener("close",()=>{this.#t===i&&(this.#c(),e.onClose());}),i.addEventListener("error",()=>e.onError());})}#d(e){this.#t=e,this.#r=void 0;}#c(){this.#i(),this.#t=void 0;}#o(){this.#i();let e=this.#e;e!==void 0&&(e.start(r=>this.#n(r)),this.#s=setNonBlockingInterval(()=>{if(!e.isStale(Date.now()))return;let r=this.#t;r?.readyState===WebSocket.OPEN&&r.close();},Hs));}#i(){this.#s!==void 0&&(clearInterval(this.#s),this.#s=void 0),this.#e?.stop();}async#u(){let e=this.#t,r=this.#r;return this.#t=void 0,this.#r=void 0,e!==void 0?e:r?.then(()=>this.#t,()=>{})}};function Ns(t,e){if(e===void 0)return new WebSocket(t);try{let r=Reflect.construct(WebSocket,[t,{headers:e}]);if(r instanceof WebSocket)return r}catch(r){throw new c("WebSocket headers require a header-capable WebSocket implementation.",{cause:r})}throw new c("WebSocket headers require a header-capable WebSocket implementation.")}function Vs(t,e){let r=Math.min(e.baseMs*2**t,e.maxMs);return Math.random()*r}var p=class{#e=new Set;#t;constructor(e){this.#t=e?.deriveServerState??(()=>{});}add(e,r={}){let n={queue:pushable({objectMode:true})};r.matches!==void 0&&(n.matches=r.matches);let s={subscription:e,subscriber:n};return {change:this.#r(s),entry:s}}#r(e){let r=this.serverState();return this.#e.add(e),{before:r,after:this.serverState()}}remove(e){let r=this.serverState();return this.#e.delete(e),e.subscriber.queue.end(),{before:r,after:this.serverState()}}dispatch(e){for(let{subscriber:r}of this.#e)(r.matches===void 0||r.matches(e))&&r.queue.push(e);}hasActiveSubscriptions(){return this.#e.size>0}endAll(e){for(let{subscriber:r}of this.#e)r.queue.end(e);this.#e.clear();}serverState(){return this.#t(this.#e)}};function pe(t,e,r){let n=D(r.assetsIds,e.assetsIds),s=D(e.assetsIds,r.assetsIds);n.length>0&&t(ar(n,r.customFeatureEnabled));let i=r.assetsIds[0];n.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&i!==void 0&&t(ar([i],r.customFeatureEnabled)),s.length>0&&t($s(s));}function fe(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(dr(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(ur(r.markets));return}let n=D(r.markets,e.markets),s=D(e.markets,r.markets);n.length>0&&t(ur(n)),s.length>0&&t(dr(s));}function lr(t){let e=new Set,r=false;for(let{subscription:n}of t){for(let s of n.tokenIds)e.add(s);r||=n.customFeatureEnabled===true;}return {assetsIds:Array.from(e),customFeatureEnabled:r}}function pr(t){let e=false,r=new Set;for(let{subscription:n}of t){if(Sr(n)){e=true;continue}for(let s of n.markets??[])r.add(s);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function fr(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function ar(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function $s(t){return {assets_ids:t,operation:"unsubscribe"}}function mr(t,e){let r={auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},type:"user"};return t.includeAllMarkets||(r.markets=t.markets),r}function ur(t){return {markets:t,operation:"subscribe"}}function dr(t){return {markets:t,operation:"unsubscribe"}}function hr(t){return e=>{switch(e.type){case "price_change":return e.payload.priceChanges.some(r=>t.tokenIds.includes(r.tokenId));case "new_market":return t.customFeatureEnabled===true;case "market_resolved":return t.customFeatureEnabled===true&&(e.payload.tokenIds??[]).some(r=>t.tokenIds.includes(r));case "best_bid_ask":return t.customFeatureEnabled===true&&t.tokenIds.includes(e.payload.tokenId);default:return t.tokenIds.includes(e.payload.tokenId)}}}function yr(t){if(Sr(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function Sr(t){return (t.markets?.length??0)===0}function D(t,e){let r=new Set(e);return t.filter(n=>!r.has(n))}var S=class{#e;#t;#r=new d({heartbeat:new A});#s=new l;#n=new p({deriveServerState:lr});constructor(e){this.#e=e.url;}async subscribe(e){let{change:r,entry:n}=this.#n.add(e,{matches:hr(e)});return await this.#a(n,r),m(n.subscriber.queue,()=>this.#d(n))}async#a(e,r){let{before:n,after:s}=r;try{(await this.#o()).reusedOpenSocket&&pe(o=>this.#r.send(o),n,s);}catch(i){throw await this.#d(e),i}}async#d(e){let{before:r,after:n}=this.#n.remove(e);if(!this.#n.hasActiveSubscriptions()){await this.close();return}pe(s=>this.#r.send(s),r,n);}async close(){this.#t===void 0&&(this.#t=this.#c().finally(()=>{this.#t=void 0;})),await this.#t;}async#c(){this.#s.stop(),this.#n.endAll(),await this.#r.close();}#o(){return this.#r.connect({onClose:()=>this.#l(),onError:()=>this.#p(),onMessage:e=>this.#u(e),onOpen:()=>this.#i(),url:this.#e})}#i(){this.#s.resetBackoff(),this.#f();}#u(e){let r=Array.isArray(e)?e:[e];for(let n of r){let s=MarketEventSchema.safeParse(n);s.success&&this.#n.dispatch(s.data);}}#l(){this.#n.hasActiveSubscriptions()&&this.#m();}#p(){}#f(){this.#r.send(fr(this.#n.serverState()));}#m(){this.#s.schedule({reconnect:()=>this.#o(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};var q=class{#e;#t;#r;#s=new d({heartbeat:new A});#n=new l;#a=new p({deriveServerState:pr});constructor(e){this.#e=e.url,this.#t=e.credentials;}async subscribe(e){let{change:r,entry:n}=this.#a.add(e,{matches:yr(e)});return await this.#d(n,r),m(n.subscriber.queue,()=>this.#c(n))}async#d(e,r){let{before:n,after:s}=r;try{(await this.#i()).reusedOpenSocket&&fe(o=>this.#s.send(o),n,s);}catch(i){throw await this.#c(e),i}}async#c(e){let{before:r,after:n}=this.#a.remove(e);if(!this.#a.hasActiveSubscriptions()){await this.close();return}fe(s=>this.#s.send(s),r,n);}async close(){this.#r===void 0&&(this.#r=this.#o().finally(()=>{this.#r=void 0;})),await this.#r;}async#o(){this.#n.stop(),this.#a.endAll(),await this.#s.close();}#i(){return this.#s.connect({onClose:()=>this.#p(),onError:()=>this.#f(),onMessage:e=>this.#l(e),onOpen:e=>this.#u(e),prepare:()=>this.#t,url:this.#e})}#u(e){this.#n.resetBackoff(),this.#m(e);}#l(e){let r=Array.isArray(e)?e:[e];for(let n of r){let s=UserEventSchema.safeParse(n);s.success&&this.#a.dispatch(s.data);}}#p(){this.#a.hasActiveSubscriptions()&&this.#h();}#f(){}#m(e){this.#s.send(mr(this.#a.serverState(),e));}#h(){this.#n.schedule({reconnect:()=>this.#i(),shouldReconnect:()=>this.#a.hasActiveSubscriptions()});}};function Rr(t,e){return {...e,quote:r=>t.quote(e,r)}}function gr(t,e){let r=e.rfqId,n=e.quoteId;return {...e,confirm:()=>t.respondToConfirmation(r,n,RfqConfirmationDecision.Confirm),decline:()=>t.respondToConfirmation(r,n,RfqConfirmationDecision.Decline)}}function Ar(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function qr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function vr(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function Pr(t,e){let r=X(t);return {auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},identity:{maker_address:r.maker,signature_type:r.signatureType,signer_address:r.signer},type:"auth"}}function Cr(t,e){return {price_e6:e.price.toString(),rfq_id:t.rfqId,signed_order:e.signedOrder,size_e6:e.size.toString(),type:"RFQ_QUOTE"}}function Er(t,e,r){let n=X(t);return {maker_address:n.maker,quote_id:r,rfq_id:e,signer_address:n.signer,type:"RFQ_QUOTE_CANCEL"}}function kr(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var W=class{#e=new Map;#t;constructor(e){this.#t=e;}waitFor(e,r){let n=Zs(),s,i=setNonBlockingTimeout(()=>{this.remove(e,s),n.reject(new f(r));},this.#t);s=n.promise.finally(()=>clearTimeout(i));let o=this.#e.get(e)??[];return o.push({...n,promise:s}),this.#e.set(e,o),s}resolve(e,r){let n=this.#e.get(e),s=n?.shift();s!==void 0&&(n!==void 0&&n.length===0&&this.#e.delete(e),s.resolve(r));}reject(e,r){let n=this.#e.get(e),s=n?.shift();s!==void 0&&(n!==void 0&&n.length===0&&this.#e.delete(e),s.reject(r));}remove(e,r){let n=this.#e.get(e);if(n===void 0)return;let s=n.filter(i=>i.promise!==r);s.length===0?this.#e.delete(e):this.#e.set(e,s);}rejectAll(e){for(let r of this.#e.values())for(let n of r)n.reject(e);this.#e.clear();}};function Zs(){let t,e;return {promise:new Promise((n,s)=>{t=n,e=s;}),reject:e,resolve:t}}var wr="0x0000000000000000000000000000000000000000000000000000000000000000";async function Mr(t){let e=X(t.account),r={builder:wr,maker:e.maker,makerAmount:toBaseUnits(Xs(t.orderSide,t.orderPrice,t.size)),metadata:wr,salt:ri().toString(),side:ti(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(ei(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},n;try{n=await t.signer.signTypedData(Jc({domain:xr(t),order:r}));}catch(s){throw j.fromError(s,"Could not sign the RFQ quote order.")}return {...r,signature:Kc({domain:xr(t),order:r,signature:n})}}function xr(t){return {chainId:t.chainId,exchange:t.exchange,protocolVersion:"3"}}function Xs(t,e,r){return t===OrderSide.SELL?r.toString():((e*r+999999n)/1000000n).toString()}function ei(t,e,r){return t===OrderSide.SELL?(e*r/1000000n).toString():r.toString()}function ti(t){return t===OrderSide.BUY?0:1}function ri(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var Lr=DecimalishSchema.transform(t=>Dr(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),ii=z.strictObject({price:Lr.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:Lr.optional(),source:z.enum(["collateral","inventory"]).default("collateral")});function Fr(t){return U$1(t,ii)}async function Br(t){let e=t.response.price,r=t.response.size===void 0?ui(t.request.requestedSize,e):t.response.size,n=await Mr({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:ci(t.request,t.response.source,e),orderSide:ai(t.response.source),signer:t.signer,size:r,tokenId:oi(t.request,t.response.source)});return {price:e,signedOrder:n,size:r}}function oi(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function ci(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function ai(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function ui(t,e){let r=Dr(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function Dr(t){let e=/^(\d+)(?:\.(\d*))?$/.exec(t);if(e===null)throw new a("Value must be a valid decimal.");let[,r="",n=""]=e;if(n.length>6)throw new a("Value must have at most 6 decimal places.");let s=BigInt(r)*1000000n+BigInt(n.padEnd(6,"0"));if(s<=0n)throw new a("Value must be greater than 0.");return s}var mi=3e4,hi=3e4,v=class{#e;#t;#r;#s;#n;#a;#d;#c;#o;#i;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#r=e.credentials,this.#s=e.exchange,this.#n=e.headers,this.#a=e.signer,this.#d=e.url;}async connect(){if(this.#c!==void 0){if(!this.#c.closed)return this.#c;this.#c=void 0;}if(this.#i!==void 0)return this.#i;let e=new be({account:this.#e,chainId:this.#t,credentials:this.#r,exchange:this.#s,headers:this.#n,onClose:()=>this.#u(e),signer:this.#a,url:this.#d});this.#o=e;let r;return r=(async()=>{try{return await e.connect(),this.#c=e,e}catch(n){throw await e.close(),n}finally{this.#i===r&&(this.#i=void 0),this.#o===e&&(this.#o=void 0);}})(),this.#i=r,r}async close(){let e=this.#c,r=this.#o,n=this.#i;this.#c=void 0,this.#o=void 0,this.#i=void 0,await Promise.allSettled([e?.close(),r?.close(),n?.catch(()=>{})]).then(()=>{});}#u(e){this.#c===e&&(this.#c=void 0),this.#o===e&&(this.#o=void 0);}},be=class{#e;#t;#r;#s;#n;#a;#d;#c;#o=new d;#i=pushable({objectMode:true});#u=new W(hi);#l;#p;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#r=e.credentials,this.#s=e.exchange,this.#n=e.headers,this.#a=e.onClose,this.#d=e.signer,this.#c=e.url;}get closed(){return this.#l!==void 0}async connect(){let e=yi();this.#p=e;let r=setNonBlockingTimeout(()=>{e.reject(new c("RFQ quoter authentication timed out."));},mi);try{await this.#o.connect({headers:this.#n,onClose:()=>this.#A(),onError:()=>{},onMessage:n=>this.#R(n),onOpen:()=>this.#b(),url:this.#c}),await e.promise;}finally{clearTimeout(r),this.#p=void 0;}}async#f(e){if(!this.#o.send(e))throw new c("RFQ quoter websocket is not open.")}async close(){this.#l===void 0&&(this.#l=this.#m()),await this.#l;}[Symbol.asyncIterator](){return this.#i[Symbol.asyncIterator]()}async#m(){let e=new c("RFQ quoter websocket closed.");await this.#y(e);}async#h(e){this.#l===void 0&&(this.#l=this.#y(e)),await this.#l;}async#y(e){this.#S(e),this.#i.end(),await this.#o.close(),this.#a();}#S(e){this.#p?.reject(e),this.#u.rejectAll(e);}#b(){this.#o.send(Pr(this.#e,this.#r));}#R(e){if(this.#l!==void 0||!RfqKnownInboundMessageSchema.safeParse(e).success)return;let r=RfqQuoterInboundMessageSchema.safeParse(e);if(!r.success){let s=new c("Invalid RFQ quoter message.",{cause:r.error});this.#h(s);return}let n=r.data;switch(n.type){case "auth":this.#g(n);return;case "quote_request":this.#i.push(Rr(this,n));return;case "quote_ack":this.#u.resolve(Q(n.rfqId),Ar(n));return;case "quote_cancel_ack":this.#u.resolve(ye(n.rfqId,n.quoteId),qr(n));return;case "confirmation_request":this.#i.push(gr(this,n));return;case "confirmation_ack":this.#u.resolve(Se(n.rfqId,n.quoteId),vr(n));return;case "execution_update":this.#i.push(n);return;case "rfq_error":this.#q(n);return}}#g(e){if(e.success===true){this.#p?.resolve(void 0);return}this.#p?.reject(new c(`RFQ quoter authentication failed: ${e.error}`));}#A(){this.#a(),this.close();}#q(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#h(new c("Uncorrelated RFQ quoter error."));return}this.#u.reject(Q(e.rfqId),new Vd(e.message,{code:e.code,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_QUOTE_CANCEL"){if(e.rfqId===void 0||e.quoteId===void 0){this.#h(new c("Uncorrelated RFQ quoter error."));return}this.#u.reject(ye(e.rfqId,e.quoteId),new Xd(e.message,{code:e.code,quoteId:e.quoteId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_CONFIRMATION_RESPONSE"){if(e.rfqId===void 0||e.quoteId===void 0){this.#h(new c("Uncorrelated RFQ quoter error."));return}this.#u.reject(Se(e.rfqId,e.quoteId),new Zd(e.message,{code:e.code,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let n=Fr(r),s=await Br({account:this.#e,chainId:this.#t,exchange:this.#s,request:e,response:n,signer:this.#d}),i=this.#u.waitFor(Q(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#f(Cr(e,s)),await i}catch(o){throw this.#u.remove(Q(e.rfqId),i),o}}async cancelQuote(e){let r=ye(e.rfqId,e.quoteId),n=this.#u.waitFor(r,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#f(Er(this.#e,e.rfqId,e.quoteId)),await n}catch(s){throw this.#u.remove(r,n),s}}async respondToConfirmation(e,r,n){let s=Se(e,r),i=this.#u.waitFor(s,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#f(kr(e,r,n)),await i}catch(o){throw this.#u.remove(s,i),o}}};function Q(t){return `ACK_RFQ_QUOTE:${t}`}function ye(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function Se(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function yi(){let t,e;return {promise:new Promise((n,s)=>{t=n,e=s;}),reject:e,resolve:t}}var P=class{#e;#t;#r=new d({heartbeat:new F});#s=new l;#n=new p({deriveServerState:gi});constructor(e){this.#e=e;}async subscribe(e){let{change:r,entry:n}=this.#n.add(e,{matches:Pi(e)});return await this.#a(n,r),m(n.subscriber.queue,()=>this.#d(n))}async#a(e,r){try{if((await this.#o()).reusedOpenSocket){let{before:s,after:i}=r,o=bi(s,i);this.#m(o);}}catch(n){throw await this.#d(e),n}}async#d(e){let{before:r,after:n}=this.#n.remove(e),s=Ri(r,n);this.#h(s),this.#n.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#c().finally(()=>{this.#t=void 0;})),await this.#t;}async#c(){this.#s.stop(),this.#n.endAll(),await this.#r.close();}#o(){return this.#r.connect({onClose:()=>this.#l(),onError:()=>this.#p(),onMessage:e=>this.#u(e),onOpen:()=>this.#i(),url:this.#e})}#i(){this.#s.resetBackoff(),this.#f();}#u(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#n.dispatch(r.data);}#l(){this.#n.hasActiveSubscriptions()&&this.#y();}#p(){}#f(){this.#m(Array.from(this.#n.serverState().values()));}#m(e){e.length!==0&&this.#r.send(Ai(e));}#h(e){e.length!==0&&this.#r.send(qi(e));}#y(){this.#s.schedule({reconnect:()=>this.#o(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};function bi(t,e){return Array.from(e).flatMap(([r,n])=>t.has(r)?[]:[n])}function Ri(t,e){return Array.from(t).flatMap(([r,n])=>e.has(r)?[]:[n])}function gi(t){let e=new Map;for(let{subscription:r}of t)for(let n of vi(r))e.has(n.key)||e.set(n.key,n);return e}function Ai(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function qi(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function vi(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>_("comments",e));case "prices.crypto.binance":return [_("crypto_prices","update")];case "prices.crypto.chainlink":return [_("crypto_prices_chainlink","update")];case "prices.equity.pyth":return [_("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function _(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function Pi(t){switch(t.topic){case "comments":return e=>!(e.topic!=="comments"||t.types!==void 0&&t.types.length>0&&!t.types.includes(e.type)||(t.parentEntityId!==void 0||t.parentEntityType!==void 0)&&(!(e.type==="comment_created"||e.type==="comment_removed")||t.parentEntityId!==void 0&&e.payload.parentEntityID!==t.parentEntityId||t.parentEntityType!==void 0&&e.payload.parentEntityType!==t.parentEntityType));case "prices.crypto.binance":return e=>e.topic==="prices.crypto.binance"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink":return e=>e.topic==="prices.crypto.chainlink"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.equity.pyth":return e=>e.topic==="prices.equity.pyth"&&e.payload.symbol.toLowerCase()===t.symbol.toLowerCase()&&(t.types===void 0||t.types.length===0||t.types.includes(e.type));default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}var C=class{#e;#t;#r=new d({heartbeat:new B});#s=new l;#n=new p;constructor(e){this.#e=e.url;}async subscribe(e){let{entry:r}=this.#n.add(e);return await this.#a(r),m(r.subscriber.queue,()=>this.#d(r))}async#a(e){try{await this.#o();}catch(r){throw await this.#d(e),r}}async#d(e){this.#n.remove(e),this.#n.hasActiveSubscriptions()||await this.close();}async close(){this.#t===void 0&&(this.#t=this.#c().finally(()=>{this.#t=void 0;})),await this.#t;}async#c(){this.#s.stop(),this.#n.endAll(),await this.#r.close();}#o(){return this.#r.connect({onClose:()=>this.#l(),onError:()=>this.#p(),onMessage:e=>this.#u(e),onOpen:()=>this.#i(),url:this.#e})}#i(){this.#s.resetBackoff();}#u(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#n.dispatch(r.data);}#l(){this.#n.hasActiveSubscriptions()&&this.#f();}#p(){}#f(){this.#s.schedule({reconnect:()=>this.#o(),shouldReconnect:()=>this.#n.hasActiveSubscriptions()});}};var U=class{#e;#t;get context(){return this.#e}get decorators(){return this.#t}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get rfq(){return this.context.rfq}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??false}constructor(e){this.#e=e,this.#t=[];}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#t.push(e);}},Mi=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),Oi=z.object({wallet:EvmAddressSchema,credentials:Mi.optional(),nonce:z.number().int().nonnegative().optional()}).superRefine((t,e)=>{t.credentials!==void 0&&t.nonce!==void 0&&e.addIssue({code:"custom",message:"`credentials` and `nonce` are mutually exclusive.",path:["nonce"]});}).transform(t=>t.credentials!==void 0?{wallet:t.wallet,credentials:t.credentials}:t.nonce!==void 0?{wallet:t.wallet,nonce:t.nonce}:{wallet:t.wallet}),H=class extends U{constructor(e){super({apiKey:e.apiKey,environment:e.environment,data:new u({root:e.environment.data}),gamma:new u({root:e.environment.gamma}),clob:new u({root:e.environment.clob,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new u({root:e.environment.relayer,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new u({root:e.environment.rfq}),rpc:new V({url:e.environment.rpc}),webSockets:{clobMarket:new S({url:e.environment.clobMarketWs}),sports:new C({url:e.environment.sportsWs}),rtds:new P(e.environment.rtdsWs)}});}isSecureClient(){return false}isPublicClient(){return true}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close()]).then(()=>{});}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,r){let n=U$1(e,Oi);return Promise.resolve(async function*(){let s=Math.floor(Date.now()/1e3),i=n?.nonce??0,o=expectEvmAddress(yield _$1()),b=expectEvmAddress(n.wallet),R=W$1(this.environment,o,b);if(n.credentials!==void 0){let Ae=this.#e(n.credentials,R,r);try{if((await L(Ae)).includes(n.credentials.key))return Ae}catch(O){if(!(O instanceof d$1)||O.status!==401)throw O}}let x=yield {kind:"signAuthMessage",payload:tr({address:o,chainId:this.environment.chainId,nonce:i,timestamp:s})},M=await J(this,{address:o,nonce:i,signature:expectEvmSignature(x),timestamp:s});return this.#e(M,R,r)}.call(this))}#e(e,r,n){let s=new ge({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,signer:n});for(let i of this.decorators)s.extend(i);return s}},ge=class extends U{#e=false;get context(){return invariant(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=true;}constructor(e){super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,signer:e.signer,clob:new u({root:e.environment.clob,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new u({root:e.environment.relayer,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rpc:new V({url:e.environment.rpc}),gamma:new u({root:e.environment.gamma}),data:new u({root:e.environment.data}),rfq:new u({root:e.environment.rfq}),secureClob:new u({resolveHeaders:async r=>({...await this.resolveClobHeaders(r),...await this.#t(r)}),root:e.environment.clob}),webSockets:{clobMarket:new S({url:e.environment.clobMarketWs}),clobUser:new q({credentials:e.credentials,url:e.environment.clobUserWs}),rfqQuoter:new v({account:e.account,chainId:e.environment.chainId,credentials:e.credentials,exchange:e.environment.exchangeV3,headers:e.environment.rfqQuoterWsHeaders,signer:e.signer,url:e.environment.rfqQuoterWs}),sports:new C({url:e.environment.sportsWs}),rtds:new P(e.environment.rtdsWs)}});}get credentials(){return this.context.credentials}get account(){return this.context.account}get signer(){return this.context.signer}setupGaslessWallet(){return Promise.resolve(this)}get secureClob(){return this.context.secureClob}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.clobUser.close(),this.webSockets.rfqQuoter.close()]).then(()=>{});}isSecureClient(){return true}isPublicClient(){return false}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}async endAuthentication(){let e=this.closeSubscriptions(),{apiKey:r,environment:n}=this.context;try{await N(this);}finally{this.endAuthenticationLifecycle(),await e;}let s=new H({apiKey:r,environment:n});for(let i of this.decorators)s.extend(i);return s}async#t(e){try{let r=Math.floor(Date.now()/1e3);return {POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await or(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw j.fromError(r,"Could not sign the L2-authenticated request")}}};function _r(t={}){return new H({environment:t.environment??le,apiKey:t.apiKey}).extend(ir)}var Ii=k(h,e,d$1,j,f,g,c,b,a),Li=k(a);async function Fi(t){let e=_r({environment:t.environment,apiKey:t.apiKey}),r=await Bi(e,t),n=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(Z(t.signer));if(n.account.walletType===WalletType.EOA||await ca(n,{wallet:n.account.wallet,type:n.account.walletType}))return n;if(n.account.walletType===WalletType.DEPOSIT_WALLET)return await Di(n),n;throw new a(`Wallet ${n.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`)}async function Bi(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress());return Y(t.rpc,r,t.environment.walletDerivation)}async function Di(t){let e=await Y(t.rpc,t.account.signer,t.environment.walletDerivation);if(!isSameEvmAddress(t.account.wallet,e))throw new a(`Wallet ${t.account.wallet} does not match the expected Deposit Wallet ${e} for this signer, nor a deployed wallet address.`);await(await fa(t)).wait();}
|
|
2
|
-
export{
|
|
1
|
+
import {ra as ra$1,Ba as Ba$1,za,xa as xa$1,Va,Sd,Qd,Od,Md,Ld,Id,lc as lc$1,jc,hc as hc$1,jb,Ta,vc,xc,Jc,Pb,Nb,Lb,Jb,Hb,Fb,Db,Bb,zb,nb,lb,fc as fc$1,Zb,Xb,Vb,ze,gf,Xe as Xe$1,Ve,Pe,ef,cf,af,_e as _e$1,Te,Re,tc as tc$1,rc as rc$1,pc,nc as nc$1,dc,bc,$b,Gd,Dd,Cd,Fd,Ra,Pa,Na,La as La$1,Ja as Ja$1,Ha,He as He$1,Ye,va as va$1,ta as ta$1,Hc,Fc,Dc,Bc,Oc,Nc,fd,dd,bd,$c,xe as xe$1,se as se$1,je as je$1,kf,db,$a,hb,aa as aa$1,ha as ha$1,$,ka as ka$1,ud,sd,qd,md,kd,id,wd,od,zc,Tb,Rb,Y,X as X$1,ba,Z as Z$1,O as O$1,M as M$1,Q as Q$1,G,gd,Ae,Ce,Ee,pa as pa$1,_ as _$1,ca,da,Pc as Pc$1,Qc}from'./chunk-GZWA532J.js';export{cb as ApproveErc1155ForAllError,_a as ApproveErc20Error,Ec as CancelAllError,Gc as CancelMarketOrdersError,Ac as CancelOrderError,Cc as CancelOrdersError,C as CombinatorialPrepareConditionCallError,Td as ComboPositionStatus,cd as CreateLimitOrderError,_c as CreateMarketOrderError,q as CtfRedeemPositionsCallError,Rd as DownloadAccountingSnapshotError,Aa as DropNotificationsError,b as Erc20ApprovalCallError,m as Erc20TransferCallError,Ic as EstimateMarketPriceError,qa as FetchClosedOnlyModeError,Wb as FetchCommentsByIdError,ac as FetchEventError,ec as FetchEventLiveVolumeError,cc as FetchEventTagsError,Kb as FetchLastTradePriceError,Mb as FetchLastTradePricesError,qc as FetchMarketError,sc as FetchMarketTagsError,kb as FetchMidpointError,mb as FetchMidpointsError,ya as FetchNotificationsError,Cb as FetchOrderBookError,Eb as FetchOrderBooksError,ua as FetchOrderError,Ga as FetchOrderScoringError,Ia as FetchOrdersScoringError,Nd as FetchPortfolioValueError,yb as FetchPriceError,Ob as FetchPriceHistoryError,Ab as FetchPricesError,ye as FetchPublicProfileError,df as FetchRelatedTagResourcesError,bf as FetchRelatedTagsError,Qa as FetchRewardPercentagesError,Se as FetchSeriesError,We as FetchSportsMarketTypesError,Gb as FetchSpreadError,Ib as FetchSpreadsError,$e as FetchTagError,Ma as FetchTotalEarningsForUserForDayError,Pd as FetchTradedMarketCountError,wa as ListAccountTradesError,Ua as ListActivityError,gc as ListBuilderLeaderboardError,ib as ListBuilderTradesError,ic as ListBuilderVolumeError,Jd as ListClosedPositionsError,oc as ListComboMarketsError,Kd as ListComboPositionsError,Yb as ListCommentsByUserAddressError,Ub as ListCommentsError,Qb as ListCurrentRewardsError,_b as ListEventsError,uc as ListMarketHoldersError,yc as ListMarketPositionsError,Sb as ListMarketRewardsError,mc as ListMarketsError,wc as ListOpenInterestError,sa as ListOpenOrdersError,Hd as ListPositionsError,Qe as ListSeriesError,Ue as ListSportsError,Ze as ListTagsError,ff as ListTeamsError,kc as ListTraderLeaderboardError,Sa as ListTradesError,Oa as ListUserEarningsAndMarketsConfigError,Ka as ListUserEarningsForDayError,a as MAX_UINT256,t as MergePositionsCallError,ne as MergePositionsError,y as MergeV2CallError,Ge as OpenRfqSessionError,o as PerpsDepositCallError,ed as PlaceLimitOrderError,ad as PlaceMarketOrderError,Lc as PostOrderError,Mc as PostOrdersError,we as RedeemPositionsError,A as RedeemV2CallError,De as RfqCancelQuoteError,Ce as RfqCancelQuoteRejectedError,Ie as RfqConfirmationDecision,Fe as RfqConfirmationError,Ee as RfqConfirmationRejectedError,Je as RfqDirection,Ke as RfqErrorCode,Le as RfqExecutionStatus,Be as RfqQuoteError,Ae as RfqQuoteRejectedError,Me as RfqRequestedSizeUnit,Ne as RfqSide,Oe as SearchError,gb as SetupTradingApprovalsError,r as SplitPositionCallError,ee as SplitPositionError,w as SplitV2CallError,jf as TransferErc20Error,Wa as WaitForTransactionError,D as combinatorialPrepareConditionCall,v as ctfRedeemPositionsCall,l as decodeErc1155BalanceOfBatchResult,j as decodeErc1155BalanceOfResult,h as decodeErc1155IsApprovedForAllResult,e as decodeErc20AllowanceResult,E as encodeProxyCall,F as encodeSafeMultisendCall,f as erc1155ApprovalForAllCall,k as erc1155BalanceOfBatchCall,i as erc1155BalanceOfCall,g as erc1155IsApprovedForAllCall,d as erc20AllowanceCall,c as erc20ApprovalCall,n as erc20TransferCall,Xa as expectTransactionHandle,u as mergePositionsCall,z as mergeV2Call,p as perpsDepositCall,B as redeemV2Call,s as splitPositionCall,x as splitV2Call}from'./chunk-GZWA532J.js';import {a,k,h,e,d,j,f,g as g$1,c,b}from'./chunk-E2CLUN5M.js';export{h as CancelledSigningError,i as InsufficientLiquidityError,e as RateLimitError,d as RequestRejectedError,j as SigningError,f as TimeoutError,g as TransactionFailedError,c as TransportError,b as UnexpectedResponseError,a as UserInputError,k as makeErrorGuard}from'./chunk-E2CLUN5M.js';import {TxHashSchema,PaginationCursorSchema,DecimalishSchema,ApiKeySchema,EvmAddressSchema,toDecimalString,toPaginationCursor,toBaseUnits,OrderSide}from'@polymarket/bindings';export{OrderSide,OrderType}from'@polymarket/bindings';export{SignatureType}from'@polymarket/bindings/clob';export{ActivityType}from'@polymarket/bindings/data';import {WalletType}from'@polymarket/bindings/gamma';export{WalletType}from'@polymarket/bindings/gamma';import {PerpsPnlIntervalSchema,PerpsWithdrawalStatusSchema,PerpsDepositStatusSchema,PerpsInstrumentIdSchema,PerpsClientOrderIdSchema,PerpsOrderIdSchema,PerpsTimeInForceSchema,PerpsDecimalInputSchema,PerpsCommandAckSchema,FetchPerpsBalancesResponseSchema,FetchPerpsPortfolioResponseSchema,FetchPerpsAccountConfigResponseSchema,FetchPerpsOpenOrdersResponseSchema,FetchPerpsOrdersResponseSchema,ListPerpsFillsResponseSchema,ListPerpsFundingPaymentsResponseSchema,ListPerpsDepositsResponseSchema,ListPerpsWithdrawalsResponseSchema,ListPerpsEquityHistoryResponseSchema,ListPerpsPnlHistoryResponseSchema,RawPerpsOrderCommandAckSchema}from'@polymarket/bindings/perps';export{PerpsDepositStatus,PerpsInstrumentCategory,PerpsInstrumentType,PerpsInternalTransferDirection,PerpsKlineInterval,PerpsSide,PerpsTimeInForce,PerpsWithdrawalStatus}from'@polymarket/bindings/perps';import {z}from'zod';import {expectEvmAddress,isSameEvmAddress,expectEvmSignature,ResultAsync,invariant,setNonBlockingInterval,setNonBlockingTimeout,unwrap,expectPresent}from'@polymarket/types';import yo from'ky';import {PerpsMarketDataEventSchema,RealtimeEventSchema,SportsResultEventSchema,MarketEventSchema,UserEventSchema,PerpsSessionUpdateEventSchema}from'@polymarket/bindings/subscriptions';import {pushable}from'it-pushable';import {RfqKnownInboundMessageSchema,RfqQuoterInboundMessageSchema,RfqConfirmationDecision,RfqRequestedSizeUnit,RfqDirection}from'@polymarket/bindings/rfq';var io=z.object({POLY_BUILDER_API_KEY:z.string().min(1),POLY_BUILDER_TIMESTAMP:z.string().min(1),POLY_BUILDER_PASSPHRASE:z.string().min(1),POLY_BUILDER_SIGNATURE:z.string().min(1)});function oo(t){return new we(t)}function ao(t){return new xe(t)}var we=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return true}get supportGasless(){return true}async authorize(e){try{return await this.#s(e)}catch(r){throw j.fromError(r,"Could not authorize the builder-authenticated request")}}async#t(){let e=this.#e.headers,r=typeof e=="function"?await e():e,s=new Headers(r);return s.set("content-type","application/json"),s}async#s(e){let r=await fetch(this.#e.url,{body:JSON.stringify({body:e.body,method:e.method,path:e.path}),credentials:this.#e.credentials,headers:await this.#t(),method:"POST",mode:"cors"});if(!r.ok)throw new Error(`Remote signer rejected request with status ${r.status}`);return io.parse(await r.json())}},xe=class{#e;constructor(e){this.#e=e;}get isBuilderKey(){return false}get supportGasless(){return true}authorize(){return Promise.resolve({RELAYER_API_KEY:this.#e.key,RELAYER_API_KEY_ADDRESS:this.#e.address})}};function rs(t){return {domain:{chainId:t.chainId,name:"ClobAuthDomain",version:"1"},message:{address:t.address,message:"This message attests that I control the given wallet",nonce:t.nonce??0,timestamp:`${t.timestamp}`},primaryType:"ClobAuth",types:{ClobAuth:[{name:"address",type:"address"},{name:"timestamp",type:"string"},{name:"nonce",type:"uint256"},{name:"message",type:"string"}]}}}function co(t){return {listPositions:Id.bind(null,t),listClosedPositions:Ld.bind(null,t),listComboPositions:Md.bind(null,t),fetchPortfolioValue:Od.bind(null,t),fetchTradedMarketCount:Qd.bind(null,t),downloadAccountingSnapshot:Sd.bind(null,t),listMarketPositions:zc.bind(null,t),listActivity:Va.bind(null,t)}}function x(t,e={}){return {...e,user:e.user??t.account.wallet}}function Oe(t){let e=co(t);return t.isPublicClient()?e:{...e,listPositions:r=>Id(t,x(t,r)),listClosedPositions:r=>Ld(t,x(t,r)),listComboPositions:r=>Md(t,x(t,r)),fetchPortfolioValue:r=>Od(t,x(t,r)),fetchTradedMarketCount:r=>Qd(t,x(t,r)),downloadAccountingSnapshot:r=>Sd(t,x(t,r)),listActivity:r=>Va(t,x(t,r)),listAccountTrades:xa$1.bind(null,t),fetchNotifications:za.bind(null,t),dropNotifications:Ba$1.bind(null,t),fetchClosedOnlyMode:ra$1.bind(null,t)}}function Ie(t){return {listBuilderTrades:jb.bind(null,t),listBuilderLeaderboard:hc$1.bind(null,t),fetchBuilderVolume:jc.bind(null,t),listTraderLeaderboard:lc$1.bind(null,t)}}function Me(t){return {fetchEventLiveVolume:fc$1.bind(null,t),fetchMidpoint:lb.bind(null,t),fetchMidpoints:nb.bind(null,t),fetchPrice:zb.bind(null,t),fetchPrices:Bb.bind(null,t),fetchOrderBook:Db.bind(null,t),fetchOrderBooks:Fb.bind(null,t),fetchSpread:Hb.bind(null,t),fetchSpreads:Jb.bind(null,t),fetchLastTradePrice:Lb.bind(null,t),fetchLastTradePrices:Nb.bind(null,t),fetchPriceHistory:Pb.bind(null,t),estimateMarketPrice:Jc.bind(null,t),listOpenInterest:xc.bind(null,t),listMarketHolders:vc.bind(null,t),listTrades:Ta.bind(null,t)}}function Fe(t){return {listEvents:$b.bind(null,t),fetchEvent:bc.bind(null,t),fetchEventTags:dc.bind(null,t),listMarkets:nc$1.bind(null,t),listComboMarkets:pc.bind(null,t),fetchMarket:rc$1.bind(null,t),fetchMarketTags:tc$1.bind(null,t),listSeries:Re.bind(null,t),fetchSeries:Te.bind(null,t),listTags:_e$1.bind(null,t),fetchTag:af.bind(null,t),fetchRelatedTags:cf.bind(null,t),fetchRelatedTagResources:ef.bind(null,t),search:Pe.bind(null,t),listSports:Ve.bind(null,t),fetchSportsMarketTypes:Xe$1.bind(null,t),listTeams:gf.bind(null,t),fetchPublicProfile:ze.bind(null,t),listComments:Vb.bind(null,t),fetchCommentsById:Xb.bind(null,t),listCommentsByUserAddress:Zb.bind(null,t)}}function Le(t){let e={fetchPerpsBook:r=>od(t,r),fetchPerpsFees:()=>wd(t),fetchPerpsInstruments:r=>id(t,r),fetchPerpsTicker:r=>kd(t,r),fetchPerpsTickers:r=>md(t,r),listPerpsCandles:r=>qd(t,r),listPerpsFundingHistory:r=>sd(t,r),listPerpsTrades:r=>ud(t,r)};return t.isSecureClient()?{...e,depositToPerps:r=>Fd(t,r),openPerpsSession:r=>Cd(t,r),revokePerpsCredentials:r=>Dd(t,r),withdrawFromPerps:r=>Gd(t,r)}:e}function uo(t){return {listCurrentRewards:Rb.bind(null,t),listMarketRewards:Tb.bind(null,t)}}function De(t){let e=uo(t);return t.isPublicClient()?e:{...e,fetchOrderScoring:Ha.bind(null,t),fetchOrdersScoring:Ja$1.bind(null,t),listUserEarningsForDay:La$1.bind(null,t),fetchTotalEarningsForUserForDay:Na.bind(null,t),listUserEarningsAndMarketsConfig:Pa.bind(null,t),fetchRewardPercentages:Ra.bind(null,t)}}function ss(t){return {openRfqSession(){return He$1(t)}}}function Be(t){return t.isSecureClient()?{subscribe(e){return Ye(t,e)}}:{subscribe(e){return Ye(t,e)}}}function ns(t){return {createMarketOrder:$c.bind(null,t),placeMarketOrder:bd.bind(null,t),createLimitOrder:dd.bind(null,t),placeLimitOrder:fd.bind(null,t),postOrder:Nc(t),postOrders:Oc(t),cancelOrder:Bc.bind(null,t),cancelOrders:Dc.bind(null,t),cancelAll:Fc.bind(null,t),cancelMarketOrders:Hc.bind(null,t),listOpenOrders:ta$1.bind(null,t),fetchOrder:va$1.bind(null,t)}}function is(t){return {isGaslessReady:()=>Promise.resolve(true),setupTradingApprovals:hb.bind(null,t),approveErc20:$a.bind(null,t),approveErc1155ForAll:db.bind(null,t),transferErc20:kf.bind(null,t),splitPosition:je$1.bind(null,t),mergePositions:se$1.bind(null,t),redeemPositions:xe$1.bind(null,t)}}function os(t){return t.isSecureClient()?{...Oe(t),...Ie(t),...Me(t),...Fe(t),...Le(t),...De(t),...ss(t),...Be(t),...ns(t),...is(t)}:{...Oe(t),...Ie(t),...Me(t),...Fe(t),...Le(t),...De(t),...Be(t)}}var We={name:"production",chainId:137,rpc:"https://polygon.drpc.org",walletDerivation:{depositWalletFactory:expectEvmAddress("0x00000000000Fb5C9ADea0298D729A0CB3823Cc07"),depositWalletBeacon:expectEvmAddress("0x7A18EDfe055488A3128f01F563e5B479D92ffc3a"),depositWalletImplementation:expectEvmAddress("0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB"),proxyFactory:expectEvmAddress("0xaB45c5A4B0c941a2F231C04C3f49182e1A254052"),proxyImplementation:expectEvmAddress("0x44e999d5c2F66Ef0861317f9A4805AC2e90aEB4f"),safeFactory:expectEvmAddress("0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b"),safeInitCodeHash:"0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf"},contracts:{collateralToken:expectEvmAddress("0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB"),conditionalTokens:expectEvmAddress("0x4D97DCd97eC945f40cF65F87097ACe5EA0476045"),negRiskAdapter:expectEvmAddress("0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296"),collateralAdapter:expectEvmAddress("0xAdA100Db00Ca00073811820692005400218FcE1f"),negRiskCollateralAdapter:expectEvmAddress("0xadA2005600Dec949baf300f4C6120000bDB6eAab"),standardExchange:expectEvmAddress("0xE111180000d2663C0091e4f400237545B87B996B"),negRiskExchange:expectEvmAddress("0xe2222d279d744050d28e00520010520000310F59"),exchangeV3:expectEvmAddress("0xe3333700cA9d93003F00f0F71f8515005F6c00Aa"),protocolV2Router:expectEvmAddress("0x12121212006e4CD160D18e3f00711DA5c3372600"),combinatorialModule:expectEvmAddress("0x30000034706c7d8e12009dab006be20000c031a8"),positionManager:expectEvmAddress("0x006F54F7f9A22e0000CC2AB60031000000ae9fEF"),autoRedeemOperator:expectEvmAddress("0xa1200000d0002264C9a1698e001292D00E1b00af"),safeMultisend:expectEvmAddress("0xA238CBeb142c10Ef7Ad8442C6D1f9E89e07e7761"),relayHub:expectEvmAddress("0xD216153c06E857cD7f72665E0aF1d7D82172F494"),perpsDepositContract:expectEvmAddress("0xDCa4af75705dbB50f62437045afF9921947917d2")},clob:{rest:"https://clob.polymarket.com",market:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/market"},user:{ws:"wss://ws-subscriptions-clob.polymarket.com/ws/user"}},relayer:{rest:"https://relayer-v2.polymarket.com"},gamma:{rest:"https://gamma-api.polymarket.com"},data:{rest:"https://data-api.polymarket.com"},rfq:{rest:"https://combos-rfq-api.polymarket.com",ws:"wss://combos-rfq-gateway-quoter.polymarket.com/ws/rfq"},perps:{rest:"https://api.perpetuals.polymarket.com",ws:"wss://ws.perpetuals.polymarket.com/v1/ws"},rtds:{ws:"wss://ws-live-data.polymarket.com"},sports:{ws:"wss://sports-api.polymarket.com/ws"},relayerMaxPolls:100,relayerPollFrequencyMs:2e3};function po(t,e=We){return {...e,...t,walletDerivation:{...e.walletDerivation,...t.walletDerivation},contracts:{...e.contracts,...t.contracts},clob:{...Z(e.clob,t.clob),market:X(e.clob.market,t.clob?.market),user:X(e.clob.user,t.clob?.user)},relayer:Z(e.relayer,t.relayer),gamma:Z(e.gamma,t.gamma),data:Z(e.data,t.data),rfq:as(e.rfq,t.rfq),perps:as(e.perps,t.perps),rtds:X(e.rtds,t.rtds),sports:X(e.sports,t.sports)}}function Z(t,e){return {...t,...e,headers:He(t.headers,e?.headers)}}function X(t,e){return {...t,...e,headers:He(t.headers,e?.headers)}}function as(t,e){return {...t,...e,headers:He(t.headers,e?.headers)}}function He(t,e){if(!(t===void 0&&e===void 0))return {...t,...e}}var tu=po({name:"preproduction",clob:{rest:"https://clob-preprod-int-v2.polymarket.com"},data:{rest:"https://data-api-preprod-int.polymarket.com"},gamma:{rest:"https://gamma-api-preprod-int.polymarket.com"},relayer:{rest:"https://relayer-v2-preprod-int.polymarket.com"}});async function cs(t,e,r,s,n){let i=`${e}${r}${s}`;n!==void 0&&(i+=n);let o=await globalThis.crypto.subtle.importKey("raw",lo(t),{name:"HMAC",hash:"SHA-256"},false,["sign"]),h=await globalThis.crypto.subtle.sign("HMAC",o,new TextEncoder().encode(i));return ho(mo(h))}function lo(t){let e=t.replace(/-/g,"+").replace(/_/g,"/").replace(/[^A-Za-z0-9+/=]/g,""),r=atob(e),s=new Uint8Array(r.length);for(let n=0;n<r.length;n+=1)s[n]=r.charCodeAt(n);return s.buffer}function mo(t){let e=new Uint8Array(t),r="";for(let s of e)r+=String.fromCharCode(s);return btoa(r)}function ho(t){return t.replace(/\+/g,"-").replace(/\//g,"_")}var P=class{#e;#t;#s;constructor({root:e,headers:r,resolveHeaders:s}){this.#e=yo.create({prefixUrl:e,throwHttpErrors:false}),this.#t=r,this.#s=s;}get(e,r={}){return this.#n("GET",e,r)}post(e,r={}){return this.#n("POST",e,r)}patch(e,r={}){return this.#n("PATCH",e,r)}del(e,r={}){return this.#n("DELETE",e,r)}#a(e){return e.startsWith("/")?e.slice(1):e}#n(e,r,s){return this.#c(this.#r(e,r,s))}async#r(e,r,s){let n=this.#i(e,r,s),i=await this.#s?.(n),o=this.#u(this.#t,n.headers,i);return n.body!==void 0&&!o.has("content-type")&&o.set("content-type","application/json"),this.#e(this.#a(r),{body:n.body,headers:o,method:e,searchParams:n.params})}#i(e,r,s){return {body:"json"in s?this.#o(s.json):void 0,headers:s.headers,json:"json"in s?s.json:void 0,method:e,params:"params"in s?s.params:void 0,path:r}}#o(e){if(e!==void 0)return JSON.stringify(e)}#u(...e){let r=new Headers;for(let s of e)if(s!==void 0)for(let[n,i]of new Headers(s).entries())r.set(n,i);return r}#c(e$1){return ResultAsync.fromPromise(e$1.then(async r=>{if(r.ok)return r;if(r.status===429)throw new e(`Request to ${r.url} was rate limited`);let s=await this.#d(r);throw new d(s,{status:r.status})}),r=>r instanceof e||r instanceof d?r:c.fromError(r))}async#d(e){let r=e.headers.get("content-type")?.toLowerCase();if(r?.includes("application/json")){let{error:n}=await e.clone().json().catch(()=>({}));if(n)return `${String(n)} (${e.url})`}if(r?.includes("text/plain")){let n=await e.clone().text().then(i=>i.trim(),()=>"");if(n)return `${n} (${e.url})`}return e.headers.get("server")?.toLowerCase()?.includes("cloudflare")?`Request to ${e.url} was blocked by Cloudflare with status ${e.status}`:r?.includes("text/html")||r?.includes("application/xhtml+xml")?`Request to ${e.url} failed with status ${e.status} and an unexpected HTML response body`:`Request to ${e.url} failed with status ${e.status} and unreadable response body`}};function A(t,e){let r;return {close:()=>(r===void 0&&(r=Promise.resolve(t.return()).then(()=>e())),r),[Symbol.asyncIterator](){return t[Symbol.asyncIterator]()}}}var Po=1e4,So=3e4,bo=5e3,go=10*6e4,Ro=3e4,vo=25e3,qo=65e3,L=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},Po);}handleMessage(e){return e!=="PONG"?false:(this.#e=Date.now(),true)}isStale(e){return e-this.#e>So}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},ee=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e("PING");},bo);}handleMessage(){return this.#e=Date.now(),false}isStale(e){return e-this.#e>go}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}},te=class{#e=0;#t;start(e){this.#e=Date.now(),this.#t=e;}stop(){this.#t=void 0;}handleMessage(e){return e!=="ping"?false:(this.#e=Date.now(),this.#t?.("pong"),true)}isStale(e){return e-this.#e>Ro}},D=class{#e=0;#t;start(e){this.stop(),this.#e=Date.now(),this.#t=setNonBlockingInterval(()=>{e(JSON.stringify({id:0,req:"post",op:{type:"ping"}}));},vo);}handleMessage(){return this.#e=Date.now(),false}isStale(e){return e-this.#e>qo}stop(){this.#t!==void 0&&(clearInterval(this.#t),this.#t=void 0);}};var Eo=5e3,ko=250,To=3e4,g=class{#e;#t=0;schedule(e){if(this.#e!==void 0||!e.shouldReconnect())return;let r=xo(this.#t,{baseMs:ko,maxMs:To});this.#t+=1,this.#e=setNonBlockingTimeout(()=>{this.#e=void 0,this.#s(e);},r);}stop(){this.#e!==void 0&&(clearTimeout(this.#e),this.#e=void 0);}resetBackoff(){this.#t=0,this.stop();}async#s(e){if(e.shouldReconnect())try{await e.reconnect();}catch{this.schedule(e);}}},S=class{#e;#t;#s;#a;constructor(e={}){this.#e=e.heartbeat;}connect(e){if(this.#t?.readyState===WebSocket.OPEN)return Promise.resolve({reusedOpenSocket:true});if(this.#o(),this.#s!==void 0)return this.#s;let s=this.#r(e).then(()=>({reusedOpenSocket:false})).catch(n=>{throw this.#s===s&&(this.#s=void 0),n});return this.#s=s,s}send(e){return this.#n(JSON.stringify(e))}#n(e){return this.#t?.readyState!==WebSocket.OPEN?false:(this.#t.send(e),true)}async close(){let e=await this.#d();this.#c(),!(e===void 0||e.readyState===WebSocket.CLOSED)&&await new Promise(r=>{e.addEventListener("close",()=>r(),{once:true}),e.readyState!==WebSocket.CLOSING&&e.close();});}async#r(e){let r=await e.prepare?.();return new Promise((s,n)=>{let i=wo(e.url,e.headers),o=()=>{i.removeEventListener("error",h),this.#i(i),this.#u(),e.onOpen(r),s(i);},h=l=>{i.removeEventListener("open",o),n(new c(`WebSocket connection failed: ${e.url}`,{cause:l}));};i.addEventListener("open",o,{once:true}),i.addEventListener("error",h,{once:true}),i.addEventListener("message",l=>{if(this.#t!==i)return;let y=String(l.data);if(this.#e?.handleMessage(y))return;let u;try{u=JSON.parse(y);}catch{return}e.onMessage(u);}),i.addEventListener("close",()=>{this.#t===i&&(this.#o(),e.onClose());}),i.addEventListener("error",()=>e.onError());})}#i(e){this.#t=e,this.#s=void 0;}#o(){this.#c(),this.#t=void 0;}#u(){this.#c();let e=this.#e;e!==void 0&&(e.start(r=>this.#n(r)),this.#a=setNonBlockingInterval(()=>{if(!e.isStale(Date.now()))return;let r=this.#t;r?.readyState===WebSocket.OPEN&&r.close();},Eo));}#c(){this.#a!==void 0&&(clearInterval(this.#a),this.#a=void 0),this.#e?.stop();}async#d(){let e=this.#t,r=this.#s;return this.#t=void 0,this.#s=void 0,e!==void 0?e:r?.then(()=>this.#t,()=>{})}};function wo(t,e){if(e===void 0)return new WebSocket(t);try{let r=Reflect.construct(WebSocket,[t,{headers:e}]);if(r instanceof WebSocket)return r}catch(r){throw new c("WebSocket headers require a header-capable WebSocket implementation.",{cause:r})}throw new c("WebSocket headers require a header-capable WebSocket implementation.")}function xo(t,e){let r=Math.min(e.baseMs*2**t,e.maxMs);return Math.random()*r}var R=class{#e=new Set;#t;constructor(e){this.#t=e?.deriveServerState??(()=>{});}add(e,r={}){let s={queue:pushable({objectMode:true})};r.matches!==void 0&&(s.matches=r.matches);let n={subscription:e,subscriber:s};return {change:this.#s(n),entry:n}}#s(e){let r=this.serverState();return this.#e.add(e),{before:r,after:this.serverState()}}remove(e){let r=this.serverState();return this.#e.delete(e),e.subscriber.queue.end(),{before:r,after:this.serverState()}}dispatch(e){for(let{subscriber:r}of this.#e)(r.matches===void 0||r.matches(e))&&r.queue.push(e);}hasActiveSubscriptions(){return this.#e.size>0}endAll(e){for(let{subscriber:r}of this.#e)r.queue.end(e);this.#e.clear();}serverState(){return this.#t(this.#e)}};function _e(t,e,r){let s=re(r.assetsIds,e.assetsIds),n=re(e.assetsIds,r.assetsIds);s.length>0&&t(ds(s,r.customFeatureEnabled));let i=r.assetsIds[0];s.length===0&&e.customFeatureEnabled!==r.customFeatureEnabled&&i!==void 0&&t(ds([i],r.customFeatureEnabled)),n.length>0&&t(Io(n));}function Qe(t,e,r){if(r.includeAllMarkets){!e.includeAllMarkets&&e.markets.length>0&&t(ps(e.markets));return}if(e.includeAllMarkets){r.markets.length>0&&t(us(r.markets));return}let s=re(r.markets,e.markets),n=re(e.markets,r.markets);s.length>0&&t(us(s)),n.length>0&&t(ps(n));}function ls(t){let e=new Set,r=false;for(let{subscription:s}of t){for(let n of s.tokenIds)e.add(n);r||=s.customFeatureEnabled===true;}return {assetsIds:Array.from(e),customFeatureEnabled:r}}function ms(t){let e=false,r=new Set;for(let{subscription:s}of t){if(Ss(s)){e=true;continue}for(let n of s.markets??[])r.add(n);}return {includeAllMarkets:e,markets:e?[]:Array.from(r)}}function hs(t){return {assets_ids:t.assetsIds,custom_feature_enabled:t.customFeatureEnabled,type:"market"}}function ds(t,e){return {assets_ids:t,custom_feature_enabled:e,operation:"subscribe"}}function Io(t){return {assets_ids:t,operation:"unsubscribe"}}function fs(t,e){let r={auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},type:"user"};return t.includeAllMarkets||(r.markets=t.markets),r}function us(t){return {markets:t,operation:"subscribe"}}function ps(t){return {markets:t,operation:"unsubscribe"}}function ys(t){return e=>{switch(e.type){case "price_change":return e.payload.priceChanges.some(r=>t.tokenIds.includes(r.tokenId));case "new_market":return t.customFeatureEnabled===true;case "market_resolved":return t.customFeatureEnabled===true&&(e.payload.tokenIds??[]).some(r=>t.tokenIds.includes(r));case "best_bid_ask":return t.customFeatureEnabled===true&&t.tokenIds.includes(e.payload.tokenId);default:return t.tokenIds.includes(e.payload.tokenId)}}}function Ps(t){if(Ss(t))return ()=>true;let e=new Set((t.markets??[]).map(r=>r.toLowerCase()));return r=>e.has(r.payload.market.toLowerCase())}function Ss(t){return (t.markets?.length??0)===0}function re(t,e){let r=new Set(e);return t.filter(s=>!r.has(s))}var O=class{#e;#t;#s;#a=new S({heartbeat:new L});#n=new g;#r=new R({deriveServerState:ls});constructor(e){this.#e=e.headers,this.#t=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:ys(e)});return await this.#i(s,r),A(s.subscriber.queue,()=>this.#o(s))}async#i(e,r){let{before:s,after:n}=r;try{(await this.#c()).reusedOpenSocket&&_e(o=>this.#a.send(o),s,n);}catch(i){throw await this.#o(e),i}}async#o(e){let{before:r,after:s}=this.#r.remove(e);if(!this.#r.hasActiveSubscriptions()){await this.close();return}_e(n=>this.#a.send(n),r,s);}async close(){this.#s===void 0&&(this.#s=this.#u().finally(()=>{this.#s=void 0;})),await this.#s;}async#u(){this.#n.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onClose:()=>this.#l(),onError:()=>this.#h(),onMessage:e=>this.#p(e),onOpen:()=>this.#d(),headers:this.#e,url:this.#t})}#d(){this.#n.resetBackoff(),this.#y();}#p(e){let r=Array.isArray(e)?e:[e];for(let s of r){let n=MarketEventSchema.safeParse(s);n.success&&this.#r.dispatch(n.data);}}#l(){this.#r.hasActiveSubscriptions()&&this.#m();}#h(){}#y(){this.#a.send(hs(this.#r.serverState()));}#m(){this.#n.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var B=class{#e;#t;#s;#a;#n=new S({heartbeat:new L});#r=new g;#i=new R({deriveServerState:ms});constructor(e){this.#e=e.credentials,this.#t=e.headers,this.#s=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:Ps(e)});return await this.#o(s,r),A(s.subscriber.queue,()=>this.#u(s))}async#o(e,r){let{before:s,after:n}=r;try{(await this.#d()).reusedOpenSocket&&Qe(o=>this.#n.send(o),s,n);}catch(i){throw await this.#u(e),i}}async#u(e){let{before:r,after:s}=this.#i.remove(e);if(!this.#i.hasActiveSubscriptions()){await this.close();return}Qe(n=>this.#n.send(n),r,s);}async close(){this.#a===void 0&&(this.#a=this.#c().finally(()=>{this.#a=void 0;})),await this.#a;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#n.close();}#d(){return this.#n.connect({onClose:()=>this.#h(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:e=>this.#p(e),prepare:()=>this.#e,headers:this.#t,url:this.#s})}#p(e){this.#r.resetBackoff(),this.#m(e);}#l(e){let r=Array.isArray(e)?e:[e];for(let s of r){let n=UserEventSchema.safeParse(s);n.success&&this.#i.dispatch(n.data);}}#h(){this.#i.hasActiveSubscriptions()&&this.#P();}#y(){}#m(e){this.#n.send(fs(this.#i.serverState(),e));}#P(){this.#r.schedule({reconnect:()=>this.#d(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};var N=1440*60*1e3,vs=90*N,C=z.number().int().nonnegative(),se=z.object({start:C.optional(),end:C.optional()}),qs=z.object({interval:PerpsPnlIntervalSchema,start:C,end:C.optional()}),Go=z.enum(["perpsFills","perpsFundingPayments","perpsDeposits","perpsWithdrawals"]),Yo=z.enum(["perpsEquityHistory","perpsPnlHistory"]),ne=z.object({kind:Go,startTimestamp:C,endTimestamp:C,instrumentId:PerpsInstrumentIdSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional(),seenKeys:z.array(z.string())}),As=z.object({kind:Yo,startTimestamp:C,endTimestamp:C,interval:PerpsPnlIntervalSchema});async function Cs(t){return await unwrap(t.get("/v1/account/balances").andThen(G(FetchPerpsBalancesResponseSchema)))}async function Es(t){return await unwrap(t.get("/v1/account/portfolio").andThen(G(FetchPerpsPortfolioResponseSchema)))}var Jo=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function ks(t,e){let r=X$1(e,Jo);return await unwrap(t.get("/v1/account/config",{params:T(r)}).andThen(G(FetchPerpsAccountConfigResponseSchema)))}var Zo=z.object({instrumentId:PerpsInstrumentIdSchema.optional()}).default({});async function Ts(t,e){let r=X$1(e,Zo);return await unwrap(t.get("/v1/account/open-orders",{params:T(r)}).andThen(G(FetchPerpsOpenOrdersResponseSchema)))}var Xo=z.object({orderId:PerpsOrderIdSchema.optional(),clientOrderId:PerpsClientOrderIdSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional(),start:C.optional(),end:C.optional()}).default({}).transform(({end:t,start:e,...r})=>({...r,endTimestamp:t,startTimestamp:e}));async function ws(t,e){let r=X$1(e,Xo);return await unwrap(t.get("/v1/account/orders",{params:T(r)}).andThen(G(FetchPerpsOrdersResponseSchema)))}var ea=z.union([se.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:ie(e,N)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function xs(t,e={}){let{cursor:r,params:s}=X$1(e,ea);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps fills params."),i={kind:"perpsFills",seenKeys:[],...s}):i=W(n,ne);let{kind:o,seenKeys:h,...l}=i,y=new Set(i.seenKeys);return t.get("/v1/account/fills",{params:T(l)}).andThen(G(ListPerpsFillsResponseSchema)).map(u=>{let q=u.data.filter(d=>!y.has(String(d.tradeId)));return oe({getKey:d=>String(d.tradeId),getTimestamp:d=>d.timestamp,items:q,responseData:u.data,responseMore:u.more,state:i})})},r)}var ta=z.union([se.extend({cursor:PaginationCursorSchema.optional(),instrumentId:PerpsInstrumentIdSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:ie(e,N)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function Os(t,e={}){let{cursor:r,params:s}=X$1(e,ta);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps funding payment params."),i={kind:"perpsFundingPayments",seenKeys:[],...s}):i=W(n,ne);let{kind:o,seenKeys:h,...l}=i,y=new Set(i.seenKeys);return t.get("/v1/account/funding",{params:T(l)}).andThen(G(ListPerpsFundingPaymentsResponseSchema)).map(u=>{let q=u.data.filter(d=>!y.has(`${d.instrumentId}:${d.timestamp}:${d.funding}`));return oe({getKey:d=>`${d.instrumentId}:${d.timestamp}:${d.funding}`,getTimestamp:d=>d.timestamp,items:q,responseData:u.data,responseMore:u.more,state:i})})},r)}var ra=z.union([se.extend({cursor:PaginationCursorSchema.optional(),depositStatus:PerpsDepositStatusSchema.optional(),hash:TxHashSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:ie(e,vs)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function Is(t,e={}){let{cursor:r,params:s}=X$1(e,ra);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps deposit params."),i={kind:"perpsDeposits",seenKeys:[],...s}):i=W(n,ne);let{kind:o,seenKeys:h,...l}=i,y=new Set(i.seenKeys);return t.get("/v1/account/deposits",{params:T(l)}).andThen(G(ListPerpsDepositsResponseSchema)).map(u=>{let q=u.data.filter(d=>!y.has(d.hash));return oe({getKey:d=>d.hash,getTimestamp:oa,items:q,responseData:u.data,responseMore:u.more,state:i})})},r)}var sa=z.union([se.extend({cursor:PaginationCursorSchema.optional(),withdrawalStatus:PerpsWithdrawalStatusSchema.optional(),hash:TxHashSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:ie(e,vs)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function Ms(t,e={}){let{cursor:r,params:s}=X$1(e,sa);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps withdrawal params."),i={kind:"perpsWithdrawals",seenKeys:[],...s}):i=W(n,ne);let{kind:o,seenKeys:h,...l}=i,y=new Set(i.seenKeys);return t.get("/v1/account/withdrawals",{params:T(l)}).andThen(G(ListPerpsWithdrawalsResponseSchema)).map(u=>{let q=u.data.filter(d=>!y.has(String(d.withdrawalId)));return oe({getKey:d=>String(d.withdrawalId),getTimestamp:aa,items:q,responseData:u.data,responseMore:u.more,state:i})})},r)}var na=z.union([qs.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:Ds(e)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function Fs(t,e){let{cursor:r,params:s}=X$1(e,na);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps equity history params."),i={kind:"perpsEquityHistory",...s}):i=W(n,As);let{kind:o,...h}=i;return t.get("/v1/account/equity",{params:T(h)}).andThen(G(ListPerpsEquityHistoryResponseSchema)).map(l=>{let y=l.data.at(-1),u=l.more&&y!==void 0&&y.timestamp<i.endTimestamp;return {items:l.data,hasMore:u,nextCursor:u?je({...i,startTimestamp:y.timestamp+Bs(i.interval)}):void 0}})},r)}var ia=z.union([qs.extend({cursor:PaginationCursorSchema.optional()}).transform(({cursor:t,...e})=>({cursor:t,params:Ds(e)})),z.object({cursor:PaginationCursorSchema}).transform(({cursor:t})=>({cursor:t,params:void 0}))]);function Ls(t,e){let{cursor:r,params:s}=X$1(e,ia);return pa$1(n=>{let i;n===void 0?(invariant(s!==void 0,"Expected initial Perps PnL history params."),i={kind:"perpsPnlHistory",...s}):i=W(n,As);let{kind:o,...h}=i;return t.get("/v1/account/pnl",{params:T(h)}).andThen(G(ListPerpsPnlHistoryResponseSchema)).map(l=>{let y=l.data.at(-1),u=l.more&&y!==void 0&&y.timestamp<i.endTimestamp;return {items:l.data,hasMore:u,nextCursor:u?je({...i,startTimestamp:y.timestamp+Bs(i.interval)}):void 0}})},r)}function ie(t,e){let r=Date.now(),{end:s,start:n,...i}=t;return {...i,endTimestamp:s??r,startTimestamp:n??r-e}}function Ds(t){return {endTimestamp:t.end??Date.now(),interval:t.interval,startTimestamp:t.start}}function W(t,e){try{return e.parse(JSON.parse(atob(t)))}catch(r){throw new c("Invalid Perps account pagination cursor",{cause:r})}}function je(t){return toPaginationCursor(btoa(JSON.stringify(t)))}function T(t){return ca(t,da())}function oa(t){return t.confirmedTimestamp??t.createdTimestamp}function aa(t){return t.confirmedTimestamp??t.createdTimestamp}function oe(t){let e=t.responseData.at(-1),r=t.items.at(-1),s=(r===void 0?void 0:t.getTimestamp(r))??(e===void 0?void 0:t.getTimestamp(e)),n=t.responseMore&&s!==void 0&&s>t.state.startTimestamp;if(!n)return {items:t.items,hasMore:n};let i=r===void 0?s-1:s,o=new Set(t.state.endTimestamp===i?t.state.seenKeys:[]);for(let h of t.items)t.getTimestamp(h)===i&&o.add(t.getKey(h));return {items:t.items,hasMore:n,nextCursor:je({...t.state,endTimestamp:i,seenKeys:Array.from(o)})}}function Bs(t){switch(t){case "1h":return 3600*1e3;case "4h":return 14400*1e3;case "1d":return N;case "1w":return 7*N}invariant(false,`Unsupported Perps account history interval: ${String(t)}`);}var Je=z.object({instrumentId:PerpsInstrumentIdSchema,buy:z.boolean(),price:PerpsDecimalInputSchema.optional(),quantity:PerpsDecimalInputSchema,timeInForce:PerpsTimeInForceSchema,postOnly:z.boolean().optional(),clientOrderId:PerpsClientOrderIdSchema.optional()});async function Us(t,e){let[r]=await Ze(t,{orders:[e]});return expectPresent(r,"Expected Perps place order acknowledgement.")}var ua=z.object({orders:z.array(Je).min(1),expiresAt:z.number().int().positive().optional()});async function Ze(t,e){let r=X$1(e,ua);return await t.sendSignedWsCommand({op:["createOrders",r.orders.map(zs)],responseSchema:z.array(RawPerpsOrderCommandAckSchema),timeoutMessage:"Perps place order acknowledgement timed out.",expiresAt:r.expiresAt})}var pa=z.object({orderId:PerpsOrderIdSchema,order:Je,expiresAt:z.number().int().positive().optional()});async function _s(t,e){let r=X$1(e,pa),[s]=await Xe(t,{orders:[{orderId:r.orderId,order:r.order}],expiresAt:r.expiresAt});return expectPresent(s,"Expected Perps modify order acknowledgement.")}var la=z.object({orders:z.array(z.object({orderId:PerpsOrderIdSchema,order:Je})).min(1),expiresAt:z.number().int().positive().optional()});async function Xe(t,e){let r=X$1(e,la);return await t.sendSignedWsCommand({op:["modifyOrders",r.orders.map(s=>[s.orderId,zs(s.order)])],responseSchema:z.array(RawPerpsOrderCommandAckSchema),timeoutMessage:"Perps modify order acknowledgement timed out.",expiresAt:r.expiresAt})}var ma=z.union([z.object({orderId:PerpsOrderIdSchema,clientOrderId:z.undefined().optional(),expiresAt:z.number().int().positive().optional()}),z.object({clientOrderId:PerpsClientOrderIdSchema,orderId:z.undefined().optional(),expiresAt:z.number().int().positive().optional()})]);async function Qs(t,e){let r=X$1(e,ma),[s]=r.orderId!==void 0?await ae(t,{orderIds:[r.orderId],expiresAt:r.expiresAt}):await ae(t,{clientOrderIds:[r.clientOrderId],expiresAt:r.expiresAt});return expectPresent(s,"Expected Perps cancel order acknowledgement.")}var ha=z.union([z.object({orderIds:z.array(PerpsOrderIdSchema).min(1),clientOrderIds:z.undefined().optional(),expiresAt:z.number().int().positive().optional()}),z.object({clientOrderIds:z.array(PerpsClientOrderIdSchema).min(1),orderIds:z.undefined().optional(),expiresAt:z.number().int().positive().optional()})]);async function ae(t,e){let r=X$1(e,ha);return r.orderIds!==void 0?await t.sendSignedWsCommand({op:["cancelOrders",r.orderIds],responseSchema:z.array(PerpsCommandAckSchema),timeoutMessage:"Perps cancel order acknowledgement timed out.",expiresAt:r.expiresAt}):await t.sendSignedWsCommand({op:["cancelOrdersCOID",r.clientOrderIds],responseSchema:z.array(PerpsCommandAckSchema),timeoutMessage:"Perps cancel order acknowledgement timed out.",expiresAt:r.expiresAt})}var fa=z.object({instrumentId:PerpsInstrumentIdSchema,leverage:z.number().int().positive(),crossMargin:z.boolean()});async function Ks(t,e){let r=X$1(e,fa);return await t.sendSignedWsCommand({op:["updateLeverage",[r.instrumentId,r.leverage,r.crossMargin]],responseSchema:PerpsCommandAckSchema,timeoutMessage:"Perps update leverage acknowledgement timed out."})}var ya=z.object({instrumentId:PerpsInstrumentIdSchema,amount:PerpsDecimalInputSchema});async function js(t,e){let r=X$1(e,ya),s=toDecimalString(r.amount);return await t.sendSignedHttpCommand("/v1/trade/margin",{op:["updateMargin",[r.instrumentId,s]],bodyOp:{args:{amt:s,iid:r.instrumentId},type:"updateMargin"}})}function zs(t){return [t.instrumentId,t.buy,t.price===void 0?void 0:toDecimalString(t.price),toDecimalString(t.quantity),t.timeInForce,t.postOnly??false,t.clientOrderId]}function Ns(t){let[e,r]=t;switch(e){case "createOrders":return {args:r.map(Ws),type:e};case "modifyOrders":return {args:r.map(([s,n])=>({oid:s,order:Ws(n)})),type:e};case "cancelOrders":case "cancelOrdersCOID":return {args:r,type:e};case "updateLeverage":{let[s,n,i]=r;return {args:{cross:i,iid:s,lev:n},type:e}}default:invariant(false,`Unsupported Perps command: ${String(e)}`);}}function Ws(t){let e={buy:t[1],iid:t[0],po:t[5],qty:t[3],tif:t[4]};return t[2]!==void 0&&(e.p=t[2]),t[6]!==void 0&&(e.c=t[6]),e}var va=3e4,$s=3e4,qa=["balances","portfolio","orders","fills","funding","deposits","withdrawals"],Aa=z.object({id:z.number().int().positive().optional(),data:z.unknown()}),Vs=z.union([PerpsCommandAckSchema,z.array(PerpsCommandAckSchema)]).transform(t=>Array.isArray(t)?t.find(e=>e.status==="err")??t[0]:t),de=class{credentials;#e;#t;#s;#a;#n;#r=new S({heartbeat:new D});#i=pushable({objectMode:true});#o=new Map;#u=new g;#c=new Map;#d=new Map;#p=1;#l;constructor(e){this.#e=new P({headers:e.headers,resolveHeaders:async()=>this.#P(),root:e.restUrl}),this.#t=e.chainId,this.credentials=e.credentials,this.#s=e.headers,this.#a=e.onClose,this.#n=e.wsUrl;}get closed(){return this.#l!==void 0}async connect(){await this.#h(false);}async close(){this.#l===void 0&&(this.#l=this.#v()),await this.#l;}[Symbol.asyncIterator](){return this.#i[Symbol.asyncIterator]()}async fetchBalances(){return await Cs(this.#e)}async fetchPortfolio(){return await Es(this.#e)}async fetchAccountConfig(e){return await ks(this.#e,e)}async fetchOpenOrders(e){return await Ts(this.#e,e)}async fetchOrders(e){return await ws(this.#e,e)}listFills(e={}){return xs(this.#e,e)}listFundingPayments(e={}){return Os(this.#e,e)}listDeposits(e={}){return Is(this.#e,e)}listWithdrawals(e={}){return Ms(this.#e,e)}listEquityHistory(e){return Fs(this.#e,e)}listPnlHistory(e){return Ls(this.#e,e)}async placeOrder(e){return await Us(this.#f(),e)}async placeOrders(e){return await Ze(this.#f(),e)}async modifyOrder(e){return await _s(this.#f(),e)}async modifyOrders(e){return await Xe(this.#f(),e)}async cancelOrder(e){return await Qs(this.#f(),e)}async cancelOrders(e){return await ae(this.#f(),e)}async updateLeverage(e){return await Ks(this.#f(),e)}async updateMargin(e){return await js(this.#f(),e)}async#h(e){await this.#r.connect({onClose:()=>this.#E(),onError:()=>{},onMessage:r=>this.#A(r),onOpen:()=>{},headers:this.#s,url:this.#n}),await this.#y(),await this.#m(),this.#u.resetBackoff(),e&&(this.#c.clear(),this.#d.clear(),this.#i.push({reason:"reconnect",type:"resync"}));}async#y(){await this.#b({id:this.#p++,op:{args:{proxy:this.credentials.proxy,secret:this.credentials.secret},type:"auth"},req:"post"},Vs,va,"Perps session authentication timed out.");}async#m(){await this.#b({id:this.#p++,req:"sub",chs:qa},Vs,$s,"Perps session subscription timed out.");}#P(){return {"POLYMARKET-PROXY":this.credentials.proxy,"POLYMARKET-SECRET":this.credentials.secret}}#f(){return {sendSignedWsCommand:e=>this.#S(e),sendSignedHttpCommand:(e,r)=>this.#R(e,r)}}async#S(e){let r=this.#g(e.op,e.expiresAt);return await this.#b({...r,id:this.#p++,op:Ns(e.op),req:"post"},e.responseSchema,$s,e.timeoutMessage)}async#R(e,r){let s=this.#g(r.op);return await unwrap(this.#e.patch(e,{json:{...s,op:r.bodyOp}}).andThen(G(PerpsCommandAckSchema)))}#g(e,r){let s=ka(),n=Date.now(),i;try{i=gd({chainId:this.#t,op:e,privateKey:this.credentials.privateKey,salt:s,timestamp:n});}catch(h){throw j.fromError(h,"Could not sign the Perps session command")}let o={salt:s,sig:i,ts:n};return r!==void 0&&(o.exp=r),o}async#b(e,r,s,n){let i=Ca(r);this.#o.set(e.id,i);let o=setNonBlockingTimeout(()=>{i.reject(new c(n));},s);try{if(!this.#r.send(e))throw new c("Perps session transport is not open.");return await i.promise}finally{clearTimeout(o),this.#o.delete(e.id);}}async#v(){this.#u.stop(),this.#q(new c("Perps session closed.")),this.#i.end(),await this.#r.close(),this.#a(this);}#A(e){if(this.#C(e))return;let r=PerpsSessionUpdateEventSchema.safeParse(e);if(!r.success)return;let s=r.data,n=this.#k(s);this.#T(s),!n&&this.#i.push(s);}#C(e){let r=Aa.safeParse(e);if(!r.success||r.data.id===void 0)return false;let s=this.#o.get(r.data.id);if(s===void 0)return true;let n=s.schema.safeParse(r.data.data);return n.success?(Ea(n.data)?s.reject(new c(n.data.error??"Perps session request rejected.")):s.resolve(n.data),true):(s.reject(new c("Perps session empty response.")),true)}#E(){this.#q(new c("Perps session connection closed.")),this.#l===void 0&&this.#u.schedule({reconnect:()=>this.#h(true),shouldReconnect:()=>this.#l===void 0});}#q(e){for(let r of this.#o.values())r.reject(e);this.#o.clear();}#k(e){if(e.channel!=="balances"&&e.channel!=="portfolio")return false;let r=JSON.stringify(e.payload),s=this.#d.get(e.channel);return this.#d.set(e.channel,r),r===s}#T(e){let r=this.#c.get(e.channel);this.#c.set(e.channel,e.sequence),!(r===void 0||e.sequence===r+1)&&this.#i.push({channel:e.channel,previousSequence:r,reason:"sequence_gap",sequence:e.sequence,type:"resync"});}};function Ca(t){let e,r;return {promise:new Promise((n,i)=>{e=n,r=i;}),reject:r,resolve:e,schema:t}}function Ea(t){return !Array.isArray(t)&&typeof t=="object"&&t!==null&&"status"in t&&t.status==="err"}function ka(){let[t]=globalThis.crypto.getRandomValues(new Uint32Array(1));return invariant(t!==void 0,"Expected crypto.getRandomValues to return a salt."),t}var H=class{#e;#t;#s;#a;#n=new Set;#r=new Set;#i=new Set;#o=false;constructor(e){this.#e=e.chainId,this.#t=e.headers,this.#s=e.restUrl,this.#a=e.wsUrl;}connect(e){if(this.#o)return Promise.reject(new c("Perps session manager has been shut down."));let r=new de({chainId:this.#e,credentials:e,headers:this.#t,onClose:n=>this.#u(n),restUrl:this.#s,wsUrl:this.#a});this.#r.add(r);let s;return s=(async()=>{try{if(await r.connect(),this.#o)throw await r.close(),new c("Perps session manager has been shut down.");return this.#n.add(r),r}catch(n){throw await r.close(),n}finally{this.#i.delete(s),this.#r.delete(r);}})(),this.#i.add(s),s}async shutdown(){this.#o=true;let e=Array.from(this.#n),r=Array.from(this.#r),s=Array.from(this.#i);this.#n.clear(),this.#r.clear(),this.#i.clear(),await Promise.allSettled([...e.map(n=>n.close()),...r.map(n=>n.close()),...s.map(n=>n.catch(()=>{}))]).then(()=>{});}#u(e){this.#n.delete(e),this.#r.delete(e);}};var M=class{#e;#t;#s;#a=1;#n=new S({heartbeat:new D});#r=new g;#i=new R({deriveServerState:wa});constructor(e){this.#e=e.headers,this.#t=e.url;}async subscribe(e){let{change:r,entry:s}=this.#i.add(e,{matches:Oa(e)});return await this.#o(s,r),A(s.subscriber.queue,()=>this.#u(s))}async#o(e,r){try{(await this.#d()).reusedOpenSocket&&(this.#m(Gs(r.before,r.after)),this.#P(Ys(r.before,r.after)));}catch(s){throw await this.#u(e),s}}async#u(e){let{before:r,after:s}=this.#i.remove(e);this.#m(Gs(r,s)),this.#P(Ys(r,s)),this.#i.hasActiveSubscriptions()||await this.close();}async close(){this.#s===void 0&&(this.#s=this.#c().finally(()=>{this.#s=void 0;})),await this.#s;}async#c(){this.#r.stop(),this.#i.endAll(),await this.#n.close();}#d(){return this.#n.connect({onClose:()=>this.#h(),onError:()=>this.#y(),onMessage:e=>this.#l(e),onOpen:()=>this.#p(),headers:this.#e,url:this.#t})}#p(){this.#r.resetBackoff(),this.#m(Array.from(this.#i.serverState()));}#l(e){let r=PerpsMarketDataEventSchema.safeParse(e);r.success&&this.#i.dispatch(r.data);}#h(){this.#i.hasActiveSubscriptions()&&this.#S();}#y(){}#m(e){e.length!==0&&this.#n.send(this.#f("sub",e));}#P(e){e.length!==0&&this.#n.send(this.#f("unsub",e));}#f(e,r){return {id:this.#a++,req:e,chs:r}}#S(){this.#r.schedule({reconnect:()=>this.#d(),shouldReconnect:()=>this.#i.hasActiveSubscriptions()});}};function wa(t){let e=new Set,r=new Set,s=new Set,n=false,i=false;for(let{subscription:o}of t)switch(o.topic){case "perps.tickers":o.instrumentId===void 0?n=true:r.add(o.instrumentId);break;case "perps.statistics":o.instrumentId===void 0?i=true:s.add(o.instrumentId);break;default:e.add(xa(o));}if(n)e.add("tickers::all");else for(let o of r)e.add(`tickers::${o}`);if(i)e.add("statistics::all");else for(let o of s)e.add(`statistics::${o}`);return e}function Gs(t,e){return Array.from(e).filter(r=>!t.has(r))}function Ys(t,e){return Array.from(t).filter(r=>!e.has(r))}function xa(t){switch(t.topic){case "perps.trades":return `trades::${t.instrumentId}`;case "perps.bbo":return `bbo::${t.instrumentId}`;case "perps.book":return `book::${t.instrumentId}`;case "perps.candles":return `klines::${t.instrumentId}::${t.interval}`;case "perps.tickers":return t.instrumentId===void 0?"tickers::all":`tickers::${t.instrumentId}`;case "perps.statistics":return t.instrumentId===void 0?"statistics::all":`statistics::${t.instrumentId}`;default:invariant(false,`Unknown Perps topic: ${String(t)}`);}}function Oa(t){switch(t.topic){case "perps.trades":case "perps.bbo":case "perps.book":return e=>e.topic===t.topic&&e.payload.instrumentId===t.instrumentId;case "perps.candles":return e=>e.topic==="perps.candles"&&e.payload.instrumentId===t.instrumentId&&e.payload.interval===t.interval;case "perps.tickers":case "perps.statistics":return e=>e.topic===t.topic&&(t.instrumentId===void 0||e.payload.instrumentId===t.instrumentId);default:invariant(false,`Unknown Perps topic: ${String(t)}`);}}function Xs(t,e){return {...e,quote:r=>t.quote(e,r)}}function en(t,e){let r=e.rfqId,s=e.quoteId;return {...e,confirm:()=>t.respondToConfirmation(r,s,RfqConfirmationDecision.Confirm),decline:()=>t.respondToConfirmation(r,s,RfqConfirmationDecision.Decline)}}function tn(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function rn(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function sn(t){return {quoteId:t.quoteId,rfqId:t.rfqId}}function nn(t,e){let r=_$1(t);return {auth:{apiKey:e.key,passphrase:e.passphrase,secret:e.secret},identity:{maker_address:r.maker,signature_type:r.signatureType,signer_address:r.signer},type:"auth"}}function on(t,e){return {price_e6:e.price.toString(),rfq_id:t.rfqId,signed_order:e.signedOrder,size_e6:e.size.toString(),type:"RFQ_QUOTE"}}function an(t,e,r){let s=_$1(t);return {maker_address:s.maker,quote_id:r,rfq_id:e,signer_address:s.signer,type:"RFQ_QUOTE_CANCEL"}}function cn(t,e,r){return {decision:r,quote_id:e,rfq_id:t,type:"RFQ_CONFIRMATION_RESPONSE"}}var ue=class{#e=new Map;#t;constructor(e){this.#t=e;}waitFor(e,r){let s=Ma(),n,i=setNonBlockingTimeout(()=>{this.remove(e,n),s.reject(new f(r));},this.#t);n=s.promise.finally(()=>clearTimeout(i));let o=this.#e.get(e)??[];return o.push({...s,promise:n}),this.#e.set(e,o),n}resolve(e,r){let s=this.#e.get(e),n=s?.shift();n!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),n.resolve(r));}reject(e,r){let s=this.#e.get(e),n=s?.shift();n!==void 0&&(s!==void 0&&s.length===0&&this.#e.delete(e),n.reject(r));}remove(e,r){let s=this.#e.get(e);if(s===void 0)return;let n=s.filter(i=>i.promise!==r);n.length===0?this.#e.delete(e):this.#e.set(e,n);}rejectAll(e){for(let r of this.#e.values())for(let s of r)s.reject(e);this.#e.clear();}};function Ma(){let t,e;return {promise:new Promise((s,n)=>{t=s,e=n;}),reject:e,resolve:t}}var un="0x0000000000000000000000000000000000000000000000000000000000000000";async function ln(t){let e=_$1(t.account),r={builder:un,maker:e.maker,makerAmount:toBaseUnits(Fa(t.orderSide,t.orderPrice,t.size)),metadata:un,salt:Ba().toString(),side:Da(t.orderSide),signatureType:e.signatureType,signer:e.signer,takerAmount:toBaseUnits(La(t.orderSide,t.orderPrice,t.size)),timestamp:Math.floor(Date.now()/1e3).toString(),tokenId:t.tokenId},s;try{s=await t.signer.signTypedData(Pc$1({domain:pn(t),order:r}));}catch(n){throw j.fromError(n,"Could not sign the RFQ quote order.")}return {...r,signature:Qc({domain:pn(t),order:r,signature:s})}}function pn(t){return {chainId:t.chainId,exchange:t.exchange,protocolVersion:"3"}}function Fa(t,e,r){return t===OrderSide.SELL?r.toString():((e*r+999999n)/1000000n).toString()}function La(t,e,r){return t===OrderSide.SELL?(e*r/1000000n).toString():r.toString()}function Da(t){return t===OrderSide.BUY?0:1}function Ba(){let t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),BigInt(`0x${Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}`)}var fn=DecimalishSchema.transform(t=>Sn(t)).refine(t=>t<=BigInt(Number.MAX_SAFE_INTEGER),{message:"Value exceeds the temporary numeric wire limit."}),Ua=z.strictObject({price:fn.refine(t=>t<1000000n,{message:"Price must be less than 1."}),size:fn.optional(),source:z.enum(["collateral","inventory"]).default("collateral")});function yn(t){return X$1(t,Ua)}async function Pn(t){let e=t.response.price,r=t.response.size===void 0?ja(t.request.requestedSize,e):t.response.size,s=await ln({account:t.account,chainId:t.chainId,exchange:t.exchange,orderPrice:Qa(t.request,t.response.source,e),orderSide:Ka(t.response.source),signer:t.signer,size:r,tokenId:_a(t.request,t.response.source)});return {price:e,signedOrder:s,size:r}}function _a(t,e){return t.direction===RfqDirection.Buy?e==="collateral"?t.noPositionId:t.yesPositionId:e==="collateral"?t.yesPositionId:t.noPositionId}function Qa(t,e,r){return t.direction===RfqDirection.Buy&&e==="collateral"||t.direction===RfqDirection.Sell&&e==="inventory"?1000000n-r:r}function Ka(t){return t==="collateral"?OrderSide.BUY:OrderSide.SELL}function ja(t,e){let r=Sn(t.value);return t.unit===RfqRequestedSizeUnit.Shares?r:r*1000000n/e}function Sn(t){let e=/^(\d+)(?:\.(\d*))?$/.exec(t);if(e===null)throw new a("Value must be a valid decimal.");let[,r="",s=""]=e;if(s.length>6)throw new a("Value must have at most 6 decimal places.");let n=BigInt(r)*1000000n+BigInt(s.padEnd(6,"0"));if(n<=0n)throw new a("Value must be greater than 0.");return n}var Ga=3e4,Ya=3e4,U=class{#e;#t;#s;#a;#n;#r;#i;#o;#u;#c;#d=false;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#s=e.credentials,this.#a=e.exchange,this.#n=e.headers,this.#r=e.signer,this.#i=e.url;}async connect(){if(this.#d)throw new c("RFQ quoter manager has been shut down.");if(this.#o!==void 0){if(!this.#o.closed)return this.#o;this.#o=void 0;}if(this.#c!==void 0)return this.#c;let e=new it({account:this.#e,chainId:this.#t,credentials:this.#s,exchange:this.#a,headers:this.#n,onClose:()=>this.#p(e),signer:this.#r,url:this.#i});this.#u=e;let r;return r=(async()=>{try{if(await e.connect(),this.#d)throw await e.close(),new c("RFQ quoter manager has been shut down.");return this.#o=e,e}catch(s){throw await e.close(),s}finally{this.#c===r&&(this.#c=void 0),this.#u===e&&(this.#u=void 0);}})(),this.#c=r,r}async shutdown(){this.#d=true;let e=this.#o,r=this.#u,s=this.#c;this.#o=void 0,this.#u=void 0,this.#c=void 0,await Promise.allSettled([e?.close(),r?.close(),s?.catch(()=>{})]).then(()=>{});}#p(e){this.#o===e&&(this.#o=void 0),this.#u===e&&(this.#u=void 0);}},it=class{#e;#t;#s;#a;#n;#r;#i;#o;#u=new S;#c=pushable({objectMode:true});#d=new ue(Ya);#p;#l;constructor(e){this.#e=e.account,this.#t=e.chainId,this.#s=e.credentials,this.#a=e.exchange,this.#n=e.headers,this.#r=e.onClose,this.#i=e.signer,this.#o=e.url;}get closed(){return this.#p!==void 0}async connect(){let e=Ja();this.#l=e;let r=setNonBlockingTimeout(()=>{e.reject(new c("RFQ quoter authentication timed out."));},Ga);try{await this.#u.connect({headers:this.#n,onClose:()=>this.#b(),onError:()=>{},onMessage:s=>this.#R(s),onOpen:()=>this.#S(),url:this.#o}),await e.promise;}finally{clearTimeout(r),this.#l=void 0;}}async#h(e){if(!this.#u.send(e))throw new c("RFQ quoter websocket is not open.")}async close(){this.#p===void 0&&(this.#p=this.#y()),await this.#p;}[Symbol.asyncIterator](){return this.#c[Symbol.asyncIterator]()}async#y(){let e=new c("RFQ quoter websocket closed.");await this.#P(e);}async#m(e){this.#p===void 0&&(this.#p=this.#P(e)),await this.#p;}async#P(e){this.#f(e),this.#c.end(),await this.#u.close(),this.#r();}#f(e){this.#l?.reject(e),this.#d.rejectAll(e);}#S(){this.#u.send(nn(this.#e,this.#s));}#R(e){if(this.#p!==void 0||!RfqKnownInboundMessageSchema.safeParse(e).success)return;let r=RfqQuoterInboundMessageSchema.safeParse(e);if(!r.success){let n=new c("Invalid RFQ quoter message.",{cause:r.error});this.#m(n);return}let s=r.data;switch(s.type){case "auth":this.#g(s);return;case "quote_request":this.#c.push(Xs(this,s));return;case "quote_ack":this.#d.resolve(pe(s.rfqId),tn(s));return;case "quote_cancel_ack":this.#d.resolve(st(s.rfqId,s.quoteId),rn(s));return;case "confirmation_request":this.#c.push(en(this,s));return;case "confirmation_ack":this.#d.resolve(nt(s.rfqId,s.quoteId),sn(s));return;case "execution_update":this.#c.push(s);return;case "trade":this.#c.push(s);return;case "rfq_error":this.#v(s);return}}#g(e){if(e.success===true){this.#l?.resolve(void 0);return}this.#l?.reject(new c(`RFQ quoter authentication failed: ${e.error}`));}#b(){this.#r(),this.close();}#v(e){if(e.requestType==="RFQ_QUOTE"){if(e.rfqId===void 0){this.#m(new c("Uncorrelated RFQ quoter error."));return}this.#d.reject(pe(e.rfqId),new Ae(e.message,{code:e.code,errorId:e.errorId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_QUOTE_CANCEL"){if(e.rfqId===void 0||e.quoteId===void 0){this.#m(new c("Uncorrelated RFQ quoter error."));return}this.#d.reject(st(e.rfqId,e.quoteId),new Ce(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));return}if(e.requestType==="RFQ_CONFIRMATION_RESPONSE"){if(e.rfqId===void 0||e.quoteId===void 0){this.#m(new c("Uncorrelated RFQ quoter error."));return}this.#d.reject(nt(e.rfqId,e.quoteId),new Ee(e.message,{code:e.code,errorId:e.errorId,quoteId:e.quoteId,rfqId:e.rfqId}));}}async quote(e,r){let s=yn(r),n=await Pn({account:this.#e,chainId:this.#t,exchange:this.#a,request:e,response:s,signer:this.#i}),i=this.#d.waitFor(pe(e.rfqId),`Timed out waiting for RFQ quote acknowledgement for ${e.rfqId}.`);try{return await this.#h(on(e,n)),await i}catch(o){throw this.#d.remove(pe(e.rfqId),i),o}}async cancelQuote(e){let r=st(e.rfqId,e.quoteId),s=this.#d.waitFor(r,`Timed out waiting for RFQ quote cancellation acknowledgement for ${e.rfqId}.`);try{return await this.#h(an(this.#e,e.rfqId,e.quoteId)),await s}catch(n){throw this.#d.remove(r,s),n}}async respondToConfirmation(e,r,s){let n=nt(e,r),i=this.#d.waitFor(n,`Timed out waiting for RFQ confirmation acknowledgement for ${e}.`);try{return await this.#h(cn(e,r,s)),await i}catch(o){throw this.#d.remove(n,i),o}}};function pe(t){return `ACK_RFQ_QUOTE:${t}`}function st(t,e){return `ACK_RFQ_QUOTE_CANCEL:${t}:${e}`}function nt(t,e){return `ACK_RFQ_CONFIRMATION_RESPONSE:${t}:${e}`}function Ja(){let t,e;return {promise:new Promise((s,n)=>{t=s,e=n;}),reject:e,resolve:t}}var _=class{#e;#t;#s;#a=new S({heartbeat:new ee});#n=new g;#r=new R({deriveServerState:tc});constructor(e){this.#e=e.headers,this.#t=e.url;}async subscribe(e){let{change:r,entry:s}=this.#r.add(e,{matches:ic(e)});return await this.#i(s,r),A(s.subscriber.queue,()=>this.#o(s))}async#i(e,r){try{if((await this.#c()).reusedOpenSocket){let{before:n,after:i}=r,o=Xa(n,i);this.#m(o);}}catch(s){throw await this.#o(e),s}}async#o(e){let{before:r,after:s}=this.#r.remove(e),n=ec(r,s);this.#P(n),this.#r.hasActiveSubscriptions()||await this.close();}async close(){this.#s===void 0&&(this.#s=this.#u().finally(()=>{this.#s=void 0;})),await this.#s;}async#u(){this.#n.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onClose:()=>this.#l(),onError:()=>this.#h(),onMessage:e=>this.#p(e),onOpen:()=>this.#d(),headers:this.#e,url:this.#t})}#d(){this.#n.resetBackoff(),this.#y();}#p(e){let r=RealtimeEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#f();}#h(){}#y(){this.#m(Array.from(this.#r.serverState().values()));}#m(e){e.length!==0&&this.#a.send(rc(e));}#P(e){e.length!==0&&this.#a.send(sc(e));}#f(){this.#n.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};function Xa(t,e){return Array.from(e).flatMap(([r,s])=>t.has(r)?[]:[s])}function ec(t,e){return Array.from(t).flatMap(([r,s])=>e.has(r)?[]:[s])}function tc(t){let e=new Map;for(let{subscription:r}of t)for(let s of nc(r))e.has(s.key)||e.set(s.key,s);return e}function rc(t){return {action:"subscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function sc(t){return {action:"unsubscribe",subscriptions:t.map(({topic:e,type:r})=>({topic:e,type:r}))}}function nc(t){switch(t.topic){case "comments":return (t.types??["comment_created"]).map(e=>le("comments",e));case "prices.crypto.binance":return [le("crypto_prices","update")];case "prices.crypto.chainlink":return [le("crypto_prices_chainlink","update")];case "prices.equity.pyth":return [le("equity_prices","update")];default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}function le(t,e){return {key:`${t}:${e}`,topic:t,type:e}}function ic(t){switch(t.topic){case "comments":return e=>!(e.topic!=="comments"||t.types!==void 0&&t.types.length>0&&!t.types.includes(e.type)||(t.parentEntityId!==void 0||t.parentEntityType!==void 0)&&(!(e.type==="comment_created"||e.type==="comment_removed")||t.parentEntityId!==void 0&&e.payload.parentEntityID!==t.parentEntityId||t.parentEntityType!==void 0&&e.payload.parentEntityType!==t.parentEntityType));case "prices.crypto.binance":return e=>e.topic==="prices.crypto.binance"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.crypto.chainlink":return e=>e.topic==="prices.crypto.chainlink"&&(t.symbols===void 0||t.symbols.length===0||t.symbols.includes(e.payload.symbol));case "prices.equity.pyth":return e=>e.topic==="prices.equity.pyth"&&e.payload.symbol.toLowerCase()===t.symbol.toLowerCase()&&(t.types===void 0||t.types.length===0||t.types.includes(e.type));default:invariant(false,`Unknown RTDS topic: ${String(t)}`);}}var Q=class{#e;#t;#s;#a=new S({heartbeat:new te});#n=new g;#r=new R;constructor(e){this.#e=e.headers,this.#t=e.url;}async subscribe(e){let{entry:r}=this.#r.add(e);return await this.#i(r),A(r.subscriber.queue,()=>this.#o(r))}async#i(e){try{await this.#c();}catch(r){throw await this.#o(e),r}}async#o(e){this.#r.remove(e),this.#r.hasActiveSubscriptions()||await this.close();}async close(){this.#s===void 0&&(this.#s=this.#u().finally(()=>{this.#s=void 0;})),await this.#s;}async#u(){this.#n.stop(),this.#r.endAll(),await this.#a.close();}#c(){return this.#a.connect({onClose:()=>this.#l(),onError:()=>this.#h(),onMessage:e=>this.#p(e),onOpen:()=>this.#d(),headers:this.#e,url:this.#t})}#d(){this.#n.resetBackoff();}#p(e){let r=SportsResultEventSchema.safeParse(e);r.success&&this.#r.dispatch(r.data);}#l(){this.#r.hasActiveSubscriptions()&&this.#y();}#h(){}#y(){this.#n.schedule({reconnect:()=>this.#c(),shouldReconnect:()=>this.#r.hasActiveSubscriptions()});}};var me=class{#e;#t;get context(){return this.#e}get decorators(){return this.#t}get environment(){return this.context.environment}get clob(){return this.context.clob}get relayer(){return this.context.relayer}get rpc(){return this.context.rpc}get gamma(){return this.context.gamma}get data(){return this.context.data}get rfq(){return this.context.rfq}get perps(){return this.context.perps}get webSockets(){return this.context.webSockets}get supportsGasless(){return this.context.apiKey?.supportGasless??false}constructor(e){this.#e=e,this.#t=[];}async resolveClobHeaders(e){return this.context.apiKey?.isBuilderKey?this.context.apiKey.authorize(e):Promise.resolve({})}async resolveRelayerHeaders(e){return this.context.apiKey?.supportGasless?this.context.apiKey.authorize(e):Promise.resolve({})}rememberDecorator(e){this.#t.push(e);}},lc=z.object({key:ApiKeySchema,passphrase:z.string(),secret:z.string()}),mc=z.object({wallet:EvmAddressSchema,credentials:lc.optional(),nonce:z.number().int().nonnegative().optional()}).superRefine((t,e)=>{t.credentials!==void 0&&t.nonce!==void 0&&e.addIssue({code:"custom",message:"`credentials` and `nonce` are mutually exclusive.",path:["nonce"]});}).transform(t=>t.credentials!==void 0?{wallet:t.wallet,credentials:t.credentials}:t.nonce!==void 0?{wallet:t.wallet,nonce:t.nonce}:{wallet:t.wallet}),he=class extends me{constructor(e){super({apiKey:e.apiKey,environment:e.environment,data:new P({headers:e.environment.data.headers,root:e.environment.data.rest}),gamma:new P({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),clob:new P({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new P({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rfq:new P({headers:e.environment.rfq.headers,root:e.environment.rfq.rest}),perps:new P({headers:e.environment.perps.headers,root:e.environment.perps.rest}),rpc:new Y({url:e.environment.rpc}),webSockets:{clobMarket:new O({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),sports:new Q({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new _({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new M({headers:e.environment.perps.headers,url:e.environment.perps.ws})}});}isSecureClient(){return false}isPublicClient(){return true}async closeSubscriptions(){await Promise.all([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close()]).then(()=>{});}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}beginAuthentication(e,r){let s=X$1(e,mc);return Promise.resolve(async function*(){let n=Math.floor(Date.now()/1e3),i=s?.nonce??0,o=expectEvmAddress(yield ba()),h=expectEvmAddress(s.wallet),l=Z$1(this.environment,o,h);if(s.credentials!==void 0){let q=this.#e(s.credentials,l,r);try{if((await O$1(q)).includes(s.credentials.key))return q}catch(d$1){if(!(d$1 instanceof d)||d$1.status!==401)throw d$1}}let y=yield {kind:"signAuthMessage",payload:rs({address:o,chainId:this.environment.chainId,nonce:i,timestamp:n})},u=await M$1(this,{address:o,nonce:i,signature:expectEvmSignature(y),timestamp:n});return this.#e(u,l,r)}.call(this))}#e(e,r,s){let n=new at({account:r,apiKey:this.context.apiKey,credentials:e,environment:this.environment,signer:s});for(let i of this.decorators)n.extend(i);return n}},at=class extends me{#e=false;get context(){return invariant(!this.#e,"This client has ended authentication and can no longer be used."),super.context}endAuthenticationLifecycle(){this.#e=true;}constructor(e){super({account:e.account,credentials:e.credentials,apiKey:e.apiKey,environment:e.environment,signer:e.signer,clob:new P({headers:e.environment.clob.headers,root:e.environment.clob.rest,resolveHeaders:r=>this.resolveClobHeaders(r)}),relayer:new P({headers:e.environment.relayer.headers,root:e.environment.relayer.rest,resolveHeaders:r=>this.resolveRelayerHeaders(r)}),rpc:new Y({url:e.environment.rpc}),gamma:new P({headers:e.environment.gamma.headers,root:e.environment.gamma.rest}),data:new P({headers:e.environment.data.headers,root:e.environment.data.rest}),rfq:new P({headers:e.environment.rfq.headers,root:e.environment.rfq.rest}),perps:new P({headers:e.environment.perps.headers,root:e.environment.perps.rest}),secureClob:new P({headers:e.environment.clob.headers,resolveHeaders:async r=>({...await this.resolveClobHeaders(r),...await this.#t(r)}),root:e.environment.clob.rest}),webSockets:{clobMarket:new O({headers:e.environment.clob.market.headers,url:e.environment.clob.market.ws}),clobUser:new B({credentials:e.credentials,headers:e.environment.clob.user.headers,url:e.environment.clob.user.ws}),rfqQuoter:new U({account:e.account,chainId:e.environment.chainId,credentials:e.credentials,exchange:e.environment.contracts.exchangeV3,headers:e.environment.rfq.headers,signer:e.signer,url:e.environment.rfq.ws}),sports:new Q({headers:e.environment.sports.headers,url:e.environment.sports.ws}),rtds:new _({headers:e.environment.rtds.headers,url:e.environment.rtds.ws}),perpsSubscriptions:new M({headers:e.environment.perps.headers,url:e.environment.perps.ws}),perpsSession:new H({chainId:e.environment.chainId,headers:e.environment.perps.headers,restUrl:e.environment.perps.rest,wsUrl:e.environment.perps.ws})}});}get credentials(){return this.context.credentials}get account(){return this.context.account}get signer(){return this.context.signer}setupGaslessWallet(){return Promise.resolve(this)}get secureClob(){return this.context.secureClob}get webSockets(){return this.context.webSockets}async closeSubscriptions(){await Promise.allSettled([this.webSockets.clobMarket.close(),this.webSockets.rtds.close(),this.webSockets.sports.close(),this.webSockets.perpsSubscriptions.close(),this.webSockets.clobUser.close()]).then(()=>{});}isSecureClient(){return true}isPublicClient(){return false}extend(e){return this.rememberDecorator(e),Object.assign(this,e(this)),this}async endAuthentication(){let e=this.closeSubscriptions(),r=this.webSockets.perpsSession.shutdown(),s=this.webSockets.rfqQuoter.shutdown(),{apiKey:n,environment:i}=this.context;try{await Q$1(this);}finally{this.endAuthenticationLifecycle(),await Promise.allSettled([e,r,s]).then(()=>{});}let o=new he({apiKey:n,environment:i});for(let h of this.decorators)o.extend(h);return o}async#t(e){try{let r=Math.floor(Date.now()/1e3);return {POLY_ADDRESS:this.account.signer,POLY_API_KEY:this.credentials.key,POLY_PASSPHRASE:this.credentials.passphrase,POLY_SIGNATURE:await cs(this.credentials.secret,r,e.method,e.path,e.body),POLY_TIMESTAMP:`${r}`}}catch(r){throw j.fromError(r,"Could not sign the L2-authenticated request")}}};function Rn(t={}){return new he({environment:t.environment??We,apiKey:t.apiKey}).extend(os)}var hc=k(h,e,d,j,f,g$1,c,b,a),fc=k(a);async function yc(t){let e=Rn({environment:t.environment,apiKey:t.apiKey}),r=await Pc(e,t),s=await e.beginAuthentication({wallet:r,credentials:t.credentials,nonce:t.nonce},t.signer).then(aa$1(t.signer));if(s.account.walletType===WalletType.EOA||await ha$1(s,{wallet:s.account.wallet,type:s.account.walletType}))return s;if(s.account.walletType===WalletType.DEPOSIT_WALLET)return await Sc(s),s;throw new a(`Wallet ${s.account.wallet} does not exist. Provide an existing wallet address, or omit wallet to use the default Deposit Wallet flow.`)}async function Pc(t,e){if(e.wallet!==void 0)return e.wallet;let r=expectEvmAddress(await e.signer.getAddress());return $(t.rpc,r,t.environment.walletDerivation)}async function Sc(t){let e=await $(t.rpc,t.account.signer,t.environment.walletDerivation);if(!isSameEvmAddress(t.account.wallet,e))throw new a(`Wallet ${t.account.wallet} does not match the expected Deposit Wallet ${e} for this signer, nor a deployed wallet address.`);await(await ka$1(t)).wait();}
|
|
2
|
+
export{hc as CreateSecureClientError,fc as SetupGaslessWalletError,Oe as accountActions,os as allActions,Ie as analyticsActions,cs as buildHmacSignature,Rn as createPublicClient,yc as createSecureClient,Me as dataActions,Fe as discoveryActions,po as forkEnvironmentConfig,Le as perpsActions,tu as preproduction,We as production,ao as relayerApiKey,oo as remoteBuilderSigning,De as rewardsActions,ss as rfqActions,Be as subscriptionsActions,ns as tradingActions,is as walletActions};//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|