@mostlyrightmd/markets/polymarket
Classes
Section titled “Classes”PolymarketSettlementError
Section titled “PolymarketSettlementError”Settlement engine couldn’t resolve an event to a value.
Extends
Section titled “Extends”MostlyrightError
Constructors
Section titled “Constructors”new PolymarketSettlementError()
Section titled “new PolymarketSettlementError()”new PolymarketSettlementError(
message):PolymarketSettlementError
Parameters
Section titled “Parameters”message
Section titled “message”string
Returns
Section titled “Returns”Overrides
Section titled “Overrides”MostlyrightError.constructor
Properties
Section titled “Properties”defaultErrorCode
Section titled “defaultErrorCode”
readonlystaticdefaultErrorCode:"POLYMARKET_SETTLEMENT_FAILED"="POLYMARKET_SETTLEMENT_FAILED"
Subclass override — the stable string enum surfaced via errorCode.
Overrides
Section titled “Overrides”MostlyrightError.defaultErrorCode
PolymarketStrikeError
Section titled “PolymarketStrikeError”Raised on a strike phrase that cannot be parsed. A ContractError subclass (DX-H5): an unparseable strike is an invalid local call, raised before I/O.
Extends
Section titled “Extends”ContractError
Constructors
Section titled “Constructors”new PolymarketStrikeError()
Section titled “new PolymarketStrikeError()”new PolymarketStrikeError(
message):PolymarketStrikeError
Parameters
Section titled “Parameters”message
Section titled “message”string
Returns
Section titled “Returns”Overrides
Section titled “Overrides”ContractError.constructor
TooEarlyToSettleError
Section titled “TooEarlyToSettleError”Settlement attempted before the resolution source’s publication delay
has elapsed. Carries waitHours so the caller can schedule a retry.
P2: overrides payload() so toDict() (and any MCP
serializer downstream) includes the structured retry metadata. The
fields are otherwise only readable via the live JS error object.
Extends
Section titled “Extends”MostlyrightError
Constructors
Section titled “Constructors”new TooEarlyToSettleError()
Section titled “new TooEarlyToSettleError()”new TooEarlyToSettleError(
message,opts):TooEarlyToSettleError
Parameters
Section titled “Parameters”message
Section titled “message”string
resolutionSourceType
Section titled “resolutionSourceType”string
waitHours
Section titled “waitHours”number
Returns
Section titled “Returns”Overrides
Section titled “Overrides”MostlyrightError.constructor
Properties
Section titled “Properties”defaultErrorCode
Section titled “defaultErrorCode”
readonlystaticdefaultErrorCode:"POLYMARKET_TOO_EARLY"="POLYMARKET_TOO_EARLY"
Subclass override — the stable string enum surfaced via errorCode.
Overrides
Section titled “Overrides”MostlyrightError.defaultErrorCode
resolutionSourceType
Section titled “resolutionSourceType”
readonlyresolutionSourceType:string
waitHours
Section titled “waitHours”
readonlywaitHours:number
Interfaces
Section titled “Interfaces”FetchEventsOptions
Section titled “FetchEventsOptions”Extended by
Section titled “Extended by”Properties
Section titled “Properties”fetchFn()?
Section titled “fetchFn()?”
readonlyoptionalfetchFn: (input,init?) =>Promise<Response>(input,init?) =>Promise<Response>
Override fetch (for tests). Defaults to global fetch.
Parameters
Section titled “Parameters”URL | RequestInfo
RequestInit
Returns
Section titled “Returns”Promise<Response>
Parameters
Section titled “Parameters”string | URL | Request
RequestInit
Returns
Section titled “Returns”Promise<Response>
signal?
Section titled “signal?”
readonlyoptionalsignal:AbortSignal
AbortSignal for the whole paginator.
sleepBetweenMs?
Section titled “sleepBetweenMs?”
readonlyoptionalsleepBetweenMs:number
Politeness sleep between requests, in ms. Default 200 (0.2 s). Pass 0 to skip.
ParsedPolymarketStrike
Section titled “ParsedPolymarketStrike”Properties
Section titled “Properties”
readonlyoptionalhiC:number
readonlykind:PolymarketStrikeKind
readonlyoptionalloC:number
Range bounds in Celsius (between).
strikeC?
Section titled “strikeC?”
readonlyoptionalstrikeC:number
Strike in Celsius (above/below).
PolymarketDiscoverOptions
Section titled “PolymarketDiscoverOptions”Extends
Section titled “Extends”Properties
Section titled “Properties”fetchFn()?
Section titled “fetchFn()?”
readonlyoptionalfetchFn: (input,init?) =>Promise<Response>(input,init?) =>Promise<Response>
Override fetch (for tests). Defaults to global fetch.
Parameters
Section titled “Parameters”URL | RequestInfo
RequestInit
Returns
Section titled “Returns”Promise<Response>
Parameters
Section titled “Parameters”string | URL | Request
RequestInit
Returns
Section titled “Returns”Promise<Response>
Inherited from
Section titled “Inherited from”onSkip()?
Section titled “onSkip()?”
optionalonSkip: (info) =>void
Sink for dropped events. Tests pass a recorder; production can pass
console.info or omit. Receives {slug, reason} per skipped event.
Parameters
Section titled “Parameters”reason
Section titled “reason”string
null | string
Returns
Section titled “Returns”void
signal?
Section titled “signal?”
readonlyoptionalsignal:AbortSignal
AbortSignal for the whole paginator.
Inherited from
Section titled “Inherited from”sleepBetweenMs?
Section titled “sleepBetweenMs?”
readonlyoptionalsleepBetweenMs:number
Politeness sleep between requests, in ms. Default 200 (0.2 s). Pass 0 to skip.
Inherited from
Section titled “Inherited from”FetchEventsOptions.sleepBetweenMs
PolymarketDiscoveryRow
Section titled “PolymarketDiscoveryRow”Discovery row shape — one per active weather event.
Properties
Section titled “Properties”
readonlycity:null|string
endTime
Section titled “endTime”
readonlyendTime:null|string
eventId
Section titled “eventId”
readonlyeventId:null|string
readonlyicao:null|string
resolutionSourceType
Section titled “resolutionSourceType”
readonlyresolutionSourceType:null|"wunderground"|"noaa_wrh"|"hko"|"cwa"|"other"
readonlyslug:null|string
temperature_extreme
Section titled “temperature_extreme”
readonlytemperature_extreme:null|"high"|"low"|"ambiguous"
readonlytitle:null|string
PolymarketEventRaw
Section titled “PolymarketEventRaw”Raw Gamma event payload — narrow shape we depend on.
Indexable
Section titled “Indexable”[key: string]: unknown
Properties
Section titled “Properties”active?
Section titled “active?”
optionalactive:boolean
archived?
Section titled “archived?”
optionalarchived:boolean
closed?
Section titled “closed?”
optionalclosed:boolean
description?
Section titled “description?”
optionaldescription:string
endDate?
Section titled “endDate?”
optionalendDate:string
optionalid:string
optionalslug:string
optionaltags: (string| {label:string;slug:string; })[]
title?
Section titled “title?”
optionaltitle:string
PolymarketSettleArgs
Section titled “PolymarketSettleArgs”Settlement options.
Extends
Section titled “Extends”Properties
Section titled “Properties”description?
Section titled “description?”
readonlyoptionaldescription:string
Optional description override (live discovery normally supplies this).
Inherited from
Section titled “Inherited from”PolymarketSettleOptions.description
readonlyevent:PolymarketEventRaw
The raw Gamma event payload. Required because the settle engine reads
slug (for the resolution date), description (for the resolution
source), and title/slug/name (for the measure). Callers can fetch
via fetchEventById if they only have an id.
loader?
Section titled “loader?”
readonlyoptionalloader:ObservationLoader
Loader that returns observation rows for [fromDate, toDate]. Defaults
to an in-memory empty loader so callers MUST wire this for production.
readonlyoptionalnow:Date
Reference “now” for the finalization-delay check. Defaults to new Date().
Inherited from
Section titled “Inherited from”polymarketPublishedValue?
Section titled “polymarketPublishedValue?”
readonlyoptionalpolymarketPublishedValue:number
Polymarket’s published settlement value, if known. The comparison
uses whichever unit unit is set to. ±1°F (or ±0.6°C) diff emits an
alert; values outside that band don’t throw.
Inherited from
Section titled “Inherited from”PolymarketSettleOptions.polymarketPublishedValue
readonlyoptionalunit:SettlementUnit
Resolved-value unit. Defaults to the station’s native unit: °F for the 20 US Kalshi cities; °C for international stations (matches Polymarket’s published-bucket convention per the ingest-planner research).
Inherited from
Section titled “Inherited from”PolymarketSettlementResult
Section titled “PolymarketSettlementResult”Settlement result shape.
Properties
Section titled “Properties”dataQualityAlert
Section titled “dataQualityAlert”
readonlydataQualityAlert:null|string
eventId
Section titled “eventId”
readonlyeventId:string
readonlyicao:string
resolutionSourceType
Section titled “resolutionSourceType”
readonlyresolutionSourceType:"wunderground"|"noaa_wrh"|"hko"|"cwa"|"other"
resolvedValue
Section titled “resolvedValue”
readonlyresolvedValue:number
Resolved temperature in the unit the caller asked for (the unit
option; defaults to the station’s native unit — F for US-registry
stations, C for international). Convenience pointer to resolvedValueF
or resolvedValueC.
resolvedValueC
Section titled “resolvedValueC”
readonlyresolvedValueC:number
resolvedValueF
Section titled “resolvedValueF”
readonlyresolvedValueF:number
settlementDate
Section titled “settlementDate”
readonlysettlementDate:string
temperature_extreme
Section titled “temperature_extreme”
readonlytemperature_extreme:"high"|"low"
readonlyunit:SettlementUnit
Which unit resolvedValue carries.
PolymarketSettleOptions
Section titled “PolymarketSettleOptions”Settlement options.
Extended by
Section titled “Extended by”Properties
Section titled “Properties”description?
Section titled “description?”
readonlyoptionaldescription:string
Optional description override (live discovery normally supplies this).
readonlyoptionalnow:Date
Reference “now” for the finalization-delay check. Defaults to new Date().
polymarketPublishedValue?
Section titled “polymarketPublishedValue?”
readonlyoptionalpolymarketPublishedValue:number
Polymarket’s published settlement value, if known. The comparison
uses whichever unit unit is set to. ±1°F (or ±0.6°C) diff emits an
alert; values outside that band don’t throw.
readonlyoptionalunit:SettlementUnit
Resolved-value unit. Defaults to the station’s native unit: °F for the 20 US Kalshi cities; °C for international stations (matches Polymarket’s published-bucket convention per the ingest-planner research).
Type Aliases
Section titled “Type Aliases”ObservationLoader()
Section titled “ObservationLoader()”ObservationLoader: (
args) =>Promise<ReadonlyArray<InternationalRow>>
Loader contract for the resolution-source observation rows. Defaults to a no-op stub so the security/validation gates can be unit-tested without pulling live cache data; production callers wire the cache reader here.
Returning an empty array signals “no rows available for this date” and surfaces as PolymarketSettlementError downstream.
Parameters
Section titled “Parameters”fromDate
Section titled “fromDate”string
string
toDate
Section titled “toDate”string
Returns
Section titled “Returns”Promise<ReadonlyArray<InternationalRow>>
PolymarketResolutionSourceType
Section titled “PolymarketResolutionSourceType”PolymarketResolutionSourceType: typeof
POLYMARKET_RESOLUTION_SOURCE_TYPES[number]
PolymarketStrikeKind
Section titled “PolymarketStrikeKind”PolymarketStrikeKind:
"above"|"below"|"between"
SettlementUnit
Section titled “SettlementUnit”SettlementUnit:
"fahrenheit"|"celsius"
Native unit of the market’s published settlement value. P2 international Polymarket markets publish in whole-°C, US in °F. The settle engine returns the resolved value in BOTH units so the caller’s comparison against Polymarket’s published value uses the matching unit.
Variables
Section titled “Variables”DEFERRED_STATIONS
Section titled “DEFERRED_STATIONS”
constDEFERRED_STATIONS:ReadonlySet<string>
Markets routed to v0.2 sources.: Hong Kong settles against HKO (the Observatory, weather.gov.hk) and Taipei moved RCTP→RCSS (CWA). Both fully defer every measure; the old VHHH/RCTP airport ICAOs are no longer deferred.
EVENT_ID_RE
Section titled “EVENT_ID_RE”
constEVENT_ID_RE:RegExp
Event id pattern. Python widened this in P1: real Gamma IDs
are numeric strings ("12345"), but condition-tag UUIDs + slugs also
appear in the wild. Wide enough to accept real Gamma payloads but narrow
enough to defend against URL-path injection.
The plan called this “UUID4 regex” but follows Python’s actual behavior: the strict UUID4 form rejected every real Gamma event, breaking the discover → settle round-trip.
MAX_DESCRIPTION_BYTES
Section titled “MAX_DESCRIPTION_BYTES”
constMAX_DESCRIPTION_BYTES:number
Max bytes of a Polymarket event description we’ll parse. Polymarket descriptions are concise; oversized payloads indicate hostile input (ReDoS defense).
NETLOC_TO_RESOLUTION_TYPE
Section titled “NETLOC_TO_RESOLUTION_TYPE”
constNETLOC_TO_RESOLUTION_TYPE:Readonly<Record<string,string>>
Per-netloc → enum value for the resolutionSourceType field on settlement
records. hko / cwa are predeclared for v0.2 (HKO/CWA clients).
POLYMARKET_KNOWN_WRONG_STATIONS
Section titled “POLYMARKET_KNOWN_WRONG_STATIONS”
constPOLYMARKET_KNOWN_WRONG_STATIONS:Readonly<Record<string,ReadonlySet<string>>>
POLYMARKET_RESOLUTION_SOURCE_TYPES
Section titled “POLYMARKET_RESOLUTION_SOURCE_TYPES”
constPOLYMARKET_RESOLUTION_SOURCE_TYPES: readonly ["wunderground","noaa_wrh","hko","cwa","other"]
Enum values for the resolutionSourceType column.
RESOLUTION_SOURCE_ALLOWLIST
Section titled “RESOLUTION_SOURCE_ALLOWLIST”
constRESOLUTION_SOURCE_ALLOWLIST:ReadonlySet<string>
Resolution-source netlocs we trust. Anything else throws
PolymarketEventError. Mirrors Python RESOLUTION_SOURCE_ALLOWLIST.
SETTLE_DELAY_HOURS
Section titled “SETTLE_DELAY_HOURS”
constSETTLE_DELAY_HOURS:Readonly<Record<string,number>>
Per-resolution-source publication delay. Settlement refuses to settle
until now - settlementDate >= delay to avoid settling on values the
issuer hasn’t published yet.
Wunderground typically posts daily extremes ~6h after local midnight; NOAA WRH ~4h. “other” gets a conservative 24h fallback.
SLUG_DATE_RE
Section titled “SLUG_DATE_RE”
constSLUG_DATE_RE:RegExp
Slug date extractor. Polymarket weather slugs embed the resolution date
(e.g. will-nyc-be-above-80f-on-2026-05-23). Used by settle
to derive the resolution date from the slug instead of event.endDate.
Functions
Section titled “Functions”deriveCity()
Section titled “deriveCity()”deriveCity(
event):null|string
Derive a city key from slug + title + tags. Lowercase substring match against the catalog; longest-first so multi-token cities outrank prefixes. Returns null when no match — caller decides whether to drop or surface.
Parameters
Section titled “Parameters”Returns
Section titled “Returns”null | string
detectMarketMeasure()
Section titled “detectMarketMeasure()”detectMarketMeasure(
event):"default"|"high"|"low"
Detect whether the market resolves on the daily HIGH or LOW from keywords in the event title/slug/name. Distinct from the station-level measure: many cities have one airport for both, but the market still resolves on tmax XOR tmin.
Parameters
Section titled “Parameters”Returns
Section titled “Returns”"default" | "high" | "low"
discover()
Section titled “discover()”discover(
opts):Promise<PolymarketDiscoveryRow[]>
Discover active Polymarket weather events.
Returns one row per resolvable event. Events the resolver can’t match
are dropped silently (with optional onSkip callback). Events that
route to a deferred station (Taipei, HK-low) appear in the result with
icao: null and measure: null so callers can SEE them.
Parameters
Section titled “Parameters”PolymarketDiscoverOptions = {}
Returns
Section titled “Returns”Promise<PolymarketDiscoveryRow[]>
extractIcaoFromResolutionSource()
Section titled “extractIcaoFromResolutionSource()”extractIcaoFromResolutionSource(
text):null|string
Extract the canonical Wunderground PWS / airport ICAO from text.
Tier 1.5 of the resolver chain — runs between explicit event.city
and slug-derive. When a Polymarket event embeds a Wunderground PWS
URL, the URL IS the source of truth; no catalog lookup needed.
Multi-URL disambiguation: when multiple canonical Wunderground URLs appear, ALL extracted ICAOs MUST agree. Disagreement returns null so the resolver falls through to Tier 2 city-derive (prevents an issuer-side citation URL from silently swapping the settlement station).
Returns uppercase ICAO (4 chars, leading K) when a canonical URL is found AND any additional canonical URLs agree. Null otherwise — including the disagreement case.
Parameters
Section titled “Parameters”undefined | null | string
Returns
Section titled “Returns”null | string
extractResolutionSourceType()
Section titled “extractResolutionSourceType()”extractResolutionSourceType(
description):"wunderground"|"noaa_wrh"|"hko"|"cwa"|"other"
Classify a description’s resolution source by the first allowlisted netloc
found. Returns "other" when no allowlisted URL appears (the settlement
engine falls back to the 24-hour delay for “other”).
Parameters
Section titled “Parameters”description
Section titled “description”string
Returns
Section titled “Returns”"wunderground" | "noaa_wrh" | "hko" | "cwa" | "other"
fetchEventById()
Section titled “fetchEventById()”fetchEventById(
eventId,opts):Promise<null|PolymarketEventRaw>
Fetch a single event by id. Useful for the settle() flow when only an id is known.
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
FetchEventsOptions = {}
Returns
Section titled “Returns”Promise<null | PolymarketEventRaw>
fetchEvents()
Section titled “fetchEvents()”fetchEvents(
opts):Promise<PolymarketEventRaw[]>
Fetch every active weather event from Gamma, paginated by offset in
PAGE_SIZE increments until either an empty page is returned or
MAX_EVENTS is reached. Dedup by slug to defend against the rare case
where pagination overlaps under concurrent edits on Gamma’s side.
Parameters
Section titled “Parameters”FetchEventsOptions = {}
Returns
Section titled “Returns”Promise<PolymarketEventRaw[]>
parsePolymarketStrike()
Section titled “parsePolymarketStrike()”parsePolymarketStrike(
text):ParsedPolymarketStrike
Parse a Polymarket temperature strike phrase (above 30C, below 86F,
between 20 and 25C) into a normalized Celsius strike.
Parameters
Section titled “Parameters”string
Returns
Section titled “Returns”Throws
Section titled “Throws”when no recognized phrase is present.
resolveStationForEvent()
Section titled “resolveStationForEvent()”resolveStationForEvent(
event,marketMeasure):null| {city:string;icao:string;stationMeasure:"default"|"high"|"low"; }
Resolve an event to {icao, stationMeasure} using the city catalog.
Returns null when no city matches (caller drops the event). Raises DeferredMarketError when the resolution would route to a v0.2 source (Taipei RCTP, Hong Kong VHHH for the low-extreme market).
Parameters
Section titled “Parameters”marketMeasure
Section titled “marketMeasure”"default" | "high" | "low"
Returns
Section titled “Returns”null | { city: string; icao: string; stationMeasure: "default" | "high" | "low"; }
settle()
Section titled “settle()”settle(
args):Promise<PolymarketSettlementResult>
Settle a single Polymarket event.
Validates the event id, description (16 KB cap, netloc allowlist),
resolves the station via the city catalog, parses the resolution date
from the slug, enforces the per-source publication-delay window, and
pulls the daily extreme via internationalDailyExtremes.
Parameters
Section titled “Parameters”Returns
Section titled “Returns”Promise<PolymarketSettlementResult>
Throws
Section titled “Throws”PolymarketEventError on bad id / bad description / unsupported station.
Throws
Section titled “Throws”PolymarketSettlementError when no rows resolve for the station/date.
Throws
Section titled “Throws”TooEarlyToSettleError when the publication delay hasn’t elapsed.
settleById()
Section titled “settleById()”settleById(
eventId,args):Promise<PolymarketSettlementResult>
Settle by event id alone. Fetches the event from Gamma first, then
delegates to settle. Useful when a caller only has the id
(e.g. from a Kalshi-side cross-reference).
Parameters
Section titled “Parameters”eventId
Section titled “eventId”string
Omit<PolymarketSettleArgs, "event">
Returns
Section titled “Returns”Promise<PolymarketSettlementResult>
settlementDateFromSlug()
Section titled “settlementDateFromSlug()”settlementDateFromSlug(
slug):string
Parse the resolution date from a Polymarket weather slug. The LAST
YYYY-MM-DD match wins because slugs may carry both a creation date and
a resolution date (created-<date>-resolves-<date>) — the
resolution date is typically rightmost in Polymarket’s convention.
Mirrors Python _settlement_date_from_slug architect iter-1 HIGH-4.
Parameters
Section titled “Parameters”string
Returns
Section titled “Returns”string
settlePolymarketOutcome()
Section titled “settlePolymarketOutcome()”settlePolymarketOutcome(
parsed,observedC):null|0|1
Settle an observed Celsius value against a parsed Polymarket strike.
INCLUSIVE comparison (mirrors Kalshi for cross-venue consistency): above → observed >= strike; below → observed <= strike; between → lo <= observed <= hi.
Parameters
Section titled “Parameters”parsed
Section titled “parsed”observedC
Section titled “observedC”null | number
Returns
Section titled “Returns”null | 0 | 1
1 (YES), 0 (NO), or null when observedC is null (NaN label → NA
outcome, row preserved).
validateDescription()
Section titled “validateDescription()”validateDescription(
description):void
Apply the 16 KB cap + netloc allowlist to a description string.
Parameters
Section titled “Parameters”description
Section titled “description”string
Returns
Section titled “Returns”void
Throws
Section titled “Throws”PayloadTooLargeError when the UTF-8 byte length exceeds 16 KB.
Throws
Section titled “Throws”PolymarketEventError when any URL has a netloc outside the allowlist.