Get Pools Info
# get_pools.py
import binascii
from typing import List
from stellar_sdk import Address, Keypair, scval, SorobanServer, xdr, TransactionBuilder, Server, StrKey
from stellar_sdk.xdr import UInt128Parts
# ==========================
# Configuration Variables
# ==========================
# Soroban and Horizon server RPC endpoints
SOROBAN_SERVER_RPC = 'https://soroban-testnet.stellar.org:443/'
HORIZON_SERVER = 'https://horizon-testnet.stellar.org'
# Distributor's secret key (ensure this is kept secure)
SECRET = 'SCJF..........KTXQ'
# Contract IDs for the router and tokens
ROUTER_CONTRACT_ID = 'CDMSJQ4TPCTAYDRYN46FVMYIWV2A4ZTHCWWIN2NW3QZIFPJWBBEGDKDY'
TOKEN_A_CONTRACT_ID = 'CAZRY5GSFBFXD7H6GAFBA5YGYQTDXU4QKWKMYFWBAZFUCURN3WKX6LF5'
TOKEN_B_CONTRACT_ID = 'CBL6KD2LFMLAUKFFWNNXWOXFN73GAXLEA4WMJRLQ5L76DMYTM3KWQVJN'
# Stellar network passphrase and known pool hash
NETWORK_PASSPHRASE = 'Test SDF Network ; September 2015'
# ==========================
# Utility Functions
# ==========================
def order_token_ids(tokens: List[xdr.SCVal]) -> List[xdr.SCVal]:
"""
Orders token IDs based on their contract ID to maintain consistency.
Args:
tokens (List[xdr.SCVal]): List of token addresses as SCVal objects.
Returns:
List[xdr.SCVal]: Ordered list of token SCVal objects.
"""
return sorted(tokens, key=lambda token: int(token.address.contract_id.hash.hex(), 16))
def u128_to_int(value: UInt128Parts) -> int:
"""
Converts UInt128Parts from Stellar's XDR to a Python integer.
Args:
value (UInt128Parts): UInt128Parts object from Stellar SDK.
Returns:
int: Corresponding Python integer.
"""
return int(value.hi.uint64 << 64) + value.lo.uint64
def get_pools(server, address, router_contract_id, tokens: list[str]) -> dict:
tx_builder = TransactionBuilder(
source_account=server.load_account(address),
network_passphrase=NETWORK_PASSPHRASE,
base_fee=1000000 # Set base fee; adjust as necessary
).set_timeout(3600) # Set transaction timeout
tx = (
tx_builder
.append_invoke_contract_function_op(
contract_id=router_contract_id,
function_name="get_pools",
parameters=[
scval.to_vec(order_token_ids([
Address(token).to_xdr_sc_val()
for token in tokens
])),
],
)
.build()
)
simulation = server.simulate_transaction(tx)
tx_result = [xdr.SCVal.from_xdr(r.xdr) for r in simulation.results][0]
if not tx_result:
raise RuntimeError
return {
entry.key.bytes.sc_bytes.hex(): StrKey.encode_contract(binascii.unhexlify(entry.val.address.contract_id.hash.hex()))
for entry in tx_result.map.sc_map
}
def execute():
server = SorobanServer(SOROBAN_SERVER_RPC)
keypair = Keypair.from_secret(SECRET)
# Order token IDs to ensure consistency
token_a = scval.to_address(TOKEN_A_CONTRACT_ID)
token_b = scval.to_address(TOKEN_B_CONTRACT_ID)
pools = get_pools(
server,
keypair.public_key,
ROUTER_CONTRACT_ID,
[TOKEN_A_CONTRACT_ID, TOKEN_B_CONTRACT_ID],
)
for pool_hash, pool_id in pools.items():
print(f"pool '{pool_hash}', '{pool_id}'")
tx = (
TransactionBuilder(
source_account=server.load_account(keypair.public_key),
network_passphrase=NETWORK_PASSPHRASE,
base_fee=1000000
).set_timeout(3600)
.append_invoke_contract_function_op(
contract_id=ROUTER_CONTRACT_ID,
function_name="get_info",
parameters=[
scval.to_vec(order_token_ids([token_a, token_b])),
scval.to_bytes(bytes.fromhex(pool_hash)), # Known pool hash as bytes
],
)
.build()
)
simulation = server.simulate_transaction(tx)
tx_result = [xdr.SCVal.from_xdr(r.xdr) for r in simulation.results][0]
if not tx_result:
raise RuntimeError
pool_info = {
entry.key.sym.sc_symbol.decode(): entry.val
for entry in tx_result.map.sc_map
}
pool_info['pool_type'] = pool_info['pool_type'].sym.sc_symbol.decode()
pool_info['fee'] = "{0}%".format(str(int(pool_info['fee'].u32.uint32) / 10_000 * 100))
if 'a' in pool_info:
pool_info['a'] = u128_to_int(pool_info['a'].u128)
if 'n_tokens' in pool_info:
pool_info['n_tokens'] = int(pool_info['n_tokens'].u32.uint32)
print('pool hash', pool_hash)
for key, value in pool_info.items():
print(key, value)
print('-------')
if __name__ == "__main__":
execute()
const StellarSdk = require('@stellar/stellar-sdk');
const binascii = require('binascii');
const {
Contract,
TransactionBuilder,
SorobanRpc,
BASE_FEE,
Networks,
xdr,
TimeoutInfinite,
StrKey,
} = StellarSdk;
// ==========================
// Configuration Variables
// ==========================
// Soroban and Horizon server RPC endpoints
const sorobanServer = 'https://soroban-testnet.stellar.org:443/'; //testnet
const userPublicKey = 'G...';
// Contract IDs for the router and tokens
const routerContractId = 'CDMSJQ4TPCTAYDRYN46FVMYIWV2A4ZTHCWWIN2NW3QZIFPJWBBEGDKDY'; //testnet
const tokenAContractId = 'CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC'; // XLM
const tokenBContractId = 'CDNVQW44C3HALYNVQ4SOBXY5EWYTGVYXX6JPESOLQDABJI5FC5LTRRUE'; //AQUA
// ==========================
// Utility Functions
// ==========================
function orderTokensIds(tokensIds) {
/**
* Orders token IDs based on their contract ID to maintain consistency.
*
* @param {Array} tokensIds - List of token addresses as SCVal objects.
* @returns {Array} Ordered list of token SCVal objects.
*/
return tokensIds.sort((a, b) => {
const aHash = BigInt('0x' + a.address().contractId().toString('hex'));
const bHash = BigInt('0x' + b.address().contractId().toString('hex'));
// Compare BigInts directly without converting to number
if (aHash < bHash) return -1;
if (aHash > bHash) return 1;
return 0;
});
}
function u128ToInt(value) {
/**
* Converts UInt128Parts from Stellar's XDR to a JavaScript number.
*
* @param {Object} value - UInt128Parts object from Stellar SDK, with `hi` and `lo` properties.
* @returns {number|null} Corresponding JavaScript number, or null if the number is too large.
*/
const result = (BigInt(value.hi()._value) << 64n) + BigInt(value.lo()._value);
// Check if the result is within the safe integer range for JavaScript numbers
if (result <= BigInt(Number.MAX_SAFE_INTEGER)) {
return Number(result);
} else {
console.warn("Value exceeds JavaScript's safe integer range");
return null;
}
}
function contractIdToScVal(contractId) {
/**
* Converts a contract ID to a Stellar SCVal (Smart Contract Value) format.
*
* @param {string} contractId - The contract ID to convert.
* @returns {StellarSdk.xdr.ScVal} - The SCVal representation of the contract ID.
*
* @throws {Error} Throws an error if the contract ID is invalid or cannot be decoded.
*/
return StellarSdk.Address.contract(StrKey.decodeContract(contractId)).toScVal();
}
async function getPools(server, tokensContactIds) {
/**
* Retrieves the pools associated with specific token contract IDs from the Stellar network.
*
* @async
* @param {SorobanRpc.Server} server - The Stellar server instance to connect to.
* @param {string[]} tokensContactIds - An array of token contract IDs for which pools are being queried.
* @returns {Promise<Array<[string, string]>>} - A promise that resolves to an array of arrays, each containing:
* - The contract ID as an encoded string.
* - The corresponding hash value from the pool.
*/
const contract = new StellarSdk.Contract(routerContractId);
const account = await server.getAccount(userPublicKey);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: Networks.TESTNET,
})
.addOperation(
contract.call(
'get_pools',
xdr.ScVal.scvVec(
orderTokensIds(
tokensContactIds.map(id => contractIdToScVal(id))
)
)
)
)
.setTimeout(TimeoutInfinite)
.build();
const simulateResult = await server.simulateTransaction(tx);
if (!simulateResult.result) {
return [];
}
const hashArray = simulateResult.result.retval.value();
if (!hashArray.length) {
return [];
}
return hashArray.map((item) => [
StrKey.encodeContract(Buffer.from(binascii.unhexlify(item.val().value().value().toString('hex')), 'ascii')),
item.key().value().toString('hex'),
]);
}
async function getPoolInfo(server, poolId) {
/**
* Retrieves detailed information about a specific pool from the Stellar network.
*
* @async
* @param {SorobanRpc.Server} server - The Stellar server instance to connect to.
* @param {string} poolId - The ID of the pool for which information is being retrieved.
* @returns {Promise<Object>} - A promise that resolves to an object containing key-value pairs of pool information.
*/
const contract = new Contract(poolId);
const account = await server.getAccount(userPublicKey);
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: Networks.TESTNET,
})
.addOperation(
contract.call('get_info')
)
.setTimeout(TimeoutInfinite)
.build();
const simulateResult = await server.simulateTransaction(tx);
if (!simulateResult.result) {
throw new Error('Something went wrong');
}
return simulateResult.result.retval.value().reduce((acc, val) => {
acc[val.key().value().toString()] =
typeof val.val().value() === 'number'
? val.val().value()
: val.val().value().hi
? u128ToInt(val.val().value())
: val.val().value().toString();
return acc;
}, {});
}
async function getPoolsInfo() {
const server = new SorobanRpc.Server(sorobanServer);
const pools = await getPools(server, [tokenAContractId, tokenBContractId]);
console.log(pools);
// [
// [
// 'CD6P4U2BR4KGRGICBUEZHV4RFAU6365Y4LS7VESVGTKEE73SVFKODOPP',
// '9ac7a9cde23ac2ada11105eeaa42e43c2ea8332ca0aa8f41f58d7160274d718e'
// ]
// ]
const poolsInfo = await Promise.all(pools.map(([id]) => getPoolInfo(server, id)));
console.log(poolsInfo);
// [ { fee: 30, pool_type: 'constant_product' } ]
}
getPoolsInfo();
Last updated