Calculate Token Amount
CalculateAmountOptions
export interface CalculateAmountOptions {
coinType: string;
amount: string;
threshold: string;
atob: boolean;
isExact: boolean;
isInit?: boolean;
}
async calculateTokenAndThresholdAmount(options: CalculateAmountOptions) {
const { coinType, atob, isExact, threshold, isInit = false } = options;
const poolInfo = !isInit ? await this.getPoolInfo(coinType) : undefined;
const virtual_token_reserves = new Decimal(
poolInfo ? poolInfo.virtual_token_reserves : this.initial_virtual_token_reserves,
);
const virtual_sui_reserves = new Decimal(
poolInfo ? poolInfo.virtual_sui_reserves : this.initial_virtual_sui_reserves,
);
const amount = new Decimal(options.amount);
let _amount: Decimal;
let _amountThreshold: Decimal;
if (atob) {
if (isExact) {
const _fee = new Decimal(1).sub(this.platform_fee); // 0.005 fee
_amount = virtual_token_reserves.sub(
virtual_sui_reserves
.mul(virtual_token_reserves)
.div(virtual_sui_reserves.add(amount.mul(_fee))),
);
_amountThreshold = new Decimal(100).sub(threshold).div(100).mul(_amount);
} else {
const _fee = new Decimal(1).add(this.platform_fee); // 0.005 fee
const _threshold = new Decimal(100).add(threshold).div(100);
_amount = virtual_sui_reserves
.mul(virtual_token_reserves)
.div(virtual_token_reserves.sub(amount))
.sub(virtual_sui_reserves)
.mul(_fee)
.mul(_threshold);
_amountThreshold = _amount;
}
} else {
if (isExact) {
const _fee = new Decimal(1).sub(this.platform_fee); // 0.005 fee
_amount = virtual_sui_reserves
.sub(
virtual_sui_reserves
.mul(virtual_token_reserves)
.div(virtual_token_reserves.add(amount)),
)
.mul(_fee);
_amountThreshold = new Decimal(100).sub(threshold).div(100).mul(_amount);
} else {
const _fee = new Decimal(1).add(this.platform_fee); // 0.005 fee
_amount = virtual_token_reserves.sub(
virtual_sui_reserves
.mul(virtual_token_reserves)
.div(virtual_sui_reserves.add(amount.mul(_fee))),
);
_amountThreshold = new Decimal(100).add(threshold).div(100).mul(_amount);
}
}
return {
tokenAmount: _amount.toFixed(0),
thresholdAmount: _amountThreshold.toFixed(0),
};
}
Last updated