npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@mayflower-sys/avm-calc

v202608.1222.849

Published

Client-side AVM calculator for prices, reserve areas, trade quotes, and floor raises.

Readme

@mayflower-sys/avm-calc

Client-side AVM prices, reserve areas, and trade quotes. The implementation is four pure layers:

characteristic parameters + characteristic engine -> CharacteristicFunction
affine parameters         + CharacteristicFunction -> TransformedCharacteristic
segmentation parameters   + TransformedCharacteristic -> Calculator
current supply            + Calculator -> Quoter

Each layer has one job and produces an immutable value for the next layer. The public package exports a small codec-aware facade; raw Decimal math, branded types, solvers, and layer modules remain package-private.

The calculator targets 0.1% relative accuracy. On-chain settlement is always authoritative.

Geometry and stored state

1. Characteristic

A characteristic engine compiles shape parameters into a neutral function f(u) with three operations: evaluate, invert, and integrate. It knows nothing about a market's units, translations, floor, ramp, or live supply.

Built-in characteristics are:

| Engine | Parameters | Neutral function | | ------------------ | ---------------- | ------------------------------------------ | | Linear | { slope } | f(u) = slope * u | | Hinged exponential | { m, h, q, k } | m*u + q*d^2*phi2(k*d), d = max(u-h, 0) |

Both require a positive base slope so evaluation is strictly increasing and inversion is unique.

2. Affine transform

The affine layer maps world-space supply x to characteristic coordinate u, then maps the characteristic value to the market's main curve M:

u    = xScale * (x - xTranslation)
M(x) = yScale * f(u) + yTranslation

xScale and yScale must be positive. Translations are signed. xTranslation has graph-space semantics: adding delta moves the complete curve right by exactly delta, regardless of xScale.

3. Segmentation

Segmentation persists { floor, rampStart, rampScalar }. rampStart is in the neutral characteristic's u coordinate, before affine x mapping. Its derived world-space location is:

x1 = xTranslation + rampStart / xScale

This coordinate choice is deliberate:

  • an option or floor-redemption shift changes only affine xTranslation;
  • token-unit normalization changes only affine xScale;
  • both changes transform the main, ramp start, and ramp end together.

For floor F and scalar s > 1, the ramp is:

R(x) = F + s * (M(x) - M(x1))

The ramp end x2 is not stored. It is the unique intersection R(x2) = M(x2):

M(x2) = (s * M(x1) - F) / (s - 1)

If M(x1) = F, the ramp has zero width and x2 = x1. Otherwise segmentation requires M(x1) >= F, derives x2 with the main's inverse, and builds:

C(x) = F       when x < x1
       R(x)    when x1 <= x < x2
       M(x)    when x >= x2

The resulting calculator is continuous at both boundaries. rampStart, rampEnd, and rampWidth on the public calculator are world-space derived outputs; only state.segmentationParameters.rampStart is persisted.

Public API

Create a calculator with one built-in characteristic and one boundary number type:

import {
  Decimal,
  makeLinearAvmCalculatorDecimalJs,
} from "@mayflower-sys/avm-calc"

const d = (value: string | number) => new Decimal(value)

const calc = makeLinearAvmCalculatorDecimalJs(d(4), {
  // Neutral characteristic f(u) = 2u.
  characteristicParameters: { slope: d(2) },

  // Main M(x) = 2x + 5.
  affineParameters: {
    xScale: d(1),
    xTranslation: d(0),
    yScale: d(1),
    yTranslation: d(5),
  },

  // Local ramp start u1=1 maps to world x1=1. The derived ramp is
  // R(x)=3x+2 and intersects the main at world x2=3.
  segmentationParameters: {
    floor: d(5),
    rampStart: d(1),
    rampScalar: d(1.5),
  },
})

calc.currentSupply // 4: quote anchor, not geometric state
calc.state // complete persisted input; safe to pass back to this factory
calc.rampStart // 1: derived world-space boundary
calc.rampEnd // 3: derived world-space boundary
calc.rampWidth // 2: rampEnd - rampStart

calc.exchangeRateAtSupply(d(4)) // 13
calc.areaBetween(d(0), d(4)) // 33
calc.reservesInForExactSharesOut(d(1)) // 14
calc.reservesOutForExactSharesIn(d(1)) // 12

The calculator is immutable. raiseFloorPreserveArea, withCurrentSupply, translateSchedule, and contractToSupply return new calculators; all other public methods return values only.

Persist and restore

Persist currentSupply and state. Do not persist derived ramp geometry:

const restored = makeLinearAvmCalculatorDecimalJs(
  calc.currentSupply,
  calc.state,
)

The state has exactly three layers:

