@swapkit/helpers 1.0.0-rc.0 → 1.0.0-rc.1
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 +9 -2
- package/dist/index.es.js +81 -71
- package/package.json +2 -1
- package/src/helpers/liquidity.ts +19 -4
- package/src/modules/__tests__/assetValue.test.ts +11 -1
- package/dist/index.es-8503fb04.js +0 -34669
- package/dist/index.es-903b9173.cjs +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ce=Object.defineProperty;var oe=(n,e,t)=>e in n?ce(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var m=(n,e,t)=>(oe(n,typeof e!="symbol"?e+"":e,t),t),le=(n,e,t)=>{if(!e.has(n))throw TypeError("Cannot "+t)};var p=(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 h=(n,e,t)=>(le(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@swapkit/types"),ue=n=>{if(n<0)throw new Error("Invalid number of year");return 10+n},he=n=>{if(n.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!n.match(e)},de=([n,e,t,i,s])=>`${n}'/${e}'/${t}'/${i}${typeof s!="number"?"":`/${s}`}`,me=async(n,e)=>{const t=Object.entries(e||{}).reduce((s,[r,c])=>(c&&(s[r]=c),s),{});return(await fetch(`${n}${e?`?${new URLSearchParams(t).toString()}`:""}`,{method:"GET",mode:"cors",credentials:"omit",referrer:"https://sk.thorswap.net"})).json()},Y=async(n,e,t,i=!1)=>{const s=await fetch(`${n}`,{body:e,headers:t,method:"POST",referrer:"https://sk.thorswap.net"});return i?s.text():s.json()},ge="0x313ce567",z=async({chain:n,to:e})=>{try{const t=await Y(a.ChainToRPC[n],JSON.stringify({method:"eth_call",params:[{to:e.toLowerCase(),data:ge},"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),a.BaseDecimal[n]}},_e=async n=>{if(n===a.Chain.Ethereum)return a.BaseDecimal.ETH;const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?z({chain:a.Chain.Ethereum,to:e}):a.BaseDecimal.ETH},pe=async n=>{const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?z({chain:a.Chain.Avalanche,to:e.toLowerCase()}):a.BaseDecimal.AVAX},Ce=async n=>(n===a.Chain.BinanceSmartChain,a.BaseDecimal.BSC),F=async({chain:n,symbol:e})=>{switch(n){case a.Chain.Ethereum:return _e(e);case a.Chain.Avalanche:return pe(e);case a.Chain.BinanceSmartChain:return Ce(e);default:return a.BaseDecimal[n]}},fe={[a.FeeOption.Average]:1.2,[a.FeeOption.Fast]:1.5,[a.FeeOption.Fastest]:2},X=({chain:n,symbol:e})=>{switch(n){case a.Chain.Bitcoin:case a.Chain.BitcoinCash:case a.Chain.Litecoin:case a.Chain.Dogecoin:case a.Chain.Binance:case a.Chain.Ethereum:case a.Chain.Avalanche:return e===n;case a.Chain.Arbitrum:case a.Chain.Optimism:return e==="ETH";case a.Chain.Maya:return e==="CACAO";case a.Chain.Cosmos:return e==="ATOM";case a.Chain.Polygon:return e==="MATIC";case a.Chain.BinanceSmartChain:return e==="BNB";case a.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 a.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:a.BaseDecimal[n]};case a.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:a.BaseDecimal[n]};case a.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:a.BaseDecimal[n]};case a.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:a.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case a.Chain.Arbitrum:case a.Chain.Optimism:case a.Chain.BitcoinCash:case a.Chain.Litecoin:case a.Chain.Dogecoin:case a.Chain.Binance:case a.Chain.Avalanche:case a.Chain.Polygon:case a.Chain.Bitcoin:case a.Chain.Ethereum:return{identifier:`${n}.${n}`,decimal:a.BaseDecimal[n]}}},K=({chain:n,symbol:e})=>{if(e.includes("/"))return"Synth";switch(n){case a.Chain.Bitcoin:case a.Chain.BitcoinCash:case a.Chain.Dogecoin:case a.Chain.Litecoin:case a.Chain.Maya:case a.Chain.THORChain:return"Native";case a.Chain.Cosmos:return e==="ATOM"?"Native":"GAIA";case a.Chain.Binance:return e===a.Chain.Binance?"Native":"BEP2";case a.Chain.BinanceSmartChain:return e===a.Chain.Binance?"Native":"BEP20";case a.Chain.Ethereum:return e===a.Chain.Ethereum?"Native":"ERC20";case a.Chain.Avalanche:return e===a.Chain.Avalanche?"Native":"AVAX";case a.Chain.Polygon:return e===a.Chain.Polygon?"Native":"POLYGON";case a.Chain.Arbitrum:return[a.Chain.Ethereum,a.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case a.Chain.Optimism:return[a.Chain.Ethereum,a.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Ae=n=>{var c;const[e,...t]=n.split("."),i=n.includes("/"),s=t.join("."),r=(c=s==null?void 0:s.split("-"))==null?void 0:c[0];return{chain:e,symbol:s,ticker:r,synth:i}},Q=({liquidityUnits:n,poolUnits:e,runeDepth:t})=>{const i=d(n),s=d(e),r=d(t),c=i.mul(r),o=s.mul(s).mul(2),u=s.mul(i).mul(2),l=i.mul(i),g=s.mul(s).mul(s);return c.mul(o.sub(u).add(l)).div(g)},Z=({liquidityUnits:n,poolUnits:e,assetDepth:t})=>{const i=d(n),s=d(e),r=d(t),c=i.mul(r),o=s.mul(s).mul(2),u=s.mul(i).mul(2),l=i.mul(i),g=c.mul(o.sub(u).add(l)),C=s.mul(s).mul(s);return g.div(C)},we=({percent:n,runeDepth:e,liquidityUnits:t,poolUnits:i})=>Q({runeDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),$e=({percent:n,assetDepth:e,liquidityUnits:t,poolUnits:i})=>Z({assetDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),d=n=>new ne({value:n,decimal:a.BaseDecimal.THOR}),Se=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i,percent:s})=>({assetAmount:d(i).mul(n).div(e).mul(s),runeAmount:d(t).mul(n).div(e).mul(s)}),be=({runeDepth:n,poolUnits:e,assetDepth:t,liquidityUnits:i,runeAmount:s,assetAmount:r})=>{const c=d(n),o=d(t),u=d(e),l=d(s),g=d(r),C=l.mul(o),b=g.mul(c),R=l.mul(g),ie=c.mul(o),ae=u.mul(C.add(b.add(R.mul(2)))),se=C.add(b.add(ie.mul(2))),G=ae.div(se),N=d(i).add(G);if(G.baseValueNumber===0)return N.div(u).baseValueNumber;const re=u.add(N);return N.div(re).baseValueNumber},ye=({runeAmount:n,assetAmount:e,runeDepth:t,assetDepth:i})=>{const s=d(t),r=d(i),c=d(e),o=d(n),u=c.mul(s).sub(r.mul(o)),l=r.mul(o).add(s.mul(r));return Math.abs(u.div(l).baseValueNumber)},Be=({symbol:n,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${n.slice(-3)}`:n,Te=(n,e)=>{switch(n){case a.MemoType.LEAVE:case a.MemoType.BOND:{const{address:t}=e;return`${n}:${t}`}case a.MemoType.UNBOND:{const{address:t,unbondAmount:i}=e;return`${n}:${t}:${i*10**8}`}case a.MemoType.THORNAME_REGISTER:{const{name:t,chain:i,address:s,owner:r}=e;return`${n}:${t}:${i}:${s}${r?`:${r}`:""}`}case a.MemoType.DEPOSIT:{const{chain:t,symbol:i,address:s,singleSide:r}=e;return r?`${n}:${t}/${i}::t:0`:`${n}:${t}.${i}:${s||""}:t:0`}case a.MemoType.WITHDRAW:{const{chain:t,ticker:i,symbol:s,basisPoints:r,targetAssetString:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=Be({chain:t,symbol:s,ticker:i});return`${n}:${t}${o?"/":"."}${l}:${r}${u}`}case a.MemoType.OPEN_LOAN:case a.MemoType.CLOSE_LOAN:{const{asset:t,address:i}=e;return`${n}:${t}:${i}`}default:return""}},$=8,k=({value:n,bigIntDecimal:e=$,decimal:t=$})=>{const i=n<0n;let s=n.toString().substring(i?1:0);const r=t-(s.length-1);r>0&&(s="0".repeat(r)+s);const c=s.length-t;let o=s.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?"-":""}${s.slice(0,c)}.${o}`.replace(/\.?0*$/,"")},U=Object.values(a.Chain),ve=(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>`)},w=n=>10n**BigInt(n),y=n=>Math.log10(parseFloat(n.toString()));var f,B,D,ee,V,te,M,P,A,T,E,L,S,O;const v=class v{constructor(e){p(this,f);p(this,D);p(this,V);p(this,M);p(this,A);p(this,E);p(this,S);m(this,"decimalMultiplier",10n**8n);m(this,"bigIntValue",0n);m(this,"decimal");const t=typeof e=="object",i=t?e.value:e;this.decimal=t?e.decimal:void 0,this.decimalMultiplier=w(Math.max(h(this,E,L).call(this,h(this,A,T).call(this,i)),this.decimal||0)),h(this,D,ee).call(this,i)}static fromBigInt(e,t){return new v({decimal:t,value:k({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:i}){return v.fromBigInt(new v(e).bigIntValue*w(i)/w(t),i)}get unsafeNumber(){return parseFloat((this.bigIntValue/this.decimalMultiplier).toString())}get baseValue(){return h(this,S,O).call(this,"string")}get baseValueNumber(){return h(this,S,O).call(this,"number")}get baseValueBigInt(){return h(this,S,O).call(this,"number")}get value(){return this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||y(this.decimalMultiplier))}add(...e){return h(this,f,B).call(this,"add",...e)}sub(...e){return h(this,f,B).call(this,"sub",...e)}mul(...e){return h(this,f,B).call(this,"mul",...e)}div(...e){return h(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)}getBigIntValue(e,t){return!t&&typeof e=="object"?e.bigIntValue:(e=typeof e=="object"?e.value:e,h(this,M,P).call(this,h(this,A,T).call(this,e),t))}formatBigIntToSafeValue(e,t){const i=t||this.decimal||$,s=Math.max(i,y(this.decimalMultiplier)),r=e<0n;let c=e.toString().substring(r?1:0);const o=s-(c.length-1);o>0&&(c="0".repeat(o)+c);const u=c.length-s;let l=c.slice(-s);return parseInt(l[i])>=5?l=`${l.substring(0,i-1)}${(parseInt(l[i-1])+1).toString()}`:l=l.substring(0,i),`${r?"-":""}${c.slice(0,u)}.${l}`.replace(/\.?0*$/,"")}toSignificant(e){const t=this.value.split("."),i=t[0],s=t[1];return s?`${i}.${s.slice(0,e||this.decimal)}`.replace(/\.?0*$/,""):i}};f=new WeakSet,B=function(e,...t){const i=h(this,V,te).call(this,this,...t),s=w(i),r=t.reduce((o,u)=>{const l=this.getBigIntValue(u,i);if(e==="div"&&l===0n)throw new RangeError("Division by zero");return e==="add"?o+l:e==="sub"?o-l:e==="mul"?o*l/s:o*s/l},this.bigIntValue*s/this.decimalMultiplier),c=k({bigIntDecimal:i,decimal:Math.max(i,y(this.decimalMultiplier)),value:r});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},D=new WeakSet,ee=function(e,t){const i=h(this,A,T).call(this,e)||"0";this.bigIntValue=t||h(this,M,P).call(this,i)},V=new WeakSet,te=function(...e){const t=e.map(i=>typeof i=="object"?i.decimal||y(i.decimalMultiplier):h(this,E,L).call(this,h(this,A,T).call(this,i))).filter(Boolean);return Math.max(...t,$)},M=new WeakSet,P=function(e,t){const i=t?w(t):this.decimalMultiplier,s=y(i),[r,c=""]=e.split(".");return BigInt(`${r}${c.padEnd(s,"0")}`)},A=new WeakSet,T=function(e){const i=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):e}`.replaceAll(",",".").split(".");return i.length>1?`${i.slice(0,-1).join("")}.${i.at(-1)}`:i[0]},E=new WeakSet,L=function(e){var i;const t=((i=e.split(".")[1])==null?void 0:i.length)||0;return Math.max(t,$)},S=new WeakSet,O=function(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 i}};let I=v,x;const H=n=>{if(!x)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return x.get(n.toUpperCase())||{decimal:a.BaseDecimal.THOR,identifier:""}},W=async(n,e=0)=>{ve(n);const t=await F(q(n));return new _({decimal:t,value:e,identifier:n})};class _ extends I{constructor(t){super(t.value instanceof I?t.value:{decimal:t.decimal,value:t.value});m(this,"address");m(this,"chain");m(this,"isSynthetic",!1);m(this,"isGasAsset",!1);m(this,"symbol");m(this,"ticker");m(this,"type");const i="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,s=q(i);this.type=K(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}static async fromString(t,i=0){return W(t,i)}static fromStringSync(t,i=0){const{decimal:s,identifier:r}=H(t);return r?new _({decimal:s,identifier:r,value:i}):void 0}static async fromIdentifier(t,i=0){return W(t,i)}static fromIdentifierSync(t,i=0){const{decimal:s,identifier:r}=H(t);return new _({decimal:s,identifier:r,value:i})}static fromChainOrSignature(t,i=0){const{decimal:s,identifier:r}=J(t);return new _({value:i,decimal:s,identifier:r})}static async fromTCQuote(t,i=0){const s=await F(q(t)),r=this.shiftDecimals({value:i,from:a.BaseDecimal.THOR,to:s});return new _({value:r,identifier:t,decimal:s})}static fromTCQuoteStatic(t,i=0){const s=H(t),r=this.shiftDecimals({value:i,from:a.BaseDecimal.THOR,to:s.decimal});return new _({...s,value:r})}static async loadStaticAssets(){return new Promise(async(t,i)=>{try{const{ThorchainList:s,NativeList:r,...c}=await Promise.resolve().then(()=>require("./index.es-903b9173.cjs"));x=[r,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:g,chain:C,...b})=>{const R="decimals"in b?b.decimals:a.BaseDecimal[C];u.set(g,{identifier:g,decimal:R})}),u),new Map),t({ok:!0})}catch(s){console.error(s),i({ok:!1,error:s,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}get assetValue(){return`${this.value} ${this.ticker}`}toString(){return`${this.chain}.${this.symbol}`}eq({chain:t,symbol:i}){return this.chain===t&&this.symbol===i}}const Ie=n=>{const e=_.fromChainOrSignature(n);switch(n){case a.Chain.Bitcoin:case a.Chain.Litecoin:case a.Chain.BitcoinCash:return e.add(10001);case a.Chain.Dogecoin:return e.add(100000001);case a.Chain.Avalanche:case a.Chain.Ethereum:return e.add(10*10**9);case a.Chain.THORChain:case a.Chain.Maya:return e.add(0);default:return e.add(1)}},q=n=>{const e=n.slice(0,14).includes("/"),t=n.includes(".")?n:`${a.Chain.THORChain}.${n}`,[i,s]=t.split("."),[r,c]=s.split("-");return{address:c==null?void 0:c.toLowerCase(),chain:i,isGasAsset:X({chain:i,symbol:s}),isSynthetic:e,symbol:c?`${r}-${(c==null?void 0:c.toLowerCase())??""}`:s,ticker:e?s:r}},Me={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 j extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:Me[e],message:e}}),Object.setPrototypeOf(this,j.prototype)}}class ne extends I{eq(e){return this.eqValue(e)}toString(){return this.value}}exports.AssetValue=_;exports.DEFAULT_DECIMAL=$;exports.SwapKitError=j;exports.SwapKitNumber=ne;exports.assetFromString=Ae;exports.derivationPathToString=de;exports.formatBigIntToSafeValue=k;exports.gasFeeMultiplier=fe;exports.getAssetType=K;exports.getAsymmetricAssetShare=Z;exports.getAsymmetricAssetWithdrawAmount=$e;exports.getAsymmetricRuneShare=Q;exports.getAsymmetricRuneWithdrawAmount=we;exports.getCommonAssetInfo=J;exports.getDecimal=F;exports.getEstimatedPoolShare=be;exports.getLiquiditySlippage=ye;exports.getMemoFor=Te;exports.getMinAmountByChain=Ie;exports.getRequest=me;exports.getSymmetricWithdraw=Se;exports.getTHORNameCost=ue;exports.isGasAsset=X;exports.postRequest=Y;exports.validateTHORName=he;
|
|
1
|
+
"use strict";var le=Object.create;var H=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var he=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty;var ge=(n,e,t)=>e in n?H(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var _e=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of he(e))!me.call(n,s)&&s!==t&&H(n,s,{get:()=>e[s],enumerable:!(i=ue(e,s))||i.enumerable});return n};var pe=(n,e,t)=>(t=n!=null?le(de(n)):{},_e(e||!n||!n.__esModule?H(t,"default",{value:n,enumerable:!0}):t,n));var m=(n,e,t)=>(ge(n,typeof e!="symbol"?e+"":e,t),t),Ce=(n,e,t)=>{if(!e.has(n))throw TypeError("Cannot "+t)};var p=(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 h=(n,e,t)=>(Ce(n,e,"access private method"),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("@swapkit/types"),fe=n=>{if(n<0)throw new Error("Invalid number of year");return 10+n},Ae=n=>{if(n.length>30)return!1;const e=/^[a-zA-Z0-9+_-]+$/g;return!!n.match(e)},we=([n,e,t,i,s])=>`${n}'/${e}'/${t}'/${i}${typeof s!="number"?"":`/${s}`}`,Se=async(n,e)=>{const t=Object.entries(e||{}).reduce((s,[r,c])=>(c&&(s[r]=c),s),{});return(await fetch(`${n}${e?`?${new URLSearchParams(t).toString()}`:""}`,{method:"GET",mode:"cors",credentials:"omit",referrer:"https://sk.thorswap.net"})).json()},z=async(n,e,t,i=!1)=>{const s=await fetch(`${n}`,{body:e,headers:t,method:"POST",referrer:"https://sk.thorswap.net"});return i?s.text():s.json()},$e="0x313ce567",X=async({chain:n,to:e})=>{try{const t=await z(a.ChainToRPC[n],JSON.stringify({method:"eth_call",params:[{to:e.toLowerCase(),data:$e},"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),a.BaseDecimal[n]}},be=async n=>{if(n===a.Chain.Ethereum)return a.BaseDecimal.ETH;const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?X({chain:a.Chain.Ethereum,to:e}):a.BaseDecimal.ETH},ye=async n=>{const[,e]=n.split("-");return e!=null&&e.startsWith("0x")?X({chain:a.Chain.Avalanche,to:e.toLowerCase()}):a.BaseDecimal.AVAX},Be=async n=>(n===a.Chain.BinanceSmartChain,a.BaseDecimal.BSC),j=async({chain:n,symbol:e})=>{switch(n){case a.Chain.Ethereum:return be(e);case a.Chain.Avalanche:return ye(e);case a.Chain.BinanceSmartChain:return Be(e);default:return a.BaseDecimal[n]}},Te={[a.FeeOption.Average]:1.2,[a.FeeOption.Fast]:1.5,[a.FeeOption.Fastest]:2},J=({chain:n,symbol:e})=>{switch(n){case a.Chain.Bitcoin:case a.Chain.BitcoinCash:case a.Chain.Litecoin:case a.Chain.Dogecoin:case a.Chain.Binance:case a.Chain.Ethereum:case a.Chain.Avalanche:return e===n;case a.Chain.Arbitrum:case a.Chain.Optimism:return e==="ETH";case a.Chain.Maya:return e==="CACAO";case a.Chain.Cosmos:return e==="ATOM";case a.Chain.Polygon:return e==="MATIC";case a.Chain.BinanceSmartChain:return e==="BNB";case a.Chain.THORChain:return e==="RUNE"}},K=n=>{switch(n){case"ETH.THOR":return{identifier:"ETH.THOR-0xa5f2211b9b8170f694421f2046281775e8468044",decimal:18};case"ETH.vTHOR":return{identifier:"ETH.vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d",decimal:18};case a.Chain.Cosmos:return{identifier:"GAIA.ATOM",decimal:a.BaseDecimal[n]};case a.Chain.THORChain:return{identifier:"THOR.RUNE",decimal:a.BaseDecimal[n]};case a.Chain.BinanceSmartChain:return{identifier:"BSC.BNB",decimal:a.BaseDecimal[n]};case a.Chain.Maya:return{identifier:"MAYA.CACAO",decimal:a.BaseDecimal.MAYA};case"MAYA.MAYA":return{identifier:"MAYA.MAYA",decimal:4};case a.Chain.Arbitrum:case a.Chain.Optimism:case a.Chain.BitcoinCash:case a.Chain.Litecoin:case a.Chain.Dogecoin:case a.Chain.Binance:case a.Chain.Avalanche:case a.Chain.Polygon:case a.Chain.Bitcoin:case a.Chain.Ethereum:return{identifier:`${n}.${n}`,decimal:a.BaseDecimal[n]}}},Q=({chain:n,symbol:e})=>{if(e.includes("/"))return"Synth";switch(n){case a.Chain.Bitcoin:case a.Chain.BitcoinCash:case a.Chain.Dogecoin:case a.Chain.Litecoin:case a.Chain.Maya:case a.Chain.THORChain:return"Native";case a.Chain.Cosmos:return e==="ATOM"?"Native":"GAIA";case a.Chain.Binance:return e===a.Chain.Binance?"Native":"BEP2";case a.Chain.BinanceSmartChain:return e===a.Chain.Binance?"Native":"BEP20";case a.Chain.Ethereum:return e===a.Chain.Ethereum?"Native":"ERC20";case a.Chain.Avalanche:return e===a.Chain.Avalanche?"Native":"AVAX";case a.Chain.Polygon:return e===a.Chain.Polygon?"Native":"POLYGON";case a.Chain.Arbitrum:return[a.Chain.Ethereum,a.Chain.Arbitrum].includes(e)?"Native":"ARBITRUM";case a.Chain.Optimism:return[a.Chain.Ethereum,a.Chain.Optimism].includes(e)?"Native":"OPTIMISM"}},Ie=n=>{var c;const[e,...t]=n.split("."),i=n.includes("/"),s=t.join("."),r=(c=s==null?void 0:s.split("-"))==null?void 0:c[0];return{chain:e,symbol:s,ticker:r,synth:i}},Z=({liquidityUnits:n,poolUnits:e,runeDepth:t})=>{const i=d(n),s=d(e),r=d(t),c=i.mul(r),o=s.mul(s).mul(2),u=s.mul(i).mul(2),l=i.mul(i),g=s.mul(s).mul(s);return c.mul(o.sub(u).add(l)).div(g)},ee=({liquidityUnits:n,poolUnits:e,assetDepth:t})=>{const i=d(n),s=d(e),r=d(t),c=i.mul(r),o=s.mul(s).mul(2),u=s.mul(i).mul(2),l=i.mul(i),g=c.mul(o.sub(u).add(l)),C=s.mul(s).mul(s);return g.div(C)},ve=({percent:n,runeDepth:e,liquidityUnits:t,poolUnits:i})=>Z({runeDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),Me=({percent:n,assetDepth:e,liquidityUnits:t,poolUnits:i})=>ee({assetDepth:e,liquidityUnits:t,poolUnits:i}).mul(n),d=n=>new ae({value:n,decimal:a.BaseDecimal.THOR}),te=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})=>({assetAmount:d(i).mul(n).div(e),runeAmount:d(t).mul(n).div(e)}),Ee=({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i,percent:s})=>Object.fromEntries(Object.entries(te({liquidityUnits:n,poolUnits:e,runeDepth:t,assetDepth:i})).map(([r,c])=>[r,c.mul(s)])),Oe=({runeDepth:n,poolUnits:e,assetDepth:t,liquidityUnits:i,runeAmount:s,assetAmount:r})=>{const c=d(n),o=d(t),u=d(e),l=d(s),g=d(r),C=l.mul(o),b=g.mul(c),R=l.mul(g),se=c.mul(o),re=u.mul(C.add(b.add(R.mul(2)))),ce=C.add(b.add(se.mul(2))),U=re.div(ce),N=d(i).add(U);if(U.baseValueNumber===0)return N.div(u).baseValueNumber;const oe=u.add(N);return N.div(oe).baseValueNumber},De=({runeAmount:n,assetAmount:e,runeDepth:t,assetDepth:i})=>{const s=d(t),r=d(i),c=d(e),o=d(n),u=c.mul(s).sub(r.mul(o)),l=r.mul(o).add(s.mul(r));return Math.abs(u.div(l).baseValueNumber)},Ve=({symbol:n,ticker:e,chain:t})=>t==="ETH"&&e!=="ETH"?`${e}-${n.slice(-3)}`:n,Re=(n,e)=>{switch(n){case a.MemoType.LEAVE:case a.MemoType.BOND:{const{address:t}=e;return`${n}:${t}`}case a.MemoType.UNBOND:{const{address:t,unbondAmount:i}=e;return`${n}:${t}:${i*10**8}`}case a.MemoType.THORNAME_REGISTER:{const{name:t,chain:i,address:s,owner:r}=e;return`${n}:${t}:${i}:${s}${r?`:${r}`:""}`}case a.MemoType.DEPOSIT:{const{chain:t,symbol:i,address:s,singleSide:r}=e;return r?`${n}:${t}/${i}::t:0`:`${n}:${t}.${i}:${s||""}:t:0`}case a.MemoType.WITHDRAW:{const{chain:t,ticker:i,symbol:s,basisPoints:r,targetAssetString:c,singleSide:o}=e,u=!o&&c?`:${c}`:"",l=Ve({chain:t,symbol:s,ticker:i});return`${n}:${t}${o?"/":"."}${l}:${r}${u}`}case a.MemoType.OPEN_LOAN:case a.MemoType.CLOSE_LOAN:{const{asset:t,address:i}=e;return`${n}:${t}:${i}`}default:return""}},S=8,P=({value:n,bigIntDecimal:e=S,decimal:t=S})=>{const i=n<0n;let s=n.toString().substring(i?1:0);const r=t-(s.length-1);r>0&&(s="0".repeat(r)+s);const c=s.length-t;let o=s.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?"-":""}${s.slice(0,c)}.${o}`.replace(/\.?0*$/,"")},W=Object.values(a.Chain),Ne=(n="")=>{const e=n.toUpperCase(),[t]=e.split(".");if(W.includes(t))return!0;const[i]=e.split("/");if(W.includes(i))return!0;throw new Error(`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`)},w=n=>10n**BigInt(n),y=n=>Math.log10(parseFloat(n.toString()));var f,B,D,ne,V,ie,M,L,A,T,E,x,$,O;const I=class I{constructor(e){p(this,f);p(this,D);p(this,V);p(this,M);p(this,A);p(this,E);p(this,$);m(this,"decimalMultiplier",10n**8n);m(this,"bigIntValue",0n);m(this,"decimal");const t=typeof e=="object",i=t?e.value:e;this.decimal=t?e.decimal:void 0,this.decimalMultiplier=w(Math.max(h(this,E,x).call(this,h(this,A,T).call(this,i)),this.decimal||0)),h(this,D,ne).call(this,i)}static fromBigInt(e,t){return new I({decimal:t,value:P({value:e,bigIntDecimal:t,decimal:t})})}static shiftDecimals({value:e,from:t,to:i}){return I.fromBigInt(new I(e).bigIntValue*w(i)/w(t),i)}get unsafeNumber(){return parseFloat((this.bigIntValue/this.decimalMultiplier).toString())}get baseValue(){return h(this,$,O).call(this,"string")}get baseValueNumber(){return h(this,$,O).call(this,"number")}get baseValueBigInt(){return h(this,$,O).call(this,"number")}get value(){return this.formatBigIntToSafeValue(this.bigIntValue,this.decimal||y(this.decimalMultiplier))}add(...e){return h(this,f,B).call(this,"add",...e)}sub(...e){return h(this,f,B).call(this,"sub",...e)}mul(...e){return h(this,f,B).call(this,"mul",...e)}div(...e){return h(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)}getBigIntValue(e,t){return!t&&typeof e=="object"?e.bigIntValue:(e=typeof e=="object"?e.value:e,h(this,M,L).call(this,h(this,A,T).call(this,e),t))}formatBigIntToSafeValue(e,t){const i=t||this.decimal||S,s=Math.max(i,y(this.decimalMultiplier)),r=e<0n;let c=e.toString().substring(r?1:0);const o=s-(c.length-1);o>0&&(c="0".repeat(o)+c);const u=c.length-s;let l=c.slice(-s);return parseInt(l[i])>=5?l=`${l.substring(0,i-1)}${(parseInt(l[i-1])+1).toString()}`:l=l.substring(0,i),`${r?"-":""}${c.slice(0,u)}.${l}`.replace(/\.?0*$/,"")}toSignificant(e){const t=this.value.split("."),i=t[0],s=t[1];return s?`${i}.${s.slice(0,e||this.decimal)}`.replace(/\.?0*$/,""):i}};f=new WeakSet,B=function(e,...t){const i=h(this,V,ie).call(this,this,...t),s=w(i),r=t.reduce((o,u)=>{const l=this.getBigIntValue(u,i);if(e==="div"&&l===0n)throw new RangeError("Division by zero");return e==="add"?o+l:e==="sub"?o-l:e==="mul"?o*l/s:o*s/l},this.bigIntValue*s/this.decimalMultiplier),c=P({bigIntDecimal:i,decimal:Math.max(i,y(this.decimalMultiplier)),value:r});return new this.constructor({decimal:this.decimal,value:c,identifier:this.toString()})},D=new WeakSet,ne=function(e,t){const i=h(this,A,T).call(this,e)||"0";this.bigIntValue=t||h(this,M,L).call(this,i)},V=new WeakSet,ie=function(...e){const t=e.map(i=>typeof i=="object"?i.decimal||y(i.decimalMultiplier):h(this,E,x).call(this,h(this,A,T).call(this,i))).filter(Boolean);return Math.max(...t,S)},M=new WeakSet,L=function(e,t){const i=t?w(t):this.decimalMultiplier,s=y(i),[r,c=""]=e.split(".");return BigInt(`${r}${c.padEnd(s,"0")}`)},A=new WeakSet,T=function(e){const i=`${typeof e=="number"?Number(e).toLocaleString("fullwide",{useGrouping:!1,maximumFractionDigits:20}):e}`.replaceAll(",",".").split(".");return i.length>1?`${i.slice(0,-1).join("")}.${i.at(-1)}`:i[0]},E=new WeakSet,x=function(e){var i;const t=((i=e.split(".")[1])==null?void 0:i.length)||0;return Math.max(t,S)},$=new WeakSet,O=function(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 i}};let v=I,q;const k=n=>{if(!q)throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");return q.get(n.toUpperCase())||{decimal:a.BaseDecimal.THOR,identifier:""}},Y=async(n,e=0)=>{Ne(n);const t=await j(F(n));return new _({decimal:t,value:e,identifier:n})};class _ extends v{constructor(t){super(t.value instanceof v?t.value:{decimal:t.decimal,value:t.value});m(this,"address");m(this,"chain");m(this,"isSynthetic",!1);m(this,"isGasAsset",!1);m(this,"symbol");m(this,"ticker");m(this,"type");const i="identifier"in t?t.identifier:`${t.chain}.${t.symbol}`,s=F(i);this.type=Q(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}static async fromString(t,i=0){return Y(t,i)}static fromStringSync(t,i=0){const{decimal:s,identifier:r}=k(t);return r?new _({decimal:s,identifier:r,value:i}):void 0}static async fromIdentifier(t,i=0){return Y(t,i)}static fromIdentifierSync(t,i=0){const{decimal:s,identifier:r}=k(t);return new _({decimal:s,identifier:r,value:i})}static fromChainOrSignature(t,i=0){const{decimal:s,identifier:r}=K(t);return new _({value:i,decimal:s,identifier:r})}static async fromTCQuote(t,i=0){const s=await j(F(t)),r=this.shiftDecimals({value:i,from:a.BaseDecimal.THOR,to:s});return new _({value:r,identifier:t,decimal:s})}static fromTCQuoteStatic(t,i=0){const s=k(t),r=this.shiftDecimals({value:i,from:a.BaseDecimal.THOR,to:s.decimal});return new _({...s,value:r})}static async loadStaticAssets(){return new Promise(async(t,i)=>{try{const{ThorchainList:s,NativeList:r,...c}=await import("@swapkit/tokens");q=[r,...Object.values(c)].reduce((u,{tokens:l})=>(l.forEach(({identifier:g,chain:C,...b})=>{const R="decimals"in b?b.decimals:a.BaseDecimal[C];u.set(g,{identifier:g,decimal:R})}),u),new Map),t({ok:!0})}catch(s){console.error(s),i({ok:!1,error:s,message:"Couldn't load static assets. Ensure you have installed @swapkit/tokens package"})}})}get assetValue(){return`${this.value} ${this.ticker}`}toString(){return`${this.chain}.${this.symbol}`}eq({chain:t,symbol:i}){return this.chain===t&&this.symbol===i}}const He=n=>{const e=_.fromChainOrSignature(n);switch(n){case a.Chain.Bitcoin:case a.Chain.Litecoin:case a.Chain.BitcoinCash:return e.add(10001);case a.Chain.Dogecoin:return e.add(100000001);case a.Chain.Avalanche:case a.Chain.Ethereum:return e.add(10*10**9);case a.Chain.THORChain:case a.Chain.Maya:return e.add(0);default:return e.add(1)}},F=n=>{const e=n.slice(0,14).includes("/"),t=n.includes(".")?n:`${a.Chain.THORChain}.${n}`,[i,s]=t.split("."),[r,c]=s.split("-");return{address:c==null?void 0:c.toLowerCase(),chain:i,isGasAsset:J({chain:i,symbol:s}),isSynthetic:e,symbol:c?`${r}-${(c==null?void 0:c.toLowerCase())??""}`:s,ticker:e?s:r}},ke={core_wallet_connection_not_found:10001,core_estimated_max_spendable_chain_not_supported:10002,core_extend_error:10003,core_inbound_data_not_found:10004,core_approve_asset_address_or_from_not_found:10005,core_chain_halted:10099,core_wallet_xdefi_not_installed:10101,core_wallet_evmwallet_not_installed:10102,core_wallet_walletconnect_not_installed:10103,core_wallet_keystore_not_installed:10104,core_wallet_ledger_not_installed:10105,core_wallet_trezor_not_installed:10106,core_wallet_keplr_not_installed:10107,core_wallet_okx_not_installed:10108,core_swap_invalid_params:10200,core_swap_route_not_complete:10201,core_swap_asset_not_recognized:10202,core_swap_contract_not_found:10203,core_swap_route_transaction_not_found:10204,core_swap_contract_not_supported:10205,core_swap_transaction_error:10206,core_swap_quote_mode_not_supported:10207,core_transaction_deposit_error:10301,core_transaction_create_liquidity_rune_error:10302,core_transaction_create_liquidity_asset_error:10303,core_transaction_create_liquidity_invalid_params:10304,core_transaction_add_liquidity_invalid_params:10305,core_transaction_add_liquidity_no_rune_address:10306,core_transaction_add_liquidity_rune_error:10307,core_transaction_add_liquidity_asset_error:10308,core_transaction_withdraw_error:10309,core_transaction_deposit_to_pool_error:10310,core_transaction_deposit_insufficient_funds_error:10311,core_transaction_deposit_gas_error:10312,core_transaction_deposit_server_error:10313,wallet_ledger_connection_error:20001,helpers_number_different_decimals:99101};class G extends Error{constructor(e,t){console.error(t),super(e,{cause:{code:ke[e],message:e}}),Object.setPrototypeOf(this,G.prototype)}}class ae extends v{eq(e){return this.eqValue(e)}toString(){return this.value}}exports.AssetValue=_;exports.DEFAULT_DECIMAL=S;exports.SwapKitError=G;exports.SwapKitNumber=ae;exports.assetFromString=Ie;exports.derivationPathToString=we;exports.formatBigIntToSafeValue=P;exports.gasFeeMultiplier=Te;exports.getAssetType=Q;exports.getAsymmetricAssetShare=ee;exports.getAsymmetricAssetWithdrawAmount=Me;exports.getAsymmetricRuneShare=Z;exports.getAsymmetricRuneWithdrawAmount=ve;exports.getCommonAssetInfo=K;exports.getDecimal=j;exports.getEstimatedPoolShare=Oe;exports.getLiquiditySlippage=De;exports.getMemoFor=Re;exports.getMinAmountByChain=He;exports.getRequest=Se;exports.getSymmetricPoolShare=te;exports.getSymmetricWithdraw=Ee;exports.getTHORNameCost=fe;exports.isGasAsset=J;exports.postRequest=z;exports.validateTHORName=Ae;
|
package/dist/index.d.ts
CHANGED
|
@@ -228,15 +228,22 @@ export declare const getRequest: <T>(url: string, params?: {
|
|
|
228
228
|
[x: string]: any;
|
|
229
229
|
} | undefined) => Promise<T>;
|
|
230
230
|
|
|
231
|
-
export declare const
|
|
231
|
+
export declare const getSymmetricPoolShare: ({ liquidityUnits, poolUnits, runeDepth, assetDepth, }: ShareParams<{
|
|
232
232
|
runeDepth: string;
|
|
233
233
|
assetDepth: string;
|
|
234
|
-
percent: number;
|
|
235
234
|
}>) => {
|
|
236
235
|
assetAmount: SwapKitNumber;
|
|
237
236
|
runeAmount: SwapKitNumber;
|
|
238
237
|
};
|
|
239
238
|
|
|
239
|
+
export declare const getSymmetricWithdraw: ({ liquidityUnits, poolUnits, runeDepth, assetDepth, percent, }: ShareParams<{
|
|
240
|
+
runeDepth: string;
|
|
241
|
+
assetDepth: string;
|
|
242
|
+
percent: number;
|
|
243
|
+
}>) => {
|
|
244
|
+
[k: string]: SwapKitNumber;
|
|
245
|
+
};
|
|
246
|
+
|
|
240
247
|
export declare const getTHORNameCost: (year: number) => number;
|
|
241
248
|
|
|
242
249
|
export declare const isGasAsset: ({ chain, symbol }: {
|
package/dist/index.es.js
CHANGED
|
@@ -15,12 +15,12 @@ const vt = (n) => {
|
|
|
15
15
|
if (n < 0)
|
|
16
16
|
throw new Error("Invalid number of year");
|
|
17
17
|
return 10 + n;
|
|
18
|
-
},
|
|
18
|
+
}, Ct = (n) => {
|
|
19
19
|
if (n.length > 30)
|
|
20
20
|
return !1;
|
|
21
21
|
const t = /^[a-zA-Z0-9+_-]+$/g;
|
|
22
22
|
return !!n.match(t);
|
|
23
|
-
},
|
|
23
|
+
}, yt = ([n, t, e, r, s]) => `${n}'/${t}'/${e}'/${r}${typeof s != "number" ? "" : `/${s}`}`, Tt = async (n, t) => {
|
|
24
24
|
const e = Object.entries(t || {}).reduce(
|
|
25
25
|
(s, [a, c]) => (c && (s[a] = c), s),
|
|
26
26
|
{}
|
|
@@ -73,7 +73,7 @@ const vt = (n) => {
|
|
|
73
73
|
default:
|
|
74
74
|
return h[n];
|
|
75
75
|
}
|
|
76
|
-
},
|
|
76
|
+
}, Bt = {
|
|
77
77
|
[x.Average]: 1.2,
|
|
78
78
|
[x.Fast]: 1.5,
|
|
79
79
|
[x.Fastest]: 2
|
|
@@ -157,7 +157,7 @@ const vt = (n) => {
|
|
|
157
157
|
case i.Optimism:
|
|
158
158
|
return [i.Ethereum, i.Optimism].includes(t) ? "Native" : "OPTIMISM";
|
|
159
159
|
}
|
|
160
|
-
},
|
|
160
|
+
}, Mt = (n) => {
|
|
161
161
|
var c;
|
|
162
162
|
const [t, ...e] = n.split("."), r = n.includes("/"), s = e.join("."), a = (c = s == null ? void 0 : s.split("-")) == null ? void 0 : c[0];
|
|
163
163
|
return { chain: t, symbol: s, ticker: a, synth: r };
|
|
@@ -175,26 +175,35 @@ const vt = (n) => {
|
|
|
175
175
|
}) => {
|
|
176
176
|
const r = m(n), s = m(t), a = m(e), c = r.mul(a), o = s.mul(s).mul(2), l = s.mul(r).mul(2), u = r.mul(r), g = c.mul(o.sub(l).add(u)), $ = s.mul(s).mul(s);
|
|
177
177
|
return g.div($);
|
|
178
|
-
},
|
|
178
|
+
}, Et = ({
|
|
179
179
|
percent: n,
|
|
180
180
|
runeDepth: t,
|
|
181
181
|
liquidityUnits: e,
|
|
182
182
|
poolUnits: r
|
|
183
|
-
}) => gt({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(n),
|
|
183
|
+
}) => gt({ runeDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), Ot = ({
|
|
184
184
|
percent: n,
|
|
185
185
|
assetDepth: t,
|
|
186
186
|
liquidityUnits: e,
|
|
187
187
|
poolUnits: r
|
|
188
|
-
}) => pt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), m = (n) => new
|
|
188
|
+
}) => pt({ assetDepth: t, liquidityUnits: e, poolUnits: r }).mul(n), m = (n) => new bt({ value: n, decimal: h.THOR }), ft = ({
|
|
189
|
+
liquidityUnits: n,
|
|
190
|
+
poolUnits: t,
|
|
191
|
+
runeDepth: e,
|
|
192
|
+
assetDepth: r
|
|
193
|
+
}) => ({
|
|
194
|
+
assetAmount: m(r).mul(n).div(t),
|
|
195
|
+
runeAmount: m(e).mul(n).div(t)
|
|
196
|
+
}), Vt = ({
|
|
189
197
|
liquidityUnits: n,
|
|
190
198
|
poolUnits: t,
|
|
191
199
|
runeDepth: e,
|
|
192
200
|
assetDepth: r,
|
|
193
201
|
percent: s
|
|
194
|
-
}) => (
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
202
|
+
}) => Object.fromEntries(
|
|
203
|
+
Object.entries(ft({ liquidityUnits: n, poolUnits: t, runeDepth: e, assetDepth: r })).map(
|
|
204
|
+
([a, c]) => [a, c.mul(s)]
|
|
205
|
+
)
|
|
206
|
+
), Nt = ({
|
|
198
207
|
runeDepth: n,
|
|
199
208
|
poolUnits: t,
|
|
200
209
|
assetDepth: e,
|
|
@@ -202,12 +211,12 @@ const vt = (n) => {
|
|
|
202
211
|
runeAmount: s,
|
|
203
212
|
assetAmount: a
|
|
204
213
|
}) => {
|
|
205
|
-
const c = m(n), o = m(e), l = m(t), u = m(s), g = m(a), $ = u.mul(o),
|
|
214
|
+
const c = m(n), o = m(e), l = m(t), u = m(s), g = m(a), $ = u.mul(o), v = g.mul(c), D = u.mul(g), K = c.mul(o), tt = l.mul($.add(v.add(D.mul(2)))), et = $.add(v.add(K.mul(2))), G = tt.div(et), H = m(r).add(G);
|
|
206
215
|
if (G.baseValueNumber === 0)
|
|
207
216
|
return H.div(l).baseValueNumber;
|
|
208
217
|
const nt = l.add(H);
|
|
209
218
|
return H.div(nt).baseValueNumber;
|
|
210
|
-
},
|
|
219
|
+
}, Rt = ({
|
|
211
220
|
runeAmount: n,
|
|
212
221
|
assetAmount: t,
|
|
213
222
|
runeDepth: e,
|
|
@@ -215,11 +224,11 @@ const vt = (n) => {
|
|
|
215
224
|
}) => {
|
|
216
225
|
const s = m(e), a = m(r), c = m(t), o = m(n), l = c.mul(s).sub(a.mul(o)), u = a.mul(o).add(s.mul(a));
|
|
217
226
|
return Math.abs(l.div(u).baseValueNumber);
|
|
218
|
-
},
|
|
227
|
+
}, At = ({
|
|
219
228
|
symbol: n,
|
|
220
229
|
ticker: t,
|
|
221
230
|
chain: e
|
|
222
|
-
}) => e === "ETH" && t !== "ETH" ? `${t}-${n.slice(-3)}` : n,
|
|
231
|
+
}) => e === "ETH" && t !== "ETH" ? `${t}-${n.slice(-3)}` : n, kt = (n, t) => {
|
|
223
232
|
switch (n) {
|
|
224
233
|
case f.LEAVE:
|
|
225
234
|
case f.BOND: {
|
|
@@ -239,7 +248,7 @@ const vt = (n) => {
|
|
|
239
248
|
return a ? `${n}:${e}/${r}::t:0` : `${n}:${e}.${r}:${s || ""}:t:0`;
|
|
240
249
|
}
|
|
241
250
|
case f.WITHDRAW: {
|
|
242
|
-
const { chain: e, ticker: r, symbol: s, basisPoints: a, targetAssetString: c, singleSide: o } = t, l = !o && c ? `:${c}` : "", u =
|
|
251
|
+
const { chain: e, ticker: r, symbol: s, basisPoints: a, targetAssetString: c, singleSide: o } = t, l = !o && c ? `:${c}` : "", u = At({ chain: e, symbol: s, ticker: r });
|
|
243
252
|
return `${n}:${e}${o ? "/" : "."}${u}:${a}${l}`;
|
|
244
253
|
}
|
|
245
254
|
case f.OPEN_LOAN:
|
|
@@ -265,7 +274,7 @@ const vt = (n) => {
|
|
|
265
274
|
/\.?0*$/,
|
|
266
275
|
""
|
|
267
276
|
);
|
|
268
|
-
}, W = Object.values(i),
|
|
277
|
+
}, W = Object.values(i), $t = (n = "") => {
|
|
269
278
|
const t = n.toUpperCase(), [e] = t.split(".");
|
|
270
279
|
if (W.includes(e))
|
|
271
280
|
return !0;
|
|
@@ -275,23 +284,23 @@ const vt = (n) => {
|
|
|
275
284
|
throw new Error(
|
|
276
285
|
`Invalid identifier: ${n}. Expected format: <Chain>.<Ticker> or <Chain>.<Ticker>-<ContractAddress>`
|
|
277
286
|
);
|
|
278
|
-
},
|
|
279
|
-
var w,
|
|
287
|
+
}, S = (n) => 10n ** BigInt(n), C = (n) => Math.log10(parseFloat(n.toString()));
|
|
288
|
+
var w, y, R, J, k, Q, O, L, b, T, V, j, I, N;
|
|
280
289
|
const M = class M {
|
|
281
290
|
constructor(t) {
|
|
282
291
|
p(this, w);
|
|
283
292
|
p(this, R);
|
|
284
293
|
p(this, k);
|
|
285
|
-
p(this, V);
|
|
286
|
-
p(this, b);
|
|
287
294
|
p(this, O);
|
|
288
|
-
p(this,
|
|
295
|
+
p(this, b);
|
|
296
|
+
p(this, V);
|
|
297
|
+
p(this, I);
|
|
289
298
|
_(this, "decimalMultiplier", 10n ** 8n);
|
|
290
299
|
_(this, "bigIntValue", 0n);
|
|
291
300
|
_(this, "decimal");
|
|
292
301
|
const e = typeof t == "object", r = e ? t.value : t;
|
|
293
|
-
this.decimal = e ? t.decimal : void 0, this.decimalMultiplier =
|
|
294
|
-
Math.max(d(this,
|
|
302
|
+
this.decimal = e ? t.decimal : void 0, this.decimalMultiplier = S(
|
|
303
|
+
Math.max(d(this, V, j).call(this, d(this, b, T).call(this, r)), this.decimal || 0)
|
|
295
304
|
), d(this, R, J).call(this, r);
|
|
296
305
|
}
|
|
297
306
|
static fromBigInt(t, e) {
|
|
@@ -306,7 +315,7 @@ const M = class M {
|
|
|
306
315
|
to: r
|
|
307
316
|
}) {
|
|
308
317
|
return M.fromBigInt(
|
|
309
|
-
new M(t).bigIntValue *
|
|
318
|
+
new M(t).bigIntValue * S(r) / S(e),
|
|
310
319
|
r
|
|
311
320
|
);
|
|
312
321
|
}
|
|
@@ -314,13 +323,13 @@ const M = class M {
|
|
|
314
323
|
return parseFloat((this.bigIntValue / this.decimalMultiplier).toString());
|
|
315
324
|
}
|
|
316
325
|
get baseValue() {
|
|
317
|
-
return d(this,
|
|
326
|
+
return d(this, I, N).call(this, "string");
|
|
318
327
|
}
|
|
319
328
|
get baseValueNumber() {
|
|
320
|
-
return d(this,
|
|
329
|
+
return d(this, I, N).call(this, "number");
|
|
321
330
|
}
|
|
322
331
|
get baseValueBigInt() {
|
|
323
|
-
return d(this,
|
|
332
|
+
return d(this, I, N).call(this, "number");
|
|
324
333
|
}
|
|
325
334
|
get value() {
|
|
326
335
|
return this.formatBigIntToSafeValue(
|
|
@@ -329,16 +338,16 @@ const M = class M {
|
|
|
329
338
|
);
|
|
330
339
|
}
|
|
331
340
|
add(...t) {
|
|
332
|
-
return d(this, w,
|
|
341
|
+
return d(this, w, y).call(this, "add", ...t);
|
|
333
342
|
}
|
|
334
343
|
sub(...t) {
|
|
335
|
-
return d(this, w,
|
|
344
|
+
return d(this, w, y).call(this, "sub", ...t);
|
|
336
345
|
}
|
|
337
346
|
mul(...t) {
|
|
338
|
-
return d(this, w,
|
|
347
|
+
return d(this, w, y).call(this, "mul", ...t);
|
|
339
348
|
}
|
|
340
349
|
div(...t) {
|
|
341
|
-
return d(this, w,
|
|
350
|
+
return d(this, w, y).call(this, "div", ...t);
|
|
342
351
|
}
|
|
343
352
|
gt(t) {
|
|
344
353
|
return this.bigIntValue > this.getBigIntValue(t);
|
|
@@ -356,7 +365,7 @@ const M = class M {
|
|
|
356
365
|
return this.bigIntValue === this.getBigIntValue(t);
|
|
357
366
|
}
|
|
358
367
|
getBigIntValue(t, e) {
|
|
359
|
-
return !e && typeof t == "object" ? t.bigIntValue : (t = typeof t == "object" ? t.value : t, d(this,
|
|
368
|
+
return !e && typeof t == "object" ? t.bigIntValue : (t = typeof t == "object" ? t.value : t, d(this, O, L).call(this, d(this, b, T).call(this, t), e));
|
|
360
369
|
}
|
|
361
370
|
formatBigIntToSafeValue(t, e) {
|
|
362
371
|
const r = e || this.decimal || B, s = Math.max(
|
|
@@ -381,8 +390,8 @@ const M = class M {
|
|
|
381
390
|
) : r;
|
|
382
391
|
}
|
|
383
392
|
};
|
|
384
|
-
w = new WeakSet(),
|
|
385
|
-
const r = d(this, k, Q).call(this, this, ...e), s =
|
|
393
|
+
w = new WeakSet(), y = function(t, ...e) {
|
|
394
|
+
const r = d(this, k, Q).call(this, this, ...e), s = S(r), a = e.reduce(
|
|
386
395
|
(o, l) => {
|
|
387
396
|
const u = this.getBigIntValue(l, r);
|
|
388
397
|
if (t === "div" && u === 0n)
|
|
@@ -398,28 +407,28 @@ w = new WeakSet(), T = function(t, ...e) {
|
|
|
398
407
|
});
|
|
399
408
|
return new this.constructor({ decimal: this.decimal, value: c, identifier: this.toString() });
|
|
400
409
|
}, R = new WeakSet(), J = function(t, e) {
|
|
401
|
-
const r = d(this, b,
|
|
402
|
-
this.bigIntValue = e || d(this,
|
|
410
|
+
const r = d(this, b, T).call(this, t) || "0";
|
|
411
|
+
this.bigIntValue = e || d(this, O, L).call(this, r);
|
|
403
412
|
}, k = new WeakSet(), Q = function(...t) {
|
|
404
413
|
const e = t.map(
|
|
405
|
-
(r) => typeof r == "object" ? r.decimal || C(r.decimalMultiplier) : d(this,
|
|
414
|
+
(r) => typeof r == "object" ? r.decimal || C(r.decimalMultiplier) : d(this, V, j).call(this, d(this, b, T).call(this, r))
|
|
406
415
|
).filter(Boolean);
|
|
407
416
|
return Math.max(...e, B);
|
|
408
|
-
},
|
|
409
|
-
const r = e ?
|
|
417
|
+
}, O = new WeakSet(), L = function(t, e) {
|
|
418
|
+
const r = e ? S(e) : this.decimalMultiplier, s = C(r), [a, c = ""] = t.split(".");
|
|
410
419
|
return BigInt(`${a}${c.padEnd(s, "0")}`);
|
|
411
|
-
}, b = new WeakSet(),
|
|
420
|
+
}, b = new WeakSet(), T = function(t) {
|
|
412
421
|
const r = `${typeof t == "number" ? Number(t).toLocaleString("fullwide", {
|
|
413
422
|
useGrouping: !1,
|
|
414
423
|
maximumFractionDigits: 20
|
|
415
424
|
}) : t}`.replaceAll(",", ".").split(".");
|
|
416
425
|
return r.length > 1 ? `${r.slice(0, -1).join("")}.${r.at(-1)}` : r[0];
|
|
417
|
-
},
|
|
426
|
+
}, V = new WeakSet(), j = function(t) {
|
|
418
427
|
var r;
|
|
419
428
|
const e = ((r = t.split(".")[1]) == null ? void 0 : r.length) || 0;
|
|
420
429
|
return Math.max(e, B);
|
|
421
|
-
},
|
|
422
|
-
const e = this.decimalMultiplier /
|
|
430
|
+
}, I = new WeakSet(), N = function(t) {
|
|
431
|
+
const e = this.decimalMultiplier / S(this.decimal || 0), r = this.bigIntValue / e;
|
|
423
432
|
switch (t) {
|
|
424
433
|
case "number":
|
|
425
434
|
return Number(r);
|
|
@@ -429,13 +438,13 @@ w = new WeakSet(), T = function(t, ...e) {
|
|
|
429
438
|
return r;
|
|
430
439
|
}
|
|
431
440
|
};
|
|
432
|
-
let E = M,
|
|
433
|
-
const
|
|
434
|
-
if (!
|
|
441
|
+
let E = M, q;
|
|
442
|
+
const P = (n) => {
|
|
443
|
+
if (!q)
|
|
435
444
|
throw new Error("Static assets not loaded, call await AssetValue.loadStaticAssets() first");
|
|
436
|
-
return
|
|
445
|
+
return q.get(n.toUpperCase()) || { decimal: h.THOR, identifier: "" };
|
|
437
446
|
}, Y = async (n, t = 0) => {
|
|
438
|
-
|
|
447
|
+
$t(n);
|
|
439
448
|
const e = await X(F(n));
|
|
440
449
|
return new A({ decimal: e, value: t, identifier: n });
|
|
441
450
|
};
|
|
@@ -458,7 +467,7 @@ class A extends E {
|
|
|
458
467
|
return Y(e, r);
|
|
459
468
|
}
|
|
460
469
|
static fromStringSync(e, r = 0) {
|
|
461
|
-
const { decimal: s, identifier: a } =
|
|
470
|
+
const { decimal: s, identifier: a } = P(
|
|
462
471
|
e
|
|
463
472
|
);
|
|
464
473
|
return a ? new A({ decimal: s, identifier: a, value: r }) : void 0;
|
|
@@ -467,7 +476,7 @@ class A extends E {
|
|
|
467
476
|
return Y(e, r);
|
|
468
477
|
}
|
|
469
478
|
static fromIdentifierSync(e, r = 0) {
|
|
470
|
-
const { decimal: s, identifier: a } =
|
|
479
|
+
const { decimal: s, identifier: a } = P(e);
|
|
471
480
|
return new A({ decimal: s, identifier: a, value: r });
|
|
472
481
|
}
|
|
473
482
|
static fromChainOrSignature(e, r = 0) {
|
|
@@ -479,7 +488,7 @@ class A extends E {
|
|
|
479
488
|
return new A({ value: a, identifier: e, decimal: s });
|
|
480
489
|
}
|
|
481
490
|
static fromTCQuoteStatic(e, r = 0) {
|
|
482
|
-
const s =
|
|
491
|
+
const s = P(e), a = this.shiftDecimals({
|
|
483
492
|
value: r,
|
|
484
493
|
from: h.THOR,
|
|
485
494
|
to: s.decimal
|
|
@@ -496,10 +505,10 @@ class A extends E {
|
|
|
496
505
|
ThorchainList: s,
|
|
497
506
|
NativeList: a,
|
|
498
507
|
...c
|
|
499
|
-
} = await import("
|
|
500
|
-
|
|
501
|
-
(l, { tokens: u }) => (u.forEach(({ identifier: g, chain: $, ...
|
|
502
|
-
const D = "decimals" in
|
|
508
|
+
} = await import("@swapkit/tokens");
|
|
509
|
+
q = [a, ...Object.values(c)].reduce(
|
|
510
|
+
(l, { tokens: u }) => (u.forEach(({ identifier: g, chain: $, ...v }) => {
|
|
511
|
+
const D = "decimals" in v ? v.decimals : h[$];
|
|
503
512
|
l.set(g, { identifier: g, decimal: D });
|
|
504
513
|
}), l),
|
|
505
514
|
/* @__PURE__ */ new Map()
|
|
@@ -524,7 +533,7 @@ class A extends E {
|
|
|
524
533
|
return this.chain === e && this.symbol === r;
|
|
525
534
|
}
|
|
526
535
|
}
|
|
527
|
-
const
|
|
536
|
+
const Dt = (n) => {
|
|
528
537
|
const t = A.fromChainOrSignature(n);
|
|
529
538
|
switch (n) {
|
|
530
539
|
case i.Bitcoin:
|
|
@@ -552,7 +561,7 @@ const kt = (n) => {
|
|
|
552
561
|
symbol: c ? `${a}-${(c == null ? void 0 : c.toLowerCase()) ?? ""}` : s,
|
|
553
562
|
ticker: t ? s : a
|
|
554
563
|
};
|
|
555
|
-
},
|
|
564
|
+
}, wt = {
|
|
556
565
|
/**
|
|
557
566
|
* Core
|
|
558
567
|
*/
|
|
@@ -611,10 +620,10 @@ const kt = (n) => {
|
|
|
611
620
|
};
|
|
612
621
|
class Z extends Error {
|
|
613
622
|
constructor(t, e) {
|
|
614
|
-
console.error(e), super(t, { cause: { code:
|
|
623
|
+
console.error(e), super(t, { cause: { code: wt[t], message: t } }), Object.setPrototypeOf(this, Z.prototype);
|
|
615
624
|
}
|
|
616
625
|
}
|
|
617
|
-
class
|
|
626
|
+
class bt extends E {
|
|
618
627
|
eq(t) {
|
|
619
628
|
return this.eqValue(t);
|
|
620
629
|
}
|
|
@@ -626,26 +635,27 @@ export {
|
|
|
626
635
|
A as AssetValue,
|
|
627
636
|
B as DEFAULT_DECIMAL,
|
|
628
637
|
Z as SwapKitError,
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
638
|
+
bt as SwapKitNumber,
|
|
639
|
+
Mt as assetFromString,
|
|
640
|
+
yt as derivationPathToString,
|
|
632
641
|
U as formatBigIntToSafeValue,
|
|
633
|
-
|
|
642
|
+
Bt as gasFeeMultiplier,
|
|
634
643
|
_t as getAssetType,
|
|
635
644
|
pt as getAsymmetricAssetShare,
|
|
636
|
-
|
|
645
|
+
Ot as getAsymmetricAssetWithdrawAmount,
|
|
637
646
|
gt as getAsymmetricRuneShare,
|
|
638
|
-
|
|
647
|
+
Et as getAsymmetricRuneWithdrawAmount,
|
|
639
648
|
ht as getCommonAssetInfo,
|
|
640
649
|
X as getDecimal,
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
650
|
+
Nt as getEstimatedPoolShare,
|
|
651
|
+
Rt as getLiquiditySlippage,
|
|
652
|
+
kt as getMemoFor,
|
|
653
|
+
Dt as getMinAmountByChain,
|
|
645
654
|
Tt as getRequest,
|
|
655
|
+
ft as getSymmetricPoolShare,
|
|
646
656
|
Vt as getSymmetricWithdraw,
|
|
647
657
|
vt as getTHORNameCost,
|
|
648
658
|
mt as isGasAsset,
|
|
649
659
|
ct as postRequest,
|
|
650
|
-
|
|
660
|
+
Ct as validateTHORName
|
|
651
661
|
};
|
package/package.json
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
"extends": "../../../internal/eslint-config"
|
|
14
14
|
},
|
|
15
15
|
"peerDependencies": {
|
|
16
|
+
"@swapkit/tokens": "1.0.0-rc.0",
|
|
16
17
|
"@swapkit/types": "1.0.0-rc.0"
|
|
17
18
|
},
|
|
18
19
|
"exports": {
|
|
@@ -38,7 +39,7 @@
|
|
|
38
39
|
"repository": "https://github.com/thorswap/SwapKit.git",
|
|
39
40
|
"type": "module",
|
|
40
41
|
"types": "./dist/index.d.ts",
|
|
41
|
-
"version": "1.0.0-rc.
|
|
42
|
+
"version": "1.0.0-rc.1",
|
|
42
43
|
"scripts": {
|
|
43
44
|
"build": "vite build",
|
|
44
45
|
"clean": "rm -rf dist vite.config.ts.* .turbo node_modules",
|
package/src/helpers/liquidity.ts
CHANGED
|
@@ -83,6 +83,19 @@ export const getAsymmetricAssetWithdrawAmount = ({
|
|
|
83
83
|
const toTCSwapKitNumber = (value: string) =>
|
|
84
84
|
new SwapKitNumber({ value, decimal: BaseDecimal.THOR });
|
|
85
85
|
|
|
86
|
+
export const getSymmetricPoolShare = ({
|
|
87
|
+
liquidityUnits,
|
|
88
|
+
poolUnits,
|
|
89
|
+
runeDepth,
|
|
90
|
+
assetDepth,
|
|
91
|
+
}: ShareParams<{
|
|
92
|
+
runeDepth: string;
|
|
93
|
+
assetDepth: string;
|
|
94
|
+
}>) => ({
|
|
95
|
+
assetAmount: toTCSwapKitNumber(assetDepth).mul(liquidityUnits).div(poolUnits),
|
|
96
|
+
runeAmount: toTCSwapKitNumber(runeDepth).mul(liquidityUnits).div(poolUnits),
|
|
97
|
+
});
|
|
98
|
+
|
|
86
99
|
export const getSymmetricWithdraw = ({
|
|
87
100
|
liquidityUnits,
|
|
88
101
|
poolUnits,
|
|
@@ -93,10 +106,12 @@ export const getSymmetricWithdraw = ({
|
|
|
93
106
|
runeDepth: string;
|
|
94
107
|
assetDepth: string;
|
|
95
108
|
percent: number;
|
|
96
|
-
}>) =>
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
109
|
+
}>) =>
|
|
110
|
+
Object.fromEntries(
|
|
111
|
+
Object.entries(getSymmetricPoolShare({ liquidityUnits, poolUnits, runeDepth, assetDepth })).map(
|
|
112
|
+
([name, value]) => [name, value.mul(percent)],
|
|
113
|
+
),
|
|
114
|
+
);
|
|
100
115
|
|
|
101
116
|
export const getEstimatedPoolShare = ({
|
|
102
117
|
runeDepth,
|
|
@@ -20,11 +20,21 @@ describe('AssetValue', () => {
|
|
|
20
20
|
const ethSynth = new AssetValue({
|
|
21
21
|
chain: Chain.THORChain,
|
|
22
22
|
symbol: 'ETH/ETH',
|
|
23
|
-
decimal:
|
|
23
|
+
decimal: 8,
|
|
24
24
|
value: 1234567890,
|
|
25
25
|
});
|
|
26
|
+
|
|
26
27
|
expect(ethSynth.assetValue).toBe('1234567890 ETH/ETH');
|
|
27
28
|
expect(ethSynth.toString()).toBe('THOR.ETH/ETH');
|
|
29
|
+
|
|
30
|
+
const atomDerived = new AssetValue({
|
|
31
|
+
identifier: 'THOR.ATOM',
|
|
32
|
+
decimal: 6,
|
|
33
|
+
value: 123456789,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
expect(atomDerived.assetValue).toBe('123456789 ATOM');
|
|
37
|
+
expect(atomDerived.toString()).toBe('THOR.ATOM');
|
|
28
38
|
});
|
|
29
39
|
});
|
|
30
40
|
|