@swapkit/helpers 1.0.0-rc.8 → 1.0.0-rc.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.es.js +709 -379
- package/package.json +8 -5
- package/src/helpers/asset.ts +7 -13
- package/src/helpers/others.ts +0 -48
- package/src/helpers/request.ts +16 -0
- package/src/index.ts +1 -0
- package/src/modules/__tests__/assetValue.test.ts +6 -7
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var oe=Object.create;var N=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var he=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var me=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var ge=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ue(e))!de.call(n,a)&&a!==t&&N(n,a,{get:()=>e[a],enumerable:!(i=le(e,a))||i.enumerable});return n};var _e=(n,e,t)=>(t=n!=null?oe(he(n)):{},ge(e||!n||!n.__esModule?N(t,"default",{value:n,enumerable:!0}):t,n));var g=(n,e,t)=>(me(n,typeof e!="symbol"?e+"":e,t),t),pe=(n,e,t)=>{if(!e.has(n))throw TypeError("Cannot "+t)};var C=(n,e,t)=>{if(e.has(n))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(n):e.set(n,t)};var m=(n,e,t)=>(pe(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("@swapkit/types"),Ce=n=>{if(n<0)throw new Error("Invalid number of year");return 10+n},fe=n=>{if(n.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!n.match(e)},Ae=([n,e,t,i,a])=>`${n}'/${e}'/${t}'/${i}${typeof a!="number"?"":`/${a}`}`,Se=async(n,e)=>{try{const t=Object.entries(e||{}).reduce((a,[s,c])=>(c&&(a[s]=c),a),{});return(await fetch(`${n}${e?`?${new URLSearchParams(t).toString()}`:""}`,{method:"GET",mode:"cors",credentials:"omit",referrer:"https://sk.thorswap.net"})).json()}catch(t){return console.error(t),{}}},K=async(n,e,t,i=!1)=>{try{const a=await fetch(`${n}`,{body:e,headers:t,method:"POST",referrer:"https://sk.thorswap.net"});return i?a.text():a.json()}catch{return{}}},we="0x313ce567",Y=async({chain:n,to:e})=>{try{const t=await K(r.ChainToRPC[n],JSON.stringify({method:"eth_call",params:[{to:e.toLowerCase(),data:we},"latest"],id:44,jsonrpc:"2.0"}),{accept:"*/*","cache-control":"no-cache","content-type":"application/json"},!0),{result:i}=JSON.parse(t);return parseInt(BigInt(i).toString())}catch(t){return console.error(t),r.BaseDecimal[n]}},$e=async n=>{if(n===r.Chain.Ethereum)return r.BaseDecimal.ETH;const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?Y({chain:r.Chain.Ethereum,to:e}):r.BaseDecimal.ETH},Be=async n=>{const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?Y({chain:r.Chain.Avalanche,to:e.toLowerCase()}):r.BaseDecimal.AVAX},be=async n=>(n===r.Chain.BinanceSmartChain,r.BaseDecimal.BSC),q=async({chain:n,symbol:e})=>{switch(n){case r.Chain.Ethereum:return $e(e);case r.Chain.Avalanche:return Be(e);case r.Chain.BinanceSmartChain:return be(e);default:return r.BaseDecimal[n]}},ye={[r.FeeOption.Average]:1.2,[r.FeeOption.Fast]:1.5,[r.FeeOption.Fastest]:2},z=({chain:n,symbol:e})=>{switch(n){case r.Chain.Bitcoin:case r.Chain.BitcoinCash:case r.Chain.Litecoin:case r.Chain.Dogecoin:case r.Chain.Binance:case r.Chain.Ethereum:case r.Chain.Avalanche:return e===n;case r.Chain.Arbitrum:case r.Chain.Optimism:return e==="ETH";case r.Chain.Maya:return e==="CACAO";case r.Chain.Kujira:return e==="KUJI";case r.Chain.Cosmos:return e==="ATOM";case r.Chain.Polygon:return e==="MATIC";case r.Chain.BinanceSmartChain:return e==="BNB";case r.Chain.THORChain:return e==="RUNE"}},J=n=>{switch(n){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case r.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:r.BaseDecimal[n]};case r.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:r.BaseDecimal[n]};case r.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:r.BaseDecimal[n]};case r.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:r.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case r.Chain.Kujira:case r.Chain.Arbitrum:case r.Chain.Optimism:case r.Chain.BitcoinCash:case r.Chain.Litecoin:case r.Chain.Dogecoin:case r.Chain.Binance:case r.Chain.Avalanche:case r.Chain.Polygon:case r.Chain.Bitcoin:case r.Chain.Ethereum:return{identifier:`${n}.${n}`,decimal:r.BaseDecimal[n]}}},Q=({chain:n,symbol:e})=>{if(e.includes("/"))return"Synth";switch(n){case r.Chain.Bitcoin:case r.Chain.BitcoinCash:case r.Chain.Dogecoin:case r.Chain.Litecoin:case r.Chain.Maya:case r.Chain.THORChain:return"Native";case r.Chain.Cosmos:return e==="ATOM"?"Native":r.Chain.Cosmos;case r.Chain.Kujira:return e===r.Chain.Kujira?"Native":r.Chain.Kujira;case r.Chain.Binance:return e===r.Chain.Binance?"Native":"BEP2";case r.Chain.BinanceSmartChain:return e===r.Chain.Binance?"Native":"BEP20";case r.Chain.Ethereum:return e===r.Chain.Ethereum?"Native":"ERC20";case r.Chain.Avalanche:return e===r.Chain.Avalanche?"Native":r.Chain.Avalanche;case r.Chain.Polygon:return e===r.Chain.Polygon?"Native":"POLYGON";case r.Chain.Arbitrum:return[r.Chain.Ethereum,r.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case r.Chain.Optimism:return[r.Chain.Ethereum,r.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Ie=n=>{var c;const[e,...t]=n.split("."),i=n.includes("/"),a=t.join("."),s=(c=a==null?void 0:a.split("-"))==null?void 0:c[0];return{chain:e,symbol:a,ticker:s,synth:i}},Te=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),ve=n=>n.filter(e=>!Te.test(e.toString())&&!e.toString().includes("undefined")),X=({liquidityUnits:n,poolUnits:e,runeDepth:t})=>{const i=d(n),a=d(e),s=d(t),c=i.mul(s),o=a.mul(a).mul(2),l=a.mul(i).mul(2),u=i.mul(i),h=a.mul(a).mul(a);return c.mul(o.sub(l).add(u)).div(h)},Z=({liquidityUnits:n,poolUnits:e,assetDepth:t})=>{const i=d(n),a=d(e),s=d(t),c=i.mul(s),o=a.mul(a).mul(2),l=a.mul(i).mul(2),u=i.mul(i),h=c.mul(o.sub(l).add(u)),p=a.mul(a).mul(a);return h.div(p)},Me=({percent:n,runeDepth:e,liquidityUnits:t,poolUnits:i})=>X({runeDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),Ve=({percent:n,assetDepth:e,liquidityUnits:t,poolUnits:i})=>Z({assetDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),d=n=>new ie({value:n,decimal:r.BaseDecimal.THOR}),ee=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})=>({assetAmount:d(i).mul(n).div(e),runeAmount:d(t).mul(n).div(e)}),Oe=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i,percent:a})=>Object.fromEntries(Object.entries(ee({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})).map(([s,c])=>[s,c.mul(a)])),Ee=({runeDepth:n,poolUnits:e,assetDepth:t,liquidityUnits:i,runeAmount:a,assetAmount:s})=>{const c=d(n),o=d(t),l=d(e),u=d(a),h=d(s),p=u.mul(o),$=h.mul(c),E=u.mul(h),ae=c.mul(o),re=l.mul(p.add($.add(E.mul(2)))),se=p.add($.add(ae.mul(2))),W=re.div(se),R=d(i).add(W);if(W.baseValueNumber===0)return R.div(l).baseValueNumber;const ce=l.add(R);return R.div(ce).baseValueNumber},Re=({runeAmount:n,assetAmount:e,runeDepth:t,assetDepth:i})=>{const a=d(t),s=d(i),c=d(e),o=d(n),l=c.mul(a).sub(s.mul(o)),u=s.mul(o).add(a.mul(s));return Math.abs(l.div(u).baseValueNumber)},Ne=({symbol:n,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${n.slice(-3)}`:n,De=(n,e)=>{switch(n){case r.MemoType.LEAVE:case r.MemoType.BOND:{const{address:t}=e;return`${n}:${t}`}case r.MemoType.UNBOND:{const{address:t,unbondAmount:i}=e;return`${n}:${t}:${i*10**8}`}case r.MemoType.THORNAME_REGISTER:{const{name:t,chain:i,address:a,owner:s}=e;return`${n}:${t}:${i}:${a}${s?`:${s}`:""}`}case r.MemoType.DEPOSIT:{const{chain:t,symbol:i,address:a,singleSide:s}=e;return s?`${n}:${t}/${i}::t:0`:`${n}:${t}.${i}:${a||""}:t:0`}case r.MemoType.WITHDRAW:{const{chain:t,ticker:i,symbol:a,basisPoints:s,targetAssetString:c,singleSide:o}=e,l=!o&&c?`:${c}`:"",u=Ne({chain:t,symbol:a,ticker:i});return`${n}:${t}${o?"/":"."}${u}:${s}${l}`}case r.MemoType.OPEN_LOAN:case r.MemoType.CLOSE_LOAN:{const{asset:t,address:i}=e;return`${n}:${t}:${i}`}default:return""}},G=Object.values(r.Chain),He=(n="")=>{const e=n.toUpperCase(),[t]=e.split(".");if(G.includes(t))return!0;const[i]=e.split("/");if(G.includes(i))return!0;throw new Error(`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},I=8,S=n=>10n**BigInt(n),B=n=>Math.log10(parseFloat(n.toString()));function P({value:n,bigIntDecimal:e=I,decimal:t=I}){const i=n<0n;let a=n.toString().substring(i?1:0);const s=t-(a.length-1);s>0&&(a="0".repeat(s)+a);const c=a.length-t;let o=a.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${i?"-":""}${a.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var f,b,V,te,O,ne,v,k,A,y,M,L;const T=class T{constructor(e){C(this,f);C(this,V);C(this,O);C(this,v);C(this,A);C(this,M);g(this,"decimalMultiplier",10n**8n);g(this,"bigIntValue",0n);g(this,"decimal");const t=D(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=S(Math.max(m(this,M,L).call(this,m(this,A,y).call(this,t)),this.decimal||0)),m(this,V,te).call(this,t)}static fromBigInt(e,t){return new T({decimal:t,value:P({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:i}){return T.fromBigInt(new T(e).bigIntValue*S(i)/S(t),i)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return m(this,f,b).call(this,"add",...e)}sub(...e){return m(this,f,b).call(this,"sub",...e)}mul(...e){return m(this,f,b).call(this,"mul",...e)}div(...e){return m(this,f,b).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||B(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/S(this.decimal||r.BaseDecimal.THOR),i=this.bigIntValue/t;switch(e){case"number":return Number(i);case"string":return i.toString();default:return i}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const i=D(e),a=m(this,A,y).call(this,i);return a==="0"||a==="undefined"?0n:m(this,v,k).call(this,a,t)}formatBigIntToSafeValue(e,t){const i=t||this.decimal||I,a=Math.max(i,B(this.decimalMultiplier)),s=e<0n,c=e.toString().substring(s?1:0),o=a-(c.length-1),l=o>0?"0".repeat(o)+c:c,u=l.length-a;let h=l.slice(-a);return parseInt(h[i])>=5?h=`${h.substring(0,i-1)}${(parseInt(h[i-1])+1).toString()}`:h=h.substring(0,i),`${s?"-":""}${l.slice(0,u)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,i]=this.getValue("string").split("."),a=t||"",s=i||"",c=parseInt(a)?a.length+s.length:s.length;if(c<=e)return this.getValue("string");if(a.length>=e)return a.slice(0,e).padEnd(a.length,"0");if(parseInt(a))return`${a}.${s.slice(0,e-a.length)}`.padEnd(c-e,"0");const o=parseInt(s),l=`${o}`.slice(0,e);return`0.${l.padStart(s.length-`${o}`.length+l.length,"0")}`}};f=new WeakSet,b=function(e,...t){const i=m(this,O,ne).call(this,this,...t),a=S(i),s=t.reduce((o,l)=>{const u=this.getBigIntValue(l,i);switch(e){case"add":return o+u;case"sub":return o-u;case"mul":return o*u/a;case"div":{if(u===0n)throw new RangeError("Division by zero");return o*a/u}default:return o}},this.bigIntValue*a/this.decimalMultiplier),c=P({bigIntDecimal:i,decimal:Math.max(i,B(this.decimalMultiplier)),value:s});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},V=new WeakSet,te=function(e){const t=m(this,A,y).call(this,e)||"0";this.bigIntValue=m(this,v,k).call(this,t)},O=new WeakSet,ne=function(...e){const t=e.map(i=>typeof i=="object"?i.decimal||B(i.decimalMultiplier):m(this,M,L).call(this,m(this,A,y).call(this,i))).filter(Boolean);return Math.max(...t,I)},v=new WeakSet,k=function(e,t){const i=t?S(t):this.decimalMultiplier,a=B(i),[s="",c=""]=e.split(".");return BigInt(`${s}${c.padEnd(a,"0")}`)},A=new WeakSet,y=function(e){const i=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):D(e)}`.replaceAll(",",".").split(".");return i.length>1?`${i.slice(0,-1).join("")}.${i.at(-1)}`:i[0]},M=new WeakSet,L=function(e){var i;const t=((i=e.split(".")[1])==null?void 0:i.length)||0;return Math.max(t,I)};let w=T;function D(n){return typeof n=="object"?"getValue"in n?n.getValue("string"):n.value:n}let x;const H=n=>{if(!x)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return x.get(n.toUpperCase())||{decimal:r.BaseDecimal.THOR,identifier:""}},U=async(n,e=0)=>{He(n);const t=await q(j(n));return new _({decimal:t,value:e,identifier:n})};class _ extends w{constructor(t){super(t.value instanceof w?t.value:{decimal:t.decimal,value:t.value});g(this,"address");g(this,"chain");g(this,"isSynthetic",!1);g(this,"isGasAsset",!1);g(this,"symbol");g(this,"ticker");g(this,"type");const i="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,a=j(i);this.type=Q(a),this.chain=a.chain,this.ticker=a.ticker,this.symbol=a.symbol,this.address=a.address,this.isSynthetic=a.isSynthetic,this.isGasAsset=a.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const i=this.isSynthetic?this.ticker:`${this.chain}.${this.ticker}`;return t?i:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:i}){return this.chain===t&&this.symbol===i}static async fromString(t,i=0){return U(t,i)}static fromStringSync(t,i=0){const{decimal:a,identifier:s}=H(t);return s?new _({decimal:a,identifier:s,value:i}):void 0}static async fromIdentifier(t,i=0){return U(t,i)}static fromIdentifierSync(t,i=0){const{decimal:a,identifier:s}=H(t);return new _({decimal:a,identifier:s,value:i})}static fromChainOrSignature(t,i=0){const{decimal:a,identifier:s}=J(t);return new _({value:i,decimal:a,identifier:s})}static async fromTCQuote(t,i=0){const a=await q(j(t)),s=this.shiftDecimals({value:i,from:r.BaseDecimal.THOR,to:a});return new _({value:s,identifier:t,decimal:a})}static fromTCQuoteStatic(t,i=0){const a=H(t),s=this.shiftDecimals({value:i,from:r.BaseDecimal.THOR,to:a.decimal});return new _({...a,value:s})}static async loadStaticAssets(){return new Promise(async(t,i)=>{try{const{ThorchainList:a,NativeList:s,...c}=await import("@swapkit/tokens");x=[s,...Object.values(c)].reduce((l,{tokens:u})=>(u.forEach(({identifier:h,chain:p,...$})=>{const E="decimals"in $?$.decimals:r.BaseDecimal[p];l.set(h,{identifier:h,decimal:E})}),l),new Map),t({ok:!0})}catch(a){console.error(a),i({ok:!1,error:a,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const Pe=n=>{const e=_.fromChainOrSignature(n);switch(n){case r.Chain.Bitcoin:case r.Chain.Litecoin:case r.Chain.BitcoinCash:return e.add(10001);case r.Chain.Dogecoin:return e.add(100000001);case r.Chain.Avalanche:case r.Chain.Ethereum:return e.add(10*10**9);case r.Chain.THORChain:case r.Chain.Maya:return e.add(0);default:return e.add(1)}},j=n=>{const e=n.slice(0,14).includes("/"),t=n.includes(".")?n:`${r.Chain.THORChain}.${n}`,[i,a]=t.split("."),[s,c]=a.split("-");return{address:c==null?void 0:c.toLowerCase(),chain:i,isGasAsset:z({chain:i,symbol:a}),isSynthetic:e,symbol:c?`${s}-${(c==null?void 0:c.toLowerCase())??""}`:a,ticker:e?a:s}},ke={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class F extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ke[e],message:e}}),Object.setPrototypeOf(this,F.prototype)}}class ie extends w{eq(e){return this.eqValue(e)}}exports.AssetValue=_;exports.BigIntArithmetics=w;exports.SwapKitError=F;exports.SwapKitNumber=ie;exports.assetFromString=Ie;exports.derivationPathToString=Ae;exports.filterAssets=ve;exports.formatBigIntToSafeValue=P;exports.gasFeeMultiplier=ye;exports.getAssetType=Q;exports.getAsymmetricAssetShare=Z;exports.getAsymmetricAssetWithdrawAmount=Ve;exports.getAsymmetricRuneShare=X;exports.getAsymmetricRuneWithdrawAmount=Me;exports.getCommonAssetInfo=J;exports.getDecimal=q;exports.getEstimatedPoolShare=Ee;exports.getLiquiditySlippage=Re;exports.getMemoFor=De;exports.getMinAmountByChain=Pe;exports.getRequest=Se;exports.getSymmetricPoolShare=ee;exports.getSymmetricWithdraw=Oe;exports.getTHORNameCost=Ce;exports.isGasAsset=z;exports.postRequest=K;exports.validateTHORName=fe;
|
|
1
|
+
"use strict";var Ae=Object.create;var N=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Re=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty;var Ie=(s,e,t)=>e in s?N(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Be=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Se(e))!ve.call(s,n)&&n!==t&&N(s,n,{get:()=>e[n],enumerable:!(r=Te(e,n))||r.enumerable});return s};var $e=(s,e,t)=>(t=s!=null?Ae(Re(s)):{},Be(e||!s||!s.__esModule?N(t,"default",{value:s,enumerable:!0}):t,s));var p=(s,e,t)=>(Ie(s,typeof e!="symbol"?e+"":e,t),t),Ee=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var _=(s,e,t)=>{if(e.has(s))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(s):e.set(s,t)};var m=(s,e,t)=>(Ee(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Oe="0x313ce567",re=async({chain:s,to:e})=>{try{const{result:t}=await pe.post(i.ChainToRPC[s],{headers:{accept:"*/*","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Oe},"latest"]})});return parseInt(BigInt(t).toString())}catch(t){return console.error(t),i.BaseDecimal[s]}},Me=async s=>{if(s===i.Chain.Ethereum)return i.BaseDecimal.ETH;const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},ke=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?re({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},qe=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),K=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Me(e);case i.Chain.Avalanche:return ke(e);case i.Chain.BinanceSmartChain:return qe(e);default:return i.BaseDecimal[s]}},Ve={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},se=({chain:s,symbol:e})=>{switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Ethereum:case i.Chain.Avalanche:return e===s;case i.Chain.Arbitrum:case i.Chain.Optimism:return e==="ETH";case i.Chain.Maya:return e==="CACAO";case i.Chain.Kujira:return e==="KUJI";case i.Chain.Cosmos:return e==="ATOM";case i.Chain.Polygon:return e==="MATIC";case i.Chain.BinanceSmartChain:return e==="BNB";case i.Chain.THORChain:return e==="RUNE"}},ne=s=>{switch(s){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case i.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:i.BaseDecimal[s]};case i.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:i.BaseDecimal[s]};case i.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:i.BaseDecimal[s]};case i.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:i.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case i.Chain.Kujira:case i.Chain.Arbitrum:case i.Chain.Optimism:case i.Chain.BitcoinCash:case i.Chain.Litecoin:case i.Chain.Dogecoin:case i.Chain.Binance:case i.Chain.Avalanche:case i.Chain.Polygon:case i.Chain.Bitcoin:case i.Chain.Ethereum:return{identifier:`${s}.${s}`,decimal:i.BaseDecimal[s]}}},ie=({chain:s,symbol:e})=>{if(e.includes("/"))return"Synth";switch(s){case i.Chain.Bitcoin:case i.Chain.BitcoinCash:case i.Chain.Dogecoin:case i.Chain.Litecoin:case i.Chain.Maya:case i.Chain.THORChain:return"Native";case i.Chain.Cosmos:return e==="ATOM"?"Native":i.Chain.Cosmos;case i.Chain.Kujira:return e===i.Chain.Kujira?"Native":i.Chain.Kujira;case i.Chain.Binance:return e===i.Chain.Binance?"Native":"BEP2";case i.Chain.BinanceSmartChain:return e===i.Chain.Binance?"Native":"BEP20";case i.Chain.Ethereum:return e===i.Chain.Ethereum?"Native":"ERC20";case i.Chain.Avalanche:return e===i.Chain.Avalanche?"Native":i.Chain.Avalanche;case i.Chain.Polygon:return e===i.Chain.Polygon?"Native":"POLYGON";case i.Chain.Arbitrum:return[i.Chain.Ethereum,i.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case i.Chain.Optimism:return[i.Chain.Ethereum,i.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Pe=s=>{var o;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(o=n==null?void 0:n.split("-"))==null?void 0:o[0];return{chain:e,symbol:n,ticker:a,synth:r}},Ne=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),xe=s=>s.filter(e=>!Ne.test(e.toString())&&!e.toString().includes("undefined")),ae=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return o.mul(c.sub(u).add(l)).div(h)},oe=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),o=r.mul(a),c=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=o.mul(c.sub(u).add(l)),g=n.mul(n).mul(n);return h.div(g)},De=({percent:s,runeDepth:e,liquidityUnits:t,poolUnits:r})=>ae({runeDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),He=({percent:s,assetDepth:e,liquidityUnits:t,poolUnits:r})=>oe({assetDepth:e,liquidityUnits:t,poolUnits:r}).mul(s),d=s=>new _e({value:s,decimal:i.BaseDecimal.THOR}),ce=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})=>({assetAmount:d(r).mul(s).div(e),runeAmount:d(t).mul(s).div(e)}),je=({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r,percent:n})=>Object.fromEntries(Object.entries(ce({liquidityUnits:s,poolUnits:e,runeDepth:t,assetDepth:r})).map(([a,o])=>[a,o.mul(n)])),Le=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const o=d(s),c=d(t),u=d(e),l=d(n),h=d(a),g=l.mul(c),C=h.mul(o),V=l.mul(h),ye=o.mul(c),be=u.mul(g.add(C.add(V.mul(2)))),Ce=g.add(C.add(ye.mul(2))),J=be.div(Ce),P=d(r).add(J);if(J.baseValueNumber===0)return P.div(u).baseValueNumber;const we=u.add(P);return P.div(we).baseValueNumber},Ue=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{const n=d(t),a=d(r),o=d(e),c=d(s),u=o.mul(n).sub(a.mul(c)),l=a.mul(c).add(n.mul(a));return Math.abs(u.div(l).baseValueNumber)},Fe=({symbol:s,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${s.slice(-3)}`:s,We=(s,e)=>{switch(s){case i.MemoType.LEAVE:case i.MemoType.BOND:{const{address:t}=e;return`${s}:${t}`}case i.MemoType.UNBOND:{const{address:t,unbondAmount:r}=e;return`${s}:${t}:${r*10**8}`}case i.MemoType.THORNAME_REGISTER:{const{name:t,chain:r,address:n,owner:a}=e;return`${s}:${t}:${r}:${n}${a?`:${a}`:""}`}case i.MemoType.DEPOSIT:{const{chain:t,symbol:r,address:n,singleSide:a}=e;return a?`${s}:${t}/${r}::t:0`:`${s}:${t}.${r}:${n||""}:t:0`}case i.MemoType.WITHDRAW:{const{chain:t,ticker:r,symbol:n,basisPoints:a,targetAssetString:o,singleSide:c}=e,u=!c&&o?`:${o}`:"",l=Fe({chain:t,symbol:n,ticker:r});return`${s}:${t}${c?"/":"."}${l}:${a}${u}`}case i.MemoType.OPEN_LOAN:case i.MemoType.CLOSE_LOAN:{const{asset:t,address:r}=e;return`${s}:${t}:${r}`}default:return""}},Ge=s=>{if(s<0)throw new Error("Invalid number of year");return 10+s},Ke=s=>{if(s.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!s.match(e)},Ye=([s,e,t,r,n])=>`${s}'/${e}'/${t}'/${r}${typeof n!="number"?"":`/${n}`}`;class Q extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",o=`${n} ${a}`.trim(),c=o?`status code ${o}`:"an unknown error";super(`Request failed with ${c}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=e,this.request=t,this.options=r}}class ue extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const O=s=>s!==null&&typeof s=="object",E=(...s)=>{for(const e of s)if((!O(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return Y({},...s)},le=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,o]of n.entries())r&&o==="undefined"||o===void 0?t.delete(a):t.set(a,o);return t},Y=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(O(r)){for(let[n,a]of Object.entries(r))O(a)&&n in e&&(a=Y(e[n],a)),e={...e,[n]:a};O(r.headers)&&(t=le(t,r.headers),e.headers=t)}return e},ze=(()=>{let s=!1,e=!1;const t=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";return t&&r&&(e=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return s=!0,"half"}}).headers.has("Content-Type")),s&&!e})(),Je=typeof globalThis.AbortController=="function",Qe=typeof globalThis.ReadableStream=="function",Xe=typeof globalThis.FormData=="function",he=["get","post","put","patch","head","delete"],Ze={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},x=2147483647,de=Symbol("stop"),et={json:!0,parseJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},tt={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0},rt=s=>he.includes(s)?s.toUpperCase():s,st=["get","put","head","delete","options","trace"],nt=[408,413,429,500,502,503,504],me=[413,429,503],X={limit:2,methods:st,statusCodes:nt,afterStatusCodes:me,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:s=>.3*2**(s-1)*1e3},it=(s={})=>{if(typeof s=="number")return{...X,limit:s};if(s.methods&&!Array.isArray(s.methods))throw new Error("retry.methods must be an array");if(s.statusCodes&&!Array.isArray(s.statusCodes))throw new Error("retry.statusCodes must be an array");return{...X,...s,afterStatusCodes:me}};async function at(s,e,t,r){return new Promise((n,a)=>{const o=setTimeout(()=>{t&&t.abort(),a(new ue(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(o)})})}async function ot(s,{signal:e}){return new Promise((t,r)=>{e&&(e.throwIfAborted(),e.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(a),r(e.reason)}const a=setTimeout(()=>{e==null||e.removeEventListener("abort",n),t()},s)})}const ct=(s,e)=>{const t={};for(const r in e)!(r in tt)&&!(r in et)&&!(r in s)&&(t[r]=e[r]);return t};class M{static create(e,t){const r=new M(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>x)throw new RangeError(`The \`timeout\` option cannot be greater than ${x}`);await Promise.resolve();let c=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(c.clone()));l instanceof globalThis.Response&&(c=l)}if(r._decorateResponse(c),!c.ok&&r._options.throwHttpErrors){let u=new Q(c,r.request,r._options);for(const l of r._options.hooks.beforeError)u=await l(u);throw u}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!Qe)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(c.clone(),r._options.onDownloadProgress)}return c},o=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[c,u]of Object.entries(Ze))o[c]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await o).clone();if(c==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[c]()};return o}constructor(e,t={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:le(this._input.headers,t.headers),hooks:Y({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:rt(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:it(t.retry),throwHttpErrors:t.throwHttpErrors!==!1,timeout:t.timeout??1e4,fetch:t.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(Je){if(this.abortController=new globalThis.AbortController,this._options.signal){const r=this._options.signal;this._options.signal.addEventListener("abort",()=>{this.abortController.abort(r.reason)})}this._options.signal=this.abortController.signal}if(ze&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const n="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),a=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,n);(Xe&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(a,{...this.request}),this._options)}this._options.json!==void 0&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof ue)){if(e instanceof Q){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const r=e.response.headers.get("Retry-After");if(r&&this._options.retry.afterStatusCodes.includes(e.response.status)){let n=Number(r);return Number.isNaN(n)?n=Date.parse(r)-Date.now():n*=1e3,this._options.retry.maxRetryAfter!==void 0&&n>this._options.retry.maxRetryAfter?0:n}if(e.response.status===413)return 0}const t=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,t)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const r=Math.min(this._calculateRetryDelay(t),x);if(r!==0&&this._retryCount>0){await ot(r,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===de)return;return this._retry(e)}throw t}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const r=await t(this.request,this._options);if(r instanceof Request){this.request=r;break}if(r instanceof Response)return r}const e=ct(this.request,this._options);return this._options.timeout===!1?this._options.fetch(this.request.clone(),e):at(this.request.clone(),e,this.abortController,this._options)}_stream(e,t){const r=Number(e.headers.get("content-length"))||0;let n=0;return e.status===204?(t&&t({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(a){const o=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function c(){const{done:u,value:l}=await o.read();if(u){a.close();return}if(t){n+=l.byteLength;const h=r===0?0:n/r;t({percent:h,transferredBytes:n,totalBytes:r},l)}a.enqueue(l),await c()}await c()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const j=s=>{const e=(t,r)=>M.create(t,E(s,r));for(const t of he)e[t]=(r,n)=>M.create(r,E(s,n,{method:t}));return e.create=t=>j(E(t)),e.extend=t=>j(E(s,t)),e.stop=de,e},ut=j(),lt=ut,Z=lt.create({headers:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net","Content-Type":"application/json"}}),pe={get:(s,e)=>Z.get(s,e).json(),post:(s,e)=>Z.post(s,e).json()},ee=Object.values(i.Chain),ht=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(ee.includes(t))return!0;const[r]=e.split("/");if(ee.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},v=8,w=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function L({value:s,bigIntDecimal:e=v,decimal:t=v}){const r=s<0n;let n=s.toString().substring(r?1:0);const a=t-(n.length-1);a>0&&(n="0".repeat(a)+n);const o=n.length-t;let c=n.slice(-t);return parseInt(c[e])>=5?c=`${c.substring(0,e-1)}${(parseInt(c[e-1])+1).toString()}`:c=c.substring(0,e),`${r?"-":""}${n.slice(0,o)}.${c}`.replace(/\.?0*$/,"")}var y,S,k,fe,q,ge,B,U,b,R,$,F;const I=class I{constructor(e){_(this,y);_(this,k);_(this,q);_(this,B);_(this,b);_(this,$);p(this,"decimalMultiplier",10n**8n);p(this,"bigIntValue",0n);p(this,"decimal");const t=D(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,$,F).call(this,m(this,b,R).call(this,t)),this.decimal||0)),m(this,k,fe).call(this,t)}static fromBigInt(e,t){return new I({decimal:t,value:L({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return I.fromBigInt(new I(e).bigIntValue*w(r)/w(t),r)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return m(this,y,S).call(this,"add",...e)}sub(...e){return m(this,y,S).call(this,"sub",...e)}mul(...e){return m(this,y,S).call(this,"mul",...e)}div(...e){return m(this,y,S).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||T(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/w(this.decimal||i.BaseDecimal.THOR),r=this.bigIntValue/t;switch(e){case"number":return Number(r);case"string":return r.toString();default:return r}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const r=D(e),n=m(this,b,R).call(this,r);return n==="0"||n==="undefined"?0n:m(this,B,U).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||v,n=Math.max(r,T(this.decimalMultiplier)),a=e<0n,o=e.toString().substring(a?1:0),c=n-(o.length-1),u=c>0?"0".repeat(c)+o:o,l=u.length-n;let h=u.slice(-n);return parseInt(h[r])>=5?h=`${h.substring(0,r-1)}${(parseInt(h[r-1])+1).toString()}`:h=h.substring(0,r),`${a?"-":""}${u.slice(0,l)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"",o=parseInt(n)?n.length+a.length:a.length;if(o<=e)return this.getValue("string");if(n.length>=e)return n.slice(0,e).padEnd(n.length,"0");if(parseInt(n))return`${n}.${a.slice(0,e-n.length)}`.padEnd(o-e,"0");const c=parseInt(a),u=`${c}`.slice(0,e);return`0.${u.padStart(a.length-`${c}`.length+u.length,"0")}`}};y=new WeakSet,S=function(e,...t){const r=m(this,q,ge).call(this,this,...t),n=w(r),a=t.reduce((c,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return c+l;case"sub":return c-l;case"mul":return c*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return c*n/l}default:return c}},this.bigIntValue*n/this.decimalMultiplier),o=L({bigIntDecimal:r,decimal:Math.max(r,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:o,identifier:this.toString()})},k=new WeakSet,fe=function(e){const t=m(this,b,R).call(this,e)||"0";this.bigIntValue=m(this,B,U).call(this,t)},q=new WeakSet,ge=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):m(this,$,F).call(this,m(this,b,R).call(this,r))).filter(Boolean);return Math.max(...t,v)},B=new WeakSet,U=function(e,t){const r=t?w(t):this.decimalMultiplier,n=T(r),[a="",o=""]=e.split(".");return BigInt(`${a}${o.padEnd(n,"0")}`)},b=new WeakSet,R=function(e){const r=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):D(e)}`.replaceAll(",",".").split(".");return r.length>1?`${r.slice(0,-1).join("")}.${r.at(-1)}`:r[0]},$=new WeakSet,F=function(e){var r;const t=((r=e.split(".")[1])==null?void 0:r.length)||0;return Math.max(t,v)};let A=I;function D(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}let W;const H=s=>{if(!W)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return W.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},te=async(s,e=0)=>{ht(s);const t=await K(G(s));return new f({decimal:t,value:e,identifier:s})};class f extends A{constructor(t){super(t.value instanceof A?t.value:{decimal:t.decimal,value:t.value});p(this,"address");p(this,"chain");p(this,"isSynthetic",!1);p(this,"isGasAsset",!1);p(this,"symbol");p(this,"ticker");p(this,"type");const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,n=G(r);this.type=ie(n),this.chain=n.chain,this.ticker=n.ticker,this.symbol=n.symbol,this.address=n.address,this.isSynthetic=n.isSynthetic,this.isGasAsset=n.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const r=this.isSynthetic?this.ticker:`${this.chain}.${this.ticker}`;return t?r:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:r}){return this.chain===t&&this.symbol===r}static async fromString(t,r=0){return te(t,r)}static fromStringSync(t,r=0){const{decimal:n,identifier:a}=H(t);return a?new f({decimal:n,identifier:a,value:r}):void 0}static async fromIdentifier(t,r=0){return te(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=H(t);return new f({decimal:n,identifier:a,value:r})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ne(t);return new f({value:r,decimal:n,identifier:a})}static async fromTCQuote(t,r=0){const n=await K(G(t)),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n});return new f({value:a,identifier:t,decimal:n})}static fromTCQuoteStatic(t,r=0){const n=H(t),a=this.shiftDecimals({value:r,from:i.BaseDecimal.THOR,to:n.decimal});return new f({...n,value:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...o}=await import("@swapkit/tokens");W=[a,...Object.values(o)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...C})=>{const V="decimals"in C?C.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:V})}),u),new Map),t({ok:!0})}catch(n){console.error(n),r({ok:!1,error:n,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const dt=s=>{const e=f.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.add(10001);case i.Chain.Dogecoin:return e.add(100000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.add(10*10**9);case i.Chain.THORChain:case i.Chain.Maya:return e.add(0);default:return e.add(1)}},G=s=>{const e=s.slice(0,14).includes("/"),t=s.includes(".")?s:`${i.Chain.THORChain}.${s}`,[r,n]=t.split("."),[a,o]=n.split("-");return{address:o==null?void 0:o.toLowerCase(),chain:r,isGasAsset:se({chain:r,symbol:n}),isSynthetic:e,symbol:o?`${a}-${(o==null?void 0:o.toLowerCase())??""}`:n,ticker:e?n:a}},mt={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class z extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:mt[e],message:e}}),Object.setPrototypeOf(this,z.prototype)}}class _e extends A{eq(e){return this.eqValue(e)}}exports.AssetValue=f;exports.BigIntArithmetics=A;exports.RequestClient=pe;exports.SwapKitError=z;exports.SwapKitNumber=_e;exports.assetFromString=Pe;exports.derivationPathToString=Ye;exports.filterAssets=xe;exports.formatBigIntToSafeValue=L;exports.gasFeeMultiplier=Ve;exports.getAssetType=ie;exports.getAsymmetricAssetShare=oe;exports.getAsymmetricAssetWithdrawAmount=He;exports.getAsymmetricRuneShare=ae;exports.getAsymmetricRuneWithdrawAmount=De;exports.getCommonAssetInfo=ne;exports.getDecimal=K;exports.getEstimatedPoolShare=Le;exports.getLiquiditySlippage=Ue;exports.getMemoFor=We;exports.getMinAmountByChain=dt;exports.getSymmetricPoolShare=ce;exports.getSymmetricWithdraw=je;exports.getTHORNameCost=Ge;exports.isGasAsset=se;exports.validateTHORName=Ke;
|
package/dist/index.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { CoinGeckoList } from '@swapkit/tokens';
|
|
|
3
3
|
import { FeeOption } from '@swapkit/types';
|
|
4
4
|
import type { MayaList } from '@swapkit/tokens';
|
|
5
5
|
import { MemoType } from '@swapkit/types';
|
|
6
|
+
import type { Options } from 'ky';
|
|
6
7
|
import type { PancakeswapETHList } from '@swapkit/tokens';
|
|
7
8
|
import type { PancakeswapList } from '@swapkit/tokens';
|
|
8
9
|
import type { PangolinList } from '@swapkit/tokens';
|
|
@@ -231,10 +232,6 @@ export declare const getMemoFor: <T extends MemoType>(memoType: T, options: Memo
|
|
|
231
232
|
|
|
232
233
|
export declare const getMinAmountByChain: (chain: Chain) => AssetValue;
|
|
233
234
|
|
|
234
|
-
export declare const getRequest: <T>(url: string, params?: {
|
|
235
|
-
[x: string]: any;
|
|
236
|
-
} | undefined) => Promise<T>;
|
|
237
|
-
|
|
238
235
|
export declare const getSymmetricPoolShare: ({ liquidityUnits, poolUnits, runeDepth, assetDepth, }: ShareParams<{
|
|
239
236
|
runeDepth: string;
|
|
240
237
|
assetDepth: string;
|
|
@@ -306,7 +303,10 @@ declare type PoolParams<T = {}> = T & {
|
|
|
306
303
|
assetDepth: string;
|
|
307
304
|
};
|
|
308
305
|
|
|
309
|
-
export declare const
|
|
306
|
+
export declare const RequestClient: {
|
|
307
|
+
get: <T>(url: string | URL | Request, options?: Options) => Promise<T>;
|
|
308
|
+
post: <T_1>(url: string | URL | Request, options?: Options) => Promise<T_1>;
|
|
309
|
+
};
|
|
310
310
|
|
|
311
311
|
declare type ShareParams<T = {}> = T & {
|
|
312
312
|
liquidityUnits: string;
|