type LinearAvmState<N> = {
  readonly characteristicParameters: { readonly slope: N }
  readonly affineParameters: {
    readonly xScale: N
    readonly xTranslation: N
    readonly yScale: N
    readonly yTranslation: N
  }
  readonly segmentationParameters: {
    readonly floor: N
    readonly rampStart: N // characteristic-coordinate u, not world x
    readonly rampScalar: N
  }
}

Calculator members

| Member | Contract | | --------------------------------------- | --------------------------------------------------------------------------------------------------------- | | currentSupply | Live supply anchor used by trade quotes | | state | Complete persisted characteristic, affine, and segmentation input | | rampStart, rampEnd, rampWidth | Derived world-space segmentation geometry | | exchangeRateAtSupply(supply) | Piecewise spot price at any world-space supply | | areaBetween(lo, width) | Reserve area over [lo, lo + width] | | reservesInForExactSharesOut(shares) | Buy cost for exact shares | | sharesOutForExactReservesIn(reserves) | Shares bought for exact reserves | | reservesOutForExactSharesIn(shares) | Sell proceeds, or null if shares exceed supply | | sharesInForExactReservesOut(reserves) | Shares sold, or null if reserves are unreachable | | raiseFloorPreserveArea(floor) | New calculator with higher floor, unchanged main and live spot, and preserved area through current supply | | withCurrentSupply(supply) | New calculator with the same curve re-anchored to a new live supply | | translateSchedule(by) | New calculator with schedule and supply anchor shifted together by by world units; spot unchanged | | contractToSupply(supply) | New calculator accepting a post-sell supply, applying the sell-contraction transition and re-anchoring |

translateSchedule is the option-execution shift (positive by) and the floor-redemption shift (negative by); it rejects a negative shift that would move the ramp start below zero. contractToSupply implements both contraction rows of the transition-ownership table below and leaves the curve untouched when the accepted supply is at or above the ramp end.

An area-preserving floor raise searches only for a new local ramp start. Every candidate ramp end is derived from the unchanged transformed characteristic. A raise is rejected if current supply is not above the old ramp end or if the new ramp end would pass current supply and change the live spot.

Number boundaries

Factory suffixes select the number type used by every input and output:

| Factory suffix | Number type | | -------------- | ------------------------------- | | ...String | Decimal strings such as "1.5" | | ...Float | Native number | | ...DecimalJs | decimal.js Decimal |

Custom numeric types use the codec factories:

import {
  makeLinearAvmCalculatorWithCodec,
  type Fixed,
  type NumberCodec,
} from "@mayflower-sys/avm-calc"

type Money = { readonly units: bigint; readonly decimals: number }

const MoneyCodec: NumberCodec<Money> = {
  toFixed: (value): Fixed => ({
    value: value.units,
    scale: value.decimals,
  }),
  fromFixed: (value) => ({
    units: value.value,
    decimals: value.scale,
  }),
}

const makeCalculator = makeLinearAvmCalculatorWithCodec(MoneyCodec)

Fixed means value * 10^(-scale). The codec is the only public numeric seam. Construction validates all three state layers with Effect Schema. Invalid boundary input throws a ParseError; invalid cross-layer geometry throws an Error describing the violated invariant.

Maintainer guide: pure module seams

The root package intentionally does not export its math internals. Inside this package, construction reads left to right:

const quoter = pipe(
  Linear.make(characteristicParameters),
  Affine.make(affineParameters),
  Segmentation.make(segmentationParameters),
  Quoter.make(currentSupply),
)

Conventions for the internal modules:

  • A characteristic engine's make(parameters) compiles a neutral function.
  • A layer's make(parameters) is a unary pipe stage; its data-first overload remains available as make(value, parameters).
  • Operations use Effect dual, so both operation(value, args) and pipe(value, operation(args)) work.
  • Values are immutable. Transformations compile a new layer value and do not mutate captured parameters.
  • Option represents unreachable quote math internally. Only the public codec facade converts it to null.
  • Raw decimal.js values stay inside math modules. Effect Schema brands and codecs validate only at layer or package boundaries.

The important transition ownership is:

| Transition | State changed | State deliberately unchanged | | --------------------------- | --------------------------------------- | ------------------------------------------------- | | Horizontal schedule shift | Affine xTranslation | Characteristic and segmentation parameters | | Token-unit normalization | Affine xScale | Characteristic and segmentation parameters | | Sell contraction into ramp | Affine yTranslation | Characteristic, floor, local ramp start, scalar | | Sell contraction into floor | Affine yTranslation, local ramp start | Characteristic, floor, scalar | | Area-preserving floor raise | Floor and local ramp start | Characteristic, complete affine transform, scalar |

This ownership table is the architectural boundary: a new characteristic engine should not reimplement transforms, segmentation, quoting, contraction, or floor raising.