@subwallet/invariant-vara-sdk
Version:
<div align="center"> <h1>⚡Invariant protocol⚡</h1> <p> <a href="https://invariant.app/math-spec-vara.pdf">MATH SPEC 📄</a> | <a href="https://discord.gg/VzS3C9wR">DISCORD 🌐</a> | </p> </div>
512 lines (511 loc) • 32.8 kB
JavaScript
import { decodeAddress } from '@gear-js/api';
import { TypeRegistry } from '@polkadot/types';
import { TransactionBuilder, throwOnErrorReply, getServiceNamePrefix, getFnNamePrefix, ZERO_ADDRESS } from 'sails-js';
export class InvariantContract {
api;
_programId;
registry;
service;
constructor(api, _programId) {
this.api = api;
this._programId = _programId;
const types = {
InvariantConfig: { "admin": "[u8;32]", "protocolFee": "Percentage" },
Percentage: "(u128)",
FeeTier: { "fee": "Percentage", "tickSpacing": "u16" },
PoolKey: { "tokenX": "[u8;32]", "tokenY": "[u8;32]", "feeTier": "FeeTier" },
TokenAmount: "(U256)",
SqrtPrice: "(u128)",
Liquidity: "(U256)",
Position: { "poolKey": "PoolKey", "liquidity": "Liquidity", "lowerTickIndex": "i32", "upperTickIndex": "i32", "feeGrowthInsideX": "FeeGrowth", "feeGrowthInsideY": "FeeGrowth", "lastBlockNumber": "u64", "tokensOwedX": "TokenAmount", "tokensOwedY": "TokenAmount" },
FeeGrowth: "(u128)",
CalculateSwapResult: { "amountIn": "TokenAmount", "amountOut": "TokenAmount", "startSqrtPrice": "SqrtPrice", "targetSqrtPrice": "SqrtPrice", "fee": "TokenAmount", "pool": "Pool", "ticks": "Vec<Tick>" },
Pool: { "liquidity": "Liquidity", "sqrtPrice": "SqrtPrice", "currentTickIndex": "i32", "feeGrowthGlobalX": "FeeGrowth", "feeGrowthGlobalY": "FeeGrowth", "feeProtocolTokenX": "TokenAmount", "feeProtocolTokenY": "TokenAmount", "startTimestamp": "u64", "lastTimestamp": "u64", "feeReceiver": "[u8;32]" },
Tick: { "index": "i32", "sign": "bool", "liquidityChange": "Liquidity", "liquidityGross": "Liquidity", "sqrtPrice": "SqrtPrice", "feeGrowthOutsideX": "FeeGrowth", "feeGrowthOutsideY": "FeeGrowth", "secondsOutside": "u64" },
SwapHop: { "poolKey": "PoolKey", "xToY": "bool" },
InvariantError: { "_enum": ["NotAdmin", "NotFeeReceiver", "PoolAlreadyExist", "PoolNotFound", "TickAlreadyExist", "InvalidTickIndexOrTickSpacing", "PositionNotFound", "TickNotFound", "FeeTierNotFound", "PoolKeyNotFound", "AmountIsZero", "WrongLimit", "PriceLimitReached", "NoGainSwap", "InvalidTickSpacing", "FeeTierAlreadyExist", "PoolKeyAlreadyExist", "UnauthorizedFeeReceiver", "ZeroLiquidity", "RecoverableTransferError", "UnrecoverableTransferError", "TransferError", "TokensAreSame", "AmountUnderMinimumAmountOut", "InvalidFee", "NotEmptyTickDeinitialization", "InvalidInitTick", "InvalidInitSqrtPrice", "NotEnoughGasToExecute", "TickLimitReached", "InvalidTickIndex", "NoBalanceForTheToken", "FailedToChangeTokenBalance", "ReplyHandlingFailed", "InvalidVaraDepositAttempt", "InvalidVaraWithdrawAttempt"] },
LiquidityTick: { "index": "i32", "liquidityChange": "Liquidity", "sign": "bool" },
PositionTick: { "index": "i32", "feeGrowthOutsideX": "FeeGrowth", "feeGrowthOutsideY": "FeeGrowth", "secondsOutside": "u64" },
QuoteResult: { "amountIn": "TokenAmount", "amountOut": "TokenAmount", "targetSqrtPrice": "SqrtPrice", "ticks": "Vec<Tick>" },
};
this.registry = new TypeRegistry();
this.registry.setKnownTypes({ types });
this.registry.register(types);
this.service = new Service(this);
}
get programId() {
if (!this._programId)
throw new Error(`Program ID is not set`);
return this._programId;
}
newCtorFromCode(code, config) {
const builder = new TransactionBuilder(this.api, this.registry, 'upload_program', ['New', config], '(String, InvariantConfig)', 'String', code);
this._programId = builder.programId;
return builder;
}
newCtorFromCodeId(codeId, config) {
const builder = new TransactionBuilder(this.api, this.registry, 'create_program', ['New', config], '(String, InvariantConfig)', 'String', codeId);
this._programId = builder.programId;
return builder;
}
}
export class Service {
_program;
constructor(_program) {
this._program = _program;
}
addFeeTier(fee_tier) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'AddFeeTier', fee_tier], '(String, String, FeeTier)', 'FeeTier', this._program.programId);
}
changeFeeReceiver(pool_key, fee_receiver) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'ChangeFeeReceiver', pool_key, fee_receiver], '(String, String, PoolKey, [u8;32])', 'Null', this._program.programId);
}
changeProtocolFee(protocol_fee) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'ChangeProtocolFee', protocol_fee], '(String, String, u128)', 'u128', this._program.programId);
}
claimFee(index) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'ClaimFee', index], '(String, String, u32)', '(U256, U256)', this._program.programId);
}
createPool(token_x, token_y, fee_tier, init_sqrt_price, init_tick) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'CreatePool', token_x, token_y, fee_tier, init_sqrt_price, init_tick], '(String, String, [u8;32], [u8;32], FeeTier, u128, i32)', 'Null', this._program.programId);
}
createPosition(pool_key, lower_tick, upper_tick, liquidity_delta, slippage_limit_lower, slippage_limit_upper) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'CreatePosition', pool_key, lower_tick, upper_tick, liquidity_delta, slippage_limit_lower, slippage_limit_upper], '(String, String, PoolKey, i32, i32, U256, u128, u128)', 'Position', this._program.programId);
}
depositSingleToken(token, amount) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'DepositSingleToken', token, amount], '(String, String, [u8;32], U256)', 'U256', this._program.programId);
}
depositTokenPair(token_x, token_y) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'DepositTokenPair', token_x, token_y], '(String, String, ([u8;32], U256), ([u8;32], U256))', '(U256, U256)', this._program.programId);
}
depositVara() {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'DepositVara'], '(String, String)', 'U256', this._program.programId);
}
removeFeeTier(fee_tier) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'RemoveFeeTier', fee_tier], '(String, String, FeeTier)', 'FeeTier', this._program.programId);
}
removePosition(index) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'RemovePosition', index], '(String, String, u32)', '(U256, U256)', this._program.programId);
}
swap(pool_key, x_to_y, amount, by_amount_in, sqrt_price_limit) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'Swap', pool_key, x_to_y, amount, by_amount_in, sqrt_price_limit], '(String, String, PoolKey, bool, U256, bool, u128)', 'CalculateSwapResult', this._program.programId);
}
swapRoute(amount_in, expected_amount_out, slippage, swaps) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'SwapRoute', amount_in, expected_amount_out, slippage, swaps], '(String, String, U256, U256, u128, Vec<SwapHop>)', 'U256', this._program.programId);
}
transferPosition(index, receiver) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'TransferPosition', index, receiver], '(String, String, u32, [u8;32])', 'Null', this._program.programId);
}
withdrawProtocolFee(pool_key) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'WithdrawProtocolFee', pool_key], '(String, String, PoolKey)', 'Null', this._program.programId);
}
withdrawSingleToken(token, amount) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'WithdrawSingleToken', token, amount], '(String, String, [u8;32], Option<U256>)', 'U256', this._program.programId);
}
withdrawTokenPair(token_x, token_y) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'WithdrawTokenPair', token_x, token_y], '(String, String, ([u8;32], Option<U256>), ([u8;32], Option<U256>))', '(U256, U256)', this._program.programId);
}
withdrawVara(value) {
if (!this._program.programId)
throw new Error('Program ID is not set');
return new TransactionBuilder(this._program.api, this._program.registry, 'send_message', ['Service', 'WithdrawVara', value], '(String, String, Option<U256>)', 'U256', this._program.programId);
}
async feeTierExists(fee_tier, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, FeeTier)', ['Service', 'FeeTierExists', fee_tier]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, bool)', reply.payload);
return result[2].toJSON();
}
async getAllPoolsForPair(token0, token1, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, [u8;32], [u8;32])', ['Service', 'GetAllPoolsForPair', token0, token1]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Result<Vec<(FeeTier, Pool)>, InvariantError>)', reply.payload);
return result[2].toJSON();
}
async getAllPositions(owner_id, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, [u8;32])', ['Service', 'GetAllPositions', owner_id]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Vec<Position>)', reply.payload);
return result[2].toJSON();
}
async getFeeTiers(originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String)', ['Service', 'GetFeeTiers']).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Vec<FeeTier>)', reply.payload);
return result[2].toJSON();
}
async getLiquidityTicks(pool_key, tickmap, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, PoolKey, Vec<i32>)', ['Service', 'GetLiquidityTicks', pool_key, tickmap]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Result<Vec<LiquidityTick>, InvariantError>)', reply.payload);
return result[2].toJSON();
}
async getLiquidityTicksAmount(pool_key, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, PoolKey)', ['Service', 'GetLiquidityTicksAmount', pool_key]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, u32)', reply.payload);
return result[2].toNumber();
}
async getPool(token_x, token_y, fee_tier, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, [u8;32], [u8;32], FeeTier)', ['Service', 'GetPool', token_x, token_y, fee_tier]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Result<Pool, InvariantError>)', reply.payload);
return result[2].toJSON();
}
async getPoolKeys(size, offset, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, u16, u16)', ['Service', 'GetPoolKeys', size, offset]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, (Vec<PoolKey>, u16))', reply.payload);
return result[2].toJSON();
}
async getPosition(owner_id, index, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, [u8;32], u32)', ['Service', 'GetPosition', owner_id, index]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Result<Position, InvariantError>)', reply.payload);
return result[2].toJSON();
}
async getPositionTicks(owner, offset, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, [u8;32], u32)', ['Service', 'GetPositionTicks', owner, offset]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Vec<PositionTick>)', reply.payload);
return result[2].toJSON();
}
async getPositionWithAssociates(owner, index, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, [u8;32], u32)', ['Service', 'GetPositionWithAssociates', owner, index]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Result<(Position, Pool, Tick, Tick), InvariantError>)', reply.payload);
return result[2].toJSON();
}
async getPositions(owner_id, size, offset, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, [u8;32], u32, u32)', ['Service', 'GetPositions', owner_id, size, offset]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Result<(Vec<(Pool, Vec<(Position, u32)>)>, u32), InvariantError>)', reply.payload);
return result[2].toJSON();
}
async getProtocolFee(originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String)', ['Service', 'GetProtocolFee']).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Percentage)', reply.payload);
return result[2].toJSON();
}
async getTick(key, index, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, PoolKey, i32)', ['Service', 'GetTick', key, index]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Result<Tick, InvariantError>)', reply.payload);
return result[2].toJSON();
}
async getTickmap(pool_key, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, PoolKey)', ['Service', 'GetTickmap', pool_key]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Vec<(u16, u64)>)', reply.payload);
return result[2].toJSON();
}
async getUserBalances(user, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, [u8;32])', ['Service', 'GetUserBalances', user]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Vec<([u8;32], TokenAmount)>)', reply.payload);
return result[2].toJSON();
}
async getUserPositionAmount(owner_id, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, [u8;32])', ['Service', 'GetUserPositionAmount', owner_id]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, u32)', reply.payload);
return result[2].toNumber();
}
async isTickInitialized(key, index, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, PoolKey, i32)', ['Service', 'IsTickInitialized', key, index]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, bool)', reply.payload);
return result[2].toJSON();
}
async quote(pool_key, x_to_y, amount, by_amount_in, sqrt_price_limit, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, PoolKey, bool, TokenAmount, bool, SqrtPrice)', ['Service', 'Quote', pool_key, x_to_y, amount, by_amount_in, sqrt_price_limit]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Result<QuoteResult, InvariantError>)', reply.payload);
return result[2].toJSON();
}
async quoteRoute(amount_in, swaps, originAddress, value, atBlock) {
const payload = this._program.registry.createType('(String, String, TokenAmount, Vec<SwapHop>)', ['Service', 'QuoteRoute', amount_in, swaps]).toHex();
if (!this._program.programId)
throw new Error('Program ID is not set');
const reply = await this._program.api.message.calculateReply({
destination: this._program.programId,
origin: originAddress ? decodeAddress(originAddress) : ZERO_ADDRESS,
payload,
value: value || 0,
gasLimit: this._program.api.blockGasLimit.toBigInt(),
at: atBlock,
});
throwOnErrorReply(reply.code, reply.payload.toU8a(), this._program.api.specVersion, this._program.registry);
const result = this._program.registry.createType('(String, String, Result<TokenAmount, InvariantError>)', reply.payload);
return result[2].toJSON();
}
subscribeToPositionCreatedEventEvent(callback) {
return this._program.api.gearEvents.subscribeToGearEvent('UserMessageSent', ({ data: { message } }) => {
if (!message.source.eq(this._program.programId) || !message.destination.eq(ZERO_ADDRESS)) {
return;
}
const payload = message.payload.toHex();
if (getServiceNamePrefix(payload) === 'Service' && getFnNamePrefix(payload) === 'PositionCreatedEvent') {
callback(this._program.registry.createType('(String, String, {"timestamp":"u64","address":"[u8;32]","poolKey":"PoolKey","liquidityDelta":"Liquidity","lowerTick":"i32","upperTick":"i32","currentSqrtPrice":"SqrtPrice"})', message.payload)[2].toJSON());
}
});
}
subscribeToPositionRemovedEventEvent(callback) {
return this._program.api.gearEvents.subscribeToGearEvent('UserMessageSent', ({ data: { message } }) => {
if (!message.source.eq(this._program.programId) || !message.destination.eq(ZERO_ADDRESS)) {
return;
}
const payload = message.payload.toHex();
if (getServiceNamePrefix(payload) === 'Service' && getFnNamePrefix(payload) === 'PositionRemovedEvent') {
callback(this._program.registry.createType('(String, String, {"timestamp":"u64","address":"[u8;32]","poolKey":"PoolKey","liquidity":"Liquidity","lowerTickIndex":"i32","upperTickIndex":"i32","sqrtPrice":"SqrtPrice"})', message.payload)[2].toJSON());
}
});
}
subscribeToCrossTickEventEvent(callback) {
return this._program.api.gearEvents.subscribeToGearEvent('UserMessageSent', ({ data: { message } }) => {
if (!message.source.eq(this._program.programId) || !message.destination.eq(ZERO_ADDRESS)) {
return;
}
const payload = message.payload.toHex();
if (getServiceNamePrefix(payload) === 'Service' && getFnNamePrefix(payload) === 'CrossTickEvent') {
callback(this._program.registry.createType('(String, String, {"timestamp":"u64","address":"[u8;32]","poolKey":"PoolKey","indexes":"Vec<i32>"})', message.payload)[2].toJSON());
}
});
}
subscribeToSwapEventEvent(callback) {
return this._program.api.gearEvents.subscribeToGearEvent('UserMessageSent', ({ data: { message } }) => {
if (!message.source.eq(this._program.programId) || !message.destination.eq(ZERO_ADDRESS)) {
return;
}
const payload = message.payload.toHex();
if (getServiceNamePrefix(payload) === 'Service' && getFnNamePrefix(payload) === 'SwapEvent') {
callback(this._program.registry.createType('(String, String, {"timestamp":"u64","address":"[u8;32]","poolKey":"PoolKey","amountIn":"TokenAmount","amountOut":"TokenAmount","fee":"TokenAmount","startSqrtPrice":"SqrtPrice","targetSqrtPrice":"SqrtPrice","xToY":"bool"})', message.payload)[2].toJSON());
}
});
}
}