Skip to main content

Entrypoints

This section outlines the core entrypoints for the Invariant smart contract, providing developers with essential methods to interact with the protocol. These entrypoints cover various aspects of the contract, including protocol fee management, fee tier administration, pool creation and management, position handling, and swap functionality.

Constructor

Contract Invariant(
mut config: InvariantConfig,
clamm: CLAMM,
reserveTemplateId: ByteVec,
mut lastReserveId: ByteVec,
mut feeTierCount: U256,
mut poolKeyCount: U256
) extends PoolKeyHelper(), Decimal(), PoolKeys(), Pools(clamm),
Ticks(), Tickmap(), Positions(clamm), FeeTierHelper(), Reserves();

This constructor method initializes the contract with the specified protocol fee and administrator.

Input parameters

NameTypeDescription
configInvariantConfigConfig struct defining the admin and protocol fee.
clammCLAMMContractId of the CLAMM module.
reserveTemplateIdByteVecContractId of a Reserve Contract.
lastReserveIdByteVecContractId of the same Reserve Contract.
feeTierCountU256Should be initialized to 0.
poolKeyCountU256Should be initialized to 0.

Protocol fee

Get protocol fee

pub fn getProtocolFee() -> U256;

This method retrieves the current protocol fee percentage.

Output parameters

TypeDescription
U256The current protocol fee.

Withdraw protocol fee

Fee receiver only

This action is only available to the fee receiver.

pub fn withdrawProtocolFee(poolKey: PoolKey) -> ();

This operation enables the withdrawal of protocol fees associated with a specific pool, based on the provided pool key. The withdrawn funds are sent to the fee receiver wallet.

Input parameters

NameTypeDescription
poolKeyPoolKeyThe pool key that corresponds to the withdrawal of fees from the associated pool.

Errors

CodeDescription
PoolNotFoundReverts the call when a pool associated with the poolKey doesn't exist.
NotFeeReceiverReverts the call when the caller is unauthorized receiver.

Change protocol fee

Administrator only

This action is only available to the administrator.

@using(updateFields = true)
pub fn changeProtocolFee(newProtocolFee: U256) -> ();

This function allows for the adjustment of the current protocol fee percentage.

Input parameters

NameTypeDescription
newProtocolFeeU256The new protocol fee percentage.

Errors

CodeDescription
PoolNotFoundReverts the call when a pool associated with the poolKey doesn't exist.
NotAdminReverts the call when the caller is an unauthorized user.

Change fee receiver

Administrator only

This action is only available to the administrator.

pub fn changeFeeReceiver(poolKey: PoolKey, newFeeReceiver: Address) -> ();

This function allows for the modification of the fee receiver of a pool.

Input parameters

NameTypeDescription
poolKeyPoolKeyThe pool key of the pool where the change is to be made.
newFeeReceiverAddressThe new fee receiver's address of the pool.

Errors

CodeDescription
NotAdminReverts the call when the caller is unauthorized user.

Fee tier

Add fee tier

Administrator only

This action is only available to the administrator.

@using(preapprovedAssets = true, updateFields = true)
pub fn addFeeTier(feeTier: FeeTier) -> ();

This function enables the addition of a new fee tier, which users can subsequently utilize when creating pools. Up to 32 fee tiers can exist.

Input parameters

NameTypeDescription
feeTierFeeTierThe fee tier to be added.

Errors

CodeDescription
NotAdminFails if an unauthorized user attempts to create a fee tier.
InvalidTickSpacingFails if the tick spacing is invalid.
FeeTierAlreadyExistFails if the fee tier already exists.
InvalidFeeFails if fee is invalid.
FeeTierLimitReachedFails if the maximal number of fee tiers (32) already exists.

Fee Tier exists

pub fn feeTierExist(feeTier: FeeTier) -> Bool;

This function is used to verify the existence of a specified fee tier.

Input parameters

NameTypeDescription
feeTierFeeTierThe key associated with the fee tier to be checked for existence.

Output parameters

TypeDescription
BoolBoolean indicating if the fee tier exists.

Get fee tiers

pub fn getFeeTiers() -> ByteVec;

Retrieves available fee tiers.

Output parameters

TypeDescription
ByteVecByteVec containing all fee tiers.

Remove fee tier

Administrator only

This action is only available to the administrator.

pub fn removeFeeTier(feeTier: FeeTier) -> ();

This function removes a fee tier based on the provided fee tier key. After removal, the fee tier will no longer be available for use in pool creation. It is important to note that existing pools with that fee tier will remain unaffected.

Input parameters

NameTypeDescription
feeTierFeeTierThe key associated with the fee tier to be removed.

Errors

CodeDescription
NotAdminFails if an unauthorized user attempts to create a fee tier.
FeeTierNotFoundFails if fee tier does not exist.

Pools

Create pool

Permission-less

Anyone can add a pool and no permissions are needed.

token standard

The tokens are expected to use Alephium's Fungible Token Standard.

While not required, consider also adding them to the official Token List.

token sorting

This function employs the token[0|1] naming convention, indicating that arranging these tokens in ascending order by contractId is not necessary.

