Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get Liquidity ticks #110

Merged
merged 6 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
83 changes: 83 additions & 0 deletions contracts/invariant.ral
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ struct FeeTiers {
mut feeTiers: [FeeTier; 32]
}

struct LiquidityTick {
mut index: I256,
mut liquidityChange: U256,
mut sign: Bool
}

Contract Invariant(
mut config: InvariantConfig,
clamm: CLAMM,
Expand Down Expand Up @@ -592,4 +598,81 @@ Contract Invariant(
pub fn getUserPositionCount(owner: Address) -> U256 {
return positionCount(owner)
}

pub fn getLiquidityTicks(poolKey: PoolKey, indexes: ByteVec, length: U256) -> ByteVec {
let mut emptyTicks = #
Sniezka1927 marked this conversation as resolved.
Show resolved Hide resolved

let keyBytes = poolKeyBytes(poolKey)

for (let mut i = 0; i < length; i = i + 1) {
let index = toI256!(u256From4Byte!(byteVecSlice!(indexes, i * 4, (i + 1) * 4))) - GlobalMaxTick

let key = keyBytes ++ toByteVec!(index)
let tick = ticks[key]
emptyTicks = emptyTicks ++ toByteVec!(tick.index) ++ b`break` ++ toByteVec!(tick.liquidityChange) ++ b`break` ++ toByteVec!(tick.sign) ++ b`break`
}

return emptyTicks
}

pub fn getLiquidityTicksAmount(poolKey: PoolKey, lowerTick: I256, upperTick: I256) -> U256 {
let tickSpacing = poolKey.feeTier.tickSpacing
clamm.checkTicks(lowerTick, upperTick, tickSpacing)

let (minChunkIndex, minBit) = tickToPosition(lowerTick, tickSpacing)
let (maxChunkIndex, maxBit) = tickToPosition(upperTick, tickSpacing)
let minBatch = minChunkIndex / ChunksPerBatch
let maxBatch = maxChunkIndex / ChunksPerBatch

let mut amount = 0

if(minBatch == maxBatch) {
let key = poolKeyBytes(poolKey) ++ toByteVec!(minBatch)

if(!bitmap.contains!(key)) {
return 0
}

let batch = bitmap[key].chunks
let minIndexInBatch = minChunkIndex % ChunksPerBatch
let maxIndexInBatch = maxChunkIndex % ChunksPerBatch

if(minIndexInBatch == maxIndexInBatch) {
amount = countActiveBitsInChunk(batch[minIndexInBatch], minBit, maxBit)
return amount
}

amount = countActiveBitsInChunk(batch[minIndexInBatch], minBit, ChunkSize - 1)
for(let mut i = minIndexInBatch + 1; i < maxIndexInBatch; i = i + 1) {
amount = amount + countOnes(batch[i])
}

amount = amount + countActiveBitsInChunk(batch[maxIndexInBatch], 0, maxBit)
return amount
}

amount = countActiveBitsInChunk(getChunk(minChunkIndex, poolKey), minBit, ChunkSize - 1)
for(i = minChunkIndex + 1; i < maxChunkIndex; i = i + 1) {
amount = amount + countOnes(getChunk(i, poolKey))
}

amount = amount + countActiveBitsInChunk(getChunk(maxChunkIndex, poolKey), 0, maxBit)

return amount
}


fn countActiveBitsInChunk(chunk: U256, minBit: U256, maxBit: U256) -> U256 {
Sniezka1927 marked this conversation as resolved.
Show resolved Hide resolved
let range = (chunk >> minBit) & ((1 << (maxBit - minBit + 1)) - 1)
return countOnes(range)
}

fn countOnes(mut v: U256) -> U256 {
Sniezka1927 marked this conversation as resolved.
Show resolved Hide resolved
let mut num = 0
while(v > 0) {
num = num + (v & 1)
v = v >> 1
}
return num
}
}
9 changes: 9 additions & 0 deletions contracts/math/utils.ral
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,13 @@ Contract Utils() extends Uints(), Decimal(), Log(), PoolKeyHelper(), FeeTierHelp
pub fn toFee(feeGrowth: U256, liquidity: U256) -> U256 {
return toU256(bigMulDiv256(feeGrowth, liquidity, one(FeeGrowthScale + LiquidityScale)))
}

pub fn positionToTick(
Sniezka1927 marked this conversation as resolved.
Show resolved Hide resolved
chunk: U256,
bit: U256,
tickSpacing: U256
) -> I256 {
let tickRangeLimit = GlobalMaxTick - (GlobalMaxTick % toI256!(tickSpacing))
return toI256!(chunk * ChunkSize * tickSpacing + (bit * tickSpacing)) - tickRangeLimit
}
}
1 change: 1 addition & 0 deletions src/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const { ReserveError } = Reserve.consts
export const MAX_BATCHES_QUERIED = 18n
export const MAX_POOL_KEYS_QUERIED = 117n
export const MAX_POSITIONS_QUERIED = 83n
export const MAX_LIQUIDITY_TICKS_QUERIED = 269n

