@swapkit/helpers 1.0.0-rc.7 → 1.0.0-rc.8

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 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},z=({chain:n,symbol:e})=>{switch(n){case r.Chain.Bitcoin:case r.Chain.BitcoinCash:case r.Chain.Litecoin:case r.Chain.Dogecoin:case r.Chain.Binance:case r.Chain.Ethereum:case r.Chain.Avalanche:return e===n;case r.Chain.Arbitrum:case r.Chain.Optimism:return e==="ETH";case r.Chain.Maya:return e==="CACAO";case r.Chain.Kujira:return e==="KUJI";case r.Chain.Cosmos:return e==="ATOM";case r.Chain.Polygon:return e==="MATIC";case r.Chain.BinanceSmartChain:return e==="BNB";case r.Chain.THORChain:return e==="RUNE"}},J=n=>{switch(n){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case r.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:r.BaseDecimal[n]};case r.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:r.BaseDecimal[n]};case r.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:r.BaseDecimal[n]};case r.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:r.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case r.Chain.Kujira:case r.Chain.Arbitrum:case r.Chain.Optimism:case r.Chain.BitcoinCash:case r.Chain.Litecoin:case r.Chain.Dogecoin:case r.Chain.Binance:case r.Chain.Avalanche:case r.Chain.Polygon:case r.Chain.Bitcoin:case r.Chain.Ethereum:return{identifier:`${n}.${n}`,decimal:r.BaseDecimal[n]}}},Q=({chain:n,symbol:e})=>{if(e.includes("/"))return"Synth";switch(n){case r.Chain.Bitcoin:case r.Chain.BitcoinCash:case r.Chain.Dogecoin:case r.Chain.Litecoin:case r.Chain.Maya:case r.Chain.THORChain:return"Native";case r.Chain.Cosmos:return e==="ATOM"?"Native":r.Chain.Cosmos;case r.Chain.Kujira:return e===r.Chain.Kujira?"Native":r.Chain.Kujira;case r.Chain.Binance:return e===r.Chain.Binance?"Native":"BEP2";case r.Chain.BinanceSmartChain:return e===r.Chain.Binance?"Native":"BEP20";case r.Chain.Ethereum:return e===r.Chain.Ethereum?"Native":"ERC20";case r.Chain.Avalanche:return e===r.Chain.Avalanche?"Native":r.Chain.Avalanche;case r.Chain.Polygon:return e===r.Chain.Polygon?"Native":"POLYGON";case r.Chain.Arbitrum:return[r.Chain.Ethereum,r.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case r.Chain.Optimism:return[r.Chain.Ethereum,r.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Ie=n=>{var c;const[e,...t]=n.split("."),i=n.includes("/"),a=t.join("."),s=(c=a==null?void 0:a.split("-"))==null?void 0:c[0];return{chain:e,symbol:a,ticker:s,synth:i}},Te=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),ve=n=>n.filter(e=>!Te.test(e.toString())&&!e.toString().includes("undefined")),X=({liquidityUnits:n,poolUnits:e,runeDepth:t})=>{const i=d(n),a=d(e),s=d(t),c=i.mul(s),o=a.mul(a).mul(2),l=a.mul(i).mul(2),u=i.mul(i),h=a.mul(a).mul(a);return c.mul(o.sub(l).add(u)).div(h)},Z=({liquidityUnits:n,poolUnits:e,assetDepth:t})=>{const i=d(n),a=d(e),s=d(t),c=i.mul(s),o=a.mul(a).mul(2),l=a.mul(i).mul(2),u=i.mul(i),h=c.mul(o.sub(l).add(u)),p=a.mul(a).mul(a);return h.div(p)},Me=({percent:n,runeDepth:e,liquidityUnits:t,poolUnits:i})=>X({runeDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),Ve=({percent:n,assetDepth:e,liquidityUnits:t,poolUnits:i})=>Z({assetDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),d=n=>new ie({value:n,decimal:r.BaseDecimal.THOR}),ee=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})=>({assetAmount:d(i).mul(n).div(e),runeAmount:d(t).mul(n).div(e)}),Oe=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i,percent:a})=>Object.fromEntries(Object.entries(ee({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})).map(([s,c])=>[s,c.mul(a)])),Ee=({runeDepth:n,poolUnits:e,assetDepth:t,liquidityUnits:i,runeAmount:a,assetAmount:s})=>{const c=d(n),o=d(t),l=d(e),u=d(a),h=d(s),p=u.mul(o),$=h.mul(c),E=u.mul(h),ae=c.mul(o),re=l.mul(p.add($.add(E.mul(2)))),se=p.add($.add(ae.mul(2))),W=re.div(se),N=d(i).add(W);if(W.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""}},G=Object.values(r.Chain),Pe=(n="")=>{const e=n.toUpperCase(),[t]=e.split(".");if(G.includes(t))return!0;const[i]=e.split("/");if(G.includes(i))return!0;throw new Error(`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},I=8,S=n=>10n**BigInt(n),b=n=>Math.log10(parseFloat(n.toString()));function 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){if(!t&&typeof e=="object")return e.bigIntValue;const i=D(e),a=m(this,A,y).call(this,i);return a==="0"||a==="undefined"?0n:m(this,v,H).call(this,a,t)}formatBigIntToSafeValue(e,t){const i=t||this.decimal||I,a=Math.max(i,b(this.decimalMultiplier)),s=e<0n,c=e.toString().substring(s?1:0),o=a-(c.length-1),l=o>0?"0".repeat(o)+c:c,u=l.length-a;let h=l.slice(-a);return parseInt(h[i])>=5?h=`${h.substring(0,i-1)}${(parseInt(h[i-1])+1).toString()}`:h=h.substring(0,i),`${s?"-":""}${l.slice(0,u)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,i]=this.getValue("string").split("."),a=t||"",s=i||"",c=parseInt(a)?a.length+s.length:s.length;if(c<=e)return this.getValue("string");if(a.length>=e)return a.slice(0,e).padEnd(a.length,"0");if(parseInt(a))return`${a}.${s.slice(0,e-a.length)}`.padEnd(c-e,"0");const o=parseInt(s),l=`${o}`.slice(0,e);return`0.${l.padStart(s.length-`${o}`.length+l.length,"0")}`}};f=new WeakSet,B=function(e,...t){const i=m(this,O,ne).call(this,this,...t),a=S(i),s=t.reduce((o,l)=>{const u=this.getBigIntValue(l,i);switch(e){case"add":return o+u;case"sub":return o-u;case"mul":return o*u/a;case"div":{if(u===0n)throw new RangeError("Division by zero");return o*a/u}default:return o}},this.bigIntValue*a/this.decimalMultiplier),c=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:""}},U=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=Q(a),this.chain=a.chain,this.ticker=a.ticker,this.symbol=a.symbol,this.address=a.address,this.isSynthetic=a.isSynthetic,this.isGasAsset=a.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const i=this.isSynthetic?this.ticker:`${this.chain}.${this.ticker}`;return t?i:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:i}){return this.chain===t&&this.symbol===i}static async fromString(t,i=0){return U(t,i)}static fromStringSync(t,i=0){const{decimal:a,identifier:s}=P(t);return s?new _({decimal:a,identifier:s,value:i}):void 0}static async fromIdentifier(t,i=0){return U(t,i)}static fromIdentifierSync(t,i=0){const{decimal:a,identifier:s}=P(t);return new _({decimal:a,identifier:s,value:i})}static fromChainOrSignature(t,i=0){const{decimal:a,identifier:s}=J(t);return new _({value:i,decimal:a,identifier:s})}static async fromTCQuote(t,i=0){const a=await q(j(t)),s=this.shiftDecimals({value:i,from:r.BaseDecimal.THOR,to:a});return new _({value:s,identifier:t,decimal:a})}static fromTCQuoteStatic(t,i=0){const a=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:z({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=Q;exports.getAsymmetricAssetShare=Z;exports.getAsymmetricAssetWithdrawAmount=Ve;exports.getAsymmetricRuneShare=X;exports.getAsymmetricRuneWithdrawAmount=Me;exports.getCommonAssetInfo=J;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=z;exports.postRequest=K;exports.validateTHORName=fe;
1
+ "use strict";var oe=Object.create;var N=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var he=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var me=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var ge=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ue(e))!de.call(n,a)&&a!==t&&N(n,a,{get:()=>e[a],enumerable:!(i=le(e,a))||i.enumerable});return n};var _e=(n,e,t)=>(t=n!=null?oe(he(n)):{},ge(e||!n||!n.__esModule?N(t,"default",{value:n,enumerable:!0}):t,n));var g=(n,e,t)=>(me(n,typeof e!="symbol"?e+"":e,t),t),pe=(n,e,t)=>{if(!e.has(n))throw TypeError("Cannot "+t)};var C=(n,e,t)=>{if(e.has(n))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(n):e.set(n,t)};var m=(n,e,t)=>(pe(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("@swapkit/types"),Ce=n=>{if(n<0)throw new Error("Invalid number of year");return 10+n},fe=n=>{if(n.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!n.match(e)},Ae=([n,e,t,i,a])=>`${n}'/${e}'/${t}'/${i}${typeof a!="number"?"":`/${a}`}`,Se=async(n,e)=>{try{const t=Object.entries(e||{}).reduce((a,[s,c])=>(c&&(a[s]=c),a),{});return(await fetch(`${n}${e?`?${new URLSearchParams(t).toString()}`:""}`,{method:"GET",mode:"cors",credentials:"omit",referrer:"https://sk.thorswap.net"})).json()}catch(t){return console.error(t),{}}},K=async(n,e,t,i=!1)=>{try{const a=await fetch(`${n}`,{body:e,headers:t,method:"POST",referrer:"https://sk.thorswap.net"});return i?a.text():a.json()}catch{return{}}},we="0x313ce567",Y=async({chain:n,to:e})=>{try{const t=await K(r.ChainToRPC[n],JSON.stringify({method:"eth_call",params:[{to:e.toLowerCase(),data:we},"latest"],id:44,jsonrpc:"2.0"}),{accept:"*/*","cache-control":"no-cache","content-type":"application/json"},!0),{result:i}=JSON.parse(t);return parseInt(BigInt(i).toString())}catch(t){return console.error(t),r.BaseDecimal[n]}},$e=async n=>{if(n===r.Chain.Ethereum)return r.BaseDecimal.ETH;const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?Y({chain:r.Chain.Ethereum,to:e}):r.BaseDecimal.ETH},Be=async n=>{const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?Y({chain:r.Chain.Avalanche,to:e.toLowerCase()}):r.BaseDecimal.AVAX},be=async n=>(n===r.Chain.BinanceSmartChain,r.BaseDecimal.BSC),q=async({chain:n,symbol:e})=>{switch(n){case r.Chain.Ethereum:return $e(e);case r.Chain.Avalanche:return Be(e);case r.Chain.BinanceSmartChain:return be(e);default:return r.BaseDecimal[n]}},ye={[r.FeeOption.Average]:1.2,[r.FeeOption.Fast]:1.5,[r.FeeOption.Fastest]:2},z=({chain:n,symbol:e})=>{switch(n){case r.Chain.Bitcoin:case r.Chain.BitcoinCash:case r.Chain.Litecoin:case r.Chain.Dogecoin:case r.Chain.Binance:case r.Chain.Ethereum:case r.Chain.Avalanche:return e===n;case r.Chain.Arbitrum:case r.Chain.Optimism:return e==="ETH";case r.Chain.Maya:return e==="CACAO";case r.Chain.Kujira:return e==="KUJI";case r.Chain.Cosmos:return e==="ATOM";case r.Chain.Polygon:return e==="MATIC";case r.Chain.BinanceSmartChain:return e==="BNB";case r.Chain.THORChain:return e==="RUNE"}},J=n=>{switch(n){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case r.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:r.BaseDecimal[n]};case r.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:r.BaseDecimal[n]};case r.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:r.BaseDecimal[n]};case r.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:r.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case r.Chain.Kujira:case r.Chain.Arbitrum:case r.Chain.Optimism:case r.Chain.BitcoinCash:case r.Chain.Litecoin:case r.Chain.Dogecoin:case r.Chain.Binance:case r.Chain.Avalanche:case r.Chain.Polygon:case r.Chain.Bitcoin:case r.Chain.Ethereum:return{identifier:`${n}.${n}`,decimal:r.BaseDecimal[n]}}},Q=({chain:n,symbol:e})=>{if(e.includes("/"))return"Synth";switch(n){case r.Chain.Bitcoin:case r.Chain.BitcoinCash:case r.Chain.Dogecoin:case r.Chain.Litecoin:case r.Chain.Maya:case r.Chain.THORChain:return"Native";case r.Chain.Cosmos:return e==="ATOM"?"Native":r.Chain.Cosmos;case r.Chain.Kujira:return e===r.Chain.Kujira?"Native":r.Chain.Kujira;case r.Chain.Binance:return e===r.Chain.Binance?"Native":"BEP2";case r.Chain.BinanceSmartChain:return e===r.Chain.Binance?"Native":"BEP20";case r.Chain.Ethereum:return e===r.Chain.Ethereum?"Native":"ERC20";case r.Chain.Avalanche:return e===r.Chain.Avalanche?"Native":r.Chain.Avalanche;case r.Chain.Polygon:return e===r.Chain.Polygon?"Native":"POLYGON";case r.Chain.Arbitrum:return[r.Chain.Ethereum,r.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case r.Chain.Optimism:return[r.Chain.Ethereum,r.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Ie=n=>{var c;const[e,...t]=n.split("."),i=n.includes("/"),a=t.join("."),s=(c=a==null?void 0:a.split("-"))==null?void 0:c[0];return{chain:e,symbol:a,ticker:s,synth:i}},Te=new RegExp(/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,"gmi"),ve=n=>n.filter(e=>!Te.test(e.toString())&&!e.toString().includes("undefined")),X=({liquidityUnits:n,poolUnits:e,runeDepth:t})=>{const i=d(n),a=d(e),s=d(t),c=i.mul(s),o=a.mul(a).mul(2),l=a.mul(i).mul(2),u=i.mul(i),h=a.mul(a).mul(a);return c.mul(o.sub(l).add(u)).div(h)},Z=({liquidityUnits:n,poolUnits:e,assetDepth:t})=>{const i=d(n),a=d(e),s=d(t),c=i.mul(s),o=a.mul(a).mul(2),l=a.mul(i).mul(2),u=i.mul(i),h=c.mul(o.sub(l).add(u)),p=a.mul(a).mul(a);return h.div(p)},Me=({percent:n,runeDepth:e,liquidityUnits:t,poolUnits:i})=>X({runeDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),Ve=({percent:n,assetDepth:e,liquidityUnits:t,poolUnits:i})=>Z({assetDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),d=n=>new ie({value:n,decimal:r.BaseDecimal.THOR}),ee=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})=>({assetAmount:d(i).mul(n).div(e),runeAmount:d(t).mul(n).div(e)}),Oe=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i,percent:a})=>Object.fromEntries(Object.entries(ee({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})).map(([s,c])=>[s,c.mul(a)])),Ee=({runeDepth:n,poolUnits:e,assetDepth:t,liquidityUnits:i,runeAmount:a,assetAmount:s})=>{const c=d(n),o=d(t),l=d(e),u=d(a),h=d(s),p=u.mul(o),$=h.mul(c),E=u.mul(h),ae=c.mul(o),re=l.mul(p.add($.add(E.mul(2)))),se=p.add($.add(ae.mul(2))),W=re.div(se),R=d(i).add(W);if(W.baseValueNumber===0)return R.div(l).baseValueNumber;const ce=l.add(R);return R.div(ce).baseValueNumber},Re=({runeAmount:n,assetAmount:e,runeDepth:t,assetDepth:i})=>{const a=d(t),s=d(i),c=d(e),o=d(n),l=c.mul(a).sub(s.mul(o)),u=s.mul(o).add(a.mul(s));return Math.abs(l.div(u).baseValueNumber)},Ne=({symbol:n,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${n.slice(-3)}`:n,De=(n,e)=>{switch(n){case r.MemoType.LEAVE:case r.MemoType.BOND:{const{address:t}=e;return`${n}:${t}`}case r.MemoType.UNBOND:{const{address:t,unbondAmount:i}=e;return`${n}:${t}:${i*10**8}`}case r.MemoType.THORNAME_REGISTER:{const{name:t,chain:i,address:a,owner:s}=e;return`${n}:${t}:${i}:${a}${s?`:${s}`:""}`}case r.MemoType.DEPOSIT:{const{chain:t,symbol:i,address:a,singleSide:s}=e;return s?`${n}:${t}/${i}::t:0`:`${n}:${t}.${i}:${a||""}:t:0`}case r.MemoType.WITHDRAW:{const{chain:t,ticker:i,symbol:a,basisPoints:s,targetAssetString:c,singleSide:o}=e,l=!o&&c?`:${c}`:"",u=Ne({chain:t,symbol:a,ticker:i});return`${n}:${t}${o?"/":"."}${u}:${s}${l}`}case r.MemoType.OPEN_LOAN:case r.MemoType.CLOSE_LOAN:{const{asset:t,address:i}=e;return`${n}:${t}:${i}`}default:return""}},G=Object.values(r.Chain),He=(n="")=>{const e=n.toUpperCase(),[t]=e.split(".");if(G.includes(t))return!0;const[i]=e.split("/");if(G.includes(i))return!0;throw new Error(`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},I=8,S=n=>10n**BigInt(n),B=n=>Math.log10(parseFloat(n.toString()));function P({value:n,bigIntDecimal:e=I,decimal:t=I}){const i=n<0n;let a=n.toString().substring(i?1:0);const s=t-(a.length-1);s>0&&(a="0".repeat(s)+a);const c=a.length-t;let o=a.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${i?"-":""}${a.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var f,b,V,te,O,ne,v,k,A,y,M,L;const T=class T{constructor(e){C(this,f);C(this,V);C(this,O);C(this,v);C(this,A);C(this,M);g(this,"decimalMultiplier",10n**8n);g(this,"bigIntValue",0n);g(this,"decimal");const t=D(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=S(Math.max(m(this,M,L).call(this,m(this,A,y).call(this,t)),this.decimal||0)),m(this,V,te).call(this,t)}static fromBigInt(e,t){return new T({decimal:t,value:P({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:i}){return T.fromBigInt(new T(e).bigIntValue*S(i)/S(t),i)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return m(this,f,b).call(this,"add",...e)}sub(...e){return m(this,f,b).call(this,"sub",...e)}mul(...e){return m(this,f,b).call(this,"mul",...e)}div(...e){return m(this,f,b).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||B(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue*BigInt(this.decimal||8n)/this.decimalMultiplier}}getBaseValue(e){const t=this.decimalMultiplier/S(this.decimal||r.BaseDecimal.THOR),i=this.bigIntValue/t;switch(e){case"number":return Number(i);case"string":return i.toString();default:return i}}getBigIntValue(e,t){if(!t&&typeof e=="object")return e.bigIntValue;const i=D(e),a=m(this,A,y).call(this,i);return a==="0"||a==="undefined"?0n:m(this,v,k).call(this,a,t)}formatBigIntToSafeValue(e,t){const i=t||this.decimal||I,a=Math.max(i,B(this.decimalMultiplier)),s=e<0n,c=e.toString().substring(s?1:0),o=a-(c.length-1),l=o>0?"0".repeat(o)+c:c,u=l.length-a;let h=l.slice(-a);return parseInt(h[i])>=5?h=`${h.substring(0,i-1)}${(parseInt(h[i-1])+1).toString()}`:h=h.substring(0,i),`${s?"-":""}${l.slice(0,u)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,i]=this.getValue("string").split("."),a=t||"",s=i||"",c=parseInt(a)?a.length+s.length:s.length;if(c<=e)return this.getValue("string");if(a.length>=e)return a.slice(0,e).padEnd(a.length,"0");if(parseInt(a))return`${a}.${s.slice(0,e-a.length)}`.padEnd(c-e,"0");const o=parseInt(s),l=`${o}`.slice(0,e);return`0.${l.padStart(s.length-`${o}`.length+l.length,"0")}`}};f=new WeakSet,b=function(e,...t){const i=m(this,O,ne).call(this,this,...t),a=S(i),s=t.reduce((o,l)=>{const u=this.getBigIntValue(l,i);switch(e){case"add":return o+u;case"sub":return o-u;case"mul":return o*u/a;case"div":{if(u===0n)throw new RangeError("Division by zero");return o*a/u}default:return o}},this.bigIntValue*a/this.decimalMultiplier),c=P({bigIntDecimal:i,decimal:Math.max(i,B(this.decimalMultiplier)),value:s});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},V=new WeakSet,te=function(e){const t=m(this,A,y).call(this,e)||"0";this.bigIntValue=m(this,v,k).call(this,t)},O=new WeakSet,ne=function(...e){const t=e.map(i=>typeof i=="object"?i.decimal||B(i.decimalMultiplier):m(this,M,L).call(this,m(this,A,y).call(this,i))).filter(Boolean);return Math.max(...t,I)},v=new WeakSet,k=function(e,t){const i=t?S(t):this.decimalMultiplier,a=B(i),[s="",c=""]=e.split(".");return BigInt(`${s}${c.padEnd(a,"0")}`)},A=new WeakSet,y=function(e){const i=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):D(e)}`.replaceAll(",",".").split(".");return i.length>1?`${i.slice(0,-1).join("")}.${i.at(-1)}`:i[0]},M=new WeakSet,L=function(e){var i;const t=((i=e.split(".")[1])==null?void 0:i.length)||0;return Math.max(t,I)};let w=T;function D(n){return typeof n=="object"?"getValue"in n?n.getValue("string"):n.value:n}let x;const H=n=>{if(!x)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return x.get(n.toUpperCase())||{decimal:r.BaseDecimal.THOR,identifier:""}},U=async(n,e=0)=>{He(n);const t=await q(j(n));return new _({decimal:t,value:e,identifier:n})};class _ extends w{constructor(t){super(t.value instanceof w?t.value:{decimal:t.decimal,value:t.value});g(this,"address");g(this,"chain");g(this,"isSynthetic",!1);g(this,"isGasAsset",!1);g(this,"symbol");g(this,"ticker");g(this,"type");const i="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,a=j(i);this.type=Q(a),this.chain=a.chain,this.ticker=a.ticker,this.symbol=a.symbol,this.address=a.address,this.isSynthetic=a.isSynthetic,this.isGasAsset=a.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(t=!1){const i=this.isSynthetic?this.ticker:`${this.chain}.${this.ticker}`;return t?i:`${this.chain}.${this.symbol}`}eq({chain:t,symbol:i}){return this.chain===t&&this.symbol===i}static async fromString(t,i=0){return U(t,i)}static fromStringSync(t,i=0){const{decimal:a,identifier:s}=H(t);return s?new _({decimal:a,identifier:s,value:i}):void 0}static async fromIdentifier(t,i=0){return U(t,i)}static fromIdentifierSync(t,i=0){const{decimal:a,identifier:s}=H(t);return new _({decimal:a,identifier:s,value:i})}static fromChainOrSignature(t,i=0){const{decimal:a,identifier:s}=J(t);return new _({value:i,decimal:a,identifier:s})}static async fromTCQuote(t,i=0){const a=await q(j(t)),s=this.shiftDecimals({value:i,from:r.BaseDecimal.THOR,to:a});return new _({value:s,identifier:t,decimal:a})}static fromTCQuoteStatic(t,i=0){const a=H(t),s=this.shiftDecimals({value:i,from:r.BaseDecimal.THOR,to:a.decimal});return new _({...a,value:s})}static async loadStaticAssets(){return new Promise(async(t,i)=>{try{const{ThorchainList:a,NativeList:s,...c}=await import("@swapkit/tokens");x=[s,...Object.values(c)].reduce((l,{tokens:u})=>(u.forEach(({identifier:h,chain:p,...$})=>{const E="decimals"in $?$.decimals:r.BaseDecimal[p];l.set(h,{identifier:h,decimal:E})}),l),new Map),t({ok:!0})}catch(a){console.error(a),i({ok:!1,error:a,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const Pe=n=>{const e=_.fromChainOrSignature(n);switch(n){case r.Chain.Bitcoin:case r.Chain.Litecoin:case r.Chain.BitcoinCash:return e.add(10001);case r.Chain.Dogecoin:return e.add(100000001);case r.Chain.Avalanche:case r.Chain.Ethereum:return e.add(10*10**9);case r.Chain.THORChain:case r.Chain.Maya:return e.add(0);default:return e.add(1)}},j=n=>{const e=n.slice(0,14).includes("/"),t=n.includes(".")?n:`${r.Chain.THORChain}.${n}`,[i,a]=t.split("."),[s,c]=a.split("-");return{address:c==null?void 0:c.toLowerCase(),chain:i,isGasAsset:z({chain:i,symbol:a}),isSynthetic:e,symbol:c?`${s}-${(c==null?void 0:c.toLowerCase())??""}`:a,ticker:e?a:s}},ke={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class F extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ke[e],message:e}}),Object.setPrototypeOf(this,F.prototype)}}class ie extends w{eq(e){return this.eqValue(e)}}exports.AssetValue=_;exports.BigIntArithmetics=w;exports.SwapKitError=F;exports.SwapKitNumber=ie;exports.assetFromString=Ie;exports.derivationPathToString=Ae;exports.filterAssets=ve;exports.formatBigIntToSafeValue=P;exports.gasFeeMultiplier=ye;exports.getAssetType=Q;exports.getAsymmetricAssetShare=Z;exports.getAsymmetricAssetWithdrawAmount=Ve;exports.getAsymmetricRuneShare=X;exports.getAsymmetricRuneWithdrawAmount=Me;exports.getCommonAssetInfo=J;exports.getDecimal=q;exports.getEstimatedPoolShare=Ee;exports.getLiquiditySlippage=Re;exports.getMemoFor=De;exports.getMinAmountByChain=Pe;exports.getRequest=Se;exports.getSymmetricPoolShare=ee;exports.getSymmetricWithdraw=Oe;exports.getTHORNameCost=Ce;exports.isGasAsset=z;exports.postRequest=K;exports.validateTHORName=fe;
package/dist/index.d.ts CHANGED
@@ -95,7 +95,7 @@ export declare class BigIntArithmetics {
95
95
  lt(value: InitialisationValueType): boolean;
96
96
  lte(value: InitialisationValueType): boolean;
97
97
  eqValue(value: InitialisationValueType): boolean;
98
- getValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T];
98
+ getValue<T extends 'number' | 'string'>(type: T): NumberPrimitivesType[T];
99
99
  getBaseValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T];
100
100
  getBigIntValue(value: InitialisationValueType, decimal?: number): bigint;
101
101
  formatBigIntToSafeValue(value: bigint, decimal?: number): string;
package/dist/index.es.js CHANGED
@@ -15,12 +15,12 @@ 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
+ }, Ct = (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
- }, Ct = ([n, t, e, r, s]) => `${n}'/${t}'/${e}'/${r}${typeof s != "number" ? "" : `/${s}`}`, Tt = async (n, t) => {
23
+ }, Vt = ([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),
@@ -304,7 +304,7 @@ function U({
304
304
  ""
305
305
  );
306
306
  }
307
- var w, V, M, z, N, J, E, D, b, C, O, L;
307
+ var w, C, M, z, N, J, E, D, b, V, O, L;
308
308
  const B = class B {
309
309
  constructor(t) {
310
310
  $(this, w);
@@ -318,7 +318,7 @@ const B = class B {
318
318
  _(this, "decimal");
319
319
  const e = P(t);
320
320
  this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = S(
321
- Math.max(g(this, O, L).call(this, g(this, b, C).call(this, e)), this.decimal || 0)
321
+ Math.max(g(this, O, L).call(this, g(this, b, V).call(this, e)), this.decimal || 0)
322
322
  ), g(this, M, z).call(this, e);
323
323
  }
324
324
  static fromBigInt(t, e) {
@@ -359,16 +359,16 @@ const B = class B {
359
359
  return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
360
360
  }
361
361
  add(...t) {
362
- return g(this, w, V).call(this, "add", ...t);
362
+ return g(this, w, C).call(this, "add", ...t);
363
363
  }
364
364
  sub(...t) {
365
- return g(this, w, V).call(this, "sub", ...t);
365
+ return g(this, w, C).call(this, "sub", ...t);
366
366
  }
367
367
  mul(...t) {
368
- return g(this, w, V).call(this, "mul", ...t);
368
+ return g(this, w, C).call(this, "mul", ...t);
369
369
  }
370
370
  div(...t) {
371
- return g(this, w, V).call(this, "div", ...t);
371
+ return g(this, w, C).call(this, "div", ...t);
372
372
  }
373
373
  gt(t) {
374
374
  return this.bigIntValue > this.getBigIntValue(t);
@@ -396,24 +396,24 @@ const B = class B {
396
396
  case "string":
397
397
  return e;
398
398
  default:
399
- return this.bigIntValue;
399
+ return this.bigIntValue * BigInt(this.decimal || 8n) / this.decimalMultiplier;
400
400
  }
401
401
  }
402
402
  getBaseValue(t) {
403
- const e = this.decimalMultiplier / S(this.decimal || 0), r = this.bigIntValue / e;
403
+ const e = this.decimalMultiplier / S(this.decimal || m.THOR), r = this.bigIntValue / e;
404
404
  switch (t) {
405
405
  case "number":
406
406
  return Number(r);
407
407
  case "string":
408
408
  return r.toString();
409
409
  default:
410
- return this.bigIntValue;
410
+ return r;
411
411
  }
412
412
  }
413
413
  getBigIntValue(t, e) {
414
414
  if (!e && typeof t == "object")
415
415
  return t.bigIntValue;
416
- const r = P(t), s = g(this, b, C).call(this, r);
416
+ const r = P(t), s = g(this, b, V).call(this, r);
417
417
  return s === "0" || s === "undefined" ? 0n : g(this, E, D).call(this, s, e);
418
418
  }
419
419
  formatBigIntToSafeValue(t, e) {
@@ -445,7 +445,7 @@ const B = class B {
445
445
  )}`;
446
446
  }
447
447
  };
448
- w = new WeakSet(), V = function(t, ...e) {
448
+ w = new WeakSet(), C = function(t, ...e) {
449
449
  const r = g(this, N, J).call(this, this, ...e), s = S(r), a = e.reduce(
450
450
  (o, u) => {
451
451
  const l = this.getBigIntValue(u, r);
@@ -474,17 +474,17 @@ w = new WeakSet(), V = function(t, ...e) {
474
474
  });
475
475
  return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() });
476
476
  }, M = new WeakSet(), z = function(t) {
477
- const e = g(this, b, C).call(this, t) || "0";
477
+ const e = g(this, b, V).call(this, t) || "0";
478
478
  this.bigIntValue = g(this, E, D).call(this, e);
479
479
  }, N = new WeakSet(), J = function(...t) {
480
480
  const e = t.map(
481
- (r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) : g(this, O, L).call(this, g(this, b, C).call(this, r))
481
+ (r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) : g(this, O, L).call(this, g(this, b, V).call(this, r))
482
482
  ).filter(Boolean);
483
483
  return Math.max(...e, T);
484
484
  }, E = new WeakSet(), D = function(t, e) {
485
485
  const r = e ? S(e) : this.decimalMultiplier, s = v(r), [a = "", c = ""] = t.split(".");
486
486
  return BigInt(`${a}${c.padEnd(s, "0")}`);
487
- }, b = new WeakSet(), C = function(t) {
487
+ }, b = new WeakSet(), V = function(t) {
488
488
  const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
489
489
  useGrouping: !1,
490
490
  maximumFractionDigits: 20
@@ -699,7 +699,7 @@ export {
699
699
  Q as SwapKitError,
700
700
  bt as SwapKitNumber,
701
701
  yt as assetFromString,
702
- Ct as derivationPathToString,
702
+ Vt as derivationPathToString,
703
703
  Et as filterAssets,
704
704
  U as formatBigIntToSafeValue,
705
705
  Bt as gasFeeMultiplier,
@@ -720,5 +720,5 @@ export {
720
720
  vt as getTHORNameCost,
721
721
  dt as isGasAsset,
722
722
  at as postRequest,
723
- Vt as validateTHORName
723
+ Ct as validateTHORName
724
724
  };
package/package.json CHANGED
@@ -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.7",
42
+ "version": "1.0.0-rc.8",
43
43
  "scripts": {
44
44
  "build": "vite build",
45
45
  "clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
@@ -8,37 +8,40 @@ describe('SwapKitNumber', () => {
8
8
  const skNumber1 = new SwapKitNumber(1);
9
9
  expect(skNumber1.getValue('string')).toBe('1');
10
10
  expect(skNumber1.getValue('number')).toBe(1);
11
- expect(skNumber1.getValue('bigint')).toBe(100000000n);
11
+ expect(skNumber1.getBaseValue('bigint')).toBe(100000000n);
12
12
 
13
13
  const skNumber2 = new SwapKitNumber('1');
14
14
  expect(skNumber2.getValue('string')).toBe('1');
15
- expect(skNumber2.getValue('bigint')).toBe(100000000n);
15
+ expect(skNumber2.getBaseValue('bigint')).toBe(100000000n);
16
16
 
17
+ /**
18
+ * because by default we have 8 decimals - it will be rounded to 0 on base value
19
+ */
17
20
  const skNumber3 = new SwapKitNumber('0.0000000001');
18
21
  expect(skNumber3.getValue('string')).toBe('0.0000000001');
19
- expect(skNumber3.getValue('bigint')).toBe(1n);
22
+ expect(skNumber3.getBaseValue('bigint')).toBe(0n);
20
23
 
21
- const skNumber4 = new SwapKitNumber(0.000000001);
22
- expect(skNumber4.getValue('string')).toBe('0.000000001');
23
- expect(skNumber4.getValue('bigint')).toBe(1n);
24
+ const skNumber4 = new SwapKitNumber({ value: '0.0000000001', decimal: 10 });
25
+ expect(skNumber4.getValue('string')).toBe('0.0000000001');
26
+ expect(skNumber4.getBaseValue('bigint')).toBe(1n);
24
27
 
25
- const skNumber6 = new SwapKitNumber({ value: 0.1005, decimal: 3 });
26
- expect(skNumber6.getValue('string')).toBe('0.101');
27
- expect(skNumber6.getValue('bigint')).toBe(10050000n);
28
+ const skNumber5 = new SwapKitNumber({ value: 0.1005, decimal: 3 });
29
+ expect(skNumber5.getValue('string')).toBe('0.101');
30
+ expect(skNumber5.getBaseValue('bigint')).toBe(100n);
28
31
 
29
- const skNumber7 = new SwapKitNumber({ value: -0.1005, decimal: 3 });
30
- expect(skNumber7.getValue('string')).toBe('-0.101');
31
- expect(skNumber7.getValue('bigint')).toBe(-10050000n);
32
- expect(skNumber7.decimal).toBe(3);
33
- expect(skNumber7.getValue('number')).toBe(-0.101);
34
- expect(skNumber7.decimalMultiplier).toBe(100000000n);
32
+ const skNumber6 = new SwapKitNumber({ value: -0.1005, decimal: 3 });
33
+ expect(skNumber6.getValue('string')).toBe('-0.101');
34
+ expect(skNumber6.getBaseValue('bigint')).toBe(-100n);
35
+ expect(skNumber6.decimal).toBe(3);
36
+ expect(skNumber6.getValue('number')).toBe(-0.101);
37
+ expect(skNumber6.decimalMultiplier).toBe(100000000n);
35
38
  });
36
39
 
37
40
  test('creates SwapKitInstance from BigInt: (12.345678901234, decimals: 12)', () => {
38
41
  const skNumber = SwapKitNumber.fromBigInt(12345678901234n, 12);
39
42
 
40
43
  expect(skNumber.getValue('string')).toBe('12.345678901234');
41
- expect(skNumber.getValue('bigint')).toBe(12345678901234n);
44
+ expect(skNumber.getBaseValue('bigint')).toBe(12345678901234n);
42
45
  });
43
46
  });
44
47
 
@@ -46,7 +49,7 @@ describe('SwapKitNumber', () => {
46
49
  test('shifts up and bumps number', () => {
47
50
  const skNumber = new SwapKitNumber(1);
48
51
  expect(skNumber.getValue('string')).toBe('1');
49
- expect(skNumber.getValue('bigint')).toBe(100000000n);
52
+ expect(skNumber.getBaseValue('bigint')).toBe(100000000n);
50
53
 
51
54
  const shiftedSkNumber = SwapKitNumber.shiftDecimals({
52
55
  value: skNumber,
@@ -55,13 +58,13 @@ describe('SwapKitNumber', () => {
55
58
  });
56
59
 
57
60
  expect(shiftedSkNumber.getValue('string')).toBe('100');
58
- expect(shiftedSkNumber.getValue('bigint')).toBe(10000000000n);
61
+ expect(shiftedSkNumber.getBaseValue('bigint')).toBe(10000000000n);
59
62
  });
60
63
 
61
64
  test('shifts down and rounds down number', () => {
62
65
  const skNumber = new SwapKitNumber(2.12345678);
63
66
  expect(skNumber.getValue('string')).toBe('2.12345678');
64
- expect(skNumber.getValue('bigint')).toBe(212345678n);
67
+ expect(skNumber.getBaseValue('bigint')).toBe(212345678n);
65
68
 
66
69
  const shiftedSkNumber = SwapKitNumber.shiftDecimals({
67
70
  value: skNumber,
@@ -70,7 +73,7 @@ describe('SwapKitNumber', () => {
70
73
  });
71
74
 
72
75
  expect(shiftedSkNumber.getValue('string')).toBe('2.123456');
73
- expect(shiftedSkNumber.getValue('bigint')).toBe(212345600n);
76
+ expect(shiftedSkNumber.getBaseValue('bigint')).toBe(2123456n);
74
77
  });
75
78
  });
76
79
 
@@ -102,7 +105,7 @@ describe('SwapKitNumber', () => {
102
105
  describe('bigint', () => {
103
106
  test('returns bigint value', () => {
104
107
  const skNumber = new SwapKitNumber(1);
105
- expect(skNumber.getValue('bigint')).toBe(100000000n);
108
+ expect(skNumber.getBaseValue('bigint')).toBe(100000000n);
106
109
  });
107
110
  });
108
111
  });
@@ -158,7 +161,7 @@ describe('SwapKitNumber', () => {
158
161
  const result = skNumber1.add(skNumber2, skNumber3);
159
162
 
160
163
  expect(result.getValue('string')).toBe('15.5');
161
- expect(result.getValue('bigint')).toBe(1550000000n);
164
+ expect(result.getBaseValue('bigint')).toBe(1550000000n);
162
165
  });
163
166
 
164
167
  test('adds different type numbers correctly', () => {
@@ -166,14 +169,14 @@ describe('SwapKitNumber', () => {
166
169
  const result = skNumber1.add(6, '0.5');
167
170
 
168
171
  expect(result.getValue('string')).toBe('16.5');
169
- expect(result.getValue('bigint')).toBe(1650000000n);
172
+ expect(result.getBaseValue('bigint')).toBe(1650000000n);
170
173
  });
171
174
 
172
175
  test('adds large decimal numbers correctly', () => {
173
176
  const skNumber1 = new SwapKitNumber(0.0000000001);
174
177
  const result = skNumber1.add(6.000000000001, '0.0000000000000005');
175
178
  expect(result.getValue('string')).toBe('6.0000000001010005');
176
- expect(result.getValue('bigint')).toBe(60000000001010005n);
179
+ expect(result.getBaseValue('bigint')).toBe(600000000n);
177
180
  });
178
181
  });
179
182
 
@@ -185,7 +188,7 @@ describe('SwapKitNumber', () => {
185
188
  const result = skNumber1.sub(skNumber2, skNumber3);
186
189
 
187
190
  expect(result.getValue('string')).toBe('4.5');
188
- expect(result.getValue('bigint')).toBe(450000000n);
191
+ expect(result.getBaseValue('bigint')).toBe(450000000n);
189
192
  });
190
193
 
191
194
  test('subtracts different type numbers correctly', () => {
@@ -193,7 +196,7 @@ describe('SwapKitNumber', () => {
193
196
  const result = skNumber1.sub(6, '0.5');
194
197
 
195
198
  expect(result.getValue('string')).toBe('3.5');
196
- expect(result.getValue('bigint')).toBe(350000000n);
199
+ expect(result.getBaseValue('bigint')).toBe(350000000n);
197
200
  });
198
201
 
199
202
  test('can process negative results', () => {
@@ -203,8 +206,8 @@ describe('SwapKitNumber', () => {
203
206
 
204
207
  expect(result0.getValue('string')).toBe('0');
205
208
  expect(resultMinus.getValue('string')).toBe('-10');
206
- expect(result0.getValue('bigint')).toBe(0n);
207
- expect(resultMinus.getValue('bigint')).toBe(-1000000000n);
209
+ expect(result0.getBaseValue('bigint')).toBe(0n);
210
+ expect(resultMinus.getBaseValue('bigint')).toBe(-1000000000n);
208
211
  });
209
212
  });
210
213
 
@@ -216,7 +219,7 @@ describe('SwapKitNumber', () => {
216
219
  const result = skNumber1.mul(skNumber2, skNumber3);
217
220
 
218
221
  expect(result.getValue('string')).toBe('25');
219
- expect(result.getValue('bigint')).toBe(2500000000n);
222
+ expect(result.getBaseValue('bigint')).toBe(2500000000n);
220
223
  });
221
224
 
222
225
  test('multiplies different type numbers correctly', () => {
@@ -224,7 +227,7 @@ describe('SwapKitNumber', () => {
224
227
  const result = skNumber1.mul(6, '0.5');
225
228
 
226
229
  expect(result.getValue('string')).toBe('30');
227
- expect(result.getValue('bigint')).toBe(3000000000n);
230
+ expect(result.getBaseValue('bigint')).toBe(3000000000n);
228
231
  });
229
232
 
230
233
  test('multiplies numbers correctly if decimals of SKN is lower than number multiplied with', () => {
@@ -232,19 +235,19 @@ describe('SwapKitNumber', () => {
232
235
  const result = skNumber1.mul('0.00001');
233
236
 
234
237
  expect(result.getValue('string')).toBe('10');
235
- expect(result.getValue('bigint')).toBe(1000000000n);
238
+ expect(result.getBaseValue('bigint')).toBe(100000n);
236
239
  });
237
240
 
238
241
  test('should correctly round the result of multiplication', () => {
239
- const skNumber1 = new SwapKitNumber({ decimal: 2, value: 1.23 });
242
+ const skNumber1 = new SwapKitNumber({ decimal: 3, value: 1.23 });
240
243
  const skNumber2 = new SwapKitNumber({ decimal: 4, value: 4.56 });
241
244
 
242
245
  const result = skNumber1.mul(skNumber2);
243
246
 
244
247
  // The exact result of 1.23 * 4.56 is 5.6088
245
248
  // If we round it to 2 decimal places, we should get 5.61
246
- expect(result.getValue('string')).toBe('5.61');
247
- expect(result.getValue('bigint')).toBe(560880000n);
249
+ expect(result.getValue('string')).toBe('5.609');
250
+ expect(result.getBaseValue('bigint')).toBe(5608n);
248
251
 
249
252
  const skNumber3 = new SwapKitNumber({ decimal: 2, value: 1.23 });
250
253
  const skNumber4 = new SwapKitNumber(-1.234567891);
@@ -254,7 +257,7 @@ describe('SwapKitNumber', () => {
254
257
  // The exact result of 1.23 * -1.234567891 is -1,518518505
255
258
  // If we round it to 2 decimal places, we should get 5.61
256
259
  expect(result2.getValue('string')).toBe('-1.52');
257
- expect(result2.getValue('bigint')).toBe(-1518518505n);
260
+ expect(result2.getBaseValue('bigint')).toBe(-151n);
258
261
  });
259
262
  });
260
263
 
@@ -266,13 +269,13 @@ describe('SwapKitNumber', () => {
266
269
  const result = skNumber1.div(skNumber2, skNumber3);
267
270
 
268
271
  expect(result.getValue('string')).toBe('4');
269
- expect(result.getValue('bigint')).toBe(400000000n);
272
+ expect(result.getBaseValue('bigint')).toBe(400000000n);
270
273
 
271
274
  const skNumber4 = new SwapKitNumber(10.12);
272
275
  const result2 = skNumber4.div(0.0001);
273
276
 
274
277
  expect(result2.getValue('string')).toBe('101200');
275
- expect(result2.getValue('bigint')).toBe(10120000000000n);
278
+ expect(result2.getBaseValue('bigint')).toBe(10120000000000n);
276
279
  });
277
280
 
278
281
  test('divides different type numbers correctly', () => {
@@ -280,7 +283,7 @@ describe('SwapKitNumber', () => {
280
283
  const result = skNumber1.div(5, '0.5');
281
284
 
282
285
  expect(result.getValue('string')).toBe('8');
283
- expect(result.getValue('bigint')).toBe(800000000n);
286
+ expect(result.getBaseValue('bigint')).toBe(800000000n);
284
287
  });
285
288
 
286
289
  test('divides different type numbers correctly when decimal is set', () => {
@@ -288,7 +291,7 @@ describe('SwapKitNumber', () => {
288
291
  const result = skNumber1.div(0.001);
289
292
 
290
293
  expect(result.getValue('string')).toBe('1200');
291
- expect(result.getValue('bigint')).toBe(120000000000n);
294
+ expect(result.getBaseValue('bigint')).toBe(120000n);
292
295
  });
293
296
 
294
297
  test('divides smaller number by larger number', () => {
@@ -296,7 +299,7 @@ describe('SwapKitNumber', () => {
296
299
  const result = skNumber1.div(2);
297
300
 
298
301
  expect(result.getValue('string')).toBe('0.5');
299
- expect(result.getValue('bigint')).toBe(50000000n);
302
+ expect(result.getBaseValue('bigint')).toBe(50000000n);
300
303
  });
301
304
 
302
305
  test('divides a number with 18 decimals by a negative number with less decimals', () => {
@@ -307,7 +310,7 @@ describe('SwapKitNumber', () => {
307
310
 
308
311
  // The exact result of 1.000000000000000010 / -2 is -0.500000000000000005
309
312
  expect(result.getValue('string')).toBe('-0.500000000000000005');
310
- expect(result.getValue('bigint')).toBe(-500000000000000005n);
313
+ expect(result.getBaseValue('bigint')).toBe(-500000000000000005n);
311
314
  });
312
315
 
313
316
  test('divides a number with 2 decimals by a negative number with more decimals', () => {
@@ -318,7 +321,7 @@ describe('SwapKitNumber', () => {
318
321
 
319
322
  // The exact result of 2 / -0.000005 is -400000
320
323
  expect(result.getValue('string')).toBe('-400000');
321
- expect(result.getValue('bigint')).toBe(-40000000000000n);
324
+ expect(result.getBaseValue('bigint')).toBe(-40000000n);
322
325
  });
323
326
  });
324
327
 
@@ -329,7 +332,7 @@ describe('SwapKitNumber', () => {
329
332
 
330
333
  const result = skNumber1.mul(skNumber2);
331
334
  expect(result.getValue('string')).toBe('987654321000000987654321000');
332
- expect(result.getValue('bigint')).toBe(987654321000000987654321000000000000000000000n);
335
+ expect(result.getBaseValue('bigint')).toBe(987654321000000987654321000000000000000000000n);
333
336
  });
334
337
 
335
338
  test('divide huge numbers', () => {
@@ -338,7 +341,7 @@ describe('SwapKitNumber', () => {
338
341
 
339
342
  const result = skNumber1.div(skNumber2);
340
343
  expect(result.getValue('string')).toBe('1012.4999999873447625');
341
- expect(result.getValue('bigint')).toBe(1012499999987344762500n);
344
+ expect(result.getBaseValue('bigint')).toBe(1012499999987344762500n);
342
345
  });
343
346
  });
344
347
 
@@ -1,3 +1,5 @@
1
+ import { BaseDecimal } from '@swapkit/types';
2
+
1
3
  import type { SwapKitNumber } from './swapKitNumber.ts';
2
4
 
3
5
  type NumberPrimitivesType = {
@@ -141,7 +143,7 @@ export class BigIntArithmetics {
141
143
  return this.bigIntValue === this.getBigIntValue(value);
142
144
  }
143
145
 
144
- getValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T] {
146
+ getValue<T extends 'number' | 'string'>(type: T): NumberPrimitivesType[T] {
145
147
  const value = this.formatBigIntToSafeValue(
146
148
  this.bigIntValue,
147
149
  this.decimal || decimalFromMultiplier(this.decimalMultiplier),
@@ -156,12 +158,12 @@ export class BigIntArithmetics {
156
158
  return value;
157
159
  default:
158
160
  // @ts-expect-error False positive
159
- return this.bigIntValue;
161
+ return (this.bigIntValue * BigInt(this.decimal || 8n)) / this.decimalMultiplier;
160
162
  }
161
163
  }
162
164
 
163
165
  getBaseValue<T extends 'number' | 'string' | 'bigint'>(type: T): NumberPrimitivesType[T] {
164
- const divisor = this.decimalMultiplier / toMultiplier(this.decimal || 0);
166
+ const divisor = this.decimalMultiplier / toMultiplier(this.decimal || BaseDecimal.THOR);
165
167
  const baseValue = this.bigIntValue / divisor;
166
168
 
167
169
  switch (type) {
@@ -173,7 +175,7 @@ export class BigIntArithmetics {
173
175
  return baseValue.toString();
174
176
  default:
175
177
  // @ts-expect-error False positive
176
- return this.bigIntValue;
178
+ return baseValue;
177
179
  }
178
180
  }
179
181