@swapkit/helpers 1.0.0-rc.6 → 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 +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.es.js +48 -43
- package/package.json +1 -1
- package/src/helpers/asset.ts +7 -4
- package/src/modules/__tests__/swapKitNumber.test.ts +47 -44
- package/src/modules/bigIntArithmetics.ts +12 -6
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},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;
|
|
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'
|
|
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;
|
|
@@ -177,7 +177,7 @@ export declare const gasFeeMultiplier: Record<FeeOption, number>;
|
|
|
177
177
|
export declare const getAssetType: ({ chain, symbol }: {
|
|
178
178
|
chain: Chain;
|
|
179
179
|
symbol: string;
|
|
180
|
-
}) =>
|
|
180
|
+
}) => Chain.Avalanche | Chain.Cosmos | Chain.Kujira | "Synth" | "Native" | "BEP2" | "BEP20" | "ERC20" | "POLYGON" | "ARBITRUM" | "OPTIMISM";
|
|
181
181
|
|
|
182
182
|
export declare const getAsymmetricAssetShare: ({ liquidityUnits, poolUnits, assetDepth, }: ShareParams<{
|
|
183
183
|
assetDepth: 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
|
-
},
|
|
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
|
-
},
|
|
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),
|
|
@@ -152,9 +152,9 @@ const vt = (n) => {
|
|
|
152
152
|
case i.THORChain:
|
|
153
153
|
return "Native";
|
|
154
154
|
case i.Cosmos:
|
|
155
|
-
return t === "ATOM" ? "Native" :
|
|
155
|
+
return t === "ATOM" ? "Native" : i.Cosmos;
|
|
156
156
|
case i.Kujira:
|
|
157
|
-
return t ===
|
|
157
|
+
return t === i.Kujira ? "Native" : i.Kujira;
|
|
158
158
|
case i.Binance:
|
|
159
159
|
return t === i.Binance ? "Native" : "BEP2";
|
|
160
160
|
case i.BinanceSmartChain:
|
|
@@ -162,7 +162,7 @@ const vt = (n) => {
|
|
|
162
162
|
case i.Ethereum:
|
|
163
163
|
return t === i.Ethereum ? "Native" : "ERC20";
|
|
164
164
|
case i.Avalanche:
|
|
165
|
-
return t === i.Avalanche ? "Native" :
|
|
165
|
+
return t === i.Avalanche ? "Native" : i.Avalanche;
|
|
166
166
|
case i.Polygon:
|
|
167
167
|
return t === i.Polygon ? "Native" : "POLYGON";
|
|
168
168
|
case i.Arbitrum:
|
|
@@ -177,7 +177,9 @@ const vt = (n) => {
|
|
|
177
177
|
}, gt = new RegExp(
|
|
178
178
|
/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
|
|
179
179
|
"gmi"
|
|
180
|
-
), Et = (n) => n.filter(
|
|
180
|
+
), Et = (n) => n.filter(
|
|
181
|
+
(t) => !gt.test(t.toString()) && !t.toString().includes("undefined")
|
|
182
|
+
), _t = ({
|
|
181
183
|
liquidityUnits: n,
|
|
182
184
|
poolUnits: t,
|
|
183
185
|
runeDepth: e
|
|
@@ -227,7 +229,7 @@ const vt = (n) => {
|
|
|
227
229
|
runeAmount: s,
|
|
228
230
|
assetAmount: a
|
|
229
231
|
}) => {
|
|
230
|
-
const c = h(n), o = h(e), u = h(t), l = h(s), d = h(a), A = l.mul(o),
|
|
232
|
+
const c = h(n), o = h(e), u = h(t), l = h(s), d = h(a), A = l.mul(o), I = d.mul(c), R = l.mul(d), X = c.mul(o), Z = u.mul(A.add(I.add(R.mul(2)))), tt = A.add(I.add(X.mul(2))), F = Z.div(tt), k = h(r).add(F);
|
|
231
233
|
if (F.baseValueNumber === 0)
|
|
232
234
|
return k.div(u).baseValueNumber;
|
|
233
235
|
const et = u.add(k);
|
|
@@ -275,18 +277,18 @@ const vt = (n) => {
|
|
|
275
277
|
default:
|
|
276
278
|
return "";
|
|
277
279
|
}
|
|
278
|
-
},
|
|
280
|
+
}, G = Object.values(i), $t = (n = "") => {
|
|
279
281
|
const t = n.toUpperCase(), [e] = t.split(".");
|
|
280
|
-
if (
|
|
282
|
+
if (G.includes(e))
|
|
281
283
|
return !0;
|
|
282
284
|
const [r] = t.split("/");
|
|
283
|
-
if (
|
|
285
|
+
if (G.includes(r))
|
|
284
286
|
return !0;
|
|
285
287
|
throw new Error(
|
|
286
288
|
`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
287
289
|
);
|
|
288
|
-
}, T = 8,
|
|
289
|
-
function
|
|
290
|
+
}, T = 8, S = (n) => 10n ** BigInt(n), v = (n) => Math.log10(parseFloat(n.toString()));
|
|
291
|
+
function U({
|
|
290
292
|
value: n,
|
|
291
293
|
bigIntDecimal: t = T,
|
|
292
294
|
decimal: e = T
|
|
@@ -302,7 +304,7 @@ function G({
|
|
|
302
304
|
""
|
|
303
305
|
);
|
|
304
306
|
}
|
|
305
|
-
var w,
|
|
307
|
+
var w, C, M, z, N, J, E, D, b, V, O, L;
|
|
306
308
|
const B = class B {
|
|
307
309
|
constructor(t) {
|
|
308
310
|
$(this, w);
|
|
@@ -315,14 +317,14 @@ const B = class B {
|
|
|
315
317
|
_(this, "bigIntValue", 0n);
|
|
316
318
|
_(this, "decimal");
|
|
317
319
|
const e = P(t);
|
|
318
|
-
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier =
|
|
319
|
-
Math.max(g(this, O, L).call(this, g(this, b,
|
|
320
|
-
), g(this, M,
|
|
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, V).call(this, e)), this.decimal || 0)
|
|
322
|
+
), g(this, M, z).call(this, e);
|
|
321
323
|
}
|
|
322
324
|
static fromBigInt(t, e) {
|
|
323
325
|
return new B({
|
|
324
326
|
decimal: e,
|
|
325
|
-
value:
|
|
327
|
+
value: U({ value: t, bigIntDecimal: e, decimal: e })
|
|
326
328
|
});
|
|
327
329
|
}
|
|
328
330
|
static shiftDecimals({
|
|
@@ -331,7 +333,7 @@ const B = class B {
|
|
|
331
333
|
to: r
|
|
332
334
|
}) {
|
|
333
335
|
return B.fromBigInt(
|
|
334
|
-
new B(t).bigIntValue *
|
|
336
|
+
new B(t).bigIntValue * S(r) / S(e),
|
|
335
337
|
r
|
|
336
338
|
);
|
|
337
339
|
}
|
|
@@ -357,16 +359,16 @@ const B = class B {
|
|
|
357
359
|
return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
|
|
358
360
|
}
|
|
359
361
|
add(...t) {
|
|
360
|
-
return g(this, w,
|
|
362
|
+
return g(this, w, C).call(this, "add", ...t);
|
|
361
363
|
}
|
|
362
364
|
sub(...t) {
|
|
363
|
-
return g(this, w,
|
|
365
|
+
return g(this, w, C).call(this, "sub", ...t);
|
|
364
366
|
}
|
|
365
367
|
mul(...t) {
|
|
366
|
-
return g(this, w,
|
|
368
|
+
return g(this, w, C).call(this, "mul", ...t);
|
|
367
369
|
}
|
|
368
370
|
div(...t) {
|
|
369
|
-
return g(this, w,
|
|
371
|
+
return g(this, w, C).call(this, "div", ...t);
|
|
370
372
|
}
|
|
371
373
|
gt(t) {
|
|
372
374
|
return this.bigIntValue > this.getBigIntValue(t);
|
|
@@ -394,22 +396,25 @@ const B = class B {
|
|
|
394
396
|
case "string":
|
|
395
397
|
return e;
|
|
396
398
|
default:
|
|
397
|
-
return this.bigIntValue;
|
|
399
|
+
return this.bigIntValue * BigInt(this.decimal || 8n) / this.decimalMultiplier;
|
|
398
400
|
}
|
|
399
401
|
}
|
|
400
402
|
getBaseValue(t) {
|
|
401
|
-
const e = this.decimalMultiplier /
|
|
403
|
+
const e = this.decimalMultiplier / S(this.decimal || m.THOR), r = this.bigIntValue / e;
|
|
402
404
|
switch (t) {
|
|
403
405
|
case "number":
|
|
404
406
|
return Number(r);
|
|
405
407
|
case "string":
|
|
406
408
|
return r.toString();
|
|
407
409
|
default:
|
|
408
|
-
return
|
|
410
|
+
return r;
|
|
409
411
|
}
|
|
410
412
|
}
|
|
411
413
|
getBigIntValue(t, e) {
|
|
412
|
-
|
|
414
|
+
if (!e && typeof t == "object")
|
|
415
|
+
return t.bigIntValue;
|
|
416
|
+
const r = P(t), s = g(this, b, V).call(this, r);
|
|
417
|
+
return s === "0" || s === "undefined" ? 0n : g(this, E, D).call(this, s, e);
|
|
413
418
|
}
|
|
414
419
|
formatBigIntToSafeValue(t, e) {
|
|
415
420
|
const r = e || this.decimal || T, s = Math.max(
|
|
@@ -440,8 +445,8 @@ const B = class B {
|
|
|
440
445
|
)}`;
|
|
441
446
|
}
|
|
442
447
|
};
|
|
443
|
-
w = new WeakSet(),
|
|
444
|
-
const r = g(this, N,
|
|
448
|
+
w = new WeakSet(), C = function(t, ...e) {
|
|
449
|
+
const r = g(this, N, J).call(this, this, ...e), s = S(r), a = e.reduce(
|
|
445
450
|
(o, u) => {
|
|
446
451
|
const l = this.getBigIntValue(u, r);
|
|
447
452
|
switch (t) {
|
|
@@ -462,24 +467,24 @@ w = new WeakSet(), V = function(t, ...e) {
|
|
|
462
467
|
},
|
|
463
468
|
//normalize is to precision multiplier base
|
|
464
469
|
this.bigIntValue * s / this.decimalMultiplier
|
|
465
|
-
), c =
|
|
470
|
+
), c = U({
|
|
466
471
|
bigIntDecimal: r,
|
|
467
472
|
decimal: Math.max(r, v(this.decimalMultiplier)),
|
|
468
473
|
value: a
|
|
469
474
|
});
|
|
470
475
|
return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() });
|
|
471
|
-
}, M = new WeakSet(),
|
|
472
|
-
const e = g(this, b,
|
|
476
|
+
}, M = new WeakSet(), z = function(t) {
|
|
477
|
+
const e = g(this, b, V).call(this, t) || "0";
|
|
473
478
|
this.bigIntValue = g(this, E, D).call(this, e);
|
|
474
|
-
}, N = new WeakSet(),
|
|
479
|
+
}, N = new WeakSet(), J = function(...t) {
|
|
475
480
|
const e = t.map(
|
|
476
|
-
(r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) : g(this, O, L).call(this, g(this, b,
|
|
481
|
+
(r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) : g(this, O, L).call(this, g(this, b, V).call(this, r))
|
|
477
482
|
).filter(Boolean);
|
|
478
483
|
return Math.max(...e, T);
|
|
479
484
|
}, E = new WeakSet(), D = function(t, e) {
|
|
480
|
-
const r = e ?
|
|
485
|
+
const r = e ? S(e) : this.decimalMultiplier, s = v(r), [a = "", c = ""] = t.split(".");
|
|
481
486
|
return BigInt(`${a}${c.padEnd(s, "0")}`);
|
|
482
|
-
}, b = new WeakSet(),
|
|
487
|
+
}, b = new WeakSet(), V = function(t) {
|
|
483
488
|
const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
|
|
484
489
|
useGrouping: !1,
|
|
485
490
|
maximumFractionDigits: 20
|
|
@@ -576,8 +581,8 @@ class f extends y {
|
|
|
576
581
|
...c
|
|
577
582
|
} = await import("@swapkit/tokens");
|
|
578
583
|
j = [a, ...Object.values(c)].reduce(
|
|
579
|
-
(u, { tokens: l }) => (l.forEach(({ identifier: d, chain: A, ...
|
|
580
|
-
const R = "decimals" in
|
|
584
|
+
(u, { tokens: l }) => (l.forEach(({ identifier: d, chain: A, ...I }) => {
|
|
585
|
+
const R = "decimals" in I ? I.decimals : m[A];
|
|
581
586
|
u.set(d, { identifier: d, decimal: R });
|
|
582
587
|
}), u),
|
|
583
588
|
/* @__PURE__ */ new Map()
|
|
@@ -678,9 +683,9 @@ const Pt = (n) => {
|
|
|
678
683
|
*/
|
|
679
684
|
helpers_number_different_decimals: 99101
|
|
680
685
|
};
|
|
681
|
-
class
|
|
686
|
+
class Q extends Error {
|
|
682
687
|
constructor(t, e) {
|
|
683
|
-
console.error(e), super(t, { cause: { code: wt[t], message: t } }), Object.setPrototypeOf(this,
|
|
688
|
+
console.error(e), super(t, { cause: { code: wt[t], message: t } }), Object.setPrototypeOf(this, Q.prototype);
|
|
684
689
|
}
|
|
685
690
|
}
|
|
686
691
|
class bt extends y {
|
|
@@ -691,12 +696,12 @@ class bt extends y {
|
|
|
691
696
|
export {
|
|
692
697
|
f as AssetValue,
|
|
693
698
|
y as BigIntArithmetics,
|
|
694
|
-
|
|
699
|
+
Q as SwapKitError,
|
|
695
700
|
bt as SwapKitNumber,
|
|
696
701
|
yt as assetFromString,
|
|
697
|
-
|
|
702
|
+
Vt as derivationPathToString,
|
|
698
703
|
Et as filterAssets,
|
|
699
|
-
|
|
704
|
+
U as formatBigIntToSafeValue,
|
|
700
705
|
Bt as gasFeeMultiplier,
|
|
701
706
|
mt as getAssetType,
|
|
702
707
|
pt as getAsymmetricAssetShare,
|
|
@@ -715,5 +720,5 @@ export {
|
|
|
715
720
|
vt as getTHORNameCost,
|
|
716
721
|
dt as isGasAsset,
|
|
717
722
|
at as postRequest,
|
|
718
|
-
|
|
723
|
+
Ct as validateTHORName
|
|
719
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.
|
|
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",
|
package/src/helpers/asset.ts
CHANGED
|
@@ -154,9 +154,9 @@ export const getAssetType = ({ chain, symbol }: { chain: Chain; symbol: string }
|
|
|
154
154
|
return 'Native';
|
|
155
155
|
|
|
156
156
|
case Chain.Cosmos:
|
|
157
|
-
return symbol === 'ATOM' ? 'Native' :
|
|
157
|
+
return symbol === 'ATOM' ? 'Native' : Chain.Cosmos;
|
|
158
158
|
case Chain.Kujira:
|
|
159
|
-
return symbol ===
|
|
159
|
+
return symbol === Chain.Kujira ? 'Native' : Chain.Kujira;
|
|
160
160
|
case Chain.Binance:
|
|
161
161
|
return symbol === Chain.Binance ? 'Native' : 'BEP2';
|
|
162
162
|
case Chain.BinanceSmartChain:
|
|
@@ -164,7 +164,7 @@ export const getAssetType = ({ chain, symbol }: { chain: Chain; symbol: string }
|
|
|
164
164
|
case Chain.Ethereum:
|
|
165
165
|
return symbol === Chain.Ethereum ? 'Native' : 'ERC20';
|
|
166
166
|
case Chain.Avalanche:
|
|
167
|
-
return symbol === Chain.Avalanche ? 'Native' :
|
|
167
|
+
return symbol === Chain.Avalanche ? 'Native' : Chain.Avalanche;
|
|
168
168
|
case Chain.Polygon:
|
|
169
169
|
return symbol === Chain.Polygon ? 'Native' : 'POLYGON';
|
|
170
170
|
|
|
@@ -189,4 +189,7 @@ const potentialScamRegex = new RegExp(
|
|
|
189
189
|
'gmi',
|
|
190
190
|
);
|
|
191
191
|
export const filterAssets = (assets: AssetValue[]) =>
|
|
192
|
-
assets.filter(
|
|
192
|
+
assets.filter(
|
|
193
|
+
(asset) =>
|
|
194
|
+
!potentialScamRegex.test(asset.toString()) && !asset.toString().includes('undefined'),
|
|
195
|
+
);
|
|
@@ -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.
|
|
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.
|
|
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.
|
|
22
|
+
expect(skNumber3.getBaseValue('bigint')).toBe(0n);
|
|
20
23
|
|
|
21
|
-
const skNumber4 = new SwapKitNumber(0.
|
|
22
|
-
expect(skNumber4.getValue('string')).toBe('0.
|
|
23
|
-
expect(skNumber4.
|
|
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
|
|
26
|
-
expect(
|
|
27
|
-
expect(
|
|
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
|
|
30
|
-
expect(
|
|
31
|
-
expect(
|
|
32
|
-
expect(
|
|
33
|
-
expect(
|
|
34
|
-
expect(
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
207
|
-
expect(resultMinus.
|
|
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.
|
|
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.
|
|
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.
|
|
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:
|
|
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.
|
|
247
|
-
expect(result.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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'
|
|
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 ||
|
|
166
|
+
const divisor = this.decimalMultiplier / toMultiplier(this.decimal || BaseDecimal.THOR);
|
|
165
167
|
const baseValue = this.bigIntValue / divisor;
|
|
166
168
|
|
|
167
169
|
switch (type) {
|
|
@@ -173,14 +175,18 @@ export class BigIntArithmetics {
|
|
|
173
175
|
return baseValue.toString();
|
|
174
176
|
default:
|
|
175
177
|
// @ts-expect-error False positive
|
|
176
|
-
return
|
|
178
|
+
return baseValue;
|
|
177
179
|
}
|
|
178
180
|
}
|
|
179
181
|
|
|
180
182
|
getBigIntValue(value: InitialisationValueType, decimal?: number) {
|
|
181
183
|
if (!decimal && typeof value === 'object') return value.bigIntValue;
|
|
182
184
|
|
|
183
|
-
|
|
185
|
+
const stringValue = getStringValue(value);
|
|
186
|
+
const safeValue = this.#toSafeValue(stringValue);
|
|
187
|
+
|
|
188
|
+
if (safeValue === '0' || safeValue === 'undefined') return 0n;
|
|
189
|
+
return this.#toBigInt(safeValue, decimal);
|
|
184
190
|
}
|
|
185
191
|
|
|
186
192
|
formatBigIntToSafeValue(value: bigint, decimal?: number) {
|
|
@@ -310,7 +316,7 @@ export class BigIntArithmetics {
|
|
|
310
316
|
#toBigInt(value: string, decimal?: number) {
|
|
311
317
|
const multiplier = decimal ? toMultiplier(decimal) : this.decimalMultiplier;
|
|
312
318
|
const padDecimal = decimalFromMultiplier(multiplier);
|
|
313
|
-
const [integerPart, decimalPart = ''] = value.split('.');
|
|
319
|
+
const [integerPart = '', decimalPart = ''] = value.split('.');
|
|
314
320
|
|
|
315
321
|
return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, '0')}`);
|
|
316
322
|
}
|