@swapkit/helpers
Advanced tools
Comparing version 0.0.0-nightly-20240404172439 to 0.0.0-nightly-20240404190857
@@ -1,3 +0,958 @@ | ||
var h=(($)=>typeof require!=="undefined"?require:typeof Proxy!=="undefined"?new Proxy($,{get:(_,O)=>(typeof require!=="undefined"?require:_)[O]}):$)(function($){if(typeof require!=="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+$+'" is not supported')});export*from"@swapkit/api";import{RequestClient as i} from"@swapkit/api";import{BaseDecimal as G,Chain as Z,ChainToRPC as e,EVMChains as $0,FeeOption as C} from"@swapkit/types";async function B0($){const _=await import("@swapkit/tokens");for(let O of Object.values(_))for(let{identifier:W,chain:z,...J}of O.tokens){if("identifier"in $&&W===$.identifier)return W;if("address"in J&&"chain"in $&&z===$.chain&&J.address.toLowerCase()===$.contract.toLowerCase())return W}return}var _0="0x313ce567",g=async({chain:$,to:_})=>{try{const{result:O}=await i.post(e[$],{headers:{accept:"*/*","content-type":"application/json","cache-control":"no-cache"},body:JSON.stringify({id:44,jsonrpc:"2.0",method:"eth_call",params:[{to:_.toLowerCase(),data:_0},"latest"]})});return Number.parseInt(BigInt(O||G[$]).toString())}catch(O){return console.error(O),G[$]}},O0=($)=>{if($===Z.Ethereum)return G.ETH;const[,_]=$.split("-");return _?.startsWith("0x")?g({chain:Z.Ethereum,to:_}):G.ETH},W0=($)=>{const[,_]=$.split("-");return _?.startsWith("0x")?g({chain:Z.Avalanche,to:_.toLowerCase()}):G.AVAX},z0=($)=>{if($===Z.BinanceSmartChain)return G.BSC;return G.BSC},p=({chain:$,symbol:_})=>{switch($){case Z.Ethereum:return O0(_);case Z.Avalanche:return W0(_);case Z.BinanceSmartChain:return z0(_);default:return G[$]}},E0={[C.Average]:1.2,[C.Fast]:1.5,[C.Fastest]:2},A=({chain:$,symbol:_})=>{switch($){case Z.Arbitrum:case Z.Optimism:return _==="ETH";case Z.Maya:return _==="CACAO";case Z.Kujira:return _==="KUJI";case Z.Cosmos:return _==="ATOM";case Z.Polygon:return _==="MATIC";case Z.BinanceSmartChain:return _==="BNB";case Z.THORChain:return _==="RUNE";default:return _===$}},d=($)=>{switch($){case`${Z.Ethereum}.THOR`:return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case`${Z.Ethereum}.vTHOR`:return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case Z.Cosmos:return{identifier:"GAIA.ATOM",decimal:G[$]};case Z.THORChain:return{identifier:"THOR.RUNE",decimal:G[$]};case Z.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:G[$]};case Z.Maya:return{identifier:"MAYA.CACAO",decimal:G.MAYA};case`${Z.Maya}.MAYA`:return{identifier:"MAYA.MAYA",decimal:4};case`${Z.Kujira}.USK`:return{identifier:`${Z.Kujira}.USK`,decimal:6};default:return{identifier:`${$}.${$}`,decimal:G[$]}}},u=({chain:$,symbol:_})=>{if(_.includes("/"))return"Synth";switch($){case Z.Cosmos:return _==="ATOM"?"Native":Z.Cosmos;case Z.Kujira:return _===Z.Kujira?"Native":Z.Kujira;case Z.Binance:return _===Z.Binance?"Native":"BEP2";case Z.BinanceSmartChain:return _===Z.Binance?"Native":"BEP20";case Z.Ethereum:return _===Z.Ethereum?"Native":"ERC20";case Z.Avalanche:return _===Z.Avalanche?"Native":Z.Avalanche;case Z.Polygon:return _===Z.Polygon?"Native":"POLYGON";case Z.Arbitrum:return[Z.Ethereum,Z.Arbitrum].includes(_)?"Native":"ARBITRUM";case Z.Optimism:return[Z.Ethereum,Z.Optimism].includes(_)?"Native":"OPTIMISM";default:return"Native"}},N0=($)=>{const[_,...O]=$.split("."),W=$.includes("/"),z=O.join("."),J=z?.split("-")?.[0];return{chain:_,symbol:z,ticker:J,synth:W}},J0=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),Q0=($)=>{const[_,O]=$.split(".");if(!$0.includes(_))return!0;const[,W]=O.split("-");return A({chain:_,symbol:O})||!!W},K0=($)=>$.filter(({chain:_,value:O,symbol:W})=>{const z=`${_}.${W}`;return!J0.test(z)&&Q0(z)&&O!=="0"});import{BaseDecimal as Y0} from"@swapkit/types";function Z0({liquidityUnits:$,poolUnits:_,runeDepth:O}){const W=R($),z=R(_),J=R(O),Q=W.mul(J),Y=z.mul(z).mul(2),X=z.mul(W).mul(2),H=W.mul(W),q=z.mul(z).mul(z);return Q.mul(Y.sub(X).add(H)).div(q)}function H0({liquidityUnits:$,poolUnits:_,assetDepth:O}){const W=R($),z=R(_),J=R(O),Q=W.mul(J),Y=z.mul(z).mul(2),X=z.mul(W).mul(2),H=W.mul(W),q=Q.mul(Y.sub(X).add(H)),w=z.mul(z).mul(z);return q.div(w)}function U0({percent:$,runeDepth:_,liquidityUnits:O,poolUnits:W}){return Z0({runeDepth:_,liquidityUnits:O,poolUnits:W}).mul($)}function I0({percent:$,assetDepth:_,liquidityUnits:O,poolUnits:W}){return H0({assetDepth:_,liquidityUnits:O,poolUnits:W}).mul($)}var R=function($){return P.fromBigInt(BigInt($),Y0.THOR)};function X0({liquidityUnits:$,poolUnits:_,runeDepth:O,assetDepth:W}){return{assetAmount:R(W).mul($).div(_),runeAmount:R(O).mul($).div(_)}}function V0({liquidityUnits:$,poolUnits:_,runeDepth:O,assetDepth:W,percent:z}){return Object.fromEntries(Object.entries(X0({liquidityUnits:$,poolUnits:_,runeDepth:O,assetDepth:W})).map(([J,Q])=>[J,Q.mul(z)]))}function T0({runeDepth:$,poolUnits:_,assetDepth:O,liquidityUnits:W,runeAmount:z,assetAmount:J}){const Q=new P({value:$,decimal:8}),Y=new P({value:O,decimal:8}),X=new P({value:_,decimal:8}),H=new P({value:z,decimal:8}),q=new P({value:J,decimal:8}),w=H.mul(Y),S=q.mul(Q),r=H.mul(q),n=Q.mul(Y),s=X.mul(w.add(S.add(r.mul(2)))),t=w.add(S.add(n.mul(2))),y=s.div(t),T=R(W).add(y);if(y.getBaseValue("number")===0)return T.div(X).getBaseValue("number");const a=X.add(T);return T.div(a).getBaseValue("number")}function C0({runeAmount:$,assetAmount:_,runeDepth:O,assetDepth:W}){if($==="0"||_==="0"||O==="0"||W==="0")return 0;const z=R(O),J=R(W),Q=R(_),Y=R($),X=Q.mul(z).sub(J.mul(Y)),H=J.mul(Y).add(z.mul(J));return Math.abs(X.div(H).getBaseValue("number"))}import{Chain as f,MemoType as x} from"@swapkit/types";var D0=($,_)=>{switch($){case x.LEAVE:case x.BOND:{const{address:O}=_;return`${$}:${O}`}case x.UNBOND:{const{address:O,unbondAmount:W}=_;return`${$}:${O}:${W}`}case x.THORNAME_REGISTER:{const{name:O,chain:W,address:z,owner:J}=_;return`${$}:${O}:${W}:${z}${J?`:${J}`:""}`}case x.DEPOSIT:{const{chain:O,symbol:W,address:z,singleSide:J}=_;return J?`${$}:${O}/${W}`:`${$}:${((Y,X)=>{switch(Y){case f.Litecoin:return"l";case f.Dogecoin:return"d";case f.BitcoinCash:return"c";default:return`${Y}.${X}`}})(O,W)}:${z||""}`}case x.WITHDRAW:{const{chain:O,ticker:W,symbol:z,basisPoints:J,targetAssetString:Q,singleSide:Y}=_,X=O==="ETH"&&W!=="ETH"?`${W}-${z.slice(-3)}`:z,H=!Y&&Q?`:${Q}`:"";return`${$}:${O}${Y?"/":"."}${X}:${J}${H}`}case x.OPEN_LOAN:case x.CLOSE_LOAN:{const{asset:O,address:W}=_;return`${$}:${O}:${W}`}default:return""}};function v0($){if($<0)throw new Error("Invalid number of year");return 10+$}function S0($){if($<0)throw new Error("Invalid number of year");return Math.round((10+$*1.0512)*10000000000)/10000000000}function y0($){if($.length>30)return!1;const _=/^[a-zA-Z0-9+_-]+$/g;return!!$.match(_)}function h0($){if($.length>30)return!1;const _=/^[a-zA-Z0-9+_-]+$/g;return!!$.match(_)}function g0([$,_,O,W,z]){return`m/${$}'/${_}'/${O}'/${W}${typeof z!=="number"?"":`/${z}`}`}import{BaseDecimal as K,Chain as j,ChainToChainId as P0} from"@swapkit/types";import{Chain as j0} from"@swapkit/types";function o($=""){const _=$.toUpperCase(),[O]=_.split(".");if(c.includes(O))return!0;const[W]=_.split("/");if(c.includes(W))return!0;throw new Error(`Invalid identifier: ${$}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)}var c=[...Object.values(j0),"TERRA"];import{BaseDecimal as G0} from"@swapkit/types";function N({value:$,bigIntDecimal:_=U,decimal:O=U}){if(O===0)return $.toString();const W=$<0n;let z=$.toString().substring(W?1:0);const J=O-(z.length-1);if(J>0)z="0".repeat(J)+z;const Q=z.length-O;let Y=z.slice(-O);if(Number.parseInt(Y[_]||"0")>=5)Y=`${Y.substring(0,_-1)}${(Number.parseInt(Y[_-1]||"0")+1).toString()}`;else Y=Y.substring(0,_);return`${W?"-":""}${z.slice(0,Q)}.${Y}`.replace(/\.?0*$/,"")}var V=function($){const O=`${typeof $==="number"?R0.format($):D($)}`.replaceAll(",",".").split(".");return O.length>1?`${O.slice(0,-1).join("")}.${O.at(-1)}`:O[0]||"0"},m=function($){const _=$.split(".")[1]?.length||0;return Math.max(_,U)},D=function($){return typeof $==="object"?"getValue"in $?$.getValue("string"):$.value:$},U=8,E=($)=>10n**BigInt($),k=($)=>Math.log10(Number.parseFloat($.toString()));class F{decimalMultiplier=10n**8n;bigIntValue=0n;decimal;static fromBigInt($,_){return new F({decimal:_,value:N({value:$,bigIntDecimal:_,decimal:_})})}static shiftDecimals({value:$,from:_,to:O}){return F.fromBigInt($.getBaseValue("bigint")*E(O)/E(_),O)}constructor($){const _=D($),O=typeof $==="object";this.decimal=O?$.decimal:void 0,this.decimalMultiplier=O&&"decimalMultiplier"in $?$.decimalMultiplier:E(Math.max(m(V(_)),this.decimal||0)),this.#z(_)}set($){return new this.constructor({decimal:this.decimal,value:$,identifier:this.toString()})}add(...$){return this.#_("add",...$)}sub(...$){return this.#_("sub",...$)}mul(...$){return this.#_("mul",...$)}div(...$){return this.#_("div",...$)}gt($){return this.#$("gt",$)}gte($){return this.#$("gte",$)}lt($){return this.#$("lt",$)}lte($){return this.#$("lte",$)}eqValue($){return this.#$("eqValue",$)}getValue($){const _=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||k(this.decimalMultiplier));switch($){case"number":return Number(_);case"string":return _;case"bigint":return this.bigIntValue*10n**BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue($){const _=this.decimalMultiplier/E(this.decimal||G0.THOR),O=this.bigIntValue/_;switch($){case"number":return Number(O);case"string":return O.toString();case"bigint":return O}}getBigIntValue($,_){if(!_&&typeof $==="object")return $.bigIntValue;const O=D($),W=V(O);if(W==="0"||W==="undefined")return 0n;return this.#W(W,_)}toSignificant($=6){const[_,O]=this.getValue("string").split("."),W=_||"",z=O||"";if((Number.parseInt(W)?W.length+z.length:z.length)<=$)return this.getValue("string");if(W.length>=$)return W.slice(0,$).padEnd(W.length,"0");if(Number.parseInt(W))return`${W}.${z.slice(0,$-W.length)}`.padEnd($-W.length,"0");const Q=Number.parseInt(z),Y=`${Q}`.slice(0,$);return`0.${Y.padStart(z.length-`${Q}`.length+Y.length,"0")}`}toFixed($=6){const[_,O]=this.getValue("string").split("."),W=_||"",z=O||"";if(Number.parseInt(W))return`${W}.${z.slice(0,$)}`.padEnd($,"0");const J=Number.parseInt(z),Q=`${J}`.slice(0,$);return`0.${Q.padStart(z.length-`${J}`.length+Q.length,"0")}`}toAbbreviation($=2){const _=this.getValue("number"),O=["","K","M","B","T","Q","Qi","S"],W=Math.floor(Math.log10(Math.abs(_))/3),z=O[W];if(!z)return this.getValue("string");const J=10**(W*3);return`${(_/J).toFixed($)}${z}`}toCurrency($="$",{currencyPosition:_="start",decimal:O=2,decimalSeparator:W=".",thousandSeparator:z=","}={}){const J=this.getValue("number"),[Q="",Y=""]=J.toFixed(6).split("."),X=Q.replace(/\B(?=(\d{3})+(?!\d))/g,z),H=Q||Y?Q==="0"?`${Number.parseFloat(`0.${Y}`)}`.replace(".",W):`${X}${Number.parseInt(Y)?`${W}${Y.slice(0,O)}`:""}`:"0.00";return`${_==="start"?$:""}${H}${_==="end"?$:""}`}formatBigIntToSafeValue($,_){const O=_||this.decimal||U,W=Math.max(O,k(this.decimalMultiplier)),z=$<0n,J=$.toString().substring(z?1:0),Q=W-(J.length-1),Y=Q>0?"0".repeat(Q)+J:J,X=Y.length-W;let H=Y.slice(-W);if(Number.parseInt(H[O]||"0")>=5)H=`${H.substring(0,O-1)}${(Number.parseInt(H[O-1]||"0")+1).toString()}`;else H=H.substring(0,O);return`${z?"-":""}${Y.slice(0,X)}.${H}`.replace(/\.?0*$/,"")}#_($,..._){const O=this.#O(this,..._),W=Math.max(O,k(this.decimalMultiplier)),z=E(W),J=_.reduce((Y,X)=>{const H=this.getBigIntValue(X,W);switch($){case"add":return Y+H;case"sub":return Y-H;case"mul":return Y*H/z;case"div":{if(H===0n)throw new RangeError("Division by zero");return Y*z/H}default:return Y}},this.bigIntValue*z/this.decimalMultiplier),Q=N({bigIntDecimal:W,decimal:W,value:J});return new this.constructor({decimalMultiplier:E(W),decimal:this.decimal,value:Q,identifier:this.toString()})}#$($,..._){const O=this.#O(this,..._),W=this.getBigIntValue(_[0]||"0",O),z=this.getBigIntValue(this,O);switch($){case"gt":return z>W;case"gte":return z>=W;case"lt":return z<W;case"lte":return z<=W;case"eqValue":return z===W}}#z($){const _=V($)||"0";this.bigIntValue=this.#W(_)}#O(...$){const _=$.map((O)=>{return typeof O==="object"?O.decimal||k(O.decimalMultiplier):m(V(O))}).filter(Boolean);return Math.max(..._,U)}#W($,_){const O=_?E(_):this.decimalMultiplier,W=k(O),[z="",J=""]=$.split(".");return BigInt(`${z}${J.padEnd(W,"0")}`)}}var R0=Intl.NumberFormat("fullwide",{useGrouping:!1,maximumFractionDigits:20});class P extends F{constructor(){super(...arguments)}eq($){return this.eqValue($)}static fromBigInt($,_){return new P({decimal:_,value:N({value:$,bigIntDecimal:_,decimal:_})})}}function i0($){const _=L.fromChainOrSignature($);switch($){case j.Bitcoin:case j.Litecoin:case j.BitcoinCash:return _.set(0.00010001);case j.Dogecoin:return _.set(1.00000001);case j.Avalanche:case j.Ethereum:return _.set(0.00000001);case j.THORChain:case j.Maya:return _.set(0);case j.Cosmos:return _.set(0.000001);default:return _.set(0.00000001)}}async function b($,_=0){o($);const O=B.get($.toUpperCase()),W=O?.decimal||await p(I($));if(!O)B.set($.toUpperCase(),{identifier:$,decimal:W});return new L({decimal:W,value:M(_,W),identifier:$})}var v=function($,_=0){const[O,W]=$.split(".")?.[0]?.toUpperCase()===j.THORChain?$.split(".").slice(1).join().split("/"):$.split("/");if(!(O&&W))throw new Error("Invalid asset identifier");return new L({decimal:8,value:M(_,8),identifier:`${j.THORChain}.${O}/${W}`})},M=function($,_){return typeof $==="bigint"?N({value:$,bigIntDecimal:_,decimal:_}):$},I=function($){const _=$.slice(0,14).includes("/"),[O,W=""]=$.split(".")?.[0]?.toUpperCase()===j.THORChain?$.split(".").slice(1).join().split("/"):$.split("/");if(_&&!(O&&W))throw new Error("Invalid asset identifier");const z=$.includes(".")&&!_?$:`${j.THORChain}.${W}`,[J,...Q]=z.split("."),[Y,X]=(_?W:Q.join(".")).split("-"),H=_?W:Q.join(".");return{address:X?.toLowerCase(),chain:J,isGasAsset:A({chain:J,symbol:H}),isSynthetic:_,symbol:(_?`${O}/`:"")+(X?`${Y}-${X?.toLowerCase()??""}`:H),ticker:Y}},B=new Map;class L extends F{address;chain;isGasAsset=!1;isSynthetic=!1;symbol;tax;ticker;type;constructor({value:$,decimal:_,tax:O,chain:W,symbol:z,identifier:J}){super(typeof $==="object"?$:{decimal:_,value:$});const Q=I(J||`${W}.${z}`);this.type=u(Q),this.tax=O,this.chain=Q.chain,this.ticker=Q.ticker,this.symbol=Q.symbol,this.address=Q.address,this.isSynthetic=Q.isSynthetic,this.isGasAsset=Q.isGasAsset}toString(){return this.isSynthetic?this.symbol:`${this.chain}.${this.symbol}`}toUrl(){return this.isSynthetic?`${this.chain}.${this.symbol.replace("/",".")}`:this.toString()}eq({chain:$,symbol:_}){return this.chain===$&&this.symbol===_}chainId(){return P0[this.chain]}static fromUrl($,_=0){const[O,W,z]=$.split(".");if(!(O&&W))throw new Error("Invalid asset url");const J=O===j.THORChain&&z?`${O}.${W}/${z}`:$;return b(J,_)}static fromString($,_=0){return b($,_)}static fromIdentifier($,_=0){return b($,_)}static fromStringSync($,_=0){const{chain:O,isSynthetic:W}=I($),z=B.get($.toUpperCase());if(W)return v($,_);const{tax:J,decimal:Q,identifier:Y}=z||{decimal:K[O],identifier:$};return new L({tax:J,value:M(_,Q),identifier:W?$:Y,decimal:W?8:Q})}static async fromStringWithBase($,_=0,O=K.THOR){const W=F.shiftDecimals({value:P.fromBigInt(BigInt(_)),from:0,to:O}).getBaseValue("string");return(await L.fromString($,_)).set(W)}static fromStringWithBaseSync($,_=0,O=K.THOR){const{chain:W,isSynthetic:z}=I($),J=B.get($.toUpperCase());if(z)return v($,_);const{tax:Q,decimal:Y,identifier:X}=J||{decimal:K[W],identifier:$};return new L({tax:Q,value:M(BigInt(_),O),identifier:X,decimal:Y})}static fromIdentifierSync($,_=0){const{chain:O,isSynthetic:W}=I($),z=B.get($);if(W)return v($,_);const{tax:J,decimal:Q,identifier:Y}=z||{decimal:K[O],identifier:$};return new L({tax:J,decimal:Q,identifier:Y,value:M(_,Q)})}static fromChainOrSignature($,_=0){const{decimal:O,identifier:W}=d($);return new L({value:M(_,O),decimal:O,identifier:W})}static loadStaticAssets(){return new Promise(($,_)=>{try{import("@swapkit/tokens").then((O)=>{for(let W of Object.values(O))for(let{identifier:z,chain:J,...Q}of W.tokens)B.set(z.toUpperCase(),{identifier:z,decimal:"decimals"in Q?Q.decimals:K[J]});$({ok:!0})})}catch(O){console.error(O),_({ok:!1,error:O,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}var L0={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_plugin_not_found:10006,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_wallet_keepkey_not_installed:10109,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_invalid_sender_address:10313,core_transaction_deposit_server_error:10314,core_transaction_user_rejected:10315,wallet_ledger_connection_error:20001,wallet_ledger_connection_claimed:20002,wallet_ledger_get_address_error:20003,wallet_ledger_device_not_found:20004,wallet_ledger_device_locked:20005,chainflip_channel_error:30001,chainflip_broker_recipient_error:30002,helpers_number_different_decimals:99101};class l extends Error{constructor($,_){if(_)console.error(_,{stack:_?.stack,message:_?.message});super($,{cause:{code:L0[$],message:$}});Object.setPrototypeOf(this,l.prototype)}}export{y0 as validateTHORName,h0 as validateMAYAName,A as isGasAsset,v0 as getTHORNameCost,V0 as getSymmetricWithdraw,X0 as getSymmetricPoolShare,i0 as getMinAmountByChain,D0 as getMemoFor,S0 as getMAYANameCost,C0 as getLiquiditySlippage,T0 as getEstimatedPoolShare,p as getDecimal,d as getCommonAssetInfo,U0 as getAsymmetricRuneWithdrawAmount,Z0 as getAsymmetricRuneShare,I0 as getAsymmetricAssetWithdrawAmount,H0 as getAsymmetricAssetShare,u as getAssetType,E0 as gasFeeMultiplier,N as formatBigIntToSafeValue,B0 as findAssetBy,K0 as filterAssets,g0 as derivationPathToString,N0 as assetFromString,P as SwapKitNumber,l as SwapKitError,F as BigIntArithmetics,L as AssetValue}; | ||
var __require = ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { | ||
get: (a, b) => (typeof require !== "undefined" ? require : a)[b] | ||
}) : x)(function(x) { | ||
if (typeof require !== "undefined") | ||
return require.apply(this, arguments); | ||
throw Error('Dynamic require of "' + x + '" is not supported'); | ||
}); | ||
//# debugId=913910B4F1C6E4AF64756e2164756e21 | ||
// src/index.ts | ||
export * from "@swapkit/api"; | ||
// src/helpers/asset.ts | ||
import {RequestClient} from "@swapkit/api"; | ||
import {BaseDecimal, Chain, ChainToRPC, EVMChains, FeeOption} from "@swapkit/types"; | ||
async function findAssetBy(params) { | ||
const tokenPackages = await import("@swapkit/tokens"); | ||
for (const tokenList of Object.values(tokenPackages)) { | ||
for (const { identifier, chain: tokenChain, ...rest } of tokenList.tokens) { | ||
if ("identifier" in params && identifier === params.identifier) { | ||
return identifier; | ||
} | ||
if ("address" in rest && "chain" in params && tokenChain === params.chain && rest.address.toLowerCase() === params.contract.toLowerCase()) | ||
return identifier; | ||
} | ||
} | ||
return; | ||
} | ||
var getDecimalMethodHex = "0x313ce567"; | ||
var getContractDecimals = async ({ chain, to }) => { | ||
try { | ||
const { result } = await RequestClient.post(ChainToRPC[chain], { | ||
headers: { | ||
accept: "*/*", | ||
"content-type": "application/json", | ||
"cache-control": "no-cache" | ||
}, | ||
body: JSON.stringify({ | ||
id: 44, | ||
jsonrpc: "2.0", | ||
method: "eth_call", | ||
params: [{ to: to.toLowerCase(), data: getDecimalMethodHex }, "latest"] | ||
}) | ||
}); | ||
return Number.parseInt(BigInt(result || BaseDecimal[chain]).toString()); | ||
} catch (error) { | ||
console.error(error); | ||
return BaseDecimal[chain]; | ||
} | ||
}; | ||
var getETHAssetDecimal = (symbol) => { | ||
if (symbol === Chain.Ethereum) | ||
return BaseDecimal.ETH; | ||
const [, address] = symbol.split("-"); | ||
return address?.startsWith("0x") ? getContractDecimals({ chain: Chain.Ethereum, to: address }) : BaseDecimal.ETH; | ||
}; | ||
var getAVAXAssetDecimal = (symbol) => { | ||
const [, address] = symbol.split("-"); | ||
return address?.startsWith("0x") ? getContractDecimals({ chain: Chain.Avalanche, to: address.toLowerCase() }) : BaseDecimal.AVAX; | ||
}; | ||
var getBSCAssetDecimal = (symbol) => { | ||
if (symbol === Chain.BinanceSmartChain) | ||
return BaseDecimal.BSC; | ||
return BaseDecimal.BSC; | ||
}; | ||
var getDecimal = ({ chain, symbol }) => { | ||
switch (chain) { | ||
case Chain.Ethereum: | ||
return getETHAssetDecimal(symbol); | ||
case Chain.Avalanche: | ||
return getAVAXAssetDecimal(symbol); | ||
case Chain.BinanceSmartChain: | ||
return getBSCAssetDecimal(symbol); | ||
default: | ||
return BaseDecimal[chain]; | ||
} | ||
}; | ||
var gasFeeMultiplier = { | ||
[FeeOption.Average]: 1.2, | ||
[FeeOption.Fast]: 1.5, | ||
[FeeOption.Fastest]: 2 | ||
}; | ||
var isGasAsset = ({ chain, symbol }) => { | ||
switch (chain) { | ||
case Chain.Arbitrum: | ||
case Chain.Optimism: | ||
return symbol === "ETH"; | ||
case Chain.Maya: | ||
return symbol === "CACAO"; | ||
case Chain.Kujira: | ||
return symbol === "KUJI"; | ||
case Chain.Cosmos: | ||
return symbol === "ATOM"; | ||
case Chain.Polygon: | ||
return symbol === "MATIC"; | ||
case Chain.BinanceSmartChain: | ||
return symbol === "BNB"; | ||
case Chain.THORChain: | ||
return symbol === "RUNE"; | ||
default: | ||
return symbol === chain; | ||
} | ||
}; | ||
var getCommonAssetInfo = (assetString) => { | ||
switch (assetString) { | ||
case `${Chain.Ethereum}.THOR`: | ||
return { identifier: "ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044", decimal: 18 }; | ||
case `${Chain.Ethereum}.vTHOR`: | ||
return { identifier: "ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", decimal: 18 }; | ||
case Chain.Cosmos: | ||
return { identifier: "GAIA.ATOM", decimal: BaseDecimal[assetString] }; | ||
case Chain.THORChain: | ||
return { identifier: "THOR.RUNE", decimal: BaseDecimal[assetString] }; | ||
case Chain.BinanceSmartChain: | ||
return { identifier: "BSC.BNB", decimal: BaseDecimal[assetString] }; | ||
case Chain.Maya: | ||
return { identifier: "MAYA.CACAO", decimal: BaseDecimal.MAYA }; | ||
case `${Chain.Maya}.MAYA`: | ||
return { identifier: "MAYA.MAYA", decimal: 4 }; | ||
case `${Chain.Kujira}.USK`: | ||
return { identifier: `${Chain.Kujira}.USK`, decimal: 6 }; | ||
default: | ||
return { identifier: `${assetString}.${assetString}`, decimal: BaseDecimal[assetString] }; | ||
} | ||
}; | ||
var getAssetType = ({ chain, symbol }) => { | ||
if (symbol.includes("/")) | ||
return "Synth"; | ||
switch (chain) { | ||
case Chain.Cosmos: | ||
return symbol === "ATOM" ? "Native" : Chain.Cosmos; | ||
case Chain.Kujira: | ||
return symbol === Chain.Kujira ? "Native" : Chain.Kujira; | ||
case Chain.Binance: | ||
return symbol === Chain.Binance ? "Native" : "BEP2"; | ||
case Chain.BinanceSmartChain: | ||
return symbol === Chain.Binance ? "Native" : "BEP20"; | ||
case Chain.Ethereum: | ||
return symbol === Chain.Ethereum ? "Native" : "ERC20"; | ||
case Chain.Avalanche: | ||
return symbol === Chain.Avalanche ? "Native" : Chain.Avalanche; | ||
case Chain.Polygon: | ||
return symbol === Chain.Polygon ? "Native" : "POLYGON"; | ||
case Chain.Arbitrum: | ||
return [Chain.Ethereum, Chain.Arbitrum].includes(symbol) ? "Native" : "ARBITRUM"; | ||
case Chain.Optimism: | ||
return [Chain.Ethereum, Chain.Optimism].includes(symbol) ? "Native" : "OPTIMISM"; | ||
default: | ||
return "Native"; | ||
} | ||
}; | ||
var assetFromString = (assetString) => { | ||
const [chain, ...symbolArray] = assetString.split("."); | ||
const synth = assetString.includes("/"); | ||
const symbol = symbolArray.join("."); | ||
const ticker = symbol?.split("-")?.[0]; | ||
return { chain, symbol, ticker, synth }; | ||
}; | ||
var potentialScamRegex = new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/, "gmi"); | ||
var evmAssetHasAddress = (assetString) => { | ||
const [chain, symbol] = assetString.split("."); | ||
if (!EVMChains.includes(chain)) | ||
return true; | ||
const [, address] = symbol.split("-"); | ||
return isGasAsset({ chain, symbol }) || !!address; | ||
}; | ||
var filterAssets = (tokens) => tokens.filter(({ chain, value, symbol }) => { | ||
const assetString = `${chain}.${symbol}`; | ||
return !potentialScamRegex.test(assetString) && evmAssetHasAddress(assetString) && value !== "0"; | ||
}); | ||
// src/helpers/liquidity.ts | ||
import {BaseDecimal as BaseDecimal2} from "@swapkit/types"; | ||
function getAsymmetricRuneShare({ | ||
liquidityUnits, | ||
poolUnits, | ||
runeDepth | ||
}) { | ||
const s = toTCSwapKitNumber(liquidityUnits); | ||
const T = toTCSwapKitNumber(poolUnits); | ||
const A = toTCSwapKitNumber(runeDepth); | ||
const part1 = s.mul(A); | ||
const part2 = T.mul(T).mul(2); | ||
const part3 = T.mul(s).mul(2); | ||
const part4 = s.mul(s); | ||
const part5 = T.mul(T).mul(T); | ||
const numerator = part1.mul(part2.sub(part3).add(part4)); | ||
return numerator.div(part5); | ||
} | ||
function getAsymmetricAssetShare({ | ||
liquidityUnits, | ||
poolUnits, | ||
assetDepth | ||
}) { | ||
const s = toTCSwapKitNumber(liquidityUnits); | ||
const T = toTCSwapKitNumber(poolUnits); | ||
const A = toTCSwapKitNumber(assetDepth); | ||
const part1 = s.mul(A); | ||
const part2 = T.mul(T).mul(2); | ||
const part3 = T.mul(s).mul(2); | ||
const part4 = s.mul(s); | ||
const numerator = part1.mul(part2.sub(part3).add(part4)); | ||
const part5 = T.mul(T).mul(T); | ||
return numerator.div(part5); | ||
} | ||
function getAsymmetricRuneWithdrawAmount({ | ||
percent, | ||
runeDepth, | ||
liquidityUnits, | ||
poolUnits | ||
}) { | ||
return getAsymmetricRuneShare({ runeDepth, liquidityUnits, poolUnits }).mul(percent); | ||
} | ||
function getAsymmetricAssetWithdrawAmount({ | ||
percent, | ||
assetDepth, | ||
liquidityUnits, | ||
poolUnits | ||
}) { | ||
return getAsymmetricAssetShare({ assetDepth, liquidityUnits, poolUnits }).mul(percent); | ||
} | ||
var toTCSwapKitNumber = function(value) { | ||
return SwapKitNumber.fromBigInt(BigInt(value), BaseDecimal2.THOR); | ||
}; | ||
function getSymmetricPoolShare({ | ||
liquidityUnits, | ||
poolUnits, | ||
runeDepth, | ||
assetDepth | ||
}) { | ||
return { | ||
assetAmount: toTCSwapKitNumber(assetDepth).mul(liquidityUnits).div(poolUnits), | ||
runeAmount: toTCSwapKitNumber(runeDepth).mul(liquidityUnits).div(poolUnits) | ||
}; | ||
} | ||
function getSymmetricWithdraw({ | ||
liquidityUnits, | ||
poolUnits, | ||
runeDepth, | ||
assetDepth, | ||
percent | ||
}) { | ||
return Object.fromEntries(Object.entries(getSymmetricPoolShare({ liquidityUnits, poolUnits, runeDepth, assetDepth })).map(([name, value]) => [name, value.mul(percent)])); | ||
} | ||
function getEstimatedPoolShare({ | ||
runeDepth, | ||
poolUnits, | ||
assetDepth, | ||
liquidityUnits, | ||
runeAmount, | ||
assetAmount | ||
}) { | ||
const R = new SwapKitNumber({ value: runeDepth, decimal: 8 }); | ||
const A = new SwapKitNumber({ value: assetDepth, decimal: 8 }); | ||
const P = new SwapKitNumber({ value: poolUnits, decimal: 8 }); | ||
const runeAddAmount = new SwapKitNumber({ value: runeAmount, decimal: 8 }); | ||
const assetAddAmount = new SwapKitNumber({ value: assetAmount, decimal: 8 }); | ||
const rA = runeAddAmount.mul(A); | ||
const aR = assetAddAmount.mul(R); | ||
const ra = runeAddAmount.mul(assetAddAmount); | ||
const RA = R.mul(A); | ||
const numerator = P.mul(rA.add(aR.add(ra.mul(2)))); | ||
const denominator = rA.add(aR.add(RA.mul(2))); | ||
const liquidityUnitsAfterAdd = numerator.div(denominator); | ||
const estimatedLiquidityUnits = toTCSwapKitNumber(liquidityUnits).add(liquidityUnitsAfterAdd); | ||
if (liquidityUnitsAfterAdd.getBaseValue("number") === 0) { | ||
return estimatedLiquidityUnits.div(P).getBaseValue("number"); | ||
} | ||
const newPoolUnits = P.add(estimatedLiquidityUnits); | ||
return estimatedLiquidityUnits.div(newPoolUnits).getBaseValue("number"); | ||
} | ||
function getLiquiditySlippage({ | ||
runeAmount, | ||
assetAmount, | ||
runeDepth, | ||
assetDepth | ||
}) { | ||
if (runeAmount === "0" || assetAmount === "0" || runeDepth === "0" || assetDepth === "0") | ||
return 0; | ||
const R = toTCSwapKitNumber(runeDepth); | ||
const T = toTCSwapKitNumber(assetDepth); | ||
const assetAddAmount = toTCSwapKitNumber(assetAmount); | ||
const runeAddAmount = toTCSwapKitNumber(runeAmount); | ||
const numerator = assetAddAmount.mul(R).sub(T.mul(runeAddAmount)); | ||
const denominator = T.mul(runeAddAmount).add(R.mul(T)); | ||
return Math.abs(numerator.div(denominator).getBaseValue("number")); | ||
} | ||
// src/helpers/memo.ts | ||
import {Chain as Chain2, MemoType} from "@swapkit/types"; | ||
var getMemoFor = (memoType, options) => { | ||
switch (memoType) { | ||
case MemoType.LEAVE: | ||
case MemoType.BOND: { | ||
const { address } = options; | ||
return `${memoType}:${address}`; | ||
} | ||
case MemoType.UNBOND: { | ||
const { address, unbondAmount } = options; | ||
return `${memoType}:${address}:${unbondAmount}`; | ||
} | ||
case MemoType.THORNAME_REGISTER: { | ||
const { name, chain, address, owner } = options; | ||
return `${memoType}:${name}:${chain}:${address}${owner ? `:${owner}` : ""}`; | ||
} | ||
case MemoType.DEPOSIT: { | ||
const { chain, symbol, address, singleSide } = options; | ||
const getPoolIdentifier = (chain2, symbol2) => { | ||
switch (chain2) { | ||
case Chain2.Litecoin: | ||
return "l"; | ||
case Chain2.Dogecoin: | ||
return "d"; | ||
case Chain2.BitcoinCash: | ||
return "c"; | ||
default: | ||
return `${chain2}.${symbol2}`; | ||
} | ||
}; | ||
return singleSide ? `${memoType}:${chain}/${symbol}` : `${memoType}:${getPoolIdentifier(chain, symbol)}:${address || ""}`; | ||
} | ||
case MemoType.WITHDRAW: { | ||
const { chain, ticker, symbol, basisPoints, targetAssetString, singleSide } = options; | ||
const shortenedSymbol = chain === "ETH" && ticker !== "ETH" ? `${ticker}-${symbol.slice(-3)}` : symbol; | ||
const target = !singleSide && targetAssetString ? `:${targetAssetString}` : ""; | ||
const assetDivider = singleSide ? "/" : "."; | ||
return `${memoType}:${chain}${assetDivider}${shortenedSymbol}:${basisPoints}${target}`; | ||
} | ||
case MemoType.OPEN_LOAN: | ||
case MemoType.CLOSE_LOAN: { | ||
const { asset, address } = options; | ||
return `${memoType}:${asset}:${address}`; | ||
} | ||
default: | ||
return ""; | ||
} | ||
}; | ||
// src/helpers/others.ts | ||
function getTHORNameCost(year) { | ||
if (year < 0) | ||
throw new Error("Invalid number of year"); | ||
return 10 + year; | ||
} | ||
function getMAYANameCost(year) { | ||
if (year < 0) | ||
throw new Error("Invalid number of year"); | ||
return Math.round((10 + year * 1.0512) * 10000000000) / 10000000000; | ||
} | ||
function validateTHORName(name) { | ||
if (name.length > 30) | ||
return false; | ||
const regex = /^[a-zA-Z0-9+_-]+$/g; | ||
return !!name.match(regex); | ||
} | ||
function validateMAYAName(name) { | ||
if (name.length > 30) | ||
return false; | ||
const regex = /^[a-zA-Z0-9+_-]+$/g; | ||
return !!name.match(regex); | ||
} | ||
function derivationPathToString([network, chainId, account, change, index]) { | ||
const shortPath = typeof index !== "number"; | ||
return `m/${network}'/${chainId}'/${account}'/${change}${shortPath ? "" : `/${index}`}`; | ||
} | ||
// src/modules/assetValue.ts | ||
import {BaseDecimal as BaseDecimal4, Chain as Chain4, ChainToChainId} from "@swapkit/types"; | ||
// src/helpers/validators.ts | ||
import {Chain as Chain3} from "@swapkit/types"; | ||
function validateIdentifier(identifier = "") { | ||
const uppercasedIdentifier = identifier.toUpperCase(); | ||
const [chain] = uppercasedIdentifier.split("."); | ||
if (supportedChains.includes(chain)) | ||
return true; | ||
const [synthChain] = uppercasedIdentifier.split("/"); | ||
if (supportedChains.includes(synthChain)) | ||
return true; | ||
throw new Error(`Invalid identifier: ${identifier}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`); | ||
} | ||
var supportedChains = [...Object.values(Chain3), "TERRA"]; | ||
// src/modules/bigIntArithmetics.ts | ||
import {BaseDecimal as BaseDecimal3} from "@swapkit/types"; | ||
function formatBigIntToSafeValue({ | ||
value, | ||
bigIntDecimal = DEFAULT_DECIMAL, | ||
decimal = DEFAULT_DECIMAL | ||
}) { | ||
if (decimal === 0) | ||
return value.toString(); | ||
const isNegative = value < 0n; | ||
let valueString = value.toString().substring(isNegative ? 1 : 0); | ||
const padLength = decimal - (valueString.length - 1); | ||
if (padLength > 0) { | ||
valueString = "0".repeat(padLength) + valueString; | ||
} | ||
const decimalIndex = valueString.length - decimal; | ||
let decimalString = valueString.slice(-decimal); | ||
if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) { | ||
decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1).toString()}`; | ||
} else { | ||
decimalString = decimalString.substring(0, bigIntDecimal); | ||
} | ||
return `${isNegative ? "-" : ""}${valueString.slice(0, decimalIndex)}.${decimalString}`.replace(/\.?0*$/, ""); | ||
} | ||
var toSafeValue = function(value) { | ||
const parsedValue = typeof value === "number" ? numberFormatter.format(value) : getStringValue(value); | ||
const splitValue = `${parsedValue}`.replaceAll(",", ".").split("."); | ||
return splitValue.length > 1 ? `${splitValue.slice(0, -1).join("")}.${splitValue.at(-1)}` : splitValue[0] || "0"; | ||
}; | ||
var getFloatDecimals = function(value) { | ||
const decimals = value.split(".")[1]?.length || 0; | ||
return Math.max(decimals, DEFAULT_DECIMAL); | ||
}; | ||
var getStringValue = function(param) { | ||
return typeof param === "object" ? "getValue" in param ? param.getValue("string") : param.value : param; | ||
}; | ||
var DEFAULT_DECIMAL = 8; | ||
var toMultiplier = (decimal) => 10n ** BigInt(decimal); | ||
var decimalFromMultiplier = (multiplier) => Math.log10(Number.parseFloat(multiplier.toString())); | ||
class BigIntArithmetics { | ||
decimalMultiplier = 10n ** 8n; | ||
bigIntValue = 0n; | ||
decimal; | ||
static fromBigInt(value, decimal) { | ||
return new BigIntArithmetics({ | ||
decimal, | ||
value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }) | ||
}); | ||
} | ||
static shiftDecimals({ | ||
value, | ||
from, | ||
to | ||
}) { | ||
return BigIntArithmetics.fromBigInt(value.getBaseValue("bigint") * toMultiplier(to) / toMultiplier(from), to); | ||
} | ||
constructor(params) { | ||
const value = getStringValue(params); | ||
const isComplex = typeof params === "object"; | ||
this.decimal = isComplex ? params.decimal : undefined; | ||
this.decimalMultiplier = isComplex && "decimalMultiplier" in params ? params.decimalMultiplier : toMultiplier(Math.max(getFloatDecimals(toSafeValue(value)), this.decimal || 0)); | ||
this.#setValue(value); | ||
} | ||
set(value) { | ||
return new this.constructor({ decimal: this.decimal, value, identifier: this.toString() }); | ||
} | ||
add(...args) { | ||
return this.#arithmetics("add", ...args); | ||
} | ||
sub(...args) { | ||
return this.#arithmetics("sub", ...args); | ||
} | ||
mul(...args) { | ||
return this.#arithmetics("mul", ...args); | ||
} | ||
div(...args) { | ||
return this.#arithmetics("div", ...args); | ||
} | ||
gt(value) { | ||
return this.#comparison("gt", value); | ||
} | ||
gte(value) { | ||
return this.#comparison("gte", value); | ||
} | ||
lt(value) { | ||
return this.#comparison("lt", value); | ||
} | ||
lte(value) { | ||
return this.#comparison("lte", value); | ||
} | ||
eqValue(value) { | ||
return this.#comparison("eqValue", value); | ||
} | ||
getValue(type) { | ||
const value = this.formatBigIntToSafeValue(this.bigIntValue, this.decimal || decimalFromMultiplier(this.decimalMultiplier)); | ||
switch (type) { | ||
case "number": | ||
return Number(value); | ||
case "string": | ||
return value; | ||
case "bigint": | ||
return this.bigIntValue * 10n ** BigInt(this.decimal || 8n) / this.decimalMultiplier; | ||
} | ||
} | ||
getBaseValue(type) { | ||
const divisor = this.decimalMultiplier / toMultiplier(this.decimal || BaseDecimal3.THOR); | ||
const baseValue = this.bigIntValue / divisor; | ||
switch (type) { | ||
case "number": | ||
return Number(baseValue); | ||
case "string": | ||
return baseValue.toString(); | ||
case "bigint": | ||
return baseValue; | ||
} | ||
} | ||
getBigIntValue(value, decimal) { | ||
if (!decimal && typeof value === "object") | ||
return value.bigIntValue; | ||
const stringValue = getStringValue(value); | ||
const safeValue = toSafeValue(stringValue); | ||
if (safeValue === "0" || safeValue === "undefined") | ||
return 0n; | ||
return this.#toBigInt(safeValue, decimal); | ||
} | ||
toSignificant(significantDigits = 6) { | ||
const [int, dec] = this.getValue("string").split("."); | ||
const integer = int || ""; | ||
const decimal = dec || ""; | ||
const valueLength = Number.parseInt(integer) ? integer.length + decimal.length : decimal.length; | ||
if (valueLength <= significantDigits) { | ||
return this.getValue("string"); | ||
} | ||
if (integer.length >= significantDigits) { | ||
return integer.slice(0, significantDigits).padEnd(integer.length, "0"); | ||
} | ||
if (Number.parseInt(integer)) { | ||
return `${integer}.${decimal.slice(0, significantDigits - integer.length)}`.padEnd(significantDigits - integer.length, "0"); | ||
} | ||
const trimmedDecimal = Number.parseInt(decimal); | ||
const slicedDecimal = `${trimmedDecimal}`.slice(0, significantDigits); | ||
return `0.${slicedDecimal.padStart(decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, "0")}`; | ||
} | ||
toFixed(fixedDigits = 6) { | ||
const [int, dec] = this.getValue("string").split("."); | ||
const integer = int || ""; | ||
const decimal = dec || ""; | ||
if (Number.parseInt(integer)) { | ||
return `${integer}.${decimal.slice(0, fixedDigits)}`.padEnd(fixedDigits, "0"); | ||
} | ||
const trimmedDecimal = Number.parseInt(decimal); | ||
const slicedDecimal = `${trimmedDecimal}`.slice(0, fixedDigits); | ||
return `0.${slicedDecimal.padStart(decimal.length - `${trimmedDecimal}`.length + slicedDecimal.length, "0")}`; | ||
} | ||
toAbbreviation(digits = 2) { | ||
const value = this.getValue("number"); | ||
const abbreviations = ["", "K", "M", "B", "T", "Q", "Qi", "S"]; | ||
const tier = Math.floor(Math.log10(Math.abs(value)) / 3); | ||
const suffix = abbreviations[tier]; | ||
if (!suffix) | ||
return this.getValue("string"); | ||
const scale = 10 ** (tier * 3); | ||
const scaled = value / scale; | ||
return `${scaled.toFixed(digits)}${suffix}`; | ||
} | ||
toCurrency(currency = "$", { | ||
currencyPosition = "start", | ||
decimal = 2, | ||
decimalSeparator = ".", | ||
thousandSeparator = "," | ||
} = {}) { | ||
const value = this.getValue("number"); | ||
const [int = "", dec = ""] = value.toFixed(6).split("."); | ||
const integer = int.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator); | ||
const parsedValue = int || dec ? int === "0" ? `${Number.parseFloat(`0.${dec}`)}`.replace(".", decimalSeparator) : `${integer}${Number.parseInt(dec) ? `${decimalSeparator}${dec.slice(0, decimal)}` : ""}` : "0.00"; | ||
return `${currencyPosition === "start" ? currency : ""}${parsedValue}${currencyPosition === "end" ? currency : ""}`; | ||
} | ||
formatBigIntToSafeValue(value, decimal) { | ||
const bigIntDecimal = decimal || this.decimal || DEFAULT_DECIMAL; | ||
const decimalToUseForConversion = Math.max(bigIntDecimal, decimalFromMultiplier(this.decimalMultiplier)); | ||
const isNegative = value < 0n; | ||
const valueString = value.toString().substring(isNegative ? 1 : 0); | ||
const padLength = decimalToUseForConversion - (valueString.length - 1); | ||
const parsedValueString = padLength > 0 ? "0".repeat(padLength) + valueString : valueString; | ||
const decimalIndex = parsedValueString.length - decimalToUseForConversion; | ||
let decimalString = parsedValueString.slice(-decimalToUseForConversion); | ||
if (Number.parseInt(decimalString[bigIntDecimal] || "0") >= 5) { | ||
decimalString = `${decimalString.substring(0, bigIntDecimal - 1)}${(Number.parseInt(decimalString[bigIntDecimal - 1] || "0") + 1).toString()}`; | ||
} else { | ||
decimalString = decimalString.substring(0, bigIntDecimal); | ||
} | ||
return `${isNegative ? "-" : ""}${parsedValueString.slice(0, decimalIndex)}.${decimalString}`.replace(/\.?0*$/, ""); | ||
} | ||
#arithmetics(method, ...args) { | ||
const precisionDecimal = this.#retrievePrecisionDecimal(this, ...args); | ||
const decimal = Math.max(precisionDecimal, decimalFromMultiplier(this.decimalMultiplier)); | ||
const precisionDecimalMultiplier = toMultiplier(decimal); | ||
const result = args.reduce((acc, arg) => { | ||
const value2 = this.getBigIntValue(arg, decimal); | ||
switch (method) { | ||
case "add": | ||
return acc + value2; | ||
case "sub": | ||
return acc - value2; | ||
case "mul": | ||
return acc * value2 / precisionDecimalMultiplier; | ||
case "div": { | ||
if (value2 === 0n) | ||
throw new RangeError("Division by zero"); | ||
return acc * precisionDecimalMultiplier / value2; | ||
} | ||
default: | ||
return acc; | ||
} | ||
}, this.bigIntValue * precisionDecimalMultiplier / this.decimalMultiplier); | ||
const value = formatBigIntToSafeValue({ | ||
bigIntDecimal: decimal, | ||
decimal, | ||
value: result | ||
}); | ||
return new this.constructor({ | ||
decimalMultiplier: toMultiplier(decimal), | ||
decimal: this.decimal, | ||
value, | ||
identifier: this.toString() | ||
}); | ||
} | ||
#comparison(method, ...args) { | ||
const decimal = this.#retrievePrecisionDecimal(this, ...args); | ||
const value = this.getBigIntValue(args[0] || "0", decimal); | ||
const compareToValue = this.getBigIntValue(this, decimal); | ||
switch (method) { | ||
case "gt": | ||
return compareToValue > value; | ||
case "gte": | ||
return compareToValue >= value; | ||
case "lt": | ||
return compareToValue < value; | ||
case "lte": | ||
return compareToValue <= value; | ||
case "eqValue": | ||
return compareToValue === value; | ||
} | ||
} | ||
#setValue(value) { | ||
const safeValue = toSafeValue(value) || "0"; | ||
this.bigIntValue = this.#toBigInt(safeValue); | ||
} | ||
#retrievePrecisionDecimal(...args) { | ||
const decimals = args.map((arg) => { | ||
const isObject = typeof arg === "object"; | ||
const value = isObject ? arg.decimal || decimalFromMultiplier(arg.decimalMultiplier) : getFloatDecimals(toSafeValue(arg)); | ||
return value; | ||
}).filter(Boolean); | ||
return Math.max(...decimals, DEFAULT_DECIMAL); | ||
} | ||
#toBigInt(value, decimal) { | ||
const multiplier = decimal ? toMultiplier(decimal) : this.decimalMultiplier; | ||
const padDecimal = decimalFromMultiplier(multiplier); | ||
const [integerPart = "", decimalPart = ""] = value.split("."); | ||
return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, "0")}`); | ||
} | ||
} | ||
var numberFormatter = Intl.NumberFormat("fullwide", { | ||
useGrouping: false, | ||
maximumFractionDigits: 20 | ||
}); | ||
// src/modules/swapKitNumber.ts | ||
class SwapKitNumber extends BigIntArithmetics { | ||
constructor() { | ||
super(...arguments); | ||
} | ||
eq(value) { | ||
return this.eqValue(value); | ||
} | ||
static fromBigInt(value, decimal) { | ||
return new SwapKitNumber({ | ||
decimal, | ||
value: formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }) | ||
}); | ||
} | ||
} | ||
// src/modules/assetValue.ts | ||
function getMinAmountByChain(chain) { | ||
const asset2 = AssetValue.fromChainOrSignature(chain); | ||
switch (chain) { | ||
case Chain4.Bitcoin: | ||
case Chain4.Litecoin: | ||
case Chain4.BitcoinCash: | ||
return asset2.set(0.00010001); | ||
case Chain4.Dogecoin: | ||
return asset2.set(1.00000001); | ||
case Chain4.Avalanche: | ||
case Chain4.Ethereum: | ||
return asset2.set(0.00000001); | ||
case Chain4.THORChain: | ||
case Chain4.Maya: | ||
return asset2.set(0); | ||
case Chain4.Cosmos: | ||
return asset2.set(0.000001); | ||
default: | ||
return asset2.set(0.00000001); | ||
} | ||
} | ||
async function createAssetValue(identifier, value = 0) { | ||
validateIdentifier(identifier); | ||
const staticToken = staticTokensMap.get(identifier.toUpperCase()); | ||
const decimal = staticToken?.decimal || await getDecimal(getAssetInfo(identifier)); | ||
if (!staticToken) { | ||
staticTokensMap.set(identifier.toUpperCase(), { identifier, decimal }); | ||
} | ||
return new AssetValue({ decimal, value: safeValue(value, decimal), identifier }); | ||
} | ||
var createSyntheticAssetValue = function(identifier, value = 0) { | ||
const [synthChain, symbol] = identifier.split(".")?.[0]?.toUpperCase() === Chain4.THORChain ? identifier.split(".").slice(1).join().split("/") : identifier.split("/"); | ||
if (!(synthChain && symbol)) | ||
throw new Error("Invalid asset identifier"); | ||
return new AssetValue({ | ||
decimal: 8, | ||
value: safeValue(value, 8), | ||
identifier: `${Chain4.THORChain}.${synthChain}/${symbol}` | ||
}); | ||
}; | ||
var safeValue = function(value, decimal) { | ||
return typeof value === "bigint" ? formatBigIntToSafeValue({ value, bigIntDecimal: decimal, decimal }) : value; | ||
}; | ||
var getAssetInfo = function(identifier) { | ||
const isSynthetic = identifier.slice(0, 14).includes("/"); | ||
const [synthChain, synthSymbol = ""] = identifier.split(".")?.[0]?.toUpperCase() === Chain4.THORChain ? identifier.split(".").slice(1).join().split("/") : identifier.split("/"); | ||
if (isSynthetic && !(synthChain && synthSymbol)) | ||
throw new Error("Invalid asset identifier"); | ||
const adjustedIdentifier = identifier.includes(".") && !isSynthetic ? identifier : `${Chain4.THORChain}.${synthSymbol}`; | ||
const [chain, ...rest] = adjustedIdentifier.split("."); | ||
const [ticker, address] = (isSynthetic ? synthSymbol : rest.join(".")).split("-"); | ||
const symbol = isSynthetic ? synthSymbol : rest.join("."); | ||
return { | ||
address: address?.toLowerCase(), | ||
chain, | ||
isGasAsset: isGasAsset({ chain, symbol }), | ||
isSynthetic, | ||
symbol: (isSynthetic ? `${synthChain}/` : "") + (address ? `${ticker}-${address?.toLowerCase() ?? ""}` : symbol), | ||
ticker | ||
}; | ||
}; | ||
var staticTokensMap = new Map; | ||
class AssetValue extends BigIntArithmetics { | ||
address; | ||
chain; | ||
isGasAsset = false; | ||
isSynthetic = false; | ||
symbol; | ||
tax; | ||
ticker; | ||
type; | ||
constructor({ | ||
value, | ||
decimal, | ||
tax, | ||
chain, | ||
symbol, | ||
identifier | ||
}) { | ||
super(typeof value === "object" ? value : { decimal, value }); | ||
const assetInfo = getAssetInfo(identifier || `${chain}.${symbol}`); | ||
this.type = getAssetType(assetInfo); | ||
this.tax = tax; | ||
this.chain = assetInfo.chain; | ||
this.ticker = assetInfo.ticker; | ||
this.symbol = assetInfo.symbol; | ||
this.address = assetInfo.address; | ||
this.isSynthetic = assetInfo.isSynthetic; | ||
this.isGasAsset = assetInfo.isGasAsset; | ||
} | ||
toString() { | ||
return this.isSynthetic ? this.symbol : `${this.chain}.${this.symbol}`; | ||
} | ||
toUrl() { | ||
return this.isSynthetic ? `${this.chain}.${this.symbol.replace("/", ".")}` : this.toString(); | ||
} | ||
eq({ chain, symbol }) { | ||
return this.chain === chain && this.symbol === symbol; | ||
} | ||
chainId() { | ||
return ChainToChainId[this.chain]; | ||
} | ||
static fromUrl(urlAsset, value = 0) { | ||
const [chain, ticker, symbol] = urlAsset.split("."); | ||
if (!(chain && ticker)) | ||
throw new Error("Invalid asset url"); | ||
const assetString = chain === Chain4.THORChain && symbol ? `${chain}.${ticker}/${symbol}` : urlAsset; | ||
return createAssetValue(assetString, value); | ||
} | ||
static fromString(assetString, value = 0) { | ||
return createAssetValue(assetString, value); | ||
} | ||
static fromIdentifier(assetString, value = 0) { | ||
return createAssetValue(assetString, value); | ||
} | ||
static fromStringSync(assetString, value = 0) { | ||
const { chain, isSynthetic } = getAssetInfo(assetString); | ||
const tokenInfo = staticTokensMap.get(assetString.toUpperCase()); | ||
if (isSynthetic) | ||
return createSyntheticAssetValue(assetString, value); | ||
const { tax, decimal, identifier } = tokenInfo || { | ||
decimal: BaseDecimal4[chain], | ||
identifier: assetString | ||
}; | ||
return new AssetValue({ | ||
tax, | ||
value: safeValue(value, decimal), | ||
identifier: isSynthetic ? assetString : identifier, | ||
decimal: isSynthetic ? 8 : decimal | ||
}); | ||
} | ||
static async fromStringWithBase(assetString, value = 0, baseDecimal = BaseDecimal4.THOR) { | ||
const shiftedAmount = BigIntArithmetics.shiftDecimals({ | ||
value: SwapKitNumber.fromBigInt(BigInt(value)), | ||
from: 0, | ||
to: baseDecimal | ||
}).getBaseValue("string"); | ||
const assetValue = await AssetValue.fromString(assetString, value); | ||
return assetValue.set(shiftedAmount); | ||
} | ||
static fromStringWithBaseSync(assetString, value = 0, baseDecimal = BaseDecimal4.THOR) { | ||
const { chain, isSynthetic } = getAssetInfo(assetString); | ||
const tokenInfo = staticTokensMap.get(assetString.toUpperCase()); | ||
if (isSynthetic) | ||
return createSyntheticAssetValue(assetString, value); | ||
const { tax, decimal, identifier } = tokenInfo || { | ||
decimal: BaseDecimal4[chain], | ||
identifier: assetString | ||
}; | ||
return new AssetValue({ | ||
tax, | ||
value: safeValue(BigInt(value), baseDecimal), | ||
identifier, | ||
decimal | ||
}); | ||
} | ||
static fromIdentifierSync(assetString, value = 0) { | ||
const { chain, isSynthetic } = getAssetInfo(assetString); | ||
const tokenInfo = staticTokensMap.get(assetString); | ||
if (isSynthetic) | ||
return createSyntheticAssetValue(assetString, value); | ||
const { tax, decimal, identifier } = tokenInfo || { | ||
decimal: BaseDecimal4[chain], | ||
identifier: assetString | ||
}; | ||
return new AssetValue({ tax, decimal, identifier, value: safeValue(value, decimal) }); | ||
} | ||
static fromChainOrSignature(assetString, value = 0) { | ||
const { decimal, identifier } = getCommonAssetInfo(assetString); | ||
return new AssetValue({ value: safeValue(value, decimal), decimal, identifier }); | ||
} | ||
static loadStaticAssets() { | ||
return new Promise((resolve, reject) => { | ||
try { | ||
import("@swapkit/tokens").then((tokenPackages) => { | ||
for (const tokenList of Object.values(tokenPackages)) { | ||
for (const { identifier, chain, ...rest } of tokenList.tokens) { | ||
staticTokensMap.set(identifier.toUpperCase(), { | ||
identifier, | ||
decimal: "decimals" in rest ? rest.decimals : BaseDecimal4[chain] | ||
}); | ||
} | ||
} | ||
resolve({ ok: true }); | ||
}); | ||
} catch (error) { | ||
console.error(error); | ||
reject({ | ||
ok: false, | ||
error, | ||
message: "Couldn't load static assets. Ensure you have installed @swapkit/tokens package" | ||
}); | ||
} | ||
}); | ||
} | ||
} | ||
// src/modules/swapKitError.ts | ||
var errorMessages = { | ||
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_plugin_not_found: 10006, | ||
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_wallet_keepkey_not_installed: 10109, | ||
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_invalid_sender_address: 10313, | ||
core_transaction_deposit_server_error: 10314, | ||
core_transaction_user_rejected: 10315, | ||
wallet_ledger_connection_error: 20001, | ||
wallet_ledger_connection_claimed: 20002, | ||
wallet_ledger_get_address_error: 20003, | ||
wallet_ledger_device_not_found: 20004, | ||
wallet_ledger_device_locked: 20005, | ||
chainflip_channel_error: 30001, | ||
chainflip_broker_recipient_error: 30002, | ||
helpers_number_different_decimals: 99101 | ||
}; | ||
class SwapKitError extends Error { | ||
constructor(errorKey, sourceError) { | ||
if (sourceError) { | ||
console.error(sourceError, { | ||
stack: sourceError?.stack, | ||
message: sourceError?.message | ||
}); | ||
} | ||
super(errorKey, { | ||
cause: { code: errorMessages[errorKey], message: errorKey } | ||
}); | ||
Object.setPrototypeOf(this, SwapKitError.prototype); | ||
} | ||
} | ||
export { | ||
validateTHORName, | ||
validateMAYAName, | ||
isGasAsset, | ||
getTHORNameCost, | ||
getSymmetricWithdraw, | ||
getSymmetricPoolShare, | ||
getMinAmountByChain, | ||
getMemoFor, | ||
getMAYANameCost, | ||
getLiquiditySlippage, | ||
getEstimatedPoolShare, | ||
getDecimal, | ||
getCommonAssetInfo, | ||
getAsymmetricRuneWithdrawAmount, | ||
getAsymmetricRuneShare, | ||
getAsymmetricAssetWithdrawAmount, | ||
getAsymmetricAssetShare, | ||
getAssetType, | ||
gasFeeMultiplier, | ||
formatBigIntToSafeValue, | ||
findAssetBy, | ||
filterAssets, | ||
derivationPathToString, | ||
assetFromString, | ||
SwapKitNumber, | ||
SwapKitError, | ||
BigIntArithmetics, | ||
AssetValue | ||
}; | ||
//# debugId=9DD5965E5B1063CF64756e2164756e21 |
@@ -5,13 +5,13 @@ { | ||
"dependencies": { | ||
"@swapkit/api": "0.0.0-nightly-20240404172439" | ||
"@swapkit/api": "0.0.0-nightly-20240404190857" | ||
}, | ||
"devDependencies": { | ||
"@swapkit/tokens": "0.0.0-nightly-20240404172439", | ||
"@swapkit/types": "0.0.0-nightly-20240404172439", | ||
"@swapkit/tokens": "0.0.0-nightly-20240404190857", | ||
"@swapkit/types": "0.0.0-nightly-20240404190857", | ||
"bun-types": "1.1.1" | ||
}, | ||
"peerDependencies": { | ||
"@swapkit/api": "0.0.0-nightly-20240404172439", | ||
"@swapkit/tokens": "0.0.0-nightly-20240404172439", | ||
"@swapkit/types": "0.0.0-nightly-20240404172439" | ||
"@swapkit/api": "0.0.0-nightly-20240404190857", | ||
"@swapkit/tokens": "0.0.0-nightly-20240404190857", | ||
"@swapkit/types": "0.0.0-nightly-20240404190857" | ||
}, | ||
@@ -41,3 +41,3 @@ "files": [ | ||
"types": "./src/index.ts", | ||
"version": "0.0.0-nightly-20240404172439" | ||
"version": "0.0.0-nightly-20240404190857" | ||
} |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
205583
3382
+ Added@swapkit/api@0.0.0-nightly-20240404190857(transitive)
+ Added@swapkit/tokens@0.0.0-nightly-20240404190857(transitive)
+ Added@swapkit/types@0.0.0-nightly-20240404190857(transitive)
- Removed@swapkit/api@0.0.0-nightly-20240404172439(transitive)
- Removed@swapkit/tokens@0.0.0-nightly-20240404172439(transitive)
- Removed@swapkit/types@0.0.0-nightly-20240404172439(transitive)