export enum VMError {
ArithmeticError = 'ArithmeticError',
Expand Down
64 changes: 56 additions & 8 deletions src/invariant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,16 @@ import {
TransferPosition,
WithdrawProtocolFee
} from '../artifacts/ts'
import { FeeTier, Pool, PoolKey, Position, QuoteResult, Tick } from '../artifacts/ts/types'
import { calculateSqrtPriceAfterSlippage, calculateTick } from './math'
import {
FeeTier,
LiquidityTick,
Pool,
PoolKey,
Position,
QuoteResult,
Tick
} from '../artifacts/ts/types'
import { calculateSqrtPriceAfterSlippage, calculateTick, positionToTick } from './math'
import { Network } from './network'
import { getReserveAddress } from './testUtils'
import {
Expand All @@ -33,9 +41,18 @@ import {
getNodeUrl,
signAndSend,
decodePositions,
Page
Page,
toByteVecWithOffset,
decodeLiquidityTicks,
Tickmap
} from './utils'
import { MAX_BATCHES_QUERIED, MAX_POOL_KEYS_QUERIED, MAX_POSITIONS_QUERIED } from './consts'
import {
ChunkSize,
MAX_BATCHES_QUERIED,
MAX_LIQUIDITY_TICKS_QUERIED,
MAX_POOL_KEYS_QUERIED,
MAX_POSITIONS_QUERIED
} from './consts'
import {
Address,
ALPH_TOKEN_ID,
Expand Down Expand Up @@ -584,7 +601,7 @@ export class Invariant {
return constructTickmap(response.returns)
}

async getFullTickmap(poolKey: PoolKey) {
async getFullTickmap(poolKey: PoolKey): Promise<Tickmap> {
const promises: Promise<[bigint, bigint][]>[] = []
const maxBatch = await getMaxBatch(poolKey.feeTier.tickSpacing)
let currentBatch = 0n
Expand All @@ -599,10 +616,41 @@ export class Invariant {
const storedTickmap = new Map<bigint, bigint>(fullResult)
return { bitmap: storedTickmap }
}
// async getLiquidityTicks() {}
// async getAllLiquidityTicks() {}
async getLiquidityTicks(poolKey: PoolKey, ticks: bigint[]) {
const indexes = toByteVecWithOffset(ticks)
const response = await this.instance.view.getLiquidityTicks({
args: { poolKey, indexes, length: BigInt(ticks.length) }
})

return decodeLiquidityTicks(response.returns)
}
async getAllLiquidityTicks(poolKey: PoolKey, tickmap: Tickmap) {
const tickIndexes: bigint[] = []
for (const [chunkIndex, chunk] of tickmap.bitmap.entries()) {
for (let bit = 0n; bit < ChunkSize; bit++) {
const checkedBit = chunk & (1n << bit)
if (checkedBit) {
const tickIndex = await positionToTick(chunkIndex, bit, poolKey.feeTier.tickSpacing)
tickIndexes.push(tickIndex)
}
}
}
const limit = Number(MAX_LIQUIDITY_TICKS_QUERIED)
const promises: Promise<LiquidityTick[]>[] = []
for (let i = 0; i < tickIndexes.length; i += limit) {
promises.push(this.getLiquidityTicks(poolKey, tickIndexes.slice(i, i + limit)))
}

const liquidityTicks = await Promise.all(promises)
return liquidityTicks.flat()
}
// async getUserPositionAmount() {}
// async getLiquidityTicksAmount() {}
async getLiquidityTicksAmount(poolKey: PoolKey, lowerTick: bigint, upperTick: bigint) {
const response = await this.instance.view.getLiquidityTicksAmount({
args: { poolKey, lowerTick, upperTick }
})
return response.returns
}
async getAllPoolsForPair(token0Id: string, token1Id: string) {
return decodePools(
(
Expand Down
15 changes: 15 additions & 0 deletions src/math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,21 @@ export const calculateTokenAmounts = async (
).returns
}

export const positionToTick = async (
chunk: bigint,
bit: bigint,
tickSpacing: bigint
): Promise<bigint> => {
return (
await Utils.tests.positionToTick({
testArgs: {
chunk,
bit,
tickSpacing
}
})
).returns
}
const sqrt = (value: bigint): bigint => {
if (value < 0n) {
throw 'square root of negative numbers is not supported'
Expand Down
45 changes: 41 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,37 @@
import {
NodeProvider,
codec,
ONE_ALPH,
SignerProvider,
ZERO_ADDRESS,
node,
web3,
SignExecuteScriptTxResult,
bs58,
hexToBinUnsafe,
ALPH_TOKEN_ID
ALPH_TOKEN_ID,
decodeBool
} from '@alephium/web3'
import { CLAMM, Invariant, InvariantInstance, Reserve, Utils } from '../artifacts/ts'
import { TokenFaucet } from '../artifacts/ts/TokenFaucet'
import { FeeTier, FeeTiers, Pool, PoolKey, Position, Tick } from '../artifacts/ts/types'
import { ChunkSize, ChunksPerBatch, MaxFeeTiers } from './consts'
import {
FeeTier,
FeeTiers,
LiquidityTick,
Pool,
PoolKey,
Position,
Tick
} from '../artifacts/ts/types'
import { ChunkSize, ChunksPerBatch, GlobalMaxTick, MaxFeeTiers } from './consts'
import { getMaxTick, getMinTick } from './math'
import { Network } from './network'

const BREAK_BYTES = '627265616b'

export interface Tickmap {
bitmap: Map<bigint, bigint>
}

export const EMPTY_FEE_TIERS: FeeTiers = {
feeTiers: new Array(Number(MaxFeeTiers)).fill({
fee: 0n,
Expand Down Expand Up @@ -357,3 +370,27 @@ export const signAndSend = async (
})
return txId
}

export const toByteVecWithOffset = (
values: bigint[],
offset: bigint = GlobalMaxTick,
radix: number = 16,
length: number = 8,
filler: string = '0'
): string => {
return values.map(value => (value + offset).toString(radix).padStart(length, filler)).join('')
}

export const decodeLiquidityTicks = (string: string): LiquidityTick[] => {
const parts = string.split(BREAK_BYTES)
const ticks: LiquidityTick[] = []
for (let i = 0; i < parts.length - 1; i += 3) {
const tick: LiquidityTick = {
index: decodeI256(parts[i]),
liquidityChange: decodeU256(parts[i + 1]),
sign: decodeBool(hexToBytes(parts[i + 2]))
}
ticks.push(tick)
}
return ticks
}
Loading
Loading