@using(preapprovedAssets = true, checkExternalCaller = false)
pub fn createPool(token0: ByteVec, token1: ByteVec, feeTier: FeeTier, initSqrtPrice: U256, initTick: I256) -> ();

This function creates a pool based on a pair of tokens and the specified fee tier. Only one pool can exist with an unique combination of two tokens and a fee tier.

Input parameters

NameTypeDescription
token0ByteVecContract ID of the first token in the pair.
token1ByteVecContract ID of the second token in the pair.
feeTierFeeTierThe fee tier to be applied.
initSqrtPriceU256The square root of the price for the initial pool related to initTick.
initTickI256The initial tick value for the pool.

Errors

CodeDescription
FeeTierNotFoundFails if the specified fee tier cannot be found.
TokensAreSameFails if the user attempts to create a pool for the same tokens.
PoolKeyAlreadyExistFails if Pool with same tokens and fee tier already exist.
InvalidTickSpacingFails if the init tick is not divisible by the tick spacing.
InvalidTickIndexFails if the init tick is outside of the Min <= Init <= Max tick index range.
TickAndSqrtPriceMismatchFails if the init sqrt price is not related to the init tick.

Get pool

Option abstraction

The (Bool, Struct) tuple fulfils the same role as Rust's Option abstraction. Bool's state indicates whether the second parameter "is some?", in the case it is not a default value is passed and should not be used.

pub fn getPool(poolKey: PoolKey) -> (Bool, Pool);

This function retrieves a pool based on PoolKey. It returns false as the first tuple variable if the pool does not exist.

Input parameters

NameTypeDescription
poolKeyPoolKeyThe pool key of the pool you want to retrieve.

Output parameters

TypeDescription
BoolIf true the pool was found and retrieved successfully, false otherwise.
PoolA struct containing pool data.

Get pools for a token pair

token sorting

This function employs the token[0|1] naming convention, indicating that arranging these tokens in ascending order by contractId is not necessary.

pub fn getAllPoolsForPair(token0: ByteVec, token1: ByteVec) -> ByteVec;

This function retrieves all pools for the given token pair.

Input parameters

NameTypeDescription
token0ByteVecContract ID of the first token in the pair.
token1ByteVecContract ID of the second token in the pair.

Output parameters

TypeDescription
ByteVecByteVec containing all pools for a given key pair that indicate all pools listed.

Position

Create position

@using(preapprovedAssets = true, checkExternalCaller = false)
pub fn createPosition(
poolKey: PoolKey,
lowerTickIndex: I256,
upperTickIndex: I256,
liquidityDelta: U256,
slippageLimitLower: U256,
slippageLimitUpper: U256
) -> ();

This function creates a position based on the provided parameters. The amount of tokens specified in liquidity delta will be deducted from the user's token balances. Position creation will fail if the user does not have enough tokens or has not approved enough tokens.

Input parameters

NameTypeDescription
poolKeyPoolKeyThe pool key for which you want to create a position.
lowerTickI256The lower tick index of your position.
upperTickI256The upper tick index of your position.
liquidityDeltaU256The liquidity you want to provide.
slippageLimitLowerU256The lower limit determined by the square root of the price, which cannot be exceeded by the current sqrtPrice in the pool.
slippageLimitUpperU256The upper limit determined by the square root of the price, which cannot be exceeded by the current sqrtPrice in the pool.

Errors

CodeDescription
ZeroLiquidityFails if the user attempts to open a position with zero liquidity.
InvalidTickIndexFails if the user attempts to create a position with invalid tick indexes.
InvalidTickSpacingFails if the user attempts to create a position with invalid tick spacing.
PriceLimitReachedFails if the price has reached the slippage limit.
PoolNotFoundFails if pool does not exist.

Transfer position

@using(preapprovedAssets = true, checkExternalCaller = false)
pub fn transferPosition(index: U256, newOwner: Address) -> ();

This function changes ownership of an existing position based on the position index in the user's position list. You can only change ownership of positions that you own; otherwise, it will return an error.

Input parameters

NameTypeDescription
indexU256Index of the position in the user's position list.
newOwnerAddressAddress of the user who will receive the position.

Errors

CodeDescription
PositionNotFoundFails if position does not exist.

Remove position

@using(checkExternalCaller = false)
pub fn removePosition(index: U256) -> ();

This function removes a position from the user's position list and transfers the tokens in the position and all generated unclaimed fees to the user's address.

Input parameters

NameTypeDescription
indexU256Index of the position in the user's position list.

Errors

CodeDescription
PositionNotFoundFails if Position cannot be found.

Claim fee

@using(checkExternalCaller = false)
pub fn claimFee(index: U256) -> ();

This function allows the user to claim fees from an existing position. Tokens will be sent to the user's address.

Input parameters

NameTypeDescription
indexU256Index of the position in the user's position list.

Errors

CodeDescription
PositionNotFoundFails if Position cannot be found.

Get position

Option abstraction

The (Bool, Struct) tuple fulfils the same role as Rust's Option abstraction. Bool's state indicates whether the second parameter "is some?", in the case it is not a default value is passed and should not be used.

pub fn getPosition(owner: Address, index: U256) -> (Bool, Position);

