All files snatch.ts

100% Statements 100/100
100% Branches 41/41
100% Functions 4/4
100% Lines 100/100

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146  1x                                                 1x   12x 12x 12x   1x 4x 2x 2x   1x 11x   11x 1x 1x 1x 1x 1x 1x   10x   10x 21x 2x 2x   21x 2x 2x   17x 10x   10x 9x 2x 2x 7x 10x   10x 10x 10x 10x 10x   11x 18x 16x   14x 14x 18x 3x 3x 18x 11x 11x   18x 12x 12x 3x 3x 12x 2x 2x 2x 2x 2x 2x 18x   10x 10x 10x 11x 11x 11x 11x 11x   1x 3x 3x 3x 3x 3x 3x 1x 1x   2x 3x 3x   3x 3x 3x 3x 3x 3x 2x   2x 2x 2x 2x 2x   3x 1x 1x   1x 1x  
import type { Positions as Position } from './__generated__/graphql.js';
import { toBigIntId } from './ids.js';
 
export interface SnatchablePosition {
  id: bigint;
  stakeShares: bigint;
  taxRate: number;
  taxRateIndex?: number;
  owner?: string | null;
}
 
export interface SnatchSelectionOptions {
  shortfallShares: bigint;
  maxTaxRate: number;
  includeOwned?: boolean;
  recipientAddress?: string | null;
}
 
export interface SnatchSelectionResult {
  selected: SnatchablePosition[];
  coveredShares: bigint;
  remainingShortfall: bigint;
  maxSelectedTaxRate?: number;
  maxSelectedTaxRateIndex?: number;
}
 
const SHARE_SCALE = 1_000_000n;
 
function normaliseAddress(value?: string | null): string {
  return (value ?? '').toLowerCase();
}
 
export function minimumTaxRate<T extends { taxRate: number }>(positions: T[], fallback: number = 0): number {
  if (!positions.length) return fallback;
  return positions.reduce((min, position) => (position.taxRate < min ? position.taxRate : min), Number.POSITIVE_INFINITY);
}
 
export function selectSnatchPositions(candidates: SnatchablePosition[], options: SnatchSelectionOptions): SnatchSelectionResult {
  const { shortfallShares, maxTaxRate, includeOwned = false, recipientAddress = null } = options;
 
  if (shortfallShares <= 0n) {
    return {
      selected: [],
      coveredShares: 0n,
      remainingShortfall: 0n,
    };
  }
 
  const recipientNormalised = normaliseAddress(recipientAddress);
 
  const filtered = candidates.filter(candidate => {
    if (candidate.taxRate >= maxTaxRate) {
      return false;
    }
 
    if (!includeOwned && candidate.owner) {
      return normaliseAddress(candidate.owner) !== recipientNormalised;
    }
 
    return true;
  });
 
  const sorted = filtered.slice().sort((a, b) => {
    if (a.taxRate === b.taxRate) {
      return Number(a.stakeShares - b.stakeShares);
    }
    return a.taxRate - b.taxRate;
  });
 
  const selection: SnatchablePosition[] = [];
  let remaining = shortfallShares;
  let covered = 0n;
  let maxSelectedTaxRate: number | undefined;
  let maxSelectedTaxRateIndex: number | undefined;
 
  for (const candidate of sorted) {
    if (remaining <= 0n) break;
    if (candidate.stakeShares <= 0n) continue;
 
    selection.push(candidate);
    remaining -= candidate.stakeShares;
    if (remaining < 0n) {
      covered = shortfallShares;
      remaining = 0n;
    } else {
      covered = shortfallShares - remaining;
    }
 
    if (maxSelectedTaxRate === undefined || candidate.taxRate > maxSelectedTaxRate) {
      maxSelectedTaxRate = candidate.taxRate;
      if (typeof candidate.taxRateIndex === 'number') {
        maxSelectedTaxRateIndex = candidate.taxRateIndex;
      }
    } else if (
      candidate.taxRate === maxSelectedTaxRate &&
      typeof candidate.taxRateIndex === 'number' &&
      candidate.taxRateIndex > (maxSelectedTaxRateIndex ?? -1)
    ) {
      maxSelectedTaxRateIndex = candidate.taxRateIndex;
    }
  }
 
  return {
    selected: selection,
    coveredShares: covered,
    remainingShortfall: remaining > 0n ? remaining : 0n,
    maxSelectedTaxRate,
    maxSelectedTaxRateIndex,
  };
}
 
export function getSnatchList(
  positions: Position[],
  needed: bigint,
  taxRate: number,
  stakeTotalSupply: bigint
): bigint[] {
  if (stakeTotalSupply <= 0n) {
    throw new Error('stakeTotalSupply must be greater than zero');
  }
 
  const candidates: SnatchablePosition[] = positions.map(position => {
    const shareRatio = Number(position.share);
    const scaledShares = BigInt(Math.round(shareRatio * Number(SHARE_SCALE)));
 
    return {
      id: toBigIntId(position.id),
      owner: position.owner,
      stakeShares: (stakeTotalSupply * scaledShares) / SHARE_SCALE,
      taxRate: Number(position.taxRate),
    };
  });
 
  const result = selectSnatchPositions(candidates, {
    shortfallShares: needed,
    maxTaxRate: taxRate,
    includeOwned: true,
  });
 
  if (result.remainingShortfall > 0n) {
    throw new Error('Not enough capacity');
  }
 
  return result.selected.map(candidate => candidate.id);
}