@swapkit/helpers 1.0.0-rc.5 → 1.0.0-rc.6

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 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 oe=Object.create;var R=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?R(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&&R(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?R(t,"default",{value:n,enumerable:!0}):t,n));var g=(n,e,t)=>(me(n,typeof e!="symbol"?e+"":e,t),t),pe=(n,e,t)=>{if(!e.has(n))throw TypeError("Cannot "+t)};var C=(n,e,t)=>{if(e.has(n))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(n):e.set(n,t)};var m=(n,e,t)=>(pe(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("@swapkit/types"),Ce=n=>{if(n<0)throw new Error("Invalid number of year");return 10+n},fe=n=>{if(n.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!n.match(e)},Ae=([n,e,t,i,a])=>`${n}'/${e}'/${t}'/${i}${typeof a!="number"?"":`/${a}`}`,Se=async(n,e)=>{try{const t=Object.entries(e||{}).reduce((a,[s,c])=>(c&&(a[s]=c),a),{});return(await fetch(`${n}${e?`?${new URLSearchParams(t).toString()}`:""}`,{method:"GET",mode:"cors",credentials:"omit",referrer:"https://sk.thorswap.net"})).json()}catch(t){return console.error(t),{}}},K=async(n,e,t,i=!1)=>{try{const a=await fetch(`${n}`,{body:e,headers:t,method:"POST",referrer:"https://sk.thorswap.net"});return i?a.text():a.json()}catch{return{}}},we="0x313ce567",Y=async({chain:n,to:e})=>{try{const t=await K(r.ChainToRPC[n],JSON.stringify({method:"eth_call",params:[{to:e.toLowerCase(),data:we},"latest"],id:44,jsonrpc:"2.0"}),{accept:"*/*","cache-control":"no-cache","content-type":"application/json"},!0),{result:i}=JSON.parse(t);return parseInt(BigInt(i).toString())}catch(t){return console.error(t),r.BaseDecimal[n]}},$e=async n=>{if(n===r.Chain.Ethereum)return r.BaseDecimal.ETH;const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?Y({chain:r.Chain.Ethereum,to:e}):r.BaseDecimal.ETH},be=async n=>{const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?Y({chain:r.Chain.Avalanche,to:e.toLowerCase()}):r.BaseDecimal.AVAX},Be=async n=>(n===r.Chain.BinanceSmartChain,r.BaseDecimal.BSC),q=async({chain:n,symbol:e})=>{switch(n){case r.Chain.Ethereum:return $e(e);case r.Chain.Avalanche:return be(e);case r.Chain.BinanceSmartChain:return Be(e);default:return r.BaseDecimal[n]}},ye={[r.FeeOption.Average]:1.2,[r.FeeOption.Fast]:1.5,[r.FeeOption.Fastest]:2},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}},Te=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),ve=n=>n.filter(e=>!Te.test(e.toString())),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)},Me=({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)}),Oe=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i,percent:a})=>Object.fromEntries(Object.entries(ee({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})).map(([s,c])=>[s,c.mul(a)])),Ee=({runeDepth:n,poolUnits:e,assetDepth:t,liquidityUnits:i,runeAmount:a,assetAmount:s})=>{const c=d(n),o=d(t),l=d(e),u=d(a),h=d(s),p=u.mul(o),$=h.mul(c),E=u.mul(h),ae=c.mul(o),re=l.mul(p.add($.add(E.mul(2)))),se=p.add($.add(ae.mul(2))),G=re.div(se),N=d(i).add(G);if(G.baseValueNumber===0)return N.div(l).baseValueNumber;const ce=l.add(N);return N.div(ce).baseValueNumber},Ne=({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)},Re=({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=Re({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""}},U=Object.values(r.Chain),Pe=(n="")=>{const e=n.toUpperCase(),[t]=e.split(".");if(U.includes(t))return!0;const[i]=e.split("/");if(U.includes(i))return!0;throw new Error(`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},I=8,S=n=>10n**BigInt(n),b=n=>Math.log10(parseFloat(n.toString()));function k({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,H,A,y,M,L;const T=class T{constructor(e){C(this,f);C(this,V);C(this,O);C(this,v);C(this,A);C(this,M);g(this,"decimalMultiplier",10n**8n);g(this,"bigIntValue",0n);g(this,"decimal");const t=D(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=S(Math.max(m(this,M,L).call(this,m(this,A,y).call(this,t)),this.decimal||0)),m(this,V,te).call(this,t)}static fromBigInt(e,t){return new T({decimal:t,value:k({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:i}){return T.fromBigInt(new T(e).bigIntValue*S(i)/S(t),i)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return m(this,f,B).call(this,"add",...e)}sub(...e){return m(this,f,B).call(this,"sub",...e)}mul(...e){return m(this,f,B).call(this,"mul",...e)}div(...e){return m(this,f,B).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||b(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue}}getBaseValue(e){const t=this.decimalMultiplier/S(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,H).call(this,m(this,A,y).call(this,D(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=S(i),s=t.reduce((o,l)=>{const u=this.getBigIntValue(l,i);switch(e){case"add":return o+u;case"sub":return o-u;case"mul":return o*u/a;case"div":{if(u===0n)throw new RangeError("Division by zero");return o*a/u}default:return o}},this.bigIntValue*a/this.decimalMultiplier),c=k({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,H).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,H=function(e,t){const i=t?S(t):this.decimalMultiplier,a=b(i),[s,c=""]=e.split(".");return BigInt(`${s}${c.padEnd(a,"0")}`)},A=new WeakSet,y=function(e){const i=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):D(e)}`.replaceAll(",",".").split(".");return i.length>1?`${i.slice(0,-1).join("")}.${i.at(-1)}`:i[0]},M=new WeakSet,L=function(e){var i;const t=((i=e.split(".")[1])==null?void 0:i.length)||0;return Math.max(t,I)};let w=T;function D(n){return typeof n=="object"?"getValue"in n?n.getValue("string"):n.value:n}let x;const 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)=>{Pe(n);const t=await q(j(n));return new _({decimal:t,value:e,identifier:n})};class _ extends w{constructor(t){super(t.value instanceof w?t.value:{decimal:t.decimal,value:t.value});g(this,"address");g(this,"chain");g(this,"isSynthetic",!1);g(this,"isGasAsset",!1);g(this,"symbol");g(this,"ticker");g(this,"type");const i="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,a=j(i);this.type=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(t=!1){const i=this.isSynthetic?this.ticker:`${this.chain}.${this.ticker}`;return t?i:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:i}){return this.chain===t&&this.symbol===i}static async fromString(t,i=0){return 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 ke=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}},He={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:He[e],message:e}}),Object.setPrototypeOf(this,F.prototype)}}class ie extends w{eq(e){return this.eqValue(e)}}exports.AssetValue=_;exports.BigIntArithmetics=w;exports.SwapKitError=F;exports.SwapKitNumber=ie;exports.assetFromString=Ie;exports.derivationPathToString=Ae;exports.filterAssets=ve;exports.formatBigIntToSafeValue=k;exports.gasFeeMultiplier=ye;exports.getAssetType=X;exports.getAsymmetricAssetShare=Z;exports.getAsymmetricAssetWithdrawAmount=Ve;exports.getAsymmetricRuneShare=Q;exports.getAsymmetricRuneWithdrawAmount=Me;exports.getCommonAssetInfo=z;exports.getDecimal=q;exports.getEstimatedPoolShare=Ee;exports.getLiquiditySlippage=Ne;exports.getMemoFor=De;exports.getMinAmountByChain=ke;exports.getRequest=Se;exports.getSymmetricPoolShare=ee;exports.getSymmetricWithdraw=Oe;exports.getTHORNameCost=Ce;exports.isGasAsset=J;exports.postRequest=K;exports.validateTHORName=fe;
package/dist/index.d.ts CHANGED
@@ -30,7 +30,7 @@ export declare class AssetValue extends BigIntArithmetics {
30
30
  type: ReturnType<typeof getAssetType>;
31
31
  constructor(params: AssetValueParams);
32
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;
@@ -73,8 +73,17 @@ export declare class BigIntArithmetics {
73
73
  to: number;
74
74
  }): BigIntArithmetics;
75
75
  constructor(params: SKBigIntParams);
76
+ /**
77
+ * @deprecated Use `getBaseValue('string')` instead
78
+ */
76
79
  get baseValue(): string;
80
+ /**
81
+ * @deprecated Use `getBaseValue('number')` instead
82
+ */
77
83
  get baseValueNumber(): number;
84
+ /**
85
+ * @deprecated Use `getBaseValue('bigint')` instead
86
+ */
78
87
  get baseValueBigInt(): bigint;
79
88
  set(value: SKBigIntParams): any;
80
89
  add(...args: InitialisationValueType[]): this;
@@ -155,6 +164,8 @@ declare const errorMessages: {
155
164
  readonly helpers_number_different_decimals: 99101;
156
165
  };
157
166
 
167
+ export declare const filterAssets: (assets: AssetValue[]) => AssetValue[];
168
+
158
169
  export declare function formatBigIntToSafeValue({ value, bigIntDecimal, decimal, }: {
159
170
  value: bigint;
160
171
  bigIntDecimal?: number;
package/dist/index.es.js CHANGED
@@ -1,6 +1,6 @@
1
1
  var nt = Object.defineProperty;
2
2
  var rt = (n, t, e) => t in n ? nt(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
- var g = (n, t, e) => (rt(n, typeof t != "symbol" ? t + "" : t, e), e), st = (n, t, e) => {
3
+ var _ = (n, t, e) => (rt(n, typeof t != "symbol" ? t + "" : t, e), e), st = (n, t, e) => {
4
4
  if (!t.has(n))
5
5
  throw TypeError("Cannot " + e);
6
6
  };
@@ -9,18 +9,18 @@ var $ = (n, t, e) => {
9
9
  throw TypeError("Cannot add the same private member more than once");
10
10
  t instanceof WeakSet ? t.add(n) : t.set(n, e);
11
11
  };
12
- var _ = (n, t, e) => (st(n, t, "access private method"), e);
12
+ var g = (n, t, e) => (st(n, t, "access private method"), e);
13
13
  import { FeeOption as H, BaseDecimal as m, Chain as i, ChainToRPC as it, MemoType as p } from "@swapkit/types";
14
- const St = (n) => {
14
+ const vt = (n) => {
15
15
  if (n < 0)
16
16
  throw new Error("Invalid number of year");
17
17
  return 10 + n;
18
- }, vt = (n) => {
18
+ }, Vt = (n) => {
19
19
  if (n.length > 30)
20
20
  return !1;
21
21
  const t = /^[a-zA-Z0-9+_-]+$/g;
22
22
  return !!n.match(t);
23
- }, Vt = ([n, t, e, r, s]) => `${n}'/${t}'/${e}'/${r}${typeof s != "number" ? "" : `/${s}`}`, Bt = async (n, t) => {
23
+ }, Ct = ([n, t, e, r, s]) => `${n}'/${t}'/${e}'/${r}${typeof s != "number" ? "" : `/${s}`}`, Tt = async (n, t) => {
24
24
  try {
25
25
  const e = Object.entries(t || {}).reduce(
26
26
  (s, [a, c]) => (c && (s[a] = c), s),
@@ -81,7 +81,7 @@ const St = (n) => {
81
81
  default:
82
82
  return m[n];
83
83
  }
84
- }, Ct = {
84
+ }, Bt = {
85
85
  [H.Average]: 1.2,
86
86
  [H.Fast]: 1.5,
87
87
  [H.Fastest]: 2
@@ -174,31 +174,34 @@ const St = (n) => {
174
174
  var c;
175
175
  const [t, ...e] = n.split("."), r = n.includes("/"), s = e.join("."), a = (c = s == null ? void 0 : s.split("-")) == null ? void 0 : c[0];
176
176
  return { chain: t, symbol: s, ticker: a, synth: r };
177
- }, _t = ({
177
+ }, gt = new RegExp(
178
+ /(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
179
+ "gmi"
180
+ ), Et = (n) => n.filter((t) => !gt.test(t.toString())), _t = ({
178
181
  liquidityUnits: n,
179
182
  poolUnits: t,
180
183
  runeDepth: e
181
184
  }) => {
182
185
  const r = h(n), s = h(t), a = h(e), c = r.mul(a), o = s.mul(s).mul(2), u = s.mul(r).mul(2), l = r.mul(r), d = s.mul(s).mul(s);
183
186
  return c.mul(o.sub(u).add(l)).div(d);
184
- }, gt = ({
187
+ }, pt = ({
185
188
  liquidityUnits: n,
186
189
  poolUnits: t,
187
190
  assetDepth: e
188
191
  }) => {
189
192
  const r = h(n), s = h(t), a = h(e), c = r.mul(a), o = s.mul(s).mul(2), u = s.mul(r).mul(2), l = r.mul(r), d = c.mul(o.sub(u).add(l)), A = s.mul(s).mul(s);
190
193
  return d.div(A);
191
- }, Tt = ({
194
+ }, Ot = ({
192
195
  percent: n,
193
196
  runeDepth: t,
194
197
  liquidityUnits: e,
195
198
  poolUnits: r
196
- }) => _t({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), Et = ({
199
+ }) => _t({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), Mt = ({
197
200
  percent: n,
198
201
  assetDepth: t,
199
202
  liquidityUnits: e,
200
203
  poolUnits: r
201
- }) => gt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), h = (n) => new wt({ value: n, decimal: m.THOR }), pt = ({
204
+ }) => pt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), h = (n) => new bt({ value: n, decimal: m.THOR }), ft = ({
202
205
  liquidityUnits: n,
203
206
  poolUnits: t,
204
207
  runeDepth: e,
@@ -206,17 +209,17 @@ const St = (n) => {
206
209
  }) => ({
207
210
  assetAmount: h(r).mul(n).div(t),
208
211
  runeAmount: h(e).mul(n).div(t)
209
- }), Ot = ({
212
+ }), Nt = ({
210
213
  liquidityUnits: n,
211
214
  poolUnits: t,
212
215
  runeDepth: e,
213
216
  assetDepth: r,
214
217
  percent: s
215
218
  }) => Object.fromEntries(
216
- Object.entries(pt({ liquidityUnits: n, poolUnits: t, runeDepth: e, assetDepth: r })).map(
219
+ Object.entries(ft({ liquidityUnits: n, poolUnits: t, runeDepth: e, assetDepth: r })).map(
217
220
  ([a, c]) => [a, c.mul(s)]
218
221
  )
219
- ), Mt = ({
222
+ ), Rt = ({
220
223
  runeDepth: n,
221
224
  poolUnits: t,
222
225
  assetDepth: e,
@@ -224,12 +227,12 @@ const St = (n) => {
224
227
  runeAmount: s,
225
228
  assetAmount: a
226
229
  }) => {
227
- const c = h(n), o = h(e), u = h(t), l = h(s), d = h(a), A = l.mul(o), S = d.mul(c), R = l.mul(d), Q = c.mul(o), Z = u.mul(A.add(S.add(R.mul(2)))), tt = A.add(S.add(Q.mul(2))), U = Z.div(tt), k = h(r).add(U);
228
- if (U.baseValueNumber === 0)
230
+ const c = h(n), o = h(e), u = h(t), l = h(s), d = h(a), A = l.mul(o), S = d.mul(c), R = l.mul(d), Q = c.mul(o), Z = u.mul(A.add(S.add(R.mul(2)))), tt = A.add(S.add(Q.mul(2))), F = Z.div(tt), k = h(r).add(F);
231
+ if (F.baseValueNumber === 0)
229
232
  return k.div(u).baseValueNumber;
230
233
  const et = u.add(k);
231
234
  return k.div(et).baseValueNumber;
232
- }, Nt = ({
235
+ }, kt = ({
233
236
  runeAmount: n,
234
237
  assetAmount: t,
235
238
  runeDepth: e,
@@ -237,11 +240,11 @@ const St = (n) => {
237
240
  }) => {
238
241
  const s = h(e), a = h(r), c = h(t), o = h(n), u = c.mul(s).sub(a.mul(o)), l = a.mul(o).add(s.mul(a));
239
242
  return Math.abs(u.div(l).baseValueNumber);
240
- }, ft = ({
243
+ }, At = ({
241
244
  symbol: n,
242
245
  ticker: t,
243
246
  chain: e
244
- }) => e === "ETH" && t !== "ETH" ? `${t}-${n.slice(-3)}` : n, Rt = (n, t) => {
247
+ }) => e === "ETH" && t !== "ETH" ? `${t}-${n.slice(-3)}` : n, Ht = (n, t) => {
245
248
  switch (n) {
246
249
  case p.LEAVE:
247
250
  case p.BOND: {
@@ -261,7 +264,7 @@ const St = (n) => {
261
264
  return a ? `${n}:${e}/${r}::t:0` : `${n}:${e}.${r}:${s || ""}:t:0`;
262
265
  }
263
266
  case p.WITHDRAW: {
264
- const { chain: e, ticker: r, symbol: s, basisPoints: a, targetAssetString: c, singleSide: o } = t, u = !o && c ? `:${c}` : "", l = ft({ chain: e, symbol: s, ticker: r });
267
+ const { chain: e, ticker: r, symbol: s, basisPoints: a, targetAssetString: c, singleSide: o } = t, u = !o && c ? `:${c}` : "", l = At({ chain: e, symbol: s, ticker: r });
265
268
  return `${n}:${e}${o ? "/" : "."}${l}:${a}${u}`;
266
269
  }
267
270
  case p.OPEN_LOAN:
@@ -272,21 +275,21 @@ const St = (n) => {
272
275
  default:
273
276
  return "";
274
277
  }
275
- }, F = Object.values(i), At = (n = "") => {
278
+ }, U = Object.values(i), $t = (n = "") => {
276
279
  const t = n.toUpperCase(), [e] = t.split(".");
277
- if (F.includes(e))
280
+ if (U.includes(e))
278
281
  return !0;
279
282
  const [r] = t.split("/");
280
- if (F.includes(r))
283
+ if (U.includes(r))
281
284
  return !0;
282
285
  throw new Error(
283
286
  `Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
284
287
  );
285
- }, C = 8, I = (n) => 10n ** BigInt(n), v = (n) => Math.log10(parseFloat(n.toString()));
288
+ }, T = 8, I = (n) => 10n ** BigInt(n), v = (n) => Math.log10(parseFloat(n.toString()));
286
289
  function G({
287
290
  value: n,
288
- bigIntDecimal: t = C,
289
- decimal: e = C
291
+ bigIntDecimal: t = T,
292
+ decimal: e = T
290
293
  }) {
291
294
  const r = n < 0n;
292
295
  let s = n.toString().substring(r ? 1 : 0);
@@ -299,8 +302,8 @@ function G({
299
302
  ""
300
303
  );
301
304
  }
302
- var w, V, M, J, N, z, E, L, b, B, O, x;
303
- const y = class y {
305
+ var w, V, M, J, N, z, E, D, b, C, O, L;
306
+ const B = class B {
304
307
  constructor(t) {
305
308
  $(this, w);
306
309
  $(this, M);
@@ -308,16 +311,16 @@ const y = class y {
308
311
  $(this, E);
309
312
  $(this, b);
310
313
  $(this, O);
311
- g(this, "decimalMultiplier", 10n ** 8n);
312
- g(this, "bigIntValue", 0n);
313
- g(this, "decimal");
314
+ _(this, "decimalMultiplier", 10n ** 8n);
315
+ _(this, "bigIntValue", 0n);
316
+ _(this, "decimal");
314
317
  const e = P(t);
315
318
  this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = I(
316
- Math.max(_(this, O, x).call(this, _(this, b, B).call(this, e)), this.decimal || 0)
317
- ), _(this, M, J).call(this, e);
319
+ Math.max(g(this, O, L).call(this, g(this, b, C).call(this, e)), this.decimal || 0)
320
+ ), g(this, M, J).call(this, e);
318
321
  }
319
322
  static fromBigInt(t, e) {
320
- return new y({
323
+ return new B({
321
324
  decimal: e,
322
325
  value: G({ value: t, bigIntDecimal: e, decimal: e })
323
326
  });
@@ -327,17 +330,26 @@ const y = class y {
327
330
  from: e,
328
331
  to: r
329
332
  }) {
330
- return y.fromBigInt(
331
- new y(t).bigIntValue * I(r) / I(e),
333
+ return B.fromBigInt(
334
+ new B(t).bigIntValue * I(r) / I(e),
332
335
  r
333
336
  );
334
337
  }
338
+ /**
339
+ * @deprecated Use `getBaseValue('string')` instead
340
+ */
335
341
  get baseValue() {
336
342
  return this.getBaseValue("string");
337
343
  }
344
+ /**
345
+ * @deprecated Use `getBaseValue('number')` instead
346
+ */
338
347
  get baseValueNumber() {
339
348
  return this.getBaseValue("number");
340
349
  }
350
+ /**
351
+ * @deprecated Use `getBaseValue('bigint')` instead
352
+ */
341
353
  get baseValueBigInt() {
342
354
  return this.getBaseValue("bigint");
343
355
  }
@@ -345,16 +357,16 @@ const y = class y {
345
357
  return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
346
358
  }
347
359
  add(...t) {
348
- return _(this, w, V).call(this, "add", ...t);
360
+ return g(this, w, V).call(this, "add", ...t);
349
361
  }
350
362
  sub(...t) {
351
- return _(this, w, V).call(this, "sub", ...t);
363
+ return g(this, w, V).call(this, "sub", ...t);
352
364
  }
353
365
  mul(...t) {
354
- return _(this, w, V).call(this, "mul", ...t);
366
+ return g(this, w, V).call(this, "mul", ...t);
355
367
  }
356
368
  div(...t) {
357
- return _(this, w, V).call(this, "div", ...t);
369
+ return g(this, w, V).call(this, "div", ...t);
358
370
  }
359
371
  gt(t) {
360
372
  return this.bigIntValue > this.getBigIntValue(t);
@@ -397,10 +409,10 @@ const y = class y {
397
409
  }
398
410
  }
399
411
  getBigIntValue(t, e) {
400
- return !e && typeof t == "object" ? t.bigIntValue : _(this, E, L).call(this, _(this, b, B).call(this, P(t)), e);
412
+ return !e && typeof t == "object" ? t.bigIntValue : g(this, E, D).call(this, g(this, b, C).call(this, P(t)), e);
401
413
  }
402
414
  formatBigIntToSafeValue(t, e) {
403
- const r = e || this.decimal || C, s = Math.max(
415
+ const r = e || this.decimal || T, s = Math.max(
404
416
  r,
405
417
  v(this.decimalMultiplier)
406
418
  ), a = t < 0n, c = t.toString().substring(a ? 1 : 0), o = s - (c.length - 1), u = o > 0 ? "0".repeat(o) + c : c, l = u.length - s;
@@ -429,7 +441,7 @@ const y = class y {
429
441
  }
430
442
  };
431
443
  w = new WeakSet(), V = function(t, ...e) {
432
- const r = _(this, N, z).call(this, this, ...e), s = I(r), a = e.reduce(
444
+ const r = g(this, N, z).call(this, this, ...e), s = I(r), a = e.reduce(
433
445
  (o, u) => {
434
446
  const l = this.getBigIntValue(u, r);
435
447
  switch (t) {
@@ -457,61 +469,65 @@ w = new WeakSet(), V = function(t, ...e) {
457
469
  });
458
470
  return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() });
459
471
  }, M = new WeakSet(), J = function(t) {
460
- const e = _(this, b, B).call(this, t) || "0";
461
- this.bigIntValue = _(this, E, L).call(this, e);
472
+ const e = g(this, b, C).call(this, t) || "0";
473
+ this.bigIntValue = g(this, E, D).call(this, e);
462
474
  }, N = new WeakSet(), z = function(...t) {
463
475
  const e = t.map(
464
- (r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) : _(this, O, x).call(this, _(this, b, B).call(this, r))
476
+ (r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) : g(this, O, L).call(this, g(this, b, C).call(this, r))
465
477
  ).filter(Boolean);
466
- return Math.max(...e, C);
467
- }, E = new WeakSet(), L = function(t, e) {
478
+ return Math.max(...e, T);
479
+ }, E = new WeakSet(), D = function(t, e) {
468
480
  const r = e ? I(e) : this.decimalMultiplier, s = v(r), [a, c = ""] = t.split(".");
469
481
  return BigInt(`${a}${c.padEnd(s, "0")}`);
470
- }, b = new WeakSet(), B = function(t) {
482
+ }, b = new WeakSet(), C = function(t) {
471
483
  const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
472
484
  useGrouping: !1,
473
485
  maximumFractionDigits: 20
474
486
  }) : P(t)}`.replaceAll(",", ".").split(".");
475
487
  return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0];
476
- }, O = new WeakSet(), x = function(t) {
488
+ }, O = new WeakSet(), L = function(t) {
477
489
  var r;
478
490
  const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
479
- return Math.max(e, C);
491
+ return Math.max(e, T);
480
492
  };
481
- let T = y;
493
+ let y = B;
482
494
  function P(n) {
483
495
  return typeof n == "object" ? "getValue" in n ? n.getValue("string") : n.value : n;
484
496
  }
485
497
  let j;
486
- const D = (n) => {
498
+ const x = (n) => {
487
499
  if (!j)
488
500
  throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
489
501
  return j.get(n.toUpperCase()) || { decimal: m.THOR, identifier: "" };
490
502
  }, W = async (n, t = 0) => {
491
- At(n);
503
+ $t(n);
492
504
  const e = await K(q(n));
493
505
  return new f({ decimal: e, value: t, identifier: n });
494
506
  };
495
- class f extends T {
507
+ class f extends y {
496
508
  constructor(e) {
497
509
  super(
498
- e.value instanceof T ? e.value : { decimal: e.decimal, value: e.value }
510
+ e.value instanceof y ? e.value : { decimal: e.decimal, value: e.value }
499
511
  );
500
- g(this, "address");
501
- g(this, "chain");
502
- g(this, "isSynthetic", !1);
503
- g(this, "isGasAsset", !1);
504
- g(this, "symbol");
505
- g(this, "ticker");
506
- g(this, "type");
512
+ _(this, "address");
513
+ _(this, "chain");
514
+ _(this, "isSynthetic", !1);
515
+ _(this, "isGasAsset", !1);
516
+ _(this, "symbol");
517
+ _(this, "ticker");
518
+ _(this, "type");
507
519
  const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, s = q(r);
508
520
  this.type = mt(s), this.chain = s.chain, this.ticker = s.ticker, this.symbol = s.symbol, this.address = s.address, this.isSynthetic = s.isSynthetic, this.isGasAsset = s.isGasAsset;
509
521
  }
510
522
  get assetValue() {
511
523
  return `${this.getValue("string")} ${this.ticker}`;
512
524
  }
513
- toString() {
514
- return `${this.chain}.${this.symbol}`;
525
+ toString(e = !1) {
526
+ const r = this.isSynthetic ? this.ticker : `${this.chain}.${this.ticker}`;
527
+ return e ? r : (
528
+ // THOR.ETH/ETH | ETH.USDT-0x1234567890
529
+ `${this.chain}.${this.symbol}`
530
+ );
515
531
  }
516
532
  eq({ chain: e, symbol: r }) {
517
533
  return this.chain === e && this.symbol === r;
@@ -520,7 +536,7 @@ class f extends T {
520
536
  return W(e, r);
521
537
  }
522
538
  static fromStringSync(e, r = 0) {
523
- const { decimal: s, identifier: a } = D(
539
+ const { decimal: s, identifier: a } = x(
524
540
  e
525
541
  );
526
542
  return a ? new f({ decimal: s, identifier: a, value: r }) : void 0;
@@ -529,7 +545,7 @@ class f extends T {
529
545
  return W(e, r);
530
546
  }
531
547
  static fromIdentifierSync(e, r = 0) {
532
- const { decimal: s, identifier: a } = D(e);
548
+ const { decimal: s, identifier: a } = x(e);
533
549
  return new f({ decimal: s, identifier: a, value: r });
534
550
  }
535
551
  static fromChainOrSignature(e, r = 0) {
@@ -541,7 +557,7 @@ class f extends T {
541
557
  return new f({ value: a, identifier: e, decimal: s });
542
558
  }
543
559
  static fromTCQuoteStatic(e, r = 0) {
544
- const s = D(e), a = this.shiftDecimals({
560
+ const s = x(e), a = this.shiftDecimals({
545
561
  value: r,
546
562
  from: m.THOR,
547
563
  to: s.decimal
@@ -577,7 +593,7 @@ class f extends T {
577
593
  );
578
594
  }
579
595
  }
580
- const kt = (n) => {
596
+ const Pt = (n) => {
581
597
  const t = f.fromChainOrSignature(n);
582
598
  switch (n) {
583
599
  case i.Bitcoin:
@@ -605,7 +621,7 @@ const kt = (n) => {
605
621
  symbol: c ? `${a}-${(c == null ? void 0 : c.toLowerCase()) ?? ""}` : s,
606
622
  ticker: t ? s : a
607
623
  };
608
- }, $t = {
624
+ }, wt = {
609
625
  /**
610
626
  * Core
611
627
  */
@@ -664,39 +680,40 @@ const kt = (n) => {
664
680
  };
665
681
  class X extends Error {
666
682
  constructor(t, e) {
667
- console.error(e), super(t, { cause: { code: $t[t], message: t } }), Object.setPrototypeOf(this, X.prototype);
683
+ console.error(e), super(t, { cause: { code: wt[t], message: t } }), Object.setPrototypeOf(this, X.prototype);
668
684
  }
669
685
  }
670
- class wt extends T {
686
+ class bt extends y {
671
687
  eq(t) {
672
688
  return this.eqValue(t);
673
689
  }
674
690
  }
675
691
  export {
676
692
  f as AssetValue,
677
- T as BigIntArithmetics,
693
+ y as BigIntArithmetics,
678
694
  X as SwapKitError,
679
- wt as SwapKitNumber,
695
+ bt as SwapKitNumber,
680
696
  yt as assetFromString,
681
- Vt as derivationPathToString,
697
+ Ct as derivationPathToString,
698
+ Et as filterAssets,
682
699
  G as formatBigIntToSafeValue,
683
- Ct as gasFeeMultiplier,
700
+ Bt as gasFeeMultiplier,
684
701
  mt as getAssetType,
685
- gt as getAsymmetricAssetShare,
686
- Et as getAsymmetricAssetWithdrawAmount,
702
+ pt as getAsymmetricAssetShare,
703
+ Mt as getAsymmetricAssetWithdrawAmount,
687
704
  _t as getAsymmetricRuneShare,
688
- Tt as getAsymmetricRuneWithdrawAmount,
705
+ Ot as getAsymmetricRuneWithdrawAmount,
689
706
  ht as getCommonAssetInfo,
690
707
  K as getDecimal,
691
- Mt as getEstimatedPoolShare,
692
- Nt as getLiquiditySlippage,
693
- Rt as getMemoFor,
694
- kt as getMinAmountByChain,
695
- Bt as getRequest,
696
- pt as getSymmetricPoolShare,
697
- Ot as getSymmetricWithdraw,
698
- St as getTHORNameCost,
708
+ Rt as getEstimatedPoolShare,
709
+ kt as getLiquiditySlippage,
710
+ Ht as getMemoFor,
711
+ Pt as getMinAmountByChain,
712
+ Tt as getRequest,
713
+ ft as getSymmetricPoolShare,
714
+ Nt as getSymmetricWithdraw,
715
+ vt as getTHORNameCost,
699
716
  dt as isGasAsset,
700
717
  at as postRequest,
701
- vt as validateTHORName
718
+ Vt as validateTHORName
702
719
  };
package/package.json CHANGED
@@ -6,15 +6,15 @@
6
6
  "vite": "4.4.9",
7
7
  "vitest": "0.34.4",
8
8
  "@internal/config": "0.0.0-internal.0",
9
- "@swapkit/tokens": "1.0.0-rc.4",
10
- "@swapkit/types": "1.0.0-rc.4"
9
+ "@swapkit/tokens": "1.0.0-rc.5",
10
+ "@swapkit/types": "1.0.0-rc.5"
11
11
  },
12
12
  "eslintConfig": {
13
13
  "extends": "../../../internal/eslint-config"
14
14
  },
15
15
  "peerDependencies": {
16
- "@swapkit/tokens": "1.0.0-rc.4",
17
- "@swapkit/types": "1.0.0-rc.4"
16
+ "@swapkit/tokens": "1.0.0-rc.5",
17
+ "@swapkit/types": "1.0.0-rc.5"
18
18
  },
19
19
  "exports": {
20
20
  ".": {
@@ -39,7 +39,7 @@
39
39
  "repository": "https://github.com/thorswap/SwapKit.git",
40
40
  "type": "module",
41
41
  "types": "./dist/index.d.ts",
42
- "version": "1.0.0-rc.5",
42
+ "version": "1.0.0-rc.6",
43
43
  "scripts": {
44
44
  "build": "vite build",
45
45
  "clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
@@ -1,6 +1,8 @@
1
1
  import type { EVMChain } from '@swapkit/types';
2
2
  import { BaseDecimal, Chain, ChainToRPC, FeeOption } from '@swapkit/types';
3
3
 
4
+ import type { AssetValue } from '../index.ts';
5
+
4
6
  import { postRequest } from './others.ts';
5
7
 
6
8
  const getDecimalMethodHex = '0x313ce567';
@@ -181,3 +183,10 @@ export const assetFromString = (assetString: string) => {
181
183
 
182
184
  return { chain, symbol, ticker, synth };
183
185
  };
186
+
187
+ const potentialScamRegex = new RegExp(
188
+ /(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
189
+ 'gmi',
190
+ );
191
+ export const filterAssets = (assets: AssetValue[]) =>
192
+ assets.filter((asset) => !potentialScamRegex.test(asset.toString()));
@@ -13,6 +13,10 @@ describe('AssetValue', () => {
13
13
  symbol: 'USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e',
14
14
  });
15
15
  expect(fakeAvaxUSDCAsset.assetValue).toBe('1234567890 USDC');
16
+ expect(fakeAvaxUSDCAsset.toString()).toBe(
17
+ 'AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e',
18
+ );
19
+ expect(fakeAvaxUSDCAsset.toString(true)).toBe('AVAX.USDC');
16
20
 
17
21
  const thor = AssetValue.fromChainOrSignature('ETH.THOR');
18
22
  expect(thor.assetValue).toBe('0 THOR');
@@ -26,6 +30,8 @@ describe('AssetValue', () => {
26
30
 
27
31
  expect(ethSynth.assetValue).toBe('1234567890 ETH/ETH');
28
32
  expect(ethSynth.toString()).toBe('THOR.ETH/ETH');
33
+ expect(ethSynth.toString(true)).toBe('ETH/ETH');
34
+ expect(ethSynth.mul(21.37).getValue('string')).toBe('26382715809.3');
29
35
 
30
36
  const atomDerived = new AssetValue({
31
37
  identifier: 'THOR.ATOM',
@@ -35,6 +41,7 @@ describe('AssetValue', () => {
35
41
 
36
42
  expect(atomDerived.assetValue).toBe('123456789 ATOM');
37
43
  expect(atomDerived.toString()).toBe('THOR.ATOM');
44
+ expect(atomDerived.toString(true)).toBe('THOR.ATOM');
38
45
  });
39
46
  });
40
47
 
@@ -91,8 +91,14 @@ export class AssetValue extends BigIntArithmetics {
91
91
  return `${this.getValue('string')} ${this.ticker}`;
92
92
  }
93
93
 
94
- toString() {
95
- return `${this.chain}.${this.symbol}`;
94
+ toString(short = false) {
95
+ // THOR.RUNE | ETH/ETH
96
+ const shortFormat = this.isSynthetic ? this.ticker : `${this.chain}.${this.ticker}`;
97
+
98
+ return short
99
+ ? shortFormat
100
+ : // THOR.ETH/ETH | ETH.USDT-0x1234567890
101
+ `${this.chain}.${this.symbol}`;
96
102
  }
97
103
 
98
104
  eq({ chain, symbol }: { chain: Chain; symbol: string }) {
@@ -90,12 +90,21 @@ export class BigIntArithmetics {
90
90
  this.#setValue(value);
91
91
  }
92
92
 
93
+ /**
94
+ * @deprecated Use `getBaseValue('string')` instead
95
+ */
93
96
  get baseValue() {
94
97
  return this.getBaseValue('string') as string;
95
98
  }
99
+ /**
100
+ * @deprecated Use `getBaseValue('number')` instead
101
+ */
96
102
  get baseValueNumber() {
97
103
  return this.getBaseValue('number') as number;
98
104
  }
105
+ /**
106
+ * @deprecated Use `getBaseValue('bigint')` instead
107
+ */
99
108
  get baseValueBigInt() {
100
109
  return this.getBaseValue('bigint') as bigint;
101
110
  }