@swapkit/helpers 1.0.0-rc.5 → 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 +13 -2
- package/dist/index.es.js +126 -104
- package/package.json +5 -5
- package/src/helpers/asset.ts +15 -3
- package/src/modules/__tests__/assetValue.test.ts +7 -0
- package/src/modules/assetValue.ts +8 -2
- package/src/modules/bigIntArithmetics.ts +15 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var oe=Object.create;var N=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var he=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var me=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var ge=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ue(e))!de.call(n,a)&&a!==t&&N(n,a,{get:()=>e[a],enumerable:!(i=le(e,a))||i.enumerable});return n};var _e=(n,e,t)=>(t=n!=null?oe(he(n)):{},ge(e||!n||!n.__esModule?N(t,"default",{value:n,enumerable:!0}):t,n));var g=(n,e,t)=>(me(n,typeof e!="symbol"?e+"":e,t),t),pe=(n,e,t)=>{if(!e.has(n))throw TypeError("Cannot "+t)};var C=(n,e,t)=>{if(e.has(n))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(n):e.set(n,t)};var m=(n,e,t)=>(pe(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("@swapkit/types"),Ce=n=>{if(n<0)throw new Error("Invalid number of year");return 10+n},fe=n=>{if(n.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!n.match(e)},Ae=([n,e,t,i,a])=>`${n}'/${e}'/${t}'/${i}${typeof a!="number"?"":`/${a}`}`,we=async(n,e)=>{try{const t=Object.entries(e||{}).reduce((a,[s,c])=>(c&&(a[s]=c),a),{});return(await fetch(`${n}${e?`?${new URLSearchParams(t).toString()}`:""}`,{method:"GET",mode:"cors",credentials:"omit",referrer:"https://sk.thorswap.net"})).json()}catch(t){return console.error(t),{}}},K=async(n,e,t,i=!1)=>{try{const a=await fetch(`${n}`,{body:e,headers:t,method:"POST",referrer:"https://sk.thorswap.net"});return i?a.text():a.json()}catch{return{}}},Se="0x313ce567",Y=async({chain:n,to:e})=>{try{const t=await K(r.ChainToRPC[n],JSON.stringify({method:"eth_call",params:[{to:e.toLowerCase(),data:Se},"latest"],id:44,jsonrpc:"2.0"}),{accept:"*/*","cache-control":"no-cache","content-type":"application/json"},!0),{result:i}=JSON.parse(t);return parseInt(BigInt(i).toString())}catch(t){return console.error(t),r.BaseDecimal[n]}},$e=async n=>{if(n===r.Chain.Ethereum)return r.BaseDecimal.ETH;const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?Y({chain:r.Chain.Ethereum,to:e}):r.BaseDecimal.ETH},be=async n=>{const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?Y({chain:r.Chain.Avalanche,to:e.toLowerCase()}):r.BaseDecimal.AVAX},Be=async n=>(n===r.Chain.BinanceSmartChain,r.BaseDecimal.BSC),q=async({chain:n,symbol:e})=>{switch(n){case r.Chain.Ethereum:return $e(e);case r.Chain.Avalanche:return be(e);case r.Chain.BinanceSmartChain:return Be(e);default:return r.BaseDecimal[n]}},ye={[r.FeeOption.Average]:1.2,[r.FeeOption.Fast]:1.5,[r.FeeOption.Fastest]:2},J=({chain:n,symbol:e})=>{switch(n){case r.Chain.Bitcoin:case r.Chain.BitcoinCash:case r.Chain.Litecoin:case r.Chain.Dogecoin:case r.Chain.Binance:case r.Chain.Ethereum:case r.Chain.Avalanche:return e===n;case r.Chain.Arbitrum:case r.Chain.Optimism:return e==="ETH";case r.Chain.Maya:return e==="CACAO";case r.Chain.Kujira:return e==="KUJI";case r.Chain.Cosmos:return e==="ATOM";case r.Chain.Polygon:return e==="MATIC";case r.Chain.BinanceSmartChain:return e==="BNB";case r.Chain.THORChain:return e==="RUNE"}},z=n=>{switch(n){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case r.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:r.BaseDecimal[n]};case r.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:r.BaseDecimal[n]};case r.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:r.BaseDecimal[n]};case r.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:r.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case r.Chain.Kujira:case r.Chain.Arbitrum:case r.Chain.Optimism:case r.Chain.BitcoinCash:case r.Chain.Litecoin:case r.Chain.Dogecoin:case r.Chain.Binance:case r.Chain.Avalanche:case r.Chain.Polygon:case r.Chain.Bitcoin:case r.Chain.Ethereum:return{identifier:`${n}.${n}`,decimal:r.BaseDecimal[n]}}},X=({chain:n,symbol:e})=>{if(e.includes("/"))return"Synth";switch(n){case r.Chain.Bitcoin:case r.Chain.BitcoinCash:case r.Chain.Dogecoin:case r.Chain.Litecoin:case r.Chain.Maya:case r.Chain.THORChain:return"Native";case r.Chain.Cosmos:return e==="ATOM"?"Native":"GAIA";case r.Chain.Kujira:return e==="KUJI"?"Native":"KUJI";case r.Chain.Binance:return e===r.Chain.Binance?"Native":"BEP2";case r.Chain.BinanceSmartChain:return e===r.Chain.Binance?"Native":"BEP20";case r.Chain.Ethereum:return e===r.Chain.Ethereum?"Native":"ERC20";case r.Chain.Avalanche:return e===r.Chain.Avalanche?"Native":"AVAX";case r.Chain.Polygon:return e===r.Chain.Polygon?"Native":"POLYGON";case r.Chain.Arbitrum:return[r.Chain.Ethereum,r.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case r.Chain.Optimism:return[r.Chain.Ethereum,r.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Ie=n=>{var c;const[e,...t]=n.split("."),i=n.includes("/"),a=t.join("."),s=(c=a==null?void 0:a.split("-"))==null?void 0:c[0];return{chain:e,symbol:a,ticker:s,synth:i}},Q=({liquidityUnits:n,poolUnits:e,runeDepth:t})=>{const i=d(n),a=d(e),s=d(t),c=i.mul(s),o=a.mul(a).mul(2),l=a.mul(i).mul(2),u=i.mul(i),h=a.mul(a).mul(a);return c.mul(o.sub(l).add(u)).div(h)},Z=({liquidityUnits:n,poolUnits:e,assetDepth:t})=>{const i=d(n),a=d(e),s=d(t),c=i.mul(s),o=a.mul(a).mul(2),l=a.mul(i).mul(2),u=i.mul(i),h=c.mul(o.sub(l).add(u)),p=a.mul(a).mul(a);return h.div(p)},Te=({percent:n,runeDepth:e,liquidityUnits:t,poolUnits:i})=>Q({runeDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),ve=({percent:n,assetDepth:e,liquidityUnits:t,poolUnits:i})=>Z({assetDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),d=n=>new ie({value:n,decimal:r.BaseDecimal.THOR}),ee=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})=>({assetAmount:d(i).mul(n).div(e),runeAmount:d(t).mul(n).div(e)}),Me=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i,percent:a})=>Object.fromEntries(Object.entries(ee({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})).map(([s,c])=>[s,c.mul(a)])),Ve=({runeDepth:n,poolUnits:e,assetDepth:t,liquidityUnits:i,runeAmount:a,assetAmount:s})=>{const c=d(n),o=d(t),l=d(e),u=d(a),h=d(s),p=u.mul(o),$=h.mul(c),E=u.mul(h),ae=c.mul(o),re=l.mul(p.add($.add(E.mul(2)))),se=p.add($.add(ae.mul(2))),U=re.div(se),D=d(i).add(U);if(U.baseValueNumber===0)return D.div(l).baseValueNumber;const ce=l.add(D);return D.div(ce).baseValueNumber},Oe=({runeAmount:n,assetAmount:e,runeDepth:t,assetDepth:i})=>{const a=d(t),s=d(i),c=d(e),o=d(n),l=c.mul(a).sub(s.mul(o)),u=s.mul(o).add(a.mul(s));return Math.abs(l.div(u).baseValueNumber)},Ee=({symbol:n,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${n.slice(-3)}`:n,De=(n,e)=>{switch(n){case r.MemoType.LEAVE:case r.MemoType.BOND:{const{address:t}=e;return`${n}:${t}`}case r.MemoType.UNBOND:{const{address:t,unbondAmount:i}=e;return`${n}:${t}:${i*10**8}`}case r.MemoType.THORNAME_REGISTER:{const{name:t,chain:i,address:a,owner:s}=e;return`${n}:${t}:${i}:${a}${s?`:${s}`:""}`}case r.MemoType.DEPOSIT:{const{chain:t,symbol:i,address:a,singleSide:s}=e;return s?`${n}:${t}/${i}::t:0`:`${n}:${t}.${i}:${a||""}:t:0`}case r.MemoType.WITHDRAW:{const{chain:t,ticker:i,symbol:a,basisPoints:s,targetAssetString:c,singleSide:o}=e,l=!o&&c?`:${c}`:"",u=Ee({chain:t,symbol:a,ticker:i});return`${n}:${t}${o?"/":"."}${u}:${s}${l}`}case r.MemoType.OPEN_LOAN:case r.MemoType.CLOSE_LOAN:{const{asset:t,address:i}=e;return`${n}:${t}:${i}`}default:return""}},G=Object.values(r.Chain),Ne=(n="")=>{const e=n.toUpperCase(),[t]=e.split(".");if(G.includes(t))return!0;const[i]=e.split("/");if(G.includes(i))return!0;throw new Error(`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},I=8,w=n=>10n**BigInt(n),b=n=>Math.log10(parseFloat(n.toString()));function H({value:n,bigIntDecimal:e=I,decimal:t=I}){const i=n<0n;let a=n.toString().substring(i?1:0);const s=t-(a.length-1);s>0&&(a="0".repeat(s)+a);const c=a.length-t;let o=a.slice(-t);return parseInt(o[e])>=5?o=`${o.substring(0,e-1)}${(parseInt(o[e-1])+1).toString()}`:o=o.substring(0,e),`${i?"-":""}${a.slice(0,c)}.${o}`.replace(/\.?0*$/,"")}var f,B,V,te,O,ne,v,k,A,y,M,L;const T=class T{constructor(e){C(this,f);C(this,V);C(this,O);C(this,v);C(this,A);C(this,M);g(this,"decimalMultiplier",10n**8n);g(this,"bigIntValue",0n);g(this,"decimal");const t=R(e);this.decimal=typeof e=="object"?e.decimal:void 0,this.decimalMultiplier=w(Math.max(m(this,M,L).call(this,m(this,A,y).call(this,t)),this.decimal||0)),m(this,V,te).call(this,t)}static fromBigInt(e,t){return new T({decimal:t,value:H({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:i}){return T.fromBigInt(new T(e).bigIntValue*w(i)/w(t),i)}get baseValue(){return this.getBaseValue("string")}get baseValueNumber(){return this.getBaseValue("number")}get baseValueBigInt(){return this.getBaseValue("bigint")}set(e){return new this.constructor({decimal:this.decimal,value:e,identifier:this.toString()})}add(...e){return m(this,f,B).call(this,"add",...e)}sub(...e){return m(this,f,B).call(this,"sub",...e)}mul(...e){return m(this,f,B).call(this,"mul",...e)}div(...e){return m(this,f,B).call(this,"div",...e)}gt(e){return this.bigIntValue>this.getBigIntValue(e)}gte(e){return this.bigIntValue>=this.getBigIntValue(e)}lt(e){return this.bigIntValue<this.getBigIntValue(e)}lte(e){return this.bigIntValue<=this.getBigIntValue(e)}eqValue(e){return this.bigIntValue===this.getBigIntValue(e)}getValue(e){const t=this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||b(this.decimalMultiplier));switch(e){case"number":return Number(t);case"string":return t;default:return this.bigIntValue}}getBaseValue(e){const t=this.decimalMultiplier/w(this.decimal||0),i=this.bigIntValue/t;switch(e){case"number":return Number(i);case"string":return i.toString();default:return this.bigIntValue}}getBigIntValue(e,t){return!t&&typeof e=="object"?e.bigIntValue:m(this,v,k).call(this,m(this,A,y).call(this,R(e)),t)}formatBigIntToSafeValue(e,t){const i=t||this.decimal||I,a=Math.max(i,b(this.decimalMultiplier)),s=e<0n,c=e.toString().substring(s?1:0),o=a-(c.length-1),l=o>0?"0".repeat(o)+c:c,u=l.length-a;let h=l.slice(-a);return parseInt(h[i])>=5?h=`${h.substring(0,i-1)}${(parseInt(h[i-1])+1).toString()}`:h=h.substring(0,i),`${s?"-":""}${l.slice(0,u)}.${h}`.replace(/\.?0*$/,"")}toSignificant(e=6){const[t,i]=this.getValue("string").split("."),a=t||"",s=i||"",c=parseInt(a)?a.length+s.length:s.length;if(c<=e)return this.getValue("string");if(a.length>=e)return a.slice(0,e).padEnd(a.length,"0");if(parseInt(a))return`${a}.${s.slice(0,e-a.length)}`.padEnd(c-e,"0");const o=parseInt(s),l=`${o}`.slice(0,e);return`0.${l.padStart(s.length-`${o}`.length+l.length,"0")}`}};f=new WeakSet,B=function(e,...t){const i=m(this,O,ne).call(this,this,...t),a=w(i),s=t.reduce((o,l)=>{const u=this.getBigIntValue(l,i);switch(e){case"add":return o+u;case"sub":return o-u;case"mul":return o*u/a;case"div":{if(u===0n)throw new RangeError("Division by zero");return o*a/u}default:return o}},this.bigIntValue*a/this.decimalMultiplier),c=H({bigIntDecimal:i,decimal:Math.max(i,b(this.decimalMultiplier)),value:s});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},V=new WeakSet,te=function(e){const t=m(this,A,y).call(this,e)||"0";this.bigIntValue=m(this,v,k).call(this,t)},O=new WeakSet,ne=function(...e){const t=e.map(i=>typeof i=="object"?i.decimal||b(i.decimalMultiplier):m(this,M,L).call(this,m(this,A,y).call(this,i))).filter(Boolean);return Math.max(...t,I)},v=new WeakSet,k=function(e,t){const i=t?w(t):this.decimalMultiplier,a=b(i),[s,c=""]=e.split(".");return BigInt(`${s}${c.padEnd(a,"0")}`)},A=new WeakSet,y=function(e){const i=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):R(e)}`.replaceAll(",",".").split(".");return i.length>1?`${i.slice(0,-1).join("")}.${i.at(-1)}`:i[0]},M=new WeakSet,L=function(e){var i;const t=((i=e.split(".")[1])==null?void 0:i.length)||0;return Math.max(t,I)};let S=T;function R(n){return typeof n=="object"?"getValue"in n?n.getValue("string"):n.value:n}let x;const P=n=>{if(!x)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return x.get(n.toUpperCase())||{decimal:r.BaseDecimal.THOR,identifier:""}},W=async(n,e=0)=>{Ne(n);const t=await q(j(n));return new _({decimal:t,value:e,identifier:n})};class _ extends S{constructor(t){super(t.value instanceof S?t.value:{decimal:t.decimal,value:t.value});g(this,"address");g(this,"chain");g(this,"isSynthetic",!1);g(this,"isGasAsset",!1);g(this,"symbol");g(this,"ticker");g(this,"type");const i="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,a=j(i);this.type=X(a),this.chain=a.chain,this.ticker=a.ticker,this.symbol=a.symbol,this.address=a.address,this.isSynthetic=a.isSynthetic,this.isGasAsset=a.isGasAsset}get assetValue(){return`${this.getValue("string")} ${this.ticker}`}toString(){return`${this.chain}.${this.symbol}`}eq({chain:t,symbol:i}){return this.chain===t&&this.symbol===i}static async fromString(t,i=0){return W(t,i)}static fromStringSync(t,i=0){const{decimal:a,identifier:s}=P(t);return s?new _({decimal:a,identifier:s,value:i}):void 0}static async fromIdentifier(t,i=0){return W(t,i)}static fromIdentifierSync(t,i=0){const{decimal:a,identifier:s}=P(t);return new _({decimal:a,identifier:s,value:i})}static fromChainOrSignature(t,i=0){const{decimal:a,identifier:s}=z(t);return new _({value:i,decimal:a,identifier:s})}static async fromTCQuote(t,i=0){const a=await q(j(t)),s=this.shiftDecimals({value:i,from:r.BaseDecimal.THOR,to:a});return new _({value:s,identifier:t,decimal:a})}static fromTCQuoteStatic(t,i=0){const a=P(t),s=this.shiftDecimals({value:i,from:r.BaseDecimal.THOR,to:a.decimal});return new _({...a,value:s})}static async loadStaticAssets(){return new Promise(async(t,i)=>{try{const{ThorchainList:a,NativeList:s,...c}=await import("@swapkit/tokens");x=[s,...Object.values(c)].reduce((l,{tokens:u})=>(u.forEach(({identifier:h,chain:p,...$})=>{const E="decimals"in $?$.decimals:r.BaseDecimal[p];l.set(h,{identifier:h,decimal:E})}),l),new Map),t({ok:!0})}catch(a){console.error(a),i({ok:!1,error:a,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}}const Re=n=>{const e=_.fromChainOrSignature(n);switch(n){case r.Chain.Bitcoin:case r.Chain.Litecoin:case r.Chain.BitcoinCash:return e.add(10001);case r.Chain.Dogecoin:return e.add(100000001);case r.Chain.Avalanche:case r.Chain.Ethereum:return e.add(10*10**9);case r.Chain.THORChain:case r.Chain.Maya:return e.add(0);default:return e.add(1)}},j=n=>{const e=n.slice(0,14).includes("/"),t=n.includes(".")?n:`${r.Chain.THORChain}.${n}`,[i,a]=t.split("."),[s,c]=a.split("-");return{address:c==null?void 0:c.toLowerCase(),chain:i,isGasAsset:J({chain:i,symbol:a}),isSynthetic:e,symbol:c?`${s}-${(c==null?void 0:c.toLowerCase())??""}`:a,ticker:e?a:s}},Pe={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class F extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:Pe[e],message:e}}),Object.setPrototypeOf(this,F.prototype)}}class ie extends S{eq(e){return this.eqValue(e)}}exports.AssetValue=_;exports.BigIntArithmetics=S;exports.SwapKitError=F;exports.SwapKitNumber=ie;exports.assetFromString=Ie;exports.derivationPathToString=Ae;exports.formatBigIntToSafeValue=H;exports.gasFeeMultiplier=ye;exports.getAssetType=X;exports.getAsymmetricAssetShare=Z;exports.getAsymmetricAssetWithdrawAmount=ve;exports.getAsymmetricRuneShare=Q;exports.getAsymmetricRuneWithdrawAmount=Te;exports.getCommonAssetInfo=z;exports.getDecimal=q;exports.getEstimatedPoolShare=Ve;exports.getLiquiditySlippage=Oe;exports.getMemoFor=De;exports.getMinAmountByChain=Re;exports.getRequest=we;exports.getSymmetricPoolShare=ee;exports.getSymmetricWithdraw=Me;exports.getTHORNameCost=Ce;exports.isGasAsset=J;exports.postRequest=K;exports.validateTHORName=fe;
|
|
1
|
+
"use strict";var oe=Object.create;var R=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var he=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var me=(n,e,t)=>e in n?R(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var ge=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ue(e))!de.call(n,a)&&a!==t&&R(n,a,{get:()=>e[a],enumerable:!(i=le(e,a))||i.enumerable});return n};var _e=(n,e,t)=>(t=n!=null?oe(he(n)):{},ge(e||!n||!n.__esModule?R(t,"default",{value:n,enumerable:!0}):t,n));var g=(n,e,t)=>(me(n,typeof e!="symbol"?e+"":e,t),t),pe=(n,e,t)=>{if(!e.has(n))throw TypeError("Cannot "+t)};var C=(n,e,t)=>{if(e.has(n))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(n):e.set(n,t)};var m=(n,e,t)=>(pe(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("@swapkit/types"),Ce=n=>{if(n<0)throw new Error("Invalid number of year");return 10+n},fe=n=>{if(n.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!n.match(e)},Ae=([n,e,t,i,a])=>`${n}'/${e}'/${t}'/${i}${typeof a!="number"?"":`/${a}`}`,Se=async(n,e)=>{try{const t=Object.entries(e||{}).reduce((a,[s,c])=>(c&&(a[s]=c),a),{});return(await fetch(`${n}${e?`?${new URLSearchParams(t).toString()}`:""}`,{method:"GET",mode:"cors",credentials:"omit",referrer:"https://sk.thorswap.net"})).json()}catch(t){return console.error(t),{}}},K=async(n,e,t,i=!1)=>{try{const a=await fetch(`${n}`,{body:e,headers:t,method:"POST",referrer:"https://sk.thorswap.net"});return i?a.text():a.json()}catch{return{}}},we="0x313ce567",Y=async({chain:n,to:e})=>{try{const t=await K(r.ChainToRPC[n],JSON.stringify({method:"eth_call",params:[{to:e.toLowerCase(),data:we},"latest"],id:44,jsonrpc:"2.0"}),{accept:"*/*","cache-control":"no-cache","content-type":"application/json"},!0),{result:i}=JSON.parse(t);return parseInt(BigInt(i).toString())}catch(t){return console.error(t),r.BaseDecimal[n]}},$e=async n=>{if(n===r.Chain.Ethereum)return r.BaseDecimal.ETH;const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?Y({chain:r.Chain.Ethereum,to:e}):r.BaseDecimal.ETH},be=async n=>{const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?Y({chain:r.Chain.Avalanche,to:e.toLowerCase()}):r.BaseDecimal.AVAX},Be=async n=>(n===r.Chain.BinanceSmartChain,r.BaseDecimal.BSC),q=async({chain:n,symbol:e})=>{switch(n){case r.Chain.Ethereum:return $e(e);case r.Chain.Avalanche:return be(e);case r.Chain.BinanceSmartChain:return Be(e);default:return r.BaseDecimal[n]}},ye={[r.FeeOption.Average]:1.2,[r.FeeOption.Fast]:1.5,[r.FeeOption.Fastest]:2},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
|
@@ -30,7 +30,7 @@ export declare class AssetValue extends BigIntArithmetics {
|
|
|
30
30
|
type: ReturnType<typeof getAssetType>;
|
|
31
31
|
constructor(params: AssetValueParams);
|
|
32
32
|
get assetValue(): string;
|
|
33
|
-
toString(): string;
|
|
33
|
+
toString(short?: boolean): string;
|
|
34
34
|
eq({ chain, symbol }: {
|
|
35
35
|
chain: Chain;
|
|
36
36
|
symbol: string;
|
|
@@ -73,8 +73,17 @@ export declare class BigIntArithmetics {
|
|
|
73
73
|
to: number;
|
|
74
74
|
}): BigIntArithmetics;
|
|
75
75
|
constructor(params: SKBigIntParams);
|
|
76
|
+
/**
|
|
77
|
+
* @deprecated Use `getBaseValue('string')` instead
|
|
78
|
+
*/
|
|
76
79
|
get baseValue(): string;
|
|
80
|
+
/**
|
|
81
|
+
* @deprecated Use `getBaseValue('number')` instead
|
|
82
|
+
*/
|
|
77
83
|
get baseValueNumber(): number;
|
|
84
|
+
/**
|
|
85
|
+
* @deprecated Use `getBaseValue('bigint')` instead
|
|
86
|
+
*/
|
|
78
87
|
get baseValueBigInt(): bigint;
|
|
79
88
|
set(value: SKBigIntParams): any;
|
|
80
89
|
add(...args: InitialisationValueType[]): this;
|
|
@@ -155,6 +164,8 @@ declare const errorMessages: {
|
|
|
155
164
|
readonly helpers_number_different_decimals: 99101;
|
|
156
165
|
};
|
|
157
166
|
|
|
167
|
+
export declare const filterAssets: (assets: AssetValue[]) => AssetValue[];
|
|
168
|
+
|
|
158
169
|
export declare function formatBigIntToSafeValue({ value, bigIntDecimal, decimal, }: {
|
|
159
170
|
value: bigint;
|
|
160
171
|
bigIntDecimal?: number;
|
|
@@ -166,7 +177,7 @@ export declare const gasFeeMultiplier: Record<FeeOption, number>;
|
|
|
166
177
|
export declare const getAssetType: ({ chain, symbol }: {
|
|
167
178
|
chain: Chain;
|
|
168
179
|
symbol: string;
|
|
169
|
-
}) =>
|
|
180
|
+
}) => Chain.Avalanche | Chain.Cosmos | Chain.Kujira | "Synth" | "Native" | "BEP2" | "BEP20" | "ERC20" | "POLYGON" | "ARBITRUM" | "OPTIMISM";
|
|
170
181
|
|
|
171
182
|
export declare const getAsymmetricAssetShare: ({ liquidityUnits, poolUnits, assetDepth, }: ShareParams<{
|
|
172
183
|
assetDepth: string;
|
package/dist/index.es.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
var nt = Object.defineProperty;
|
|
2
2
|
var rt = (n, t, e) => t in n ? nt(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
|
|
3
|
-
var
|
|
3
|
+
var _ = (n, t, e) => (rt(n, typeof t != "symbol" ? t + "" : t, e), e), st = (n, t, e) => {
|
|
4
4
|
if (!t.has(n))
|
|
5
5
|
throw TypeError("Cannot " + e);
|
|
6
6
|
};
|
|
@@ -9,18 +9,18 @@ var $ = (n, t, e) => {
|
|
|
9
9
|
throw TypeError("Cannot add the same private member more than once");
|
|
10
10
|
t instanceof WeakSet ? t.add(n) : t.set(n, e);
|
|
11
11
|
};
|
|
12
|
-
var
|
|
12
|
+
var g = (n, t, e) => (st(n, t, "access private method"), e);
|
|
13
13
|
import { FeeOption as H, BaseDecimal as m, Chain as i, ChainToRPC as it, MemoType as p } from "@swapkit/types";
|
|
14
|
-
const
|
|
14
|
+
const vt = (n) => {
|
|
15
15
|
if (n < 0)
|
|
16
16
|
throw new Error("Invalid number of year");
|
|
17
17
|
return 10 + n;
|
|
18
|
-
},
|
|
18
|
+
}, Vt = (n) => {
|
|
19
19
|
if (n.length > 30)
|
|
20
20
|
return !1;
|
|
21
21
|
const t = /^[a-zA-Z0-9+_-]+$/g;
|
|
22
22
|
return !!n.match(t);
|
|
23
|
-
},
|
|
23
|
+
}, Ct = ([n, t, e, r, s]) => `${n}'/${t}'/${e}'/${r}${typeof s != "number" ? "" : `/${s}`}`, Tt = async (n, t) => {
|
|
24
24
|
try {
|
|
25
25
|
const e = Object.entries(t || {}).reduce(
|
|
26
26
|
(s, [a, c]) => (c && (s[a] = c), s),
|
|
@@ -81,7 +81,7 @@ const St = (n) => {
|
|
|
81
81
|
default:
|
|
82
82
|
return m[n];
|
|
83
83
|
}
|
|
84
|
-
},
|
|
84
|
+
}, Bt = {
|
|
85
85
|
[H.Average]: 1.2,
|
|
86
86
|
[H.Fast]: 1.5,
|
|
87
87
|
[H.Fastest]: 2
|
|
@@ -152,9 +152,9 @@ const St = (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 St = (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:
|
|
@@ -174,31 +174,36 @@ const St = (n) => {
|
|
|
174
174
|
var c;
|
|
175
175
|
const [t, ...e] = n.split("."), r = n.includes("/"), s = e.join("."), a = (c = s == null ? void 0 : s.split("-")) == null ? void 0 : c[0];
|
|
176
176
|
return { chain: t, symbol: s, ticker: a, synth: r };
|
|
177
|
-
},
|
|
177
|
+
}, gt = new RegExp(
|
|
178
|
+
/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
|
|
179
|
+
"gmi"
|
|
180
|
+
), Et = (n) => n.filter(
|
|
181
|
+
(t) => !gt.test(t.toString()) && !t.toString().includes("undefined")
|
|
182
|
+
), _t = ({
|
|
178
183
|
liquidityUnits: n,
|
|
179
184
|
poolUnits: t,
|
|
180
185
|
runeDepth: e
|
|
181
186
|
}) => {
|
|
182
187
|
const r = h(n), s = h(t), a = h(e), c = r.mul(a), o = s.mul(s).mul(2), u = s.mul(r).mul(2), l = r.mul(r), d = s.mul(s).mul(s);
|
|
183
188
|
return c.mul(o.sub(u).add(l)).div(d);
|
|
184
|
-
},
|
|
189
|
+
}, pt = ({
|
|
185
190
|
liquidityUnits: n,
|
|
186
191
|
poolUnits: t,
|
|
187
192
|
assetDepth: e
|
|
188
193
|
}) => {
|
|
189
194
|
const r = h(n), s = h(t), a = h(e), c = r.mul(a), o = s.mul(s).mul(2), u = s.mul(r).mul(2), l = r.mul(r), d = c.mul(o.sub(u).add(l)), A = s.mul(s).mul(s);
|
|
190
195
|
return d.div(A);
|
|
191
|
-
},
|
|
196
|
+
}, Ot = ({
|
|
192
197
|
percent: n,
|
|
193
198
|
runeDepth: t,
|
|
194
199
|
liquidityUnits: e,
|
|
195
200
|
poolUnits: r
|
|
196
|
-
}) => _t({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(n),
|
|
201
|
+
}) => _t({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), Mt = ({
|
|
197
202
|
percent: n,
|
|
198
203
|
assetDepth: t,
|
|
199
204
|
liquidityUnits: e,
|
|
200
205
|
poolUnits: r
|
|
201
|
-
}) =>
|
|
206
|
+
}) => pt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), h = (n) => new bt({ value: n, decimal: m.THOR }), ft = ({
|
|
202
207
|
liquidityUnits: n,
|
|
203
208
|
poolUnits: t,
|
|
204
209
|
runeDepth: e,
|
|
@@ -206,17 +211,17 @@ const St = (n) => {
|
|
|
206
211
|
}) => ({
|
|
207
212
|
assetAmount: h(r).mul(n).div(t),
|
|
208
213
|
runeAmount: h(e).mul(n).div(t)
|
|
209
|
-
}),
|
|
214
|
+
}), Nt = ({
|
|
210
215
|
liquidityUnits: n,
|
|
211
216
|
poolUnits: t,
|
|
212
217
|
runeDepth: e,
|
|
213
218
|
assetDepth: r,
|
|
214
219
|
percent: s
|
|
215
220
|
}) => Object.fromEntries(
|
|
216
|
-
Object.entries(
|
|
221
|
+
Object.entries(ft({ liquidityUnits: n, poolUnits: t, runeDepth: e, assetDepth: r })).map(
|
|
217
222
|
([a, c]) => [a, c.mul(s)]
|
|
218
223
|
)
|
|
219
|
-
),
|
|
224
|
+
), Rt = ({
|
|
220
225
|
runeDepth: n,
|
|
221
226
|
poolUnits: t,
|
|
222
227
|
assetDepth: e,
|
|
@@ -224,12 +229,12 @@ const St = (n) => {
|
|
|
224
229
|
runeAmount: s,
|
|
225
230
|
assetAmount: a
|
|
226
231
|
}) => {
|
|
227
|
-
const c = h(n), o = h(e), u = h(t), l = h(s), d = h(a), A = l.mul(o),
|
|
228
|
-
if (
|
|
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);
|
|
233
|
+
if (F.baseValueNumber === 0)
|
|
229
234
|
return k.div(u).baseValueNumber;
|
|
230
235
|
const et = u.add(k);
|
|
231
236
|
return k.div(et).baseValueNumber;
|
|
232
|
-
},
|
|
237
|
+
}, kt = ({
|
|
233
238
|
runeAmount: n,
|
|
234
239
|
assetAmount: t,
|
|
235
240
|
runeDepth: e,
|
|
@@ -237,11 +242,11 @@ const St = (n) => {
|
|
|
237
242
|
}) => {
|
|
238
243
|
const s = h(e), a = h(r), c = h(t), o = h(n), u = c.mul(s).sub(a.mul(o)), l = a.mul(o).add(s.mul(a));
|
|
239
244
|
return Math.abs(u.div(l).baseValueNumber);
|
|
240
|
-
},
|
|
245
|
+
}, At = ({
|
|
241
246
|
symbol: n,
|
|
242
247
|
ticker: t,
|
|
243
248
|
chain: e
|
|
244
|
-
}) => e === "ETH" && t !== "ETH" ? `${t}-${n.slice(-3)}` : n,
|
|
249
|
+
}) => e === "ETH" && t !== "ETH" ? `${t}-${n.slice(-3)}` : n, Ht = (n, t) => {
|
|
245
250
|
switch (n) {
|
|
246
251
|
case p.LEAVE:
|
|
247
252
|
case p.BOND: {
|
|
@@ -261,7 +266,7 @@ const St = (n) => {
|
|
|
261
266
|
return a ? `${n}:${e}/${r}::t:0` : `${n}:${e}.${r}:${s || ""}:t:0`;
|
|
262
267
|
}
|
|
263
268
|
case p.WITHDRAW: {
|
|
264
|
-
const { chain: e, ticker: r, symbol: s, basisPoints: a, targetAssetString: c, singleSide: o } = t, u = !o && c ? `:${c}` : "", l =
|
|
269
|
+
const { chain: e, ticker: r, symbol: s, basisPoints: a, targetAssetString: c, singleSide: o } = t, u = !o && c ? `:${c}` : "", l = At({ chain: e, symbol: s, ticker: r });
|
|
265
270
|
return `${n}:${e}${o ? "/" : "."}${l}:${a}${u}`;
|
|
266
271
|
}
|
|
267
272
|
case p.OPEN_LOAN:
|
|
@@ -272,21 +277,21 @@ const St = (n) => {
|
|
|
272
277
|
default:
|
|
273
278
|
return "";
|
|
274
279
|
}
|
|
275
|
-
},
|
|
280
|
+
}, G = Object.values(i), $t = (n = "") => {
|
|
276
281
|
const t = n.toUpperCase(), [e] = t.split(".");
|
|
277
|
-
if (
|
|
282
|
+
if (G.includes(e))
|
|
278
283
|
return !0;
|
|
279
284
|
const [r] = t.split("/");
|
|
280
|
-
if (
|
|
285
|
+
if (G.includes(r))
|
|
281
286
|
return !0;
|
|
282
287
|
throw new Error(
|
|
283
288
|
`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
284
289
|
);
|
|
285
|
-
},
|
|
286
|
-
function
|
|
290
|
+
}, T = 8, S = (n) => 10n ** BigInt(n), v = (n) => Math.log10(parseFloat(n.toString()));
|
|
291
|
+
function U({
|
|
287
292
|
value: n,
|
|
288
|
-
bigIntDecimal: t =
|
|
289
|
-
decimal: e =
|
|
293
|
+
bigIntDecimal: t = T,
|
|
294
|
+
decimal: e = T
|
|
290
295
|
}) {
|
|
291
296
|
const r = n < 0n;
|
|
292
297
|
let s = n.toString().substring(r ? 1 : 0);
|
|
@@ -299,8 +304,8 @@ function G({
|
|
|
299
304
|
""
|
|
300
305
|
);
|
|
301
306
|
}
|
|
302
|
-
var w, V, M,
|
|
303
|
-
const
|
|
307
|
+
var w, V, M, z, N, J, E, D, b, C, O, L;
|
|
308
|
+
const B = class B {
|
|
304
309
|
constructor(t) {
|
|
305
310
|
$(this, w);
|
|
306
311
|
$(this, M);
|
|
@@ -308,18 +313,18 @@ const y = class y {
|
|
|
308
313
|
$(this, E);
|
|
309
314
|
$(this, b);
|
|
310
315
|
$(this, O);
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
316
|
+
_(this, "decimalMultiplier", 10n ** 8n);
|
|
317
|
+
_(this, "bigIntValue", 0n);
|
|
318
|
+
_(this, "decimal");
|
|
314
319
|
const e = P(t);
|
|
315
|
-
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier =
|
|
316
|
-
Math.max(
|
|
317
|
-
),
|
|
320
|
+
this.decimal = typeof t == "object" ? t.decimal : void 0, this.decimalMultiplier = S(
|
|
321
|
+
Math.max(g(this, O, L).call(this, g(this, b, C).call(this, e)), this.decimal || 0)
|
|
322
|
+
), g(this, M, z).call(this, e);
|
|
318
323
|
}
|
|
319
324
|
static fromBigInt(t, e) {
|
|
320
|
-
return new
|
|
325
|
+
return new B({
|
|
321
326
|
decimal: e,
|
|
322
|
-
value:
|
|
327
|
+
value: U({ value: t, bigIntDecimal: e, decimal: e })
|
|
323
328
|
});
|
|
324
329
|
}
|
|
325
330
|
static shiftDecimals({
|
|
@@ -327,17 +332,26 @@ const y = class y {
|
|
|
327
332
|
from: e,
|
|
328
333
|
to: r
|
|
329
334
|
}) {
|
|
330
|
-
return
|
|
331
|
-
new
|
|
335
|
+
return B.fromBigInt(
|
|
336
|
+
new B(t).bigIntValue * S(r) / S(e),
|
|
332
337
|
r
|
|
333
338
|
);
|
|
334
339
|
}
|
|
340
|
+
/**
|
|
341
|
+
* @deprecated Use `getBaseValue('string')` instead
|
|
342
|
+
*/
|
|
335
343
|
get baseValue() {
|
|
336
344
|
return this.getBaseValue("string");
|
|
337
345
|
}
|
|
346
|
+
/**
|
|
347
|
+
* @deprecated Use `getBaseValue('number')` instead
|
|
348
|
+
*/
|
|
338
349
|
get baseValueNumber() {
|
|
339
350
|
return this.getBaseValue("number");
|
|
340
351
|
}
|
|
352
|
+
/**
|
|
353
|
+
* @deprecated Use `getBaseValue('bigint')` instead
|
|
354
|
+
*/
|
|
341
355
|
get baseValueBigInt() {
|
|
342
356
|
return this.getBaseValue("bigint");
|
|
343
357
|
}
|
|
@@ -345,16 +359,16 @@ const y = class y {
|
|
|
345
359
|
return new this.constructor({ decimal: this.decimal, value: t, identifier: this.toString() });
|
|
346
360
|
}
|
|
347
361
|
add(...t) {
|
|
348
|
-
return
|
|
362
|
+
return g(this, w, V).call(this, "add", ...t);
|
|
349
363
|
}
|
|
350
364
|
sub(...t) {
|
|
351
|
-
return
|
|
365
|
+
return g(this, w, V).call(this, "sub", ...t);
|
|
352
366
|
}
|
|
353
367
|
mul(...t) {
|
|
354
|
-
return
|
|
368
|
+
return g(this, w, V).call(this, "mul", ...t);
|
|
355
369
|
}
|
|
356
370
|
div(...t) {
|
|
357
|
-
return
|
|
371
|
+
return g(this, w, V).call(this, "div", ...t);
|
|
358
372
|
}
|
|
359
373
|
gt(t) {
|
|
360
374
|
return this.bigIntValue > this.getBigIntValue(t);
|
|
@@ -386,7 +400,7 @@ const y = class y {
|
|
|
386
400
|
}
|
|
387
401
|
}
|
|
388
402
|
getBaseValue(t) {
|
|
389
|
-
const e = this.decimalMultiplier /
|
|
403
|
+
const e = this.decimalMultiplier / S(this.decimal || 0), r = this.bigIntValue / e;
|
|
390
404
|
switch (t) {
|
|
391
405
|
case "number":
|
|
392
406
|
return Number(r);
|
|
@@ -397,10 +411,13 @@ const y = class y {
|
|
|
397
411
|
}
|
|
398
412
|
}
|
|
399
413
|
getBigIntValue(t, e) {
|
|
400
|
-
|
|
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);
|
|
401
418
|
}
|
|
402
419
|
formatBigIntToSafeValue(t, e) {
|
|
403
|
-
const r = e || this.decimal ||
|
|
420
|
+
const r = e || this.decimal || T, s = Math.max(
|
|
404
421
|
r,
|
|
405
422
|
v(this.decimalMultiplier)
|
|
406
423
|
), a = t < 0n, c = t.toString().substring(a ? 1 : 0), o = s - (c.length - 1), u = o > 0 ? "0".repeat(o) + c : c, l = u.length - s;
|
|
@@ -429,7 +446,7 @@ const y = class y {
|
|
|
429
446
|
}
|
|
430
447
|
};
|
|
431
448
|
w = new WeakSet(), V = function(t, ...e) {
|
|
432
|
-
const r =
|
|
449
|
+
const r = g(this, N, J).call(this, this, ...e), s = S(r), a = e.reduce(
|
|
433
450
|
(o, u) => {
|
|
434
451
|
const l = this.getBigIntValue(u, r);
|
|
435
452
|
switch (t) {
|
|
@@ -450,68 +467,72 @@ w = new WeakSet(), V = function(t, ...e) {
|
|
|
450
467
|
},
|
|
451
468
|
//normalize is to precision multiplier base
|
|
452
469
|
this.bigIntValue * s / this.decimalMultiplier
|
|
453
|
-
), c =
|
|
470
|
+
), c = U({
|
|
454
471
|
bigIntDecimal: r,
|
|
455
472
|
decimal: Math.max(r, v(this.decimalMultiplier)),
|
|
456
473
|
value: a
|
|
457
474
|
});
|
|
458
475
|
return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() });
|
|
459
|
-
}, M = new WeakSet(),
|
|
460
|
-
const e =
|
|
461
|
-
this.bigIntValue =
|
|
462
|
-
}, N = new WeakSet(),
|
|
476
|
+
}, M = new WeakSet(), z = function(t) {
|
|
477
|
+
const e = g(this, b, C).call(this, t) || "0";
|
|
478
|
+
this.bigIntValue = g(this, E, D).call(this, e);
|
|
479
|
+
}, N = new WeakSet(), J = function(...t) {
|
|
463
480
|
const e = t.map(
|
|
464
|
-
(r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) :
|
|
481
|
+
(r) => typeof r == "object" ? r.decimal || v(r.decimalMultiplier) : g(this, O, L).call(this, g(this, b, C).call(this, r))
|
|
465
482
|
).filter(Boolean);
|
|
466
|
-
return Math.max(...e,
|
|
467
|
-
}, E = new WeakSet(),
|
|
468
|
-
const r = e ?
|
|
483
|
+
return Math.max(...e, T);
|
|
484
|
+
}, E = new WeakSet(), D = function(t, e) {
|
|
485
|
+
const r = e ? S(e) : this.decimalMultiplier, s = v(r), [a = "", c = ""] = t.split(".");
|
|
469
486
|
return BigInt(`${a}${c.padEnd(s, "0")}`);
|
|
470
|
-
}, b = new WeakSet(),
|
|
487
|
+
}, b = new WeakSet(), C = function(t) {
|
|
471
488
|
const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
|
|
472
489
|
useGrouping: !1,
|
|
473
490
|
maximumFractionDigits: 20
|
|
474
491
|
}) : P(t)}`.replaceAll(",", ".").split(".");
|
|
475
492
|
return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0];
|
|
476
|
-
}, O = new WeakSet(),
|
|
493
|
+
}, O = new WeakSet(), L = function(t) {
|
|
477
494
|
var r;
|
|
478
495
|
const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
|
|
479
|
-
return Math.max(e,
|
|
496
|
+
return Math.max(e, T);
|
|
480
497
|
};
|
|
481
|
-
let
|
|
498
|
+
let y = B;
|
|
482
499
|
function P(n) {
|
|
483
500
|
return typeof n == "object" ? "getValue" in n ? n.getValue("string") : n.value : n;
|
|
484
501
|
}
|
|
485
502
|
let j;
|
|
486
|
-
const
|
|
503
|
+
const x = (n) => {
|
|
487
504
|
if (!j)
|
|
488
505
|
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
|
|
489
506
|
return j.get(n.toUpperCase()) || { decimal: m.THOR, identifier: "" };
|
|
490
507
|
}, W = async (n, t = 0) => {
|
|
491
|
-
|
|
508
|
+
$t(n);
|
|
492
509
|
const e = await K(q(n));
|
|
493
510
|
return new f({ decimal: e, value: t, identifier: n });
|
|
494
511
|
};
|
|
495
|
-
class f extends
|
|
512
|
+
class f extends y {
|
|
496
513
|
constructor(e) {
|
|
497
514
|
super(
|
|
498
|
-
e.value instanceof
|
|
515
|
+
e.value instanceof y ? e.value : { decimal: e.decimal, value: e.value }
|
|
499
516
|
);
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
517
|
+
_(this, "address");
|
|
518
|
+
_(this, "chain");
|
|
519
|
+
_(this, "isSynthetic", !1);
|
|
520
|
+
_(this, "isGasAsset", !1);
|
|
521
|
+
_(this, "symbol");
|
|
522
|
+
_(this, "ticker");
|
|
523
|
+
_(this, "type");
|
|
507
524
|
const r = "identifier" in e ? e.identifier : `${e.chain}.${e.symbol}`, s = q(r);
|
|
508
525
|
this.type = mt(s), this.chain = s.chain, this.ticker = s.ticker, this.symbol = s.symbol, this.address = s.address, this.isSynthetic = s.isSynthetic, this.isGasAsset = s.isGasAsset;
|
|
509
526
|
}
|
|
510
527
|
get assetValue() {
|
|
511
528
|
return `${this.getValue("string")} ${this.ticker}`;
|
|
512
529
|
}
|
|
513
|
-
toString() {
|
|
514
|
-
|
|
530
|
+
toString(e = !1) {
|
|
531
|
+
const r = this.isSynthetic ? this.ticker : `${this.chain}.${this.ticker}`;
|
|
532
|
+
return e ? r : (
|
|
533
|
+
// THOR.ETH/ETH | ETH.USDT-0x1234567890
|
|
534
|
+
`${this.chain}.${this.symbol}`
|
|
535
|
+
);
|
|
515
536
|
}
|
|
516
537
|
eq({ chain: e, symbol: r }) {
|
|
517
538
|
return this.chain === e && this.symbol === r;
|
|
@@ -520,7 +541,7 @@ class f extends T {
|
|
|
520
541
|
return W(e, r);
|
|
521
542
|
}
|
|
522
543
|
static fromStringSync(e, r = 0) {
|
|
523
|
-
const { decimal: s, identifier: a } =
|
|
544
|
+
const { decimal: s, identifier: a } = x(
|
|
524
545
|
e
|
|
525
546
|
);
|
|
526
547
|
return a ? new f({ decimal: s, identifier: a, value: r }) : void 0;
|
|
@@ -529,7 +550,7 @@ class f extends T {
|
|
|
529
550
|
return W(e, r);
|
|
530
551
|
}
|
|
531
552
|
static fromIdentifierSync(e, r = 0) {
|
|
532
|
-
const { decimal: s, identifier: a } =
|
|
553
|
+
const { decimal: s, identifier: a } = x(e);
|
|
533
554
|
return new f({ decimal: s, identifier: a, value: r });
|
|
534
555
|
}
|
|
535
556
|
static fromChainOrSignature(e, r = 0) {
|
|
@@ -541,7 +562,7 @@ class f extends T {
|
|
|
541
562
|
return new f({ value: a, identifier: e, decimal: s });
|
|
542
563
|
}
|
|
543
564
|
static fromTCQuoteStatic(e, r = 0) {
|
|
544
|
-
const s =
|
|
565
|
+
const s = x(e), a = this.shiftDecimals({
|
|
545
566
|
value: r,
|
|
546
567
|
from: m.THOR,
|
|
547
568
|
to: s.decimal
|
|
@@ -560,8 +581,8 @@ class f extends T {
|
|
|
560
581
|
...c
|
|
561
582
|
} = await import("@swapkit/tokens");
|
|
562
583
|
j = [a, ...Object.values(c)].reduce(
|
|
563
|
-
(u, { tokens: l }) => (l.forEach(({ identifier: d, chain: A, ...
|
|
564
|
-
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];
|
|
565
586
|
u.set(d, { identifier: d, decimal: R });
|
|
566
587
|
}), u),
|
|
567
588
|
/* @__PURE__ */ new Map()
|
|
@@ -577,7 +598,7 @@ class f extends T {
|
|
|
577
598
|
);
|
|
578
599
|
}
|
|
579
600
|
}
|
|
580
|
-
const
|
|
601
|
+
const Pt = (n) => {
|
|
581
602
|
const t = f.fromChainOrSignature(n);
|
|
582
603
|
switch (n) {
|
|
583
604
|
case i.Bitcoin:
|
|
@@ -605,7 +626,7 @@ const kt = (n) => {
|
|
|
605
626
|
symbol: c ? `${a}-${(c == null ? void 0 : c.toLowerCase()) ?? ""}` : s,
|
|
606
627
|
ticker: t ? s : a
|
|
607
628
|
};
|
|
608
|
-
},
|
|
629
|
+
}, wt = {
|
|
609
630
|
/**
|
|
610
631
|
* Core
|
|
611
632
|
*/
|
|
@@ -662,41 +683,42 @@ const kt = (n) => {
|
|
|
662
683
|
*/
|
|
663
684
|
helpers_number_different_decimals: 99101
|
|
664
685
|
};
|
|
665
|
-
class
|
|
686
|
+
class Q extends Error {
|
|
666
687
|
constructor(t, e) {
|
|
667
|
-
console.error(e), super(t, { cause: { code:
|
|
688
|
+
console.error(e), super(t, { cause: { code: wt[t], message: t } }), Object.setPrototypeOf(this, Q.prototype);
|
|
668
689
|
}
|
|
669
690
|
}
|
|
670
|
-
class
|
|
691
|
+
class bt extends y {
|
|
671
692
|
eq(t) {
|
|
672
693
|
return this.eqValue(t);
|
|
673
694
|
}
|
|
674
695
|
}
|
|
675
696
|
export {
|
|
676
697
|
f as AssetValue,
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
698
|
+
y as BigIntArithmetics,
|
|
699
|
+
Q as SwapKitError,
|
|
700
|
+
bt as SwapKitNumber,
|
|
680
701
|
yt as assetFromString,
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
702
|
+
Ct as derivationPathToString,
|
|
703
|
+
Et as filterAssets,
|
|
704
|
+
U as formatBigIntToSafeValue,
|
|
705
|
+
Bt as gasFeeMultiplier,
|
|
684
706
|
mt as getAssetType,
|
|
685
|
-
|
|
686
|
-
|
|
707
|
+
pt as getAsymmetricAssetShare,
|
|
708
|
+
Mt as getAsymmetricAssetWithdrawAmount,
|
|
687
709
|
_t as getAsymmetricRuneShare,
|
|
688
|
-
|
|
710
|
+
Ot as getAsymmetricRuneWithdrawAmount,
|
|
689
711
|
ht as getCommonAssetInfo,
|
|
690
712
|
K as getDecimal,
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
713
|
+
Rt as getEstimatedPoolShare,
|
|
714
|
+
kt as getLiquiditySlippage,
|
|
715
|
+
Ht as getMemoFor,
|
|
716
|
+
Pt as getMinAmountByChain,
|
|
717
|
+
Tt as getRequest,
|
|
718
|
+
ft as getSymmetricPoolShare,
|
|
719
|
+
Nt as getSymmetricWithdraw,
|
|
720
|
+
vt as getTHORNameCost,
|
|
699
721
|
dt as isGasAsset,
|
|
700
722
|
at as postRequest,
|
|
701
|
-
|
|
723
|
+
Vt as validateTHORName
|
|
702
724
|
};
|
package/package.json
CHANGED
|
@@ -6,15 +6,15 @@
|
|
|
6
6
|
"vite": "4.4.9",
|
|
7
7
|
"vitest": "0.34.4",
|
|
8
8
|
"@internal/config": "0.0.0-internal.0",
|
|
9
|
-
"@swapkit/tokens": "1.0.0-rc.
|
|
10
|
-
"@swapkit/types": "1.0.0-rc.
|
|
9
|
+
"@swapkit/tokens": "1.0.0-rc.5",
|
|
10
|
+
"@swapkit/types": "1.0.0-rc.5"
|
|
11
11
|
},
|
|
12
12
|
"eslintConfig": {
|
|
13
13
|
"extends": "../../../internal/eslint-config"
|
|
14
14
|
},
|
|
15
15
|
"peerDependencies": {
|
|
16
|
-
"@swapkit/tokens": "1.0.0-rc.
|
|
17
|
-
"@swapkit/types": "1.0.0-rc.
|
|
16
|
+
"@swapkit/tokens": "1.0.0-rc.5",
|
|
17
|
+
"@swapkit/types": "1.0.0-rc.5"
|
|
18
18
|
},
|
|
19
19
|
"exports": {
|
|
20
20
|
".": {
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"repository": "https://github.com/thorswap/SwapKit.git",
|
|
40
40
|
"type": "module",
|
|
41
41
|
"types": "./dist/index.d.ts",
|
|
42
|
-
"version": "1.0.0-rc.
|
|
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
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { EVMChain } from '@swapkit/types';
|
|
2
2
|
import { BaseDecimal, Chain, ChainToRPC, FeeOption } from '@swapkit/types';
|
|
3
3
|
|
|
4
|
+
import type { AssetValue } from '../index.ts';
|
|
5
|
+
|
|
4
6
|
import { postRequest } from './others.ts';
|
|
5
7
|
|
|
6
8
|
const getDecimalMethodHex = '0x313ce567';
|
|
@@ -152,9 +154,9 @@ export const getAssetType = ({ chain, symbol }: { chain: Chain; symbol: string }
|
|
|
152
154
|
return 'Native';
|
|
153
155
|
|
|
154
156
|
case Chain.Cosmos:
|
|
155
|
-
return symbol === 'ATOM' ? 'Native' :
|
|
157
|
+
return symbol === 'ATOM' ? 'Native' : Chain.Cosmos;
|
|
156
158
|
case Chain.Kujira:
|
|
157
|
-
return symbol ===
|
|
159
|
+
return symbol === Chain.Kujira ? 'Native' : Chain.Kujira;
|
|
158
160
|
case Chain.Binance:
|
|
159
161
|
return symbol === Chain.Binance ? 'Native' : 'BEP2';
|
|
160
162
|
case Chain.BinanceSmartChain:
|
|
@@ -162,7 +164,7 @@ export const getAssetType = ({ chain, symbol }: { chain: Chain; symbol: string }
|
|
|
162
164
|
case Chain.Ethereum:
|
|
163
165
|
return symbol === Chain.Ethereum ? 'Native' : 'ERC20';
|
|
164
166
|
case Chain.Avalanche:
|
|
165
|
-
return symbol === Chain.Avalanche ? 'Native' :
|
|
167
|
+
return symbol === Chain.Avalanche ? 'Native' : Chain.Avalanche;
|
|
166
168
|
case Chain.Polygon:
|
|
167
169
|
return symbol === Chain.Polygon ? 'Native' : 'POLYGON';
|
|
168
170
|
|
|
@@ -181,3 +183,13 @@ export const assetFromString = (assetString: string) => {
|
|
|
181
183
|
|
|
182
184
|
return { chain, symbol, ticker, synth };
|
|
183
185
|
};
|
|
186
|
+
|
|
187
|
+
const potentialScamRegex = new RegExp(
|
|
188
|
+
/(.)\1{6}|\.ORG|\.NET|\.FINANCE|\.COM|WWW|HTTP|\\\\|\/\/|[\s$%:[\]]/,
|
|
189
|
+
'gmi',
|
|
190
|
+
);
|
|
191
|
+
export const filterAssets = (assets: AssetValue[]) =>
|
|
192
|
+
assets.filter(
|
|
193
|
+
(asset) =>
|
|
194
|
+
!potentialScamRegex.test(asset.toString()) && !asset.toString().includes('undefined'),
|
|
195
|
+
);
|
|
@@ -13,6 +13,10 @@ describe('AssetValue', () => {
|
|
|
13
13
|
symbol: 'USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e',
|
|
14
14
|
});
|
|
15
15
|
expect(fakeAvaxUSDCAsset.assetValue).toBe('1234567890 USDC');
|
|
16
|
+
expect(fakeAvaxUSDCAsset.toString()).toBe(
|
|
17
|
+
'AVAX.USDC-0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e',
|
|
18
|
+
);
|
|
19
|
+
expect(fakeAvaxUSDCAsset.toString(true)).toBe('AVAX.USDC');
|
|
16
20
|
|
|
17
21
|
const thor = AssetValue.fromChainOrSignature('ETH.THOR');
|
|
18
22
|
expect(thor.assetValue).toBe('0 THOR');
|
|
@@ -26,6 +30,8 @@ describe('AssetValue', () => {
|
|
|
26
30
|
|
|
27
31
|
expect(ethSynth.assetValue).toBe('1234567890 ETH/ETH');
|
|
28
32
|
expect(ethSynth.toString()).toBe('THOR.ETH/ETH');
|
|
33
|
+
expect(ethSynth.toString(true)).toBe('ETH/ETH');
|
|
34
|
+
expect(ethSynth.mul(21.37).getValue('string')).toBe('26382715809.3');
|
|
29
35
|
|
|
30
36
|
const atomDerived = new AssetValue({
|
|
31
37
|
identifier: 'THOR.ATOM',
|
|
@@ -35,6 +41,7 @@ describe('AssetValue', () => {
|
|
|
35
41
|
|
|
36
42
|
expect(atomDerived.assetValue).toBe('123456789 ATOM');
|
|
37
43
|
expect(atomDerived.toString()).toBe('THOR.ATOM');
|
|
44
|
+
expect(atomDerived.toString(true)).toBe('THOR.ATOM');
|
|
38
45
|
});
|
|
39
46
|
});
|
|
40
47
|
|
|
@@ -91,8 +91,14 @@ export class AssetValue extends BigIntArithmetics {
|
|
|
91
91
|
return `${this.getValue('string')} ${this.ticker}`;
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
-
toString() {
|
|
95
|
-
|
|
94
|
+
toString(short = false) {
|
|
95
|
+
// THOR.RUNE | ETH/ETH
|
|
96
|
+
const shortFormat = this.isSynthetic ? this.ticker : `${this.chain}.${this.ticker}`;
|
|
97
|
+
|
|
98
|
+
return short
|
|
99
|
+
? shortFormat
|
|
100
|
+
: // THOR.ETH/ETH | ETH.USDT-0x1234567890
|
|
101
|
+
`${this.chain}.${this.symbol}`;
|
|
96
102
|
}
|
|
97
103
|
|
|
98
104
|
eq({ chain, symbol }: { chain: Chain; symbol: string }) {
|
|
@@ -90,12 +90,21 @@ export class BigIntArithmetics {
|
|
|
90
90
|
this.#setValue(value);
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
/**
|
|
94
|
+
* @deprecated Use `getBaseValue('string')` instead
|
|
95
|
+
*/
|
|
93
96
|
get baseValue() {
|
|
94
97
|
return this.getBaseValue('string') as string;
|
|
95
98
|
}
|
|
99
|
+
/**
|
|
100
|
+
* @deprecated Use `getBaseValue('number')` instead
|
|
101
|
+
*/
|
|
96
102
|
get baseValueNumber() {
|
|
97
103
|
return this.getBaseValue('number') as number;
|
|
98
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* @deprecated Use `getBaseValue('bigint')` instead
|
|
107
|
+
*/
|
|
99
108
|
get baseValueBigInt() {
|
|
100
109
|
return this.getBaseValue('bigint') as bigint;
|
|
101
110
|
}
|
|
@@ -171,7 +180,11 @@ export class BigIntArithmetics {
|
|
|
171
180
|
getBigIntValue(value: InitialisationValueType, decimal?: number) {
|
|
172
181
|
if (!decimal && typeof value === 'object') return value.bigIntValue;
|
|
173
182
|
|
|
174
|
-
|
|
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);
|
|
175
188
|
}
|
|
176
189
|
|
|
177
190
|
formatBigIntToSafeValue(value: bigint, decimal?: number) {
|
|
@@ -301,7 +314,7 @@ export class BigIntArithmetics {
|
|
|
301
314
|
#toBigInt(value: string, decimal?: number) {
|
|
302
315
|
const multiplier = decimal ? toMultiplier(decimal) : this.decimalMultiplier;
|
|
303
316
|
const padDecimal = decimalFromMultiplier(multiplier);
|
|
304
|
-
const [integerPart, decimalPart = ''] = value.split('.');
|
|
317
|
+
const [integerPart = '', decimalPart = ''] = value.split('.');
|
|
305
318
|
|
|
306
319
|
return BigInt(`${integerPart}${decimalPart.padEnd(padDecimal, '0')}`);
|
|
307
320
|
}
|