Source

js-stellar-base/src/get_liquidity_pool_id.js

  1. import xdr from './xdr';
  2. import { Asset } from './asset';
  3. import { hash } from './hashing';
  4. // LiquidityPoolFeeV18 is the default liquidity pool fee in protocol v18. It defaults to 30 base points (0.3%).
  5. export const LiquidityPoolFeeV18 = 30;
  6. /**
  7. * getLiquidityPoolId computes the Pool ID for the given assets, fee and pool type.
  8. *
  9. * @see [stellar-core getPoolID](https://github.com/stellar/stellar-core/blob/9f3a48c6a8f1aa77b6043a055d0638661f718080/src/ledger/test/LedgerTxnTests.cpp#L3746-L3751)
  10. *
  11. * @export
  12. * @param {string} liquidityPoolType – A string representing the liquidity pool type.
  13. * @param {object} liquidityPoolParameters – The liquidity pool parameters.
  14. * @param {Asset} liquidityPoolParameters.assetA – The first asset in the Pool, it must respect the rule assetA < assetB.
  15. * @param {Asset} liquidityPoolParameters.assetB – The second asset in the Pool, it must respect the rule assetA < assetB.
  16. * @param {number} liquidityPoolParameters.fee – The liquidity pool fee. For now the only fee supported is `30`.
  17. *
  18. * @return {Buffer} the raw Pool ID buffer, which can be stringfied with `toString('hex')`
  19. */
  20. export function getLiquidityPoolId(
  21. liquidityPoolType,
  22. liquidityPoolParameters = {}
  23. ) {
  24. if (liquidityPoolType !== 'constant_product') {
  25. throw new Error('liquidityPoolType is invalid');
  26. }
  27. const { assetA, assetB, fee } = liquidityPoolParameters;
  28. if (!assetA || !(assetA instanceof Asset)) {
  29. throw new Error('assetA is invalid');
  30. }
  31. if (!assetB || !(assetB instanceof Asset)) {
  32. throw new Error('assetB is invalid');
  33. }
  34. if (!fee || fee !== LiquidityPoolFeeV18) {
  35. throw new Error('fee is invalid');
  36. }
  37. if (Asset.compare(assetA, assetB) !== -1) {
  38. throw new Error('Assets are not in lexicographic order');
  39. }
  40. const lpTypeData =
  41. xdr.LiquidityPoolType.liquidityPoolConstantProduct().toXDR();
  42. const lpParamsData = new xdr.LiquidityPoolConstantProductParameters({
  43. assetA: assetA.toXDRObject(),
  44. assetB: assetB.toXDRObject(),
  45. fee
  46. }).toXDR();
  47. const payload = Buffer.concat([lpTypeData, lpParamsData]);
  48. return hash(payload);
  49. }