{"version":3,"file":"pricing.mjs","names":["forward"],"sources":["../../src/predict/pricing.ts"],"sourcesContent":["// Copyright (c) Mysten Labs, Inc.\n// SPDX-License-Identifier: Apache-2.0\n// Faithful float port of `deepbook_predict::pricing::compute_nd2` as of the anchor the\n// generated bindings are pinned to (`sui-codegen.config.ts`: the `deepbook-predict-testnet`\n// deployment). `pricing.move` is untouched across the anchors this SDK has used, so the\n// formula is unchanged from earlier deployments — the SVI-adjusted digital\n// probability, WITH the skew-correction term. It operates on the pricer's\n// ALREADY-RESOLVED forward and ALREADY-ROLLED-DOWN SVI, exactly as `load_live_pricer`\n// returns them (decoded by `reads/pricing.ts`). So the two on-chain steps that pick the\n// forward (Pyth-spot vs Block-Scholes, admin flag + freshness) and roll `a`/`b` down by\n// remaining/anchored time already happened on-chain — this module never re-derives them,\n// which is what keeps it faithful.\n//\n// This is the fast client-side board pricer: read one `Pricer` snapshot, then price every\n// strike locally with no further chain calls. `read.price` / `read.quoteMint` (a chain\n// dry-run) stay the authoritative quote at trade time. Divergence vs the chain is up to\n// ~1e-4 in probability, dominated by the chain's fixed-point truncation near ATM when sigma\n// sits at its floor (float64 here is the more precise side, not the less); negligible for\n// display. `tests/testnet/pricing.test.ts` bounds it live against the deployment.\n//\n// The on-chain formula (pricing/pricing.move `compute_nd2`):\n//   k  = ln(strike / forward)\n//   x  = k - m\n//   w  = a + b·(ρ·x + √(x² + σ²))            // a, b already rolled down\n//   d2 = −(k + w/2) / √w                       // clamped to ±8\n//   w′ = b·(ρ + x/√(x² + σ²))                  // SVI slope\n//   price = N(d2) − φ(d2)·w′ / (2·√w)          // the skew correction, clamped [0,1]\n\n/** Rolled-down SVI parameters for one expiry, in decimal (NOT the chain's 1e9/1e18 integer\n * scaling) — the surface AFTER Predict's remaining-time roll-down, as carried by the\n * on-chain `Pricer`. `a`, `rho`, `m` are signed; `b`, `sigma` are non-negative. */\nexport interface Svi {\n\ta: number;\n\tb: number;\n\trho: number;\n\tm: number;\n\tsigma: number;\n}\n\n/** A resolved pricer snapshot: the forward the contract prices against and its rolled SVI\n * surface, both in decimal. Produced by `read.pricer(market)`; consume via {@link boardPricer}\n * or the pure functions below. */\nexport interface PricerInputs {\n\t/** Forward price the digital settles against, in decimal (same units as `strike`). */\n\tforward: number;\n\tsvi: Svi;\n}\n\n/** Standard normal CDF via erf (Abramowitz–Stegun 7.1.26, |err| < 1.5e-7). */\nfunction normalCdf(x: number): number {\n\treturn 0.5 * (1 + erf(x / Math.SQRT2));\n}\n\n/** Standard normal PDF. */\nfunction normalPdf(x: number): number {\n\treturn Math.exp(-0.5 * x * x) / Math.sqrt(2 * Math.PI);\n}\n\nfunction erf(x: number): number {\n\tconst sign = x >= 0 ? 1 : -1;\n\tconst ax = Math.abs(x);\n\tconst t = 1 / (1 + 0.3275911 * ax);\n\tconst y =\n\t\t1 -\n\t\t((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) *\n\t\t\tt *\n\t\t\tMath.exp(-ax * ax);\n\treturn sign * y;\n}\n\n// Clamp |d2| at 8, matching the chain (`normal_cdf`/`normal_pdf` saturate beyond that).\nfunction clampD2(d2: number): number {\n\treturn d2 > 8 ? 8 : d2 < -8 ? -8 : d2;\n}\n\n/** P(settle > strike) — the UP digital, with the SVI skew correction. `inputs.svi` is the\n * already-rolled surface (no roll-down applied here). `forward` and `strike` share units.\n * Returns a probability in [0, 1]. */\nexport function upProbability(inputs: PricerInputs, strike: number): number {\n\tconst { forward, svi } = inputs;\n\tif (!(forward > 0)) return 0;\n\tif (strike <= 0) return 1; // neg-inf limit\n\tconst { a, b, rho, m, sigma } = svi;\n\tconst k = Math.log(strike / forward);\n\tconst km = k - m;\n\tconst root = Math.sqrt(km * km + sigma * sigma);\n\tconst inner = rho * km + root; // >= 0 for |rho| <= 1\n\tconst w = a + b * inner; // total variance\n\t// The chain guarantees w > 0 at every strike (assert_min_total_variance_positive at\n\t// load time), so this branch is unreachable in practice; return the variance→0 tail\n\t// limit rather than throw, so a UI never crashes on a degenerate snapshot.\n\tif (w <= 0) return k < 0 ? 1 : 0;\n\tconst sq = Math.sqrt(w);\n\tconst d2 = clampD2(-((k + w / 2) / sq));\n\tconst nd2 = normalCdf(d2);\n\tconst wPrime = b * (rho + km / root); // SVI slope × b\n\tconst price = nd2 - (normalPdf(d2) * wPrime) / (2 * sq); // skew correction\n\treturn price < 0 ? 0 : price > 1 ? 1 : price;\n}\n\n/** P(settle < strike) — the DOWN digital. Exactly `1 − up`, matching the chain's\n * `range_price(-inf, strike] = up(-inf) − up(strike) = 1 − up(strike)`. */\nexport function downProbability(inputs: PricerInputs, strike: number): number {\n\treturn 1 - upProbability(inputs, strike);\n}\n\n/** Probability mass in `(lower, higher]`, floored at 0 (matches `compute_range_price`'s\n * saturating subtraction). Use `lower <= 0` for the −∞ bound and `higher = Infinity` for +∞. */\nexport function rangeProbability(inputs: PricerInputs, lower: number, higher: number): number {\n\t// up(lower) − up(higher), where up(+inf) = 0 and up(<= 0) = 1.\n\tconst upLower = lower <= 0 ? 1 : upProbability(inputs, lower);\n\tconst upHigher = higher === Infinity ? 0 : upProbability(inputs, higher);\n\tconst d = upLower - upHigher;\n\treturn d < 0 ? 0 : d;\n}\n\n/** Binary probability at `strike` for the given side (`up` = P(>strike), `down` = 1 − up). */\nexport function probability(inputs: PricerInputs, strike: number, side: 'up' | 'down'): number {\n\tconst up = upProbability(inputs, strike);\n\treturn side === 'up' ? up : 1 - up;\n}\n\n/** Strike where P(settle > strike) = `p`, by bisection (UP is monotone-decreasing in\n * strike). Null when no crossing exists within ±64% of forward. */\nexport function strikeAtProbability(inputs: PricerInputs, p: number): number | null {\n\tconst { forward } = inputs;\n\tif (!(forward > 0) || !(p > 0 && p < 1)) return null;\n\tconst up = (strike: number) => upProbability(inputs, strike);\n\tlet r = 0.01;\n\twhile (up(forward * (1 - r)) < p || up(forward * (1 + r)) > p) {\n\t\tr *= 2;\n\t\tif (r > 0.64) return null;\n\t}\n\tlet lo = forward * (1 - r);\n\tlet hi = forward * (1 + r);\n\tfor (let i = 0; i < 64; i++) {\n\t\tconst mid = (lo + hi) / 2;\n\t\tif (up(mid) > p) lo = mid;\n\t\telse hi = mid;\n\t}\n\treturn (lo + hi) / 2;\n}\n\n// --- Resolving raw feed data client-side (for consumers that hold their own live oracle\n// feed and want to price with NO chain call, e.g. deepbook-app). The turnkey path is\n// `read.pricer(market)`, which reads these already resolved from the chain's `Pricer`;\n// these two helpers reproduce the on-chain resolution when you'd rather not read the chain.\n\n/** Roll `a` and `b` down by the fraction of anchored time remaining, matching the chain's\n * `roll_down_svi` (variance decays toward expiry). `remainingMs` = expiry − now;\n * `anchorTteMs` = expiry − the SVI observation's **provider `svi_timestamp`** (its per-update\n * source timestamp) — the same clock the freshness gate accepts, and what the chain anchors on\n * (`pricing.move`: \"One clock serves every job\"). Anchoring on the batch's ingestion time\n * instead rolls by the wrong fraction. `read.pricer` avoids the question entirely (the chain\n * has already rolled). `rho`, `m`, `sigma` are unchanged. Feed an UNrolled provider surface;\n * the result is what {@link upProbability} expects. */\nexport function rollDown(svi: Svi, remainingMs: number, anchorTteMs: number): Svi {\n\tconst frac = anchorTteMs > 0 ? remainingMs / anchorTteMs : 0;\n\treturn { ...svi, a: svi.a * frac, b: svi.b * frac };\n}\n\n/** The forward the contract prices against: Pyth spot re-anchored by the Block-Scholes\n * basis (`spot · forward/bsSpot`), falling back to the Block-Scholes forward when Pyth is\n * absent. Pass `pythSpot <= 0` to force the fallback. NOTE: on-chain this branch is also\n * gated by the admin flag `use_pyth_spot_for_forward` (default on) and a Pyth freshness\n * window — when the flag is off or the Pyth spot is stale, the chain uses `bsForward`. If\n * you track that config/freshness, apply it before calling (or use `read.pricer`, which\n * gets the resolved forward from the chain). */\nexport function forward(pythSpot: number, bsSpot: number, bsForward: number): number {\n\tif (pythSpot > 0 && bsSpot > 0) return pythSpot * (bsForward / bsSpot);\n\treturn bsForward;\n}\n\n/** A pricer bound to one resolved snapshot: price a whole board of strikes locally, no\n * chain calls. Returned by `read.pricer(market)`; also constructable directly from inputs\n * you already hold (e.g. from a `Pricer` snapshot decoded elsewhere). */\nexport interface BoardPricer extends PricerInputs {\n\t/** P(settle > strike). */\n\tup(strike: number): number;\n\t/** P(settle < strike) = 1 − up. */\n\tdown(strike: number): number;\n\t/** P(side wins at strike). */\n\tprobability(strike: number, side: 'up' | 'down'): number;\n\t/** Probability mass in `(lower, higher]` (use `lower<=0`/`higher=Infinity` for the tails). */\n\trange(lower: number, higher: number): number;\n\t/** Strike where P(> strike) = `p`, or null if outside ±64% of forward. */\n\tstrikeAtProbability(p: number): number | null;\n}\n\n/** Build a {@link BoardPricer} from a resolved snapshot (decimal forward + rolled SVI). Pure. */\nexport function boardPricer(inputs: PricerInputs): BoardPricer {\n\treturn {\n\t\tforward: inputs.forward,\n\t\tsvi: inputs.svi,\n\t\tup: (strike) => upProbability(inputs, strike),\n\t\tdown: (strike) => downProbability(inputs, strike),\n\t\tprobability: (strike, side) => probability(inputs, strike, side),\n\t\trange: (lower, higher) => rangeProbability(inputs, lower, higher),\n\t\tstrikeAtProbability: (p) => strikeAtProbability(inputs, p),\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;AAiDA,SAAS,UAAU,GAAmB;AACrC,QAAO,MAAO,IAAI,IAAI,IAAI,KAAK,MAAM;;;AAItC,SAAS,UAAU,GAAmB;AACrC,QAAO,KAAK,IAAI,MAAO,IAAI,EAAE,GAAG,KAAK,KAAK,IAAI,KAAK,GAAG;;AAGvD,SAAS,IAAI,GAAmB;CAC/B,MAAM,OAAO,KAAK,IAAI,IAAI;CAC1B,MAAM,KAAK,KAAK,IAAI,EAAE;CACtB,MAAM,IAAI,KAAK,IAAI,WAAY;AAM/B,QAAO,QAJN,QACI,cAAc,IAAI,eAAe,IAAI,eAAe,IAAI,cAAe,IAAI,cAC9E,IACA,KAAK,IAAI,CAAC,KAAK,GAAG;;AAKrB,SAAS,QAAQ,IAAoB;AACpC,QAAO,KAAK,IAAI,IAAI,KAAK,KAA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