This function returns false as the first tuple variable and an empty Position as the second if the position does not exist.

Input parameters

NameTypeDescription
ownerAddressAn Address identifying the user who owns the position.
indexU256Index of the position in the user's position list.

Output parameters

TypeDescription
BoolIf true the position was found and retrieved successfully, false otherwise.
PositionA struct containing position data.

Swap

Swap

@using(preapprovedAssets = true, checkExternalCaller = false)
pub fn swap(
poolKey: PoolKey,
xToY: Bool,
amount: U256,
byAmountIn: Bool,
sqrtPriceLimit: U256
) -> CalculateSwapResult

This function executes a swap based on the provided parameters. It transfers tokens from the user's address to the contract's address and vice versa. The swap will fail if the user does not have enough tokens, the swap limit is exceeded, has not approved enough tokens, or if there is insufficient liquidity.

Input parameters

NameTypeDescription
poolKeyPoolKeyPool key of the pool on which you wish to perform the swap.
xToYBoolSpecifies the direction of the swap. If true swap from the Token with lower ContractId to the one with higher, else the other way around.
amountU256Amount of tokens you want to receive or give.
byAmountInBoolIndicates whether the entered amount represents the tokens you wish to receive or give.
sqrtPriceLimitU256If the swap achieves this square root of the price, it will be canceled.

Output parameters

TypeDescription
CalculateSwapResultA struct containing the amount in and amount out with starting and target square root of price, taken fee, pool.

Errors

CodeDescription
ZeroAmountFails if the user attempts to perform a swap with zero amounts.
WrongPriceLimitFails if the square root of price or price limit is set incorrectly. Usually happens due to setting the wrong direction of the swap.
PriceLimitReachedFails if the price has reached the specified price limit (or price associated with specified square root of price).
TickLimitReachedFails if the tick index has reached the global tick limit.
NoGainSwapFails if the user would receive zero tokens.
PoolNotFoundFails if pool does not exist.

Quote

    @using(checkExternalCaller = false)
pub fn quote(
poolKey: PoolKey,
xToY: Bool,
amount: U256,
byAmountIn: Bool,
sqrtPriceLimit: U256
) -> QuoteResult;

This function performs a simulation of a swap based on the provided parameters and returns the simulation results. It does not involve any actual token transfers.

Input parameters

NameTypeDescription
poolKeyPoolKeyPool key of the pool on which you wish to perform the swap.
xToYBoolSpecifies the direction of the swap. If true swap from the Token with lower ContractId to the one with higher, else the other way around.
amountU256Amount of tokens you want to receive or give.
byAmountInBoolIndicates whether the entered amount represents the tokens you wish to receive or give.
sqrtPriceLimitU256If the swap achieves this square root of the price, it will be canceled.

Output parameters

TypeDescription
QuoteResultA struct containing amount of tokens received, amount of tokens given and square root of price after the simulated swap.

Errors

CodeDescription
ZeroAmountFails if the user attempts to perform a swap with zero amounts.
WrongPriceLimitFails if the square root of price or price limit is set incorrectly. Usually happens due to setting the wrong direction of the swap.
PriceLimitReachedFails if the price has reached the specified price limit (or price associated with specified square root of price).
TickLimitReachedFails if the tick index has reached the global tick limit.
NoGainSwapFails if the user would receive zero tokens.
PoolNotFoundFails if pool does not exist.

Tick

Get tick

Option abstraction

The (Bool, Struct) tuple fulfils the same role as Rust's Option abstraction. Bool's state indicates whether the second parameter "is some?", in the case it is not a default value is passed and should not be used.

pub fn getTick(poolKey: PoolKey, index: I256) -> (Bool, Tick);

Retrieves information about a tick at a specified index. If the tick cannot be found a (false, Tick) tuple is returned with empty Tick in the second parameter.

Input parameters

NameTypeDescription
poolKeyPoolKeyA unique key that identifies the specified pool.
indexI256The tick index.

Output parameters

TypeDescription
TickA struct containing tick data.
BoolIf true the tick was found and retrieved successfully, false otherwise.

Is tick initialized

pub fn isTickInitialized(poolKey: PoolKey, index: I256) -> Bool;

Retrieves the initialization state of a tick.

Input parameters

NameTypeDescription
poolKeyPoolKeyA unique key that identifies the specified pool.
indexI256The tick index.

Output parameters

TypeDescription
BoolIf true - initialized, if false - uninitialized.

Tickmap

Get tickmap

pub fn getTickmapSlice(poolKey: PoolKey, lowerBatch: U256, upperBatch: U256, xToY: Bool) -> ByteVec

Retrieves a slice of tickmap batches for a specified pool. The value of lowerBatch should be less than upperBatch.

Input parameters

NameTypeDescription
pool_keyPoolKeyA unique key that identifies the specified pool.
lowerBatchU256Index of the lower tickmap batch.
upperBatchU256Index of the upper tickmap batch.
xToYBoolIf xToY is true return batches from lowerBatch to upperBatch, else the other way around.

Output parameters

TypeDescription
ByteVecByteVec containing tickmap chunk index and value.