/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/@tapp-exchange/sdk@0.7.2/dist/common/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var q=class extends Error{constructor(e){super("Trade size exceeds 40% of LP Pool"),this.maxAmountIn=e}};var _tssdk = require('@aptos-labs/ts-sdk');var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios);var y=class extends Error{};var w=class{constructor(e){this._sdk=e}async getPools(e){return(await this._sdk.request.post("public/pool",{page:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _2 => _2.page]), () => (1)),size:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _3 => _3.size]), () => (10)),sortBy:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _4 => _4.sortBy]), () => ("tvl")),poolType:_optionalChain([e, 'optionalAccess', _5 => _5.type])})).result}async getInfo(e){let t=await this._sdk.request.post("public/pool_info",{poolId:e});if(!t.result)throw new y(`Pool not found. ${e}`);return t.result}};var N=(i=>(i[i.SingleAsset=0]="SingleAsset",i[i.Imbalance=1]="Imbalance",i[i.Ratio=2]="Ratio",i))(N||{});var _bignumberjs = require('bignumber.js'); var _bignumberjs2 = _interopRequireDefault(_bignumberjs);var E=u=>{let t={100:1,500:10,3e3:60,1e4:200}[u];if(t===void 0)throw new Error(`Unsupported fee tier: ${u}`);return t},p=u=>u<0?2n**64n+BigInt(u):BigInt(u),z=(u,e=60)=>{if(u<=0)throw new Error("Price must be greater than 0");let t=Math.log(1.0001),i=Math.log(u)/t;return Math.floor(i/e)*e},M=(u,e)=>{let t=E(e),i=Math.floor(Math.log(u)/Math.log(1.0001)),r=Math.round(i/t)*t;return Math.pow(1.0001,r)},m=(u,e)=>new (0, _bignumberjs.BigNumber)(u,e),$=({routeMatrix:u,amounts:e,slippage:t})=>{let i=e.at(0),r=e.at(-1),o=m(r).minus(m(r).multipliedBy(t/100)).dp(0,_bignumberjs.BigNumber.ROUND_FLOOR).toString(),n=u.flatMap(({plainPool:d,fromIdx:g,toIdx:h})=>[d.tokens[g],d.tokens[h]]),a=new Set,l=[];n.forEach(d=>{a.has(d.tokenAddr)||(a.add(d.tokenAddr),l=[...l,d.tokenAddr])});let s=new _tssdk.Serializer;s.serializeU8(1),s.serializeBool(!0),s.serializeVector(l.map(d=>_tssdk.AccountAddress.fromString(d))),s.serializeU64(BigInt(i)),s.serializeU64(BigInt(o));for(let{plainPool:d}of u)d.poolType=="CLMM"?s.serializeU64(3):d.poolType=="STABLE"?s.serializeU64(4):s.serializeU64(2),s.serialize(_tssdk.AccountAddress.fromString(d.poolId));return s.toUint8Array()};var L=443636,W=1.0001,R=Math.pow(W,-L),k=class{constructor(e){this._sdk=e}removeSingleAMMLiquidity(e){let t=new _tssdk.Serializer;return t.serialize(_tssdk.AccountAddress.fromString(e.poolId)),t.serializeU64(1),t.serialize(_tssdk.AccountAddress.fromString(e.positionAddr)),t.serializeU128(e.mintedShare),t.serializeU64(e.minAmount0),t.serializeU64(e.minAmount1),{function:`${this._sdk.sdkConfig.contractAddress}::router::remove_liquidity`,functionArguments:[t.toUint8Array()]}}removeMultipleAMMLiquidity(e){let t=new _tssdk.Serializer;return t.serialize(_tssdk.AccountAddress.fromString(e.poolId)),t.serializeU64(e.positions.length),e.positions.forEach(i=>{t.serialize(_tssdk.AccountAddress.fromString(i.positionAddr)),t.serializeU128(i.mintedShare),t.serializeU64(i.minAmount0),t.serializeU64(i.minAmount1)}),{function:`${this._sdk.sdkConfig.contractAddress}::router::remove_multi_liquidity`,functionArguments:[t.toUint8Array()]}}removeSingleCLMMLiquidity(e){let t=new _tssdk.Serializer;return t.serialize(_tssdk.AccountAddress.fromString(e.poolId)),t.serialize(_tssdk.AccountAddress.fromString(e.positionAddr)),t.serializeU128(e.mintedShare),t.serializeU64(e.minAmount0),t.serializeU64(e.minAmount1),{function:`${this._sdk.sdkConfig.contractAddress}::router::remove_liquidity`,functionArguments:[t.toUint8Array()]}}removeMultipleCLMMLiquidity(e){let t=new _tssdk.Serializer;return t.serialize(_tssdk.AccountAddress.fromString(e.poolId)),t.serializeU64(e.positions.length),e.positions.forEach(i=>{t.serialize(_tssdk.AccountAddress.fromString(i.positionAddr)),t.serializeU128(i.mintedShare),t.serializeU64(i.minAmount0),t.serializeU64(i.minAmount1)}),{function:`${this._sdk.sdkConfig.contractAddress}::router::remove_multi_liquidity`,functionArguments:[t.toUint8Array()]}}removeSingleStableLiquidity(e){let t=new _tssdk.Serializer;switch(t.serialize(_tssdk.AccountAddress.fromString(e.poolId)),t.serialize(_tssdk.AccountAddress.fromString(e.position.positionAddr)),t.serializeU8(e.liquidityType),e.liquidityType){case 0:{let i=e.position;t.serializeU256(i.mintedShare),t.serializeU64(i.tokenOutIndex),t.serializeU256(i.amount);break}case 1:{let i=e.position,r=i.amounts.map(o=>new (0, _tssdk.U256)(o));t.serializeVector(r),t.serializeU256(i.maxMintedShare);break}default:{let i=e.position,r=i.amounts.map(o=>new (0, _tssdk.U256)(o));t.serializeU256(i.mintedShare),t.serializeVector(r);break}}return{function:`${this._sdk.sdkConfig.contractAddress}::router::remove_liquidity`,functionArguments:[t.toUint8Array()]}}removeMultipleStableLiquidity(e){let t=new _tssdk.Serializer;return t.serialize(_tssdk.AccountAddress.fromString(e.poolId)),t.serializeU64(e.positions.length),e.positions.forEach(i=>{switch(t.serialize(_tssdk.AccountAddress.fromString(i.positionAddr)),t.serializeU8(e.liquidityType),e.liquidityType){case 0:{let r=i;t.serializeU256(r.mintedShare),t.serializeU64(r.tokenOutIndex),t.serializeU256(r.amount);break}case 1:{let r=i,o=r.amounts.map(n=>new (0, _tssdk.U256)(n));t.serializeVector(o),t.serializeU256(r.maxMintedShare);break}default:{let r=i,o=r.amounts.map(n=>new (0, _tssdk.U256)(n));t.serializeU256(r.mintedShare),t.serializeVector(o);break}}}),{function:`${this._sdk.sdkConfig.contractAddress}::router::remove_multi_liquidity`,functionArguments:[t.toUint8Array()]}}addAMMLiquidity(e){let t=new _tssdk.Serializer;return t.serialize(_tssdk.AccountAddress.fromString(e.poolId)),t.serializeOption(),t.serializeU64(e.amountA),t.serializeU64(e.amountB),t.serializeU64(0),t.serializeU64(0),{function:`${this._sdk.sdkConfig.contractAddress}::router::add_liquidity`,functionArguments:[t.toUint8Array()]}}addCLMMLiquidity(e){let{poolId:t,minPrice:i,maxPrice:r,amountA:o,amountB:n,fee:a,isMaxAmountB:l}=e,s=new _tssdk.Serializer;s.serialize(_tssdk.AccountAddress.fromString(t)),s.serializeOption(),o>0&&l?s.serializeU64(Math.round(o*1.1)):s.serializeU64(o),s.serializeU64(o==0||e.amountB==0||e.isMaxAmountB?n:Math.round(n*1.1)),l?s.serializeBool(!1):s.serializeBool(o!==0);let d=E(a),g=Math.floor(L/d)*d;return i===1/0?s.serializeU64(p(g)):i===M(R,a)?s.serializeU64(p(-g)):s.serializeU64(p(z(i,d))),r===1/0?s.serializeU64(p(g)):r===M(R,a)?s.serializeU64(p(-g)):s.serializeU64(p(z(r,d))),{function:`${this._sdk.sdkConfig.contractAddress}::router::add_liquidity`,functionArguments:[s.toUint8Array()]}}addStableLiquidity(e){let{poolId:t,amounts:i}=e,r=new _tssdk.Serializer;return r.serialize(_tssdk.AccountAddress.fromString(t)),r.serializeOption(),r.serializeVector(i.map(o=>new (0, _tssdk.U256)(o))),r.serializeU256(0),{function:`${this._sdk.sdkConfig.contractAddress}::router::add_liquidity`,functionArguments:[r.toUint8Array()]}}createAMMPoolAndAddLiquidity(e){let{tokenAddress:t,fee:i,amounts:r}=e,o=new _tssdk.Serializer;return o.serializeU8(2),o.serializeVector(t.map(n=>_tssdk.AccountAddress.fromString(n))),o.serializeU64(i),r.forEach(n=>{o.serializeU64(n)}),r.forEach(()=>{o.serializeU64(0)}),{function:`${this._sdk.sdkConfig.contractAddress}::router::create_pool_add_liquidity`,functionArguments:[o.toUint8Array()]}}createCLMMPoolAndAddLiquidity(e){let{tokenAddress:t,fee:i,amounts:r,initialPrice:o,minPrice:n,maxPrice:a,isMaxAmountB:l}=e,s=new _tssdk.Serializer;s.serializeU8(3),s.serializeVector(t.map(S=>_tssdk.AccountAddress.fromString(S))),s.serializeU64(i);let d=BigInt(2)**BigInt(64),g=Math.sqrt(o)*Number(d);s.serializeU128(p(g));let h=!1;r.forEach((S,U)=>{h||(h=S===0),U===0&&S>0&&l||U===1&&!h&&!l?s.serializeU64(Math.round(S*1.1)):s.serializeU64(S)}),l?s.serializeBool(!1):s.serializeBool(_optionalChain([r, 'optionalAccess', _6 => _6.at, 'call', _7 => _7(0)])!==0);let P=E(i),A=Math.floor(L/P)*P;return n===1/0?s.serializeU64(p(A)):n===M(R,i)?s.serializeU64(p(-A)):s.serializeU64(p(z(n,P))),a===1/0?s.serializeU64(p(A)):a===M(R,i)?s.serializeU64(p(-A)):s.serializeU64(p(z(a,P))),{function:`${this._sdk.sdkConfig.contractAddress}::router::create_pool_add_liquidity`,functionArguments:[s.toUint8Array()]}}createStablePoolAndAddLiquidity(e){let{tokenAddress:t,fee:i,amounts:r,amplificationFactor:o,offpeg_fee_multiplier:n=2e10}=e,a=new _tssdk.Serializer;return a.serializeU8(4),a.serializeVector(t.map(l=>_tssdk.AccountAddress.fromString(l))),a.serializeU64(i*1e4),a.serializeU256(o),a.serializeU256(n),a.serializeVector(r.map(l=>new (0, _tssdk.U256)(l))),a.serializeU256(0),{function:`${this._sdk.sdkConfig.contractAddress}::router::create_pool_add_liquidity`,functionArguments:[a.toUint8Array()]}}collectFee(e){let t=new _tssdk.Serializer;return t.serialize(_tssdk.AccountAddress.fromString(e.poolId)),t.serialize(_tssdk.AccountAddress.fromString(e.positionAddr)),{function:`${this._sdk.sdkConfig.contractAddress}::router::collect_fee`,functionArguments:[t.toUint8Array()]}}async getPositions(e){let{userAddr:t,page:i=1,size:r=10}=e;return(await this._sdk.request.post("public/position",{userAddr:t,page:i,size:r})).result}};var I=class{constructor(e){this._http=e}async post(e,t){return(await this._http.post("",{method:e,jsonrpc:"2.0",id:this._reqId(),params:{query:t}})).data}_reqId(){let t=Date.now();return Math.floor(Math.random()*(t-1+1))+1}};var T=class{constructor(e,t,i){this._entries=e,this._field=t,this._amount=i}get(){let{amountIn:e,amountOut:t}=this._findClosestAmount(),i=this._field=="input"?e:t,r=this._field=="input"?t:e;if(m(i).isZero())return{amount:this._amount,estAmount:0,field:this._field};let o=m(r).div(i),n=m(o).multipliedBy(this._amount).toFixed(0),a=m(n).gt(0)?Number(n):0,l={amount:this._amount,estAmount:a,field:this._field};return this.isAmountInGreatherThanAllowed&&(l.error=new q(this.maxAmountIn.toString())),l}_findClosestAmount(){if(!this._entries.length)throw new Error("Book entries is empty");let e=r=>this._field=="input"?m(r.amountIn):m(r.amountOut),t=this._entries[0],i=m(this._amount).minus(e(t)).abs();for(let r=1;r<this._entries.length;r++){let o=this._entries[r],n=e(o),a=m(this._amount).minus(n).abs();a.isLessThan(i)&&(t=this._entries[r],i=a)}return t}get maxAmountIn(){let e=this._entries.at(-1);return m(_nullishCoalesce(_optionalChain([this, 'access', _8 => _8._entries, 'access', _9 => _9.at, 'call', _10 => _10(-1), 'optionalAccess', _11 => _11.amountIn]), () => (0)))}get isAmountInGreatherThanAllowed(){return m(this._amount).gt(this.maxAmountIn)}};var C=class{constructor(e,t,i){this._ob=e,this._entries=this._ob.entries,this._sourceField=t,this._amount=i}get(){let{amountIn:e,amountOut:t,prices:i,routeIdx:r,amounts:o,isExceed:n}=this._findClosestAmount(),a=this._sourceField=="input"?e:t;if(m(a).isZero()||n)return{sourceAmount:this._amount,destAmount:String(0),amounts:[],sourceField:this._sourceField,destField:this._sourceField=="input"?"output":"input",routeIdx:r,prices:i,priceImpact:"0",estPriceImpact:"0",isExceed:n,routeMatrix:[]};let l=m(this._amount).div(a),s=o.map(A=>l.multipliedBy(A).toFixed(0)),d=this._sourceField=="input"?s.at(-1):s[0],g=new (0, _bignumberjs2.default)(_nullishCoalesce(d, () => (0))).gt(0)?d:String(0),h="";if(i.length==1&&_optionalChain([this, 'access', _12 => _12._entries, 'access', _13 => _13[0], 'optionalAccess', _14 => _14.prices, 'access', _15 => _15[0]])){let A=Number(this._entries[0].prices[0]),U=(Number(i[0])-Number(A))/A,_=Math.abs(U*100);_!==Math.floor(_)&&(_=Number.parseFloat(String(_))==0?.01:Number.parseFloat(_.toFixed(2))),h=String(_)}let P={sourceAmount:this._amount,destAmount:d,sourceField:this._sourceField,prices:i,routeIdx:r,amounts:s,destField:this._sourceField=="input"?"output":"input",priceImpact:h,estPriceImpact:_nullishCoalesce(g, () => ("")),isExceed:n,routeMatrix:_nullishCoalesce(this._ob.routeMatrix[r], () => ([]))};return this.isAmountInGreaterThanAllowed&&(P.error=new Error("Trade size exceeds 40% of LP Pool")),P}_findClosestAmount(){if(this._entries.length===0)throw new Error("Book entries is empty");let e=r=>this._sourceField=="input"?m(r.amounts[0]).toFixed(0):m(r.amounts.at(-1)).toFixed(0),t=this._entries[0],i=m(this._amount).minus(e(t)).abs();for(let r=1;r<this._entries.length;r++){let o=this._entries[r],n=e(o),a=m(this._amount).minus(n).abs();a.isLessThan(i)&&(t=this._entries[r],i=a)}return{amountIn:t.amounts.at(0),amountOut:t.amounts.at(-1),routeIdx:t.routeIdx,amounts:t.amounts,prices:t.prices,isExceed:t.isExceed}}get maxAmountIn(){let e=this._entries.at(-1);return m(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _16 => _16.amounts, 'access', _17 => _17[0]]), () => (0)))}get isAmountInGreaterThanAllowed(){return m(this._amount).gt(this.maxAmountIn)}};var x=class{constructor(e){this._sdk=e}swapAMMTransactionPayload({poolId:e,a2b:t,fixedAmountIn:i=!0,amount0:r,amount1:o}){let n=new _tssdk.Serializer;return n.serialize(_tssdk.AccountAddress.fromString(e)),n.serializeBool(t),n.serializeBool(i),n.serializeU64(r),n.serializeU64(o),{function:`${this._sdk.sdkConfig.contractAddress}::router::swap`,functionArguments:[n.toUint8Array()]}}swapCLMMTransactionPayload({poolId:e,amountIn:t,minAmountOut:i,a2b:r,fixedAmountIn:o=!0,targetSqrtPrice:n}){let a=new _tssdk.Serializer;return a.serialize(_tssdk.AccountAddress.fromString(e)),a.serializeBool(r),a.serializeBool(o),a.serializeU64(t),a.serializeU64(i),a.serializeU128(n),{function:`${this._sdk.sdkConfig.contractAddress}::router::swap`,functionArguments:[a.toUint8Array()]}}swapStableTransactionPayload({poolId:e,tokenIn:t,tokenOut:i,amountIn:r,minAmountOut:o}){let n=new _tssdk.Serializer;return n.serialize(_tssdk.AccountAddress.fromString(e)),n.serializeU64(t),n.serializeU64(i),n.serializeU256(r),n.serializeU256(o),{function:`${this._sdk.sdkConfig.contractAddress}::router::swap`,functionArguments:[n.toUint8Array()]}}async getEstSwapAmount(e){let{amount:t,poolId:i,pair:r,a2b:o,field:n="input"}=e,{result:a}=await this._sdk.request.post("public/sc_est_swap",{poolId:i,pair:r});if(!_optionalChain([a, 'optionalAccess', _18 => _18.books])||a.books.length!=2)throw new Error("Book structure is invalid");let{entries:l}=a.books[o?0:1];return new T(l,n,t).get()}async getRoute(e,t){let i=await this._sdk.request.post("public/pool_info",{tokenAddrs:[e,t]});if(!i.result)throw new y(`Route not found. ${e} - ${t}`);return i.result}async getSOREstSwapAmount(e){let{poolId:t,amount:i,fromAddr:r,toAddr:o,field:n="input"}=e,{result:a}=await this._sdk.request.post("public/sc_est_swap2",{poolAddr:t,pair:[r,o]}),l=(_nullishCoalesce(a, () => ([]))).find(s=>s.fromAddr==r&&s.toAddr==o);if(!l)throw new y(`Order book not found. ${r} - ${o}`);return new C(l,n,String(i)).get()}swapSORTransactionPayload({routeMatrix:e,amounts:t,slippage:i=1}){let r=$({routeMatrix:e,amounts:t,slippage:Number(i)});return{function:`${this._sdk.sdkConfig.sorContractAddress}::entry::execute_routes`,functionArguments:[[...r]]}}};var v=class{constructor(e){this._sdkConfig=e;let t=_axios2.default.create({baseURL:e.url});this._request=new I(t),this._pool=new w(this),this._swap=new x(this),this._position=new k(this)}get Pool(){return this._pool}get Swap(){return this._swap}get Position(){return this._position}get sdkConfig(){return this._sdkConfig}get request(){return this._request}};var Z={network:_tssdk.Network.TESTNET,contractAddress:"0xc861148c940f4ac95e14a892fa971c745e93675fe3d76f4f398c88d5de46f0b9",url:"https://display-engine.dev.tapp-dex.devucc.name/api/v1",sorContractAddress:"0xe34cea371eff04b98a8007ce14e5b8ee767602857547a35a48a6ecc0d91847c2"},j={network:_tssdk.Network.MAINNET,contractAddress:"0x487e905f899ccb6d46fdaec56ba1e0c4cf119862a16c409904b8c78fab1f5e8a",url:"https://api.tapp.exchange/api/v1",sorContractAddress:"0x7bd64a730c360a87da24187d6d2e9128310ff25419facb3000d6b2293a06280a"},Yt= exports.initTappSDK =u=>{let e=_optionalChain([u, 'optionalAccess', _19 => _19.network])==_tssdk.Network.TESTNET?Z:j;return new v({network:e.network,url:_nullishCoalesce(_optionalChain([u, 'optionalAccess', _20 => _20.url]), () => (e.url)),contractAddress:e.contractAddress,sorContractAddress:e.sorContractAddress})};var Y=(i=>(i.AMM="AMM",i.CLMM="CLMM",i.STABLE="STABLE",i))(Y||{});exports.LiquidityType = N; exports.PoolType = Y; exports.TradeSizeExceedsError = q; exports.initTappSDK = Yt;
//# sourceMappingURL=index.js.map