Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/dev-522-max-spend-fees.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@polymarket/client": patch
---

Size fee-inclusive BUY market orders with exact fee ratios for integer exponents and final-boundary fee rounding, while retaining a compatibility fallback for fractional exponents.
16 changes: 8 additions & 8 deletions packages/client/src/actions/orders/amounts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { OrderSide, type TickSizeValue } from '@polymarket/bindings';
import { describe, expect, it } from 'vitest';
import { computeLimitOrderAmounts, computeMarketOrderAmounts } from './amounts';
import { validatePriceOnTickGrid } from './context';
import { type ScaledPrice, toScaledPrice } from './fixed';
import { type ScaledPrice, toScaledAmount, toScaledPrice } from './fixed';

const INPUT_AMOUNT = 12.34;
const SCALED_INPUT_AMOUNT = 12_340_000n;
const SCALED_INPUT_AMOUNT = toScaledAmount(INPUT_AMOUNT);

const TICK_CASES = [
{
Expand Down Expand Up @@ -136,7 +136,7 @@ describe('computeMarketOrderAmounts', () => {
}) => {
expect(
computeMarketOrderAmounts({
amount: INPUT_AMOUNT,
amount: SCALED_INPUT_AMOUNT,
price: scaledPrice,
side: OrderSide.BUY,
tickSize,
Expand All @@ -154,7 +154,7 @@ describe('computeMarketOrderAmounts', () => {
}) => {
expect(
computeMarketOrderAmounts({
amount: INPUT_AMOUNT,
amount: SCALED_INPUT_AMOUNT,
price: scaledPrice,
protectPrice: true,
side: OrderSide.BUY,
Expand All @@ -176,7 +176,7 @@ describe('computeMarketOrderAmounts', () => {
for (const protectPrice of [false, true]) {
expect(
computeMarketOrderAmounts({
amount: INPUT_AMOUNT,
amount: SCALED_INPUT_AMOUNT,
price: scaledPrice,
protectPrice,
side: OrderSide.SELL,
Expand All @@ -189,10 +189,10 @@ describe('computeMarketOrderAmounts', () => {
}
});

it('rounds the public amount down to two decimals before calculating amounts', () => {
it('rounds the scaled amount down to two decimals before calculating amounts', () => {
expect(
computeMarketOrderAmounts({
amount: 12.349,
amount: toScaledAmount(12.349),
price: toScaledPrice(0.37),
protectPrice: true,
side: OrderSide.BUY,
Expand All @@ -207,7 +207,7 @@ describe('computeMarketOrderAmounts', () => {
it('does not round up protected SELL proceeds when division is exact', () => {
expect(
computeMarketOrderAmounts({
amount: 9.99,
amount: toScaledAmount(9.99),
price: toScaledPrice(0.1),
protectPrice: true,
side: OrderSide.SELL,
Expand Down
8 changes: 2 additions & 6 deletions packages/client/src/actions/orders/amounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export function computeLimitOrderAmounts(params: {
}

export function computeMarketOrderAmounts(params: {
amount: number;
amount: ScaledAmount;
price: ScaledPrice;
protectPrice?: boolean;
side: OrderSide;
Expand All @@ -81,11 +81,7 @@ export function computeMarketOrderAmounts(params: {
requestedAmount: bigint;
} {
const roundConfig = resolveRoundingConfig(params.tickSize);
const amount = quantize(
toScaledAmount(params.amount),
roundConfig.size,
Rounding.Down,
);
const amount = quantize(params.amount, roundConfig.size, Rounding.Down);
const rounding = params.protectPrice ? Rounding.Up : Rounding.Down;

if (params.side === OrderSide.BUY) {
Expand Down
77 changes: 77 additions & 0 deletions packages/client/src/actions/orders/fees.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { describe, expect, it } from 'vitest';
import {
adjustBuyAmountForFees,
platformFeeAmount,
platformFeeRateFactor,
} from './fees';
import { Rounding, toScaledAmount, toScaledPrice } from './fixed';

describe('platformFeeRateFactor', () => {
it('keeps the complete integer-power factor as an exact ratio', () => {
expect(platformFeeRateFactor(toScaledPrice(0.05), 0.25, 2)).toEqual({
numerator: 361n,
denominator: 640_000n,
});
});

it('keeps fractional exponents on a non-throwing compatibility path', () => {
expect(platformFeeRateFactor(toScaledPrice(0.5), 0.25, 1.5)).toEqual({
numerator: 1n,
denominator: 32n,
});
});
});

describe('platformFeeAmount', () => {
it('rounds only after applying the complete fee factor', () => {
const factor = platformFeeRateFactor(toScaledPrice(0.05), 0.25, 2);

expect(platformFeeAmount(toScaledAmount(100), factor, Rounding.Down)).toBe(
56_400n,
);
expect(platformFeeAmount(toScaledAmount(100), factor, Rounding.Up)).toBe(
56_410n,
);
});
});

describe('adjustBuyAmountForFees', () => {
it('keeps the amount unchanged when max spend covers amount plus fees', () => {
expect(
adjustBuyAmountForFees({
amount: 10,
builderTakerFeeRate: 0,
platformFeeExponent: 1,
platformFeeRate: 0.02,
maxSpend: 11,
price: toScaledPrice(0.5),
}),
).toBe(10_000_000n);
});

it('reduces the buy spend using final-boundary platform fee rounding', () => {
expect(
adjustBuyAmountForFees({
amount: 10,
builderTakerFeeRate: 0,
platformFeeExponent: 1,
platformFeeRate: 0.02,
maxSpend: 10,
price: toScaledPrice(0.5),
}),
).toBe(9_900_990n);
});

it('includes separately rounded builder taker fees in max spend', () => {
expect(
adjustBuyAmountForFees({
amount: 10,
builderTakerFeeRate: 0.01,
platformFeeExponent: 1,
platformFeeRate: 0.02,
maxSpend: 10,
price: toScaledPrice(0.5),
}),
).toBe(9_803_920n);
});
});
205 changes: 205 additions & 0 deletions packages/client/src/actions/orders/fees.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import { invariant } from '@polymarket/types';
import {
FIXED_SCALE,
mulDiv,
Rounding,
type ScaledAmount,
type ScaledPrice,
scaledQuantum,
toScaledAmount,
} from './fixed';

const FEE_DECIMALS = 5;

export type ExactRatio = Readonly<{
numerator: bigint;
denominator: bigint;
}>;

function greatestCommonDivisor(left: bigint, right: bigint): bigint {
let a = left;
let b = right;

while (b !== 0n) {
const remainder = a % b;
a = b;
b = remainder;
}

return a;
}

function exactRatio(numerator: bigint, denominator: bigint): ExactRatio {
invariant(numerator >= 0n, 'Ratio numerator must be non-negative.');
invariant(denominator > 0n, 'Ratio denominator must be positive.');

if (numerator === 0n) {
return { numerator: 0n, denominator: 1n };
}

const divisor = greatestCommonDivisor(numerator, denominator);
return {
numerator: numerator / divisor,
denominator: denominator / divisor,
};
}

function exactRatioFromNumber(value: number): ExactRatio {
invariant(
Number.isFinite(value) && value >= 0,
'Ratio value must be a non-negative finite number.',
);

const [coefficient = '0', exponentText = '0'] = value.toString().split('e');
const exponent = Number(exponentText);
const [whole, fraction = ''] = coefficient.split('.');
const digits = `${whole}${fraction}`;
const decimalPlaces = fraction.length - exponent;

if (decimalPlaces <= 0) {
return exactRatio(BigInt(digits) * 10n ** BigInt(-decimalPlaces), 1n);
}

return exactRatio(BigInt(digits), 10n ** BigInt(decimalPlaces));
}

function multiplyRatios(left: ExactRatio, right: ExactRatio): ExactRatio {
return exactRatio(
left.numerator * right.numerator,
left.denominator * right.denominator,
);
}

function powRatio(value: ExactRatio, exponent: number): ExactRatio {
const magnitude = BigInt(Math.abs(exponent));

if (exponent < 0) {
invariant(value.numerator > 0n, 'Cannot raise zero to a negative power.');
return exactRatio(
value.denominator ** magnitude,
value.numerator ** magnitude,
);
}

return exactRatio(
value.numerator ** magnitude,
value.denominator ** magnitude,
);
}

function approximateFractionalPlatformFeeRateFactor(
price: ScaledPrice,
rate: number,
exponent: number,
): ExactRatio {
const priceNumber = Number(price) / Number(FIXED_SCALE);
const factor = rate * (priceNumber * (1 - priceNumber)) ** exponent;

// The backend uses shopspring/decimal's Ln/ExpTaylor path for fractional
// powers. There is no established cross-runtime error bound against
// Math.pow, so this remains an isolated compatibility fallback. Converting
// its result here ensures all fee-base math and final rounding stay integer.
return exactRatioFromNumber(factor);
}

export function platformFeeRateFactor(
price: ScaledPrice,
rate: number,
exponent: number,
): ExactRatio {
invariant(
price > 0n && price < FIXED_SCALE,
'Fee price must be between zero and one.',
);
invariant(
Number.isFinite(rate) && rate >= 0,
'Fee rate must be a non-negative finite number.',
);
invariant(Number.isFinite(exponent), 'Fee exponent must be finite.');

if (!Number.isSafeInteger(exponent)) {
return approximateFractionalPlatformFeeRateFactor(price, rate, exponent);
}

const priceRatio = exactRatio(price, FIXED_SCALE);
const complementRatio = exactRatio(FIXED_SCALE - price, FIXED_SCALE);
const base = multiplyRatios(priceRatio, complementRatio);

return multiplyRatios(exactRatioFromNumber(rate), powRatio(base, exponent));
}

export function platformFeeAmount(
feeBase: ScaledAmount,
factor: ExactRatio,
rounding: Rounding,
): ScaledAmount {
const quantum = scaledQuantum(FEE_DECIMALS);
return (mulDiv(
feeBase,
factor.numerator,
factor.denominator * quantum,
rounding,
) * quantum) as ScaledAmount;
}

function platformFeePerBuyAmountFactor(
price: ScaledPrice,
rate: number,
exponent: number,
): ExactRatio {
return multiplyRatios(platformFeeRateFactor(price, rate, exponent), {
numerator: FIXED_SCALE,
denominator: price,
});
}

function totalBuySpend(
amount: ScaledAmount,
platformFactor: ExactRatio,
builderFactor: ExactRatio,
): bigint {
const platformFee = platformFeeAmount(amount, platformFactor, Rounding.Up);
const builderFee = platformFeeAmount(amount, builderFactor, Rounding.Up);

return amount + platformFee + builderFee;
}

export function adjustBuyAmountForFees(params: {
amount: number;
price: ScaledPrice;
maxSpend: number;
platformFeeRate: number;
platformFeeExponent: number;
builderTakerFeeRate: number;
}): ScaledAmount {
const amount = toScaledAmount(params.amount);
const maxSpend = toScaledAmount(params.maxSpend);
const platformFactor = platformFeePerBuyAmountFactor(
params.price,
params.platformFeeRate,
params.platformFeeExponent,
);
const builderFactor = exactRatioFromNumber(params.builderTakerFeeRate);

if (totalBuySpend(amount, platformFactor, builderFactor) <= maxSpend) {
return amount;
}

let lower = 0n;
let upper: bigint = amount < maxSpend ? amount : maxSpend;

while (lower < upper) {
const candidate = (lower + upper + 1n) / 2n;
const candidateAmount = candidate as ScaledAmount;

if (
totalBuySpend(candidateAmount, platformFactor, builderFactor) <= maxSpend
) {
lower = candidate;
} else {
upper = candidate - 1n;
}
}

return lower as ScaledAmount;
}
Loading