@swapkit/helpers 1.0.0-rc.3 → 1.0.0-rc.30
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 +39 -24
- package/dist/index.es.js +776 -415
- package/package.json +9 -6
- package/src/helpers/asset.ts +46 -15
- package/src/helpers/liquidity.ts +12 -10
- package/src/helpers/others.ts +0 -48
- package/src/helpers/request.ts +15 -0
- package/src/index.ts +1 -0
- package/src/modules/__tests__/assetValue.test.ts +44 -12
- package/src/modules/__tests__/swapKitNumber.test.ts +133 -47
- package/src/modules/assetValue.ts +60 -57
- package/src/modules/bigIntArithmetics.ts +102 -50
- package/src/modules/swapKitNumber.ts +8 -1
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}`}`,we=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{}}},Se="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:Se},"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},J=({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"}},z=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]}}},X=({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":"GAIA";case r.Chain.Kujira:return e==="KUJI"?"Native":"KUJI";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":"AVAX";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}},Q=({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)},Te=({percent:n,runeDepth:e,liquidityUnits:t,poolUnits:i})=>Q({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)}),Me=({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)])),Ve=({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))),U=re.div(se),D=d(i).add(U);if(U.baseValueNumber===0)return D.div(l).baseValueNumber;const ce=l.add(D);return D.div(ce).baseValueNumber},Oe=({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)},Ee=({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=Ee({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),Ne=(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,w=n=>10n**BigInt(n),b=n=>Math.log10(parseFloat(n.toString()));function H({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=R(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=w(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:H({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:i}){return T.fromBigInt(new T(e).bigIntValue*w(i)/w(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}}getBaseValue(e){const t=this.decimalMultiplier/w(this.decimal||0),i=this.bigIntValue/t;switch(e){case"number":return Number(i);case"string":return i.toString();default:return this.bigIntValue}}getBigIntValue(e,t){return!t&&typeof e=="object"?e.bigIntValue:m(this,v,k).call(this,m(this,A,y).call(this,R(e)),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=w(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=H({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?w(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}):R(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 S=T;function R(n){return typeof n=="object"?"getValue"in n?n.getValue("string"):n.value:n}let x;const P=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:""}},W=async(n,e=0)=>{Ne(n);const t=await q(j(n));return new _({decimal:t,value:e,identifier:n})};class _ extends S{constructor(t){super(t.value instanceof S?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=X(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(){return`${this.chain}.${this.symbol}`}eq({chain:t,symbol:i}){return this.chain===t&&this.symbol===i}static async fromString(t,i=0){return W(t,i)}static fromStringSync(t,i=0){const{decimal:a,identifier:s}=P(t);return s?new _({decimal:a,identifier:s,value:i}):void 0}static async fromIdentifier(t,i=0){return W(t,i)}static fromIdentifierSync(t,i=0){const{decimal:a,identifier:s}=P(t);return new _({decimal:a,identifier:s,value:i})}static fromChainOrSignature(t,i=0){const{decimal:a,identifier:s}=z(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=P(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 Re=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:J({chain:i,symbol:a}),isSynthetic:e,symbol:c?`${s}-${(c==null?void 0:c.toLowerCase())??""}`:a,ticker:e?a:s}},Pe={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:Pe[e],message:e}}),Object.setPrototypeOf(this,F.prototype)}}class ie extends S{eq(e){return this.eqValue(e)}}exports.AssetValue=_;exports.BigIntArithmetics=S;exports.SwapKitError=F;exports.SwapKitNumber=ie;exports.assetFromString=Ie;exports.derivationPathToString=Ae;exports.formatBigIntToSafeValue=H;exports.gasFeeMultiplier=ye;exports.getAssetType=X;exports.getAsymmetricAssetShare=Z;exports.getAsymmetricAssetWithdrawAmount=ve;exports.getAsymmetricRuneShare=Q;exports.getAsymmetricRuneWithdrawAmount=Te;exports.getCommonAssetInfo=z;exports.getDecimal=q;exports.getEstimatedPoolShare=Ve;exports.getLiquiditySlippage=Oe;exports.getMemoFor=De;exports.getMinAmountByChain=Re;exports.getRequest=we;exports.getSymmetricPoolShare=ee;exports.getSymmetricWithdraw=Me;exports.getTHORNameCost=Ce;exports.isGasAsset=J;exports.postRequest=K;exports.validateTHORName=fe;
|
|
1
|
+
"use strict";var we=Object.create;var x=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty;var Re=(s,e,t)=>e in s?x(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var $e=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Te(e))!Se.call(s,n)&&n!==t&&x(s,n,{get:()=>e[n],enumerable:!(r=Ae(e,n))||r.enumerable});return s};var Ie=(s,e,t)=>(t=s!=null?we(ve(s)):{},$e(e||!s||!s.__esModule?x(t,"default",{value:s,enumerable:!0}):t,s));var m=(s,e,t)=>(Re(s,typeof e!="symbol"?e+"":e,t),t),Be=(s,e,t)=>{if(!e.has(s))throw TypeError("Cannot "+t)};var A=(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 p=(s,e,t)=>(Be(s,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@swapkit/types"),Ee="0x313ce567",se=async({chain:s,to:e})=>{try{const{result:t}=await pe.post(i.ChainToRPC[s],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:e.toLowerCase(),data:Ee},"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")?se({chain:i.Chain.Ethereum,to:e}):i.BaseDecimal.ETH},Oe=async s=>{const[,e]=s.split("-");return e!=null&&e.startsWith("0x")?se({chain:i.Chain.Avalanche,to:e.toLowerCase()}):i.BaseDecimal.AVAX},Ve=async s=>(s===i.Chain.BinanceSmartChain,i.BaseDecimal.BSC),re=async({chain:s,symbol:e})=>{switch(s){case i.Chain.Ethereum:return Me(e);case i.Chain.Avalanche:return Oe(e);case i.Chain.BinanceSmartChain:return Ve(e);default:return i.BaseDecimal[s]}},qe={[i.FeeOption.Average]:1.2,[i.FeeOption.Fast]:1.5,[i.FeeOption.Fastest]:2},U=({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 c;const[e,...t]=s.split("."),r=s.includes("/"),n=t.join("."),a=(c=n==null?void 0:n.split("-"))==null?void 0:c[0];return{chain:e,symbol:n,ticker:a,synth:r}},ke=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),xe=s=>{const[e,t]=s.split(".");if(!i.EVMChainList.includes(e))return!0;const[,r]=t.split("-");return U({chain:e,symbol:t})||!!r},Ne=s=>s.filter(e=>{const t=`${e.chain}.${e.symbol}`;return!ke.test(t)&&xe(t)&&e.value!=="0"}),ae=({liquidityUnits:s,poolUnits:e,runeDepth:t})=>{const r=d(s),n=d(e),a=d(t),c=r.mul(a),o=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=n.mul(n).mul(n);return c.mul(o.sub(u).add(l)).div(h)},oe=({liquidityUnits:s,poolUnits:e,assetDepth:t})=>{const r=d(s),n=d(e),a=d(t),c=r.mul(a),o=n.mul(n).mul(2),u=n.mul(r).mul(2),l=r.mul(r),h=c.mul(o.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=>f.fromBigInt(BigInt(s),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,c])=>[a,c.mul(n)])),Le=({runeDepth:s,poolUnits:e,assetDepth:t,liquidityUnits:r,runeAmount:n,assetAmount:a})=>{const c=new f({value:s,decimal:8}),o=new f({value:t,decimal:8}),u=new f({value:e,decimal:8}),l=new f({value:n,decimal:8}),h=new f({value:a,decimal:8}),g=l.mul(o),b=h.mul(c),P=l.mul(h),_e=c.mul(o),ye=u.mul(g.add(b.add(P.mul(2)))),be=g.add(b.add(_e.mul(2))),Y=ye.div(be),k=d(r).add(Y);if(Y.getBaseValue("number")===0)return k.div(u).getBaseValue("number");const Ce=u.add(k);return k.div(Ce).getBaseValue("number")},Fe=({runeAmount:s,assetAmount:e,runeDepth:t,assetDepth:r})=>{if(s==="0"||e==="0"||t==="0"||r==="0")return 0;const n=d(t),a=d(r),c=d(e),o=d(s),u=c.mul(n).sub(a.mul(o)),l=a.mul(o).add(n.mul(a));return Math.abs(u.div(l).getBaseValue("number"))},Ue=({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:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=Ue({chain:t,symbol:n,ticker:r});return`${s}:${t}${o?"/":"."}${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 z extends Error{constructor(e,t,r){const n=e.status||e.status===0?e.status:"",a=e.statusText||"",c=`${n} ${a}`.trim(),o=c?`status code ${c}`:"an unknown error";super(`Request failed with ${o}`),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 E=s=>s!==null&&typeof s=="object",I=(...s)=>{for(const e of s)if((!E(e)||Array.isArray(e))&&e!==void 0)throw new TypeError("The `options` argument must be an object");return W({},...s)},le=(s={},e={})=>{const t=new globalThis.Headers(s),r=e instanceof globalThis.Headers,n=new globalThis.Headers(e);for(const[a,c]of n.entries())r&&c==="undefined"||c===void 0?t.delete(a):t.set(a,c);return t},W=(...s)=>{let e={},t={};for(const r of s)if(Array.isArray(r))Array.isArray(e)||(e=[]),e=[...e,...r];else if(E(r)){for(let[n,a]of Object.entries(r))E(a)&&n in e&&(a=W(e[n],a)),e={...e,[n]:a};E(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:"*/*"},N=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},st=s=>he.includes(s)?s.toUpperCase():s,rt=["get","put","head","delete","options","trace"],nt=[408,413,429,500,502,503,504],me=[413,429,503],J={limit:2,methods:rt,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{...J,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{...J,...s,afterStatusCodes:me}};async function at(s,e,t,r){return new Promise((n,a)=>{const c=setTimeout(()=>{t&&t.abort(),a(new ue(s))},r.timeout);r.fetch(s,e).then(n).catch(a).then(()=>{clearTimeout(c)})})}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 O{static create(e,t){const r=new O(e,t),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>N)throw new RangeError(`The \`timeout\` option cannot be greater than ${N}`);await Promise.resolve();let o=await r._fetch();for(const u of r._options.hooks.afterResponse){const l=await u(r.request,r._options,r._decorateResponse(o.clone()));l instanceof globalThis.Response&&(o=l)}if(r._decorateResponse(o),!o.ok&&r._options.throwHttpErrors){let u=new z(o,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(o.clone(),r._options.onDownloadProgress)}return o},c=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[o,u]of Object.entries(Ze))c[o]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||u);const h=(await c).clone();if(o==="json"){if(h.status===204||(await h.clone().arrayBuffer()).byteLength===0)return"";if(t.parseJson)return t.parseJson(await h.text())}return h[o]()};return c}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:W({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:st(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 z){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),N);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 c=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function o(){const{done:u,value:l}=await c.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 o()}await o()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}/*! MIT License © Sindre Sorhus */const D=s=>{const e=(t,r)=>O.create(t,I(s,r));for(const t of he)e[t]=(r,n)=>O.create(r,I(s,n,{method:t}));return e.create=t=>D(I(t)),e.extend=t=>D(I(s,t)),e.stop=de,e},ut=D(),lt=ut,ht=typeof window<"u"?{}:{referrer:"https://sk.thorswap.net",referer:"https://sk.thorswap.net"},Q=lt.create({headers:ht}),pe={get:(s,e)=>Q.get(s,e).json(),post:(s,e)=>Q.post(s,e).json()},X=Object.values(i.Chain),dt=(s="")=>{const e=s.toUpperCase(),[t]=e.split(".");if(X.includes(t))return!0;const[r]=e.split("/");if(X.includes(r))return!0;throw new Error(`Invalid identifier: ${s}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},S=8,C=s=>10n**BigInt(s),T=s=>Math.log10(parseFloat(s.toString()));function R({value:s,bigIntDecimal:e=S,decimal:t=S}){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 c=n.length-t;let o=n.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${r?"-":""}${n.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var y,v,V,fe,q,ge,$,H;const K=class K{constructor(e){A(this,y);A(this,V);A(this,q);A(this,$);m(this,"decimalMultiplier",10n**8n);m(this,"bigIntValue",0n);m(this,"decimal");const t=j(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=C(Math.max(Z(B(t)),this.decimal||0)),p(this,V,fe).call(this,t)}static fromBigInt(e,t){return new K({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:r}){return this.fromBigInt(e.getBaseValue("bigint")*C(r)/C(t),r)}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return p(this,y,v).call(this,"add",...e)}sub(...e){return p(this,y,v).call(this,"sub",...e)}mul(...e){return p(this,y,v).call(this,"mul",...e)}div(...e){return p(this,y,v).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/C(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=j(e),n=B(r);return n==="0"||n==="undefined"?0n:p(this,$,H).call(this,n,t)}formatBigIntToSafeValue(e,t){const r=t||this.decimal||S,n=Math.max(r,T(this.decimalMultiplier)),a=e<0n,c=e.toString().substring(a?1:0),o=n-(c.length-1),u=o>0?"0".repeat(o)+c:c,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||"";if((parseInt(n)?n.length+a.length:a.length)<=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(e-n.length,"0");const o=parseInt(a),u=`${o}`.slice(0,e);return`0.${u.padStart(a.length-`${o}`.length+u.length,"0")}`}toFixed(e=6){const[t,r]=this.getValue("string").split("."),n=t||"",a=r||"";if(parseInt(n))return`${n}.${a.slice(0,e)}`.padEnd(e,"0");const c=parseInt(a),o=`${c}`.slice(0,e);return`0.${o.padStart(a.length-`${c}`.length+o.length,"0")}`}toAbbreviation(e=2){const t=this.getValue("number"),r=["","K","M","B","T","Q","Qi","S"],n=Math.floor(Math.log10(Math.abs(t))/3),a=r[n];if(!a)return this.getValue("string");const c=10**(n*3);return`${(t/c).toFixed(e)}${a}`}toCurrency(e="$",{currencyPosition:t="start",decimal:r=2,decimalSeparator:n=".",thousandSeparator:a=","}={}){const c=this.getValue("number"),[o,u=""]=c.toFixed(6).split("."),l=o.replace(/\B(?=(\d{3})+(?!\d))/g,a),h=!o&&!u?"0.00":o==="0"?`${parseFloat(`0.${u}`)}`.replace(".",n):`${l}${parseInt(u)?`${n}${u.slice(0,r)}`:""}`;return`${t==="start"?e:""}${h}${t==="end"?e:""}`}};y=new WeakSet,v=function(e,...t){const r=p(this,q,ge).call(this,this,...t),n=C(r),a=t.reduce((o,u)=>{const l=this.getBigIntValue(u,r);switch(e){case"add":return o+l;case"sub":return o-l;case"mul":return o*l/n;case"div":{if(l===0n)throw new RangeError("Division by zero");return o*n/l}default:return o}},this.bigIntValue*n/this.decimalMultiplier),c=R({bigIntDecimal:r,decimal:Math.max(r,T(this.decimalMultiplier)),value:a});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},V=new WeakSet,fe=function(e){const t=B(e)||"0";this.bigIntValue=p(this,$,H).call(this,t)},q=new WeakSet,ge=function(...e){const t=e.map(r=>typeof r=="object"?r.decimal||T(r.decimalMultiplier):Z(B(r))).filter(Boolean);return Math.max(...t,S)},$=new WeakSet,H=function(e,t){const r=t?C(t):this.decimalMultiplier,n=T(r),[a="",c=""]=e.split(".");return BigInt(`${a}${c.padEnd(n,"0")}`)};let w=K;const mt=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});function B(s){const t=`${typeof s=="number"?mt.format(s):j(s)}`.replaceAll(",",".").split(".");return t.length>1?`${t.slice(0,-1).join("")}.${t.at(-1)}`:t[0]}function Z(s){var t;const e=((t=s.split(".")[1])==null?void 0:t.length)||0;return Math.max(e,S)}function j(s){return typeof s=="object"?"getValue"in s?s.getValue("string"):s.value:s}const M=(s,e)=>typeof s=="bigint"?R({value:s,bigIntDecimal:e,decimal:e}):s;let L;const ee=s=>{if(!L)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return L.get(s.toUpperCase())||{decimal:i.BaseDecimal.THOR,identifier:""}},te=async(s,e=0)=>{dt(s);const t=await re(F(s)),r=M(e,t);return new _({decimal:t,value:r,identifier:s})};class _ extends w{constructor(t){const r="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`;super(t.value instanceof w?t.value:{decimal:t.decimal,value:t.value});m(this,"address");m(this,"isSynthetic",!1);m(this,"isGasAsset",!1);m(this,"chain");m(this,"symbol");m(this,"ticker");m(this,"type");const n=F(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}toString(t=!1){const r=this.isSynthetic?this.symbol.split("-")[0]: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{isSynthetic:n}=F(t),{decimal:a,identifier:c}=ee(t),o=M(r,a);return c?new _({decimal:a,identifier:c,value:o}):n?new _({decimal:8,identifier:t,value:o}):void 0}static async fromIdentifier(t,r=0){return te(t,r)}static fromIdentifierSync(t,r=0){const{decimal:n,identifier:a}=ee(t),c=M(r,n);return new _({decimal:n,identifier:a,value:c})}static fromChainOrSignature(t,r=0){const{decimal:n,identifier:a}=ne(t),c=M(r,n);return new _({value:c,decimal:n,identifier:a})}static async loadStaticAssets(){return new Promise(async(t,r)=>{try{const{ThorchainList:n,NativeList:a,...c}=await import("@swapkit/tokens");L=[a,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:h,chain:g,...b})=>{const P="decimals"in b?b.decimals:i.BaseDecimal[g];u.set(h,{identifier:h,decimal:P})}),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 pt=s=>{const e=_.fromChainOrSignature(s);switch(s){case i.Chain.Bitcoin:case i.Chain.Litecoin:case i.Chain.BitcoinCash:return e.set(10001e-8);case i.Chain.Dogecoin:return e.set(1.00000001);case i.Chain.Avalanche:case i.Chain.Ethereum:return e.set(1e-8);case i.Chain.THORChain:case i.Chain.Maya:return e.set(0);default:return e.set(1e-8)}},F=s=>{const e=s.slice(0,14).includes("/"),[t,r]=s.split(".").pop().split("/"),n=s.includes(".")&&!e?s:`${i.Chain.THORChain}.${r}`,[a,c]=n.split("."),[o,u]=(e?r:c).split("-");return{address:u==null?void 0:u.toLowerCase(),chain:a,isGasAsset:U({chain:a,symbol:c}),isSynthetic:e,symbol:(e?`${t}/`:"")+(u?`${o}-${(u==null?void 0:u.toLowerCase())??""}`:c),ticker:o}},ft={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 G extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ft[e],message:e}}),Object.setPrototypeOf(this,G.prototype)}}class f extends w{eq(e){return this.eqValue(e)}static fromBigInt(e,t){return new f({decimal:t,value:R({value:e,bigIntDecimal:t,decimal:t})})}}exports.AssetValue=_;exports.BigIntArithmetics=w;exports.RequestClient=pe;exports.SwapKitError=G;exports.SwapKitNumber=f;exports.assetFromString=Pe;exports.derivationPathToString=Ye;exports.filterAssets=Ne;exports.formatBigIntToSafeValue=R;exports.gasFeeMultiplier=qe;exports.getAssetType=ie;exports.getAsymmetricAssetShare=oe;exports.getAsymmetricAssetWithdrawAmount=He;exports.getAsymmetricRuneShare=ae;exports.getAsymmetricRuneWithdrawAmount=De;exports.getCommonAssetInfo=ne;exports.getDecimal=re;exports.getEstimatedPoolShare=Le;exports.getLiquiditySlippage=Fe;exports.getMemoFor=We;exports.getMinAmountByChain=pt;exports.getSymmetricPoolShare=ce;exports.getSymmetricWithdraw=je;exports.getTHORNameCost=Ge;exports.isGasAsset=U;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';
|
|
@@ -21,27 +22,24 @@ export declare const assetFromString: (assetString: string) => {
|
|
|
21
22
|
};
|
|
22
23
|
|
|
23
24
|
export declare class AssetValue extends BigIntArithmetics {
|
|
25
|
+
constructor(params: AssetValueParams);
|
|
24
26
|
address?: string;
|
|
25
|
-
chain: Chain;
|
|
26
27
|
isSynthetic: boolean;
|
|
27
28
|
isGasAsset: boolean;
|
|
29
|
+
chain: Chain;
|
|
28
30
|
symbol: string;
|
|
29
31
|
ticker: string;
|
|
30
32
|
type: ReturnType<typeof getAssetType>;
|
|
31
|
-
|
|
32
|
-
get assetValue(): string;
|
|
33
|
-
toString(): string;
|
|
33
|
+
toString(short?: boolean): string;
|
|
34
34
|
eq({ chain, symbol }: {
|
|
35
35
|
chain: Chain;
|
|
36
36
|
symbol: string;
|
|
37
37
|
}): boolean;
|
|
38
|
-
static fromString(assetString: string, value?:
|
|
39
|
-
static fromStringSync(assetString: string, value?:
|
|
40
|
-
static fromIdentifier(assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`, value?:
|
|
41
|
-
static fromIdentifierSync(identifier: TokenNames, value?:
|
|
42
|
-
static fromChainOrSignature(assetString: CommonAssetString, value?:
|
|
43
|
-
static fromTCQuote(identifier: TCTokenNames, value?: number | string): Promise<AssetValue>;
|
|
44
|
-
static fromTCQuoteStatic(identifier: TCTokenNames, value?: number | string): AssetValue;
|
|
38
|
+
static fromString(assetString: string, value?: NumberPrimitives): Promise<AssetValue>;
|
|
39
|
+
static fromStringSync(assetString: string, value?: NumberPrimitives): AssetValue | undefined;
|
|
40
|
+
static fromIdentifier(assetString: `${Chain}.${string}` | `${Chain}/${string}` | `${Chain}.${string}-${string}`, value?: NumberPrimitives): Promise<AssetValue>;
|
|
41
|
+
static fromIdentifierSync(identifier: TokenNames, value?: NumberPrimitives): AssetValue;
|
|
42
|
+
static fromChainOrSignature(assetString: CommonAssetString, value?: NumberPrimitives): AssetValue;
|
|
45
43
|
static loadStaticAssets(): Promise<{
|
|
46
44
|
ok: true;
|
|
47
45
|
} | {
|
|
@@ -68,15 +66,12 @@ export declare class BigIntArithmetics {
|
|
|
68
66
|
decimal?: number;
|
|
69
67
|
static fromBigInt(value: bigint, decimal?: number): BigIntArithmetics;
|
|
70
68
|
static shiftDecimals({ value, from, to, }: {
|
|
71
|
-
value:
|
|
69
|
+
value: InstanceType<typeof SwapKitNumber>;
|
|
72
70
|
from: number;
|
|
73
71
|
to: number;
|
|
74
72
|
}): BigIntArithmetics;
|
|
75
73
|
constructor(params: SKBigIntParams);
|
|
76
|
-
|
|
77
|
-
get baseValueNumber(): number;
|
|
78
|
-
get baseValueBigInt(): bigint;
|
|
79
|
-
set(value: SKBigIntParams): any;
|
|
74
|
+
set(value: SKBigIntParams): this;
|
|
80
75
|
add(...args: InitialisationValueType[]): this;
|
|
81
76
|
sub(...args: InitialisationValueType[]): this;
|
|
82
77
|
mul(...args: InitialisationValueType[]): this;
|
|
@@ -86,11 +81,19 @@ export declare class BigIntArithmetics {
|
|
|
86
81
|
lt(value: InitialisationValueType): boolean;
|
|
87
82
|
lte(value: InitialisationValueType): boolean;
|
|
88
83
|
eqValue(value: InitialisationValueType): boolean;
|
|
89
|
-
getValue<T extends 'number' | 'string'
|
|
84
|
+
getValue<T extends 'number' | 'string'>(type: T): NumberPrimitivesType[T];
|
|
90
85
|
getBaseValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T];
|
|
91
86
|
getBigIntValue(value: InitialisationValueType, decimal?: number): bigint;
|
|
92
87
|
formatBigIntToSafeValue(value: bigint, decimal?: number): string;
|
|
93
88
|
toSignificant(significantDigits?: number): string;
|
|
89
|
+
toFixed(fixedDigits?: number): string;
|
|
90
|
+
toAbbreviation(digits?: number): string;
|
|
91
|
+
toCurrency(currency?: string, { currencyPosition, decimal, decimalSeparator, thousandSeparator, }?: {
|
|
92
|
+
currencyPosition?: string | undefined;
|
|
93
|
+
decimal?: number | undefined;
|
|
94
|
+
decimalSeparator?: string | undefined;
|
|
95
|
+
thousandSeparator?: string | undefined;
|
|
96
|
+
}): string;
|
|
94
97
|
}
|
|
95
98
|
|
|
96
99
|
export declare type CommonAssetString = 'MAYA.MAYA' | 'ETH.THOR' | 'ETH.vTHOR' | Chain;
|
|
@@ -155,6 +158,18 @@ declare const errorMessages: {
|
|
|
155
158
|
readonly helpers_number_different_decimals: 99101;
|
|
156
159
|
};
|
|
157
160
|
|
|
161
|
+
export declare const filterAssets: (tokens: {
|
|
162
|
+
value: string;
|
|
163
|
+
decimal: number;
|
|
164
|
+
chain: Chain;
|
|
165
|
+
symbol: string;
|
|
166
|
+
}[]) => {
|
|
167
|
+
value: string;
|
|
168
|
+
decimal: number;
|
|
169
|
+
chain: Chain;
|
|
170
|
+
symbol: string;
|
|
171
|
+
}[];
|
|
172
|
+
|
|
158
173
|
export declare function formatBigIntToSafeValue({ value, bigIntDecimal, decimal, }: {
|
|
159
174
|
value: bigint;
|
|
160
175
|
bigIntDecimal?: number;
|
|
@@ -166,7 +181,7 @@ export declare const gasFeeMultiplier: Record<FeeOption, number>;
|
|
|
166
181
|
export declare const getAssetType: ({ chain, symbol }: {
|
|
167
182
|
chain: Chain;
|
|
168
183
|
symbol: string;
|
|
169
|
-
}) =>
|
|
184
|
+
}) => Chain.Avalanche | Chain.Cosmos | Chain.Kujira | "Synth" | "Native" | "BEP2" | "BEP20" | "ERC20" | "POLYGON" | "ARBITRUM" | "OPTIMISM";
|
|
170
185
|
|
|
171
186
|
export declare const getAsymmetricAssetShare: ({ liquidityUnits, poolUnits, assetDepth, }: ShareParams<{
|
|
172
187
|
assetDepth: string;
|
|
@@ -220,10 +235,6 @@ export declare const getMemoFor: <T extends MemoType>(memoType: T, options: Memo
|
|
|
220
235
|
|
|
221
236
|
export declare const getMinAmountByChain: (chain: Chain) => AssetValue;
|
|
222
237
|
|
|
223
|
-
export declare const getRequest: <T>(url: string, params?: {
|
|
224
|
-
[x: string]: any;
|
|
225
|
-
} | undefined) => Promise<T>;
|
|
226
|
-
|
|
227
238
|
export declare const getSymmetricPoolShare: ({ liquidityUnits, poolUnits, runeDepth, assetDepth, }: ShareParams<{
|
|
228
239
|
runeDepth: string;
|
|
229
240
|
assetDepth: string;
|
|
@@ -280,7 +291,7 @@ export declare type MemoOptions<T extends MemoType> = {
|
|
|
280
291
|
[MemoType.THORNAME_REGISTER]: Omit<ThornameRegisterParam, 'preferredAsset' | 'expiryBlock'>;
|
|
281
292
|
}[T];
|
|
282
293
|
|
|
283
|
-
declare type NumberPrimitives = bigint | number | string;
|
|
294
|
+
export declare type NumberPrimitives = bigint | number | string;
|
|
284
295
|
|
|
285
296
|
declare type NumberPrimitivesType = {
|
|
286
297
|
bigint: bigint;
|
|
@@ -295,7 +306,10 @@ declare type PoolParams<T = {}> = T & {
|
|
|
295
306
|
assetDepth: string;
|
|
296
307
|
};
|
|
297
308
|
|
|
298
|
-
export declare const
|
|
309
|
+
export declare const RequestClient: {
|
|
310
|
+
get: <T>(url: string | URL | Request, options?: Options) => Promise<T>;
|
|
311
|
+
post: <T_1>(url: string | URL | Request, options?: Options) => Promise<T_1>;
|
|
312
|
+
};
|
|
299
313
|
|
|
300
314
|
declare type ShareParams<T = {}> = T & {
|
|
301
315
|
liquidityUnits: string;
|
|
@@ -313,6 +327,7 @@ export declare class SwapKitError extends Error {
|
|
|
313
327
|
|
|
314
328
|
export declare class SwapKitNumber extends BigIntArithmetics {
|
|
315
329
|
eq(value: SwapKitValueType): boolean;
|
|
330
|
+
static fromBigInt(value: bigint, decimal?: number): SwapKitNumber;
|
|
316
331
|
}
|
|
317
332
|
|
|
318
333
|
export declare type SwapKitValueType = BigIntArithmetics | string | number;
|