@swapkit/helpers 1.0.0-rc.6 → 1.0.0-rc.7
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 +1 -1
- package/dist/index.es.js +33 -28
- package/package.json +1 -1
- package/src/helpers/asset.ts +7 -4
- package/src/modules/bigIntArithmetics.ts +6 -2
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 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;
|
package/dist/index.d.ts
CHANGED
|
@@ -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
|
@@ -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, V, M,
|
|
307
|
+
var w, V, M, z, N, J, E, D, b, C, 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 =
|
|
320
|
+
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = S(
|
|
319
321
|
Math.max(g(this, O, L).call(this, g(this, b, C).call(this, e)), this.decimal || 0)
|
|
320
|
-
), g(this, M,
|
|
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
|
}
|
|
@@ -398,7 +400,7 @@ const B = class B {
|
|
|
398
400
|
}
|
|
399
401
|
}
|
|
400
402
|
getBaseValue(t) {
|
|
401
|
-
const e = this.decimalMultiplier /
|
|
403
|
+
const e = this.decimalMultiplier / S(this.decimal || 0), r = this.bigIntValue / e;
|
|
402
404
|
switch (t) {
|
|
403
405
|
case "number":
|
|
404
406
|
return Number(r);
|
|
@@ -409,7 +411,10 @@ const B = class B {
|
|
|
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, C).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(
|
|
@@ -441,7 +446,7 @@ const B = class B {
|
|
|
441
446
|
}
|
|
442
447
|
};
|
|
443
448
|
w = new WeakSet(), V = function(t, ...e) {
|
|
444
|
-
const r = g(this, N,
|
|
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,22 +467,22 @@ 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(),
|
|
476
|
+
}, M = new WeakSet(), z = function(t) {
|
|
472
477
|
const e = g(this, b, C).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
481
|
(r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) : g(this, O, L).call(this, g(this, b, C).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
487
|
}, b = new WeakSet(), C = function(t) {
|
|
483
488
|
const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
|
|
@@ -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
|
Ct 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,
|
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.7",
|
|
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
|
+
);
|
|
@@ -180,7 +180,11 @@ export class BigIntArithmetics {
|
|
|
180
180
|
getBigIntValue(value: InitialisationValueType, decimal?: number) {
|
|
181
181
|
if (!decimal && typeof value === 'object') return value.bigIntValue;
|
|
182
182
|
|
|
183
|
-
|
|
183
|
+
const stringValue = getStringValue(value);
|
|
184
|
+
const safeValue = this.#toSafeValue(stringValue);
|
|
185
|
+
|
|
186
|
+
if (safeValue === '0' || safeValue === 'undefined') return 0n;
|
|
187
|
+
return this.#toBigInt(safeValue, decimal);
|
|
184
188
|
}
|
|
185
189
|
|
|
186
190
|
formatBigIntToSafeValue(value: bigint, decimal?: number) {
|
|
@@ -310,7 +314,7 @@ export class BigIntArithmetics {
|
|
|
310
314
|
#toBigInt(value: string, decimal?: number) {
|
|
311
315
|
const multiplier = decimal ? toMultiplier(decimal) : this.decimalMultiplier;
|
|
312
316
|
const padDecimal = decimalFromMultiplier(multiplier);
|
|
313
|
-
const [integerPart, decimalPart = ''] = value.split('.');
|
|
317
|
+
const [integerPart = '', decimalPart = ''] = value.split('.');
|
|
314
318
|
|
|
315
319
|
return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, '0')}`);
|
|
316
320
|
}
|