mirror of
https://github.com/logos-messaging/OpChan.git
synced 2026-01-04 05:43:10 +00:00
36 lines
15 KiB
JavaScript
36 lines
15 KiB
JavaScript
import{N as u,D as W,E as _,F as x,G as O,J as R,K as f,L as y,M as G,O as z,Q as p,R as T,T as m,V as b,W as w,X as V,Y as $,Z as H,$ as v,a0 as C,a1 as N,a2 as E,i as q,a3 as Q,a4 as j,a5 as M,c as K,a as Y,x as U}from"./index-Cr5N_0pd.js";const g={getGasPriceInEther(o,n){const t=n*o;return Number(t)/1e18},getGasPriceInUSD(o,n,t){const a=g.getGasPriceInEther(n,t);return u.bigNumber(o).times(a).toNumber()},getPriceImpact({sourceTokenAmount:o,sourceTokenPriceInUSD:n,toTokenPriceInUSD:t,toTokenAmount:a}){const i=u.bigNumber(o).times(n),s=u.bigNumber(a).times(t);return i.minus(s).div(i).times(100).toNumber()},getMaxSlippage(o,n){const t=u.bigNumber(o).div(100);return u.multiply(n,t).toNumber()},getProviderFee(o,n=.0085){return u.bigNumber(o).times(n).toString()},isInsufficientNetworkTokenForGas(o,n){const t=n||"0";return u.bigNumber(o).eq(0)?!0:u.bigNumber(u.bigNumber(t)).gt(o)},isInsufficientSourceTokenForSwap(o,n,t){const a=t?.find(s=>s.address===n)?.quantity?.numeric;return u.bigNumber(a||"0").lt(o)},getToTokenAmount({sourceToken:o,toToken:n,sourceTokenPrice:t,toTokenPrice:a,sourceTokenAmount:i}){if(i==="0"||!o||!n)return"0";const s=o.decimals,c=t,d=n.decimals,k=a;if(k<=0)return"0";const S=u.bigNumber(i).times(.0085),P=u.bigNumber(i).minus(S).times(u.bigNumber(10).pow(s)),F=u.bigNumber(c).div(k),L=s-d;return P.times(F).div(u.bigNumber(10).pow(L)).div(u.bigNumber(10).pow(d)).toFixed(d).toString()}},B=15e4,J=6,l={initializing:!1,initialized:!1,loadingPrices:!1,loadingQuote:!1,loadingApprovalTransaction:!1,loadingBuildTransaction:!1,loadingTransaction:!1,fetchError:!1,approvalTransaction:void 0,swapTransaction:void 0,transactionError:void 0,sourceToken:void 0,sourceTokenAmount:"",sourceTokenPriceInUSD:0,toToken:void 0,toTokenAmount:"",toTokenPriceInUSD:0,networkPrice:"0",networkBalanceInUSD:"0",networkTokenSymbol:"",inputError:void 0,slippage:x.CONVERT_SLIPPAGE_TOLERANCE,tokens:void 0,popularTokens:void 0,suggestedTokens:void 0,foundTokens:void 0,myTokensWithBalance:void 0,tokensPriceMap:{},gasFee:"0",gasPriceInUSD:0,priceImpact:void 0,maxSlippage:void 0,providerFee:void 0},e=W(l),h={state:e,subscribe(o){return O(e,()=>o(e))},subscribeKey(o,n){return R(e,o,n)},getParams(){const o=f.state.activeCaipAddress,n=y.getPlainAddress(o),t=G(),a=z.getConnectorId(f.state.activeChain);if(!n)throw new Error("No address found to swap the tokens from.");const i=!e.toToken?.address||!e.toToken?.decimals,s=!e.sourceToken?.address||!e.sourceToken?.decimals||!u.bigNumber(e.sourceTokenAmount).gt(0),c=!e.sourceTokenAmount;return{networkAddress:t,fromAddress:n,fromCaipAddress:o,sourceTokenAddress:e.sourceToken?.address,toTokenAddress:e.toToken?.address,toTokenAmount:e.toTokenAmount,toTokenDecimals:e.toToken?.decimals,sourceTokenAmount:e.sourceTokenAmount,sourceTokenDecimals:e.sourceToken?.decimals,invalidToToken:i,invalidSourceToken:s,invalidSourceTokenAmount:c,availableToSwap:o&&!i&&!s&&!c,isAuthConnector:a===p.CONNECTOR_ID.AUTH}},setSourceToken(o){if(!o){e.sourceToken=o,e.sourceTokenAmount="",e.sourceTokenPriceInUSD=0;return}e.sourceToken=o,r.setTokenPrice(o.address,"sourceToken")},setSourceTokenAmount(o){e.sourceTokenAmount=o},setToToken(o){if(!o){e.toToken=o,e.toTokenAmount="",e.toTokenPriceInUSD=0;return}e.toToken=o,r.setTokenPrice(o.address,"toToken")},setToTokenAmount(o){e.toTokenAmount=o?u.formatNumberToLocalString(o,J):""},async setTokenPrice(o,n){let t=e.tokensPriceMap[o]||0;t||(e.loadingPrices=!0,t=await r.getAddressPrice(o)),n==="sourceToken"?e.sourceTokenPriceInUSD=t:n==="toToken"&&(e.toTokenPriceInUSD=t),e.loadingPrices&&(e.loadingPrices=!1),r.getParams().availableToSwap&&r.swapTokens()},switchTokens(){if(e.initializing||!e.initialized)return;const o=e.toToken?{...e.toToken}:void 0,n=e.sourceToken?{...e.sourceToken}:void 0,t=o&&e.toTokenAmount===""?"1":e.toTokenAmount;r.setSourceToken(o),r.setToToken(n),r.setSourceTokenAmount(t),r.setToTokenAmount(""),r.swapTokens()},resetState(){e.myTokensWithBalance=l.myTokensWithBalance,e.tokensPriceMap=l.tokensPriceMap,e.initialized=l.initialized,e.sourceToken=l.sourceToken,e.sourceTokenAmount=l.sourceTokenAmount,e.sourceTokenPriceInUSD=l.sourceTokenPriceInUSD,e.toToken=l.toToken,e.toTokenAmount=l.toTokenAmount,e.toTokenPriceInUSD=l.toTokenPriceInUSD,e.networkPrice=l.networkPrice,e.networkTokenSymbol=l.networkTokenSymbol,e.networkBalanceInUSD=l.networkBalanceInUSD,e.inputError=l.inputError,e.myTokensWithBalance=l.myTokensWithBalance},resetValues(){const{networkAddress:o}=r.getParams(),n=e.tokens?.find(t=>t.address===o);r.setSourceToken(n),r.setToToken(void 0)},getApprovalLoadingState(){return e.loadingApprovalTransaction},clearError(){e.transactionError=void 0},async initializeState(){if(!e.initializing){if(e.initializing=!0,!e.initialized)try{await r.fetchTokens(),e.initialized=!0}catch{e.initialized=!1,T.showError("Failed to initialize swap"),m.goBack()}e.initializing=!1}},async fetchTokens(){const{networkAddress:o}=r.getParams();await r.getTokenList(),await r.getNetworkTokenPrice(),await r.getMyTokensWithBalance();const n=e.tokens?.find(t=>t.address===o);n&&(e.networkTokenSymbol=n.symbol,r.setSourceToken(n),r.setSourceTokenAmount("0"))},async getTokenList(){const o=await b.getTokenList();e.tokens=o,e.popularTokens=o.sort((n,t)=>n.symbol<t.symbol?-1:n.symbol>t.symbol?1:0),e.suggestedTokens=o.filter(n=>!!x.SWAP_SUGGESTED_TOKENS.includes(n.symbol),{})},async getAddressPrice(o){const n=e.tokensPriceMap[o];if(n)return n;const a=(await w.fetchTokenPrice({addresses:[o]}))?.fungibles||[],s=[...e.tokens||[],...e.myTokensWithBalance||[]]?.find(k=>k.address===o)?.symbol,c=a.find(k=>k.symbol.toLowerCase()===s?.toLowerCase())?.price||0,d=parseFloat(c.toString());return e.tokensPriceMap[o]=d,d},async getNetworkTokenPrice(){const{networkAddress:o}=r.getParams(),t=(await w.fetchTokenPrice({addresses:[o]}).catch(()=>(T.showError("Failed to fetch network token price"),{fungibles:[]}))).fungibles?.[0],a=t?.price.toString()||"0";e.tokensPriceMap[o]=parseFloat(a),e.networkTokenSymbol=t?.symbol||"",e.networkPrice=a},async getMyTokensWithBalance(o){const n=await V.getMyTokensWithBalance(o),t=b.mapBalancesToSwapTokens(n);t&&(await r.getInitialGasPrice(),r.setBalances(t))},setBalances(o){const{networkAddress:n}=r.getParams(),t=f.state.activeCaipNetwork;if(!t)return;const a=o.find(i=>i.address===n);o.forEach(i=>{e.tokensPriceMap[i.address]=i.price||0}),e.myTokensWithBalance=o.filter(i=>i.address.startsWith(t.caipNetworkId)),e.networkBalanceInUSD=a?u.multiply(a.quantity.numeric,a.price).toString():"0"},async getInitialGasPrice(){const o=await b.fetchGasPrice();if(!o)return{gasPrice:null,gasPriceInUSD:null};switch(f.state?.activeCaipNetwork?.chainNamespace){case p.CHAIN.SOLANA:return e.gasFee=o.standard??"0",e.gasPriceInUSD=u.multiply(o.standard,e.networkPrice).div(1e9).toNumber(),{gasPrice:BigInt(e.gasFee),gasPriceInUSD:Number(e.gasPriceInUSD)};case p.CHAIN.EVM:default:const n=o.standard??"0",t=BigInt(n),a=BigInt(B),i=g.getGasPriceInUSD(e.networkPrice,a,t);return e.gasFee=n,e.gasPriceInUSD=i,{gasPrice:t,gasPriceInUSD:i}}},async swapTokens(){const o=$.state.address,n=e.sourceToken,t=e.toToken,a=u.bigNumber(e.sourceTokenAmount).gt(0);if(a||r.setToTokenAmount(""),!t||!n||e.loadingPrices||!a)return;e.loadingQuote=!0;const i=u.bigNumber(e.sourceTokenAmount).times(10**n.decimals).round(0);try{const s=await w.fetchSwapQuote({userAddress:o,from:n.address,to:t.address,gasPrice:e.gasFee,amount:i.toString()});e.loadingQuote=!1;const c=s?.quotes?.[0]?.toAmount;if(!c){H.open({displayMessage:"Incorrect amount",debugMessage:"Please enter a valid amount"},"error");return}const d=u.bigNumber(c).div(10**t.decimals).toString();r.setToTokenAmount(d),r.hasInsufficientToken(e.sourceTokenAmount,n.address)?e.inputError="Insufficient balance":(e.inputError=void 0,r.setTransactionDetails())}catch{e.loadingQuote=!1,e.inputError="Insufficient balance"}},async getTransaction(){const{fromCaipAddress:o,availableToSwap:n}=r.getParams(),t=e.sourceToken,a=e.toToken;if(!(!o||!n||!t||!a||e.loadingQuote))try{e.loadingBuildTransaction=!0;const i=await b.fetchSwapAllowance({userAddress:o,tokenAddress:t.address,sourceTokenAmount:e.sourceTokenAmount,sourceTokenDecimals:t.decimals});let s;return i?s=await r.createSwapTransaction():s=await r.createAllowanceTransaction(),e.loadingBuildTransaction=!1,e.fetchError=!1,s}catch{m.goBack(),T.showError("Failed to check allowance"),e.loadingBuildTransaction=!1,e.approvalTransaction=void 0,e.swapTransaction=void 0,e.fetchError=!0;return}},async createAllowanceTransaction(){const{fromCaipAddress:o,sourceTokenAddress:n,toTokenAddress:t}=r.getParams();if(!(!o||!t)){if(!n)throw new Error("createAllowanceTransaction - No source token address found.");try{const a=await w.generateApproveCalldata({from:n,to:t,userAddress:o}),i=y.getPlainAddress(a.tx.from);if(!i)throw new Error("SwapController:createAllowanceTransaction - address is required");const s={data:a.tx.data,to:i,gasPrice:BigInt(a.tx.eip155.gasPrice),value:BigInt(a.tx.value),toAmount:e.toTokenAmount};return e.swapTransaction=void 0,e.approvalTransaction={data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount},{data:s.data,to:s.to,gasPrice:s.gasPrice,value:s.value,toAmount:s.toAmount}}catch{m.goBack(),T.showError("Failed to create approval transaction"),e.approvalTransaction=void 0,e.swapTransaction=void 0,e.fetchError=!0;return}}},async createSwapTransaction(){const{networkAddress:o,fromCaipAddress:n,sourceTokenAmount:t}=r.getParams(),a=e.sourceToken,i=e.toToken;if(!n||!t||!a||!i)return;const s=v.parseUnits(t,a.decimals)?.toString();try{const c=await w.generateSwapCalldata({userAddress:n,from:a.address,to:i.address,amount:s,disableEstimate:!0}),d=a.address===o,k=BigInt(c.tx.eip155.gas),S=BigInt(c.tx.eip155.gasPrice),I=y.getPlainAddress(c.tx.to);if(!I)throw new Error("SwapController:createSwapTransaction - address is required");const P={data:c.tx.data,to:I,gas:k,gasPrice:S,value:BigInt(d?s??"0":"0"),toAmount:e.toTokenAmount};return e.gasPriceInUSD=g.getGasPriceInUSD(e.networkPrice,k,S),e.approvalTransaction=void 0,e.swapTransaction=P,P}catch{m.goBack(),T.showError("Failed to create transaction"),e.approvalTransaction=void 0,e.swapTransaction=void 0,e.fetchError=!0;return}},onEmbeddedWalletApprovalSuccess(){T.showLoading("Approve limit increase in your wallet"),m.replace("SwapPreview")},async sendTransactionForApproval(o){const{fromAddress:n,isAuthConnector:t}=r.getParams();e.loadingApprovalTransaction=!0,t?m.pushTransactionStack({onSuccess:r.onEmbeddedWalletApprovalSuccess}):T.showLoading("Approve limit increase in your wallet");try{await v.sendTransaction({address:n,to:o.to,data:o.data,value:o.value,chainNamespace:p.CHAIN.EVM}),await r.swapTokens(),await r.getTransaction(),e.approvalTransaction=void 0,e.loadingApprovalTransaction=!1}catch(i){const s=i;e.transactionError=s?.displayMessage,e.loadingApprovalTransaction=!1,T.showError(s?.displayMessage||"Transaction error"),C.sendEvent({type:"track",event:"SWAP_APPROVAL_ERROR",properties:{message:s?.displayMessage||s?.message||"Unknown",network:f.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:r.state.sourceToken?.symbol||"",swapToToken:r.state.toToken?.symbol||"",swapFromAmount:r.state.sourceTokenAmount||"",swapToAmount:r.state.toTokenAmount||"",isSmartAccount:N(p.CHAIN.EVM)===E.ACCOUNT_TYPES.SMART_ACCOUNT}})}},async sendTransactionForSwap(o){if(!o)return;const{fromAddress:n,toTokenAmount:t,isAuthConnector:a}=r.getParams();e.loadingTransaction=!0;const i=`Swapping ${e.sourceToken?.symbol} to ${u.formatNumberToLocalString(t,3)} ${e.toToken?.symbol}`,s=`Swapped ${e.sourceToken?.symbol} to ${u.formatNumberToLocalString(t,3)} ${e.toToken?.symbol}`;a?m.pushTransactionStack({onSuccess(){m.replace("Account"),T.showLoading(i),h.resetState()}}):T.showLoading("Confirm transaction in your wallet");try{const c=[e.sourceToken?.address,e.toToken?.address].join(","),d=await v.sendTransaction({address:n,to:o.to,data:o.data,value:o.value,chainNamespace:p.CHAIN.EVM});return e.loadingTransaction=!1,T.showSuccess(s),C.sendEvent({type:"track",event:"SWAP_SUCCESS",properties:{network:f.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:r.state.sourceToken?.symbol||"",swapToToken:r.state.toToken?.symbol||"",swapFromAmount:r.state.sourceTokenAmount||"",swapToAmount:r.state.toTokenAmount||"",isSmartAccount:N(p.CHAIN.EVM)===E.ACCOUNT_TYPES.SMART_ACCOUNT}}),h.resetState(),a||m.replace("Account"),h.getMyTokensWithBalance(c),d}catch(c){const d=c;e.transactionError=d?.displayMessage,e.loadingTransaction=!1,T.showError(d?.displayMessage||"Transaction error"),C.sendEvent({type:"track",event:"SWAP_ERROR",properties:{message:d?.displayMessage||d?.message||"Unknown",network:f.state.activeCaipNetwork?.caipNetworkId||"",swapFromToken:r.state.sourceToken?.symbol||"",swapToToken:r.state.toToken?.symbol||"",swapFromAmount:r.state.sourceTokenAmount||"",swapToAmount:r.state.toTokenAmount||"",isSmartAccount:N(p.CHAIN.EVM)===E.ACCOUNT_TYPES.SMART_ACCOUNT}});return}},hasInsufficientToken(o,n){return g.isInsufficientSourceTokenForSwap(o,n,e.myTokensWithBalance)},setTransactionDetails(){const{toTokenAddress:o,toTokenDecimals:n}=r.getParams();!o||!n||(e.gasPriceInUSD=g.getGasPriceInUSD(e.networkPrice,BigInt(e.gasFee),BigInt(B)),e.priceImpact=g.getPriceImpact({sourceTokenAmount:e.sourceTokenAmount,sourceTokenPriceInUSD:e.sourceTokenPriceInUSD,toTokenPriceInUSD:e.toTokenPriceInUSD,toTokenAmount:e.toTokenAmount}),e.maxSlippage=g.getMaxSlippage(e.slippage,e.toTokenAmount),e.providerFee=g.getProviderFee(e.sourceTokenAmount))}},r=_(h),X=q`
|
|
:host {
|
|
display: block;
|
|
}
|
|
|
|
:host > button {
|
|
gap: var(--wui-spacing-xxs);
|
|
padding: var(--wui-spacing-xs);
|
|
padding-right: var(--wui-spacing-1xs);
|
|
height: 40px;
|
|
border-radius: var(--wui-border-radius-l);
|
|
background: var(--wui-color-gray-glass-002);
|
|
border-width: 0px;
|
|
box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-002);
|
|
}
|
|
|
|
:host > button wui-image {
|
|
width: 24px;
|
|
height: 24px;
|
|
border-radius: var(--wui-border-radius-s);
|
|
box-shadow: inset 0 0 0 1px var(--wui-color-gray-glass-010);
|
|
}
|
|
`;var D=function(o,n,t,a){var i=arguments.length,s=i<3?n:a===null?a=Object.getOwnPropertyDescriptor(n,t):a,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(o,n,t,a);else for(var d=o.length-1;d>=0;d--)(c=o[d])&&(s=(i<3?c(s):i>3?c(n,t,s):c(n,t))||s);return i>3&&s&&Object.defineProperty(n,t,s),s};let A=class extends Y{constructor(){super(...arguments),this.text=""}render(){return U`
|
|
<button>
|
|
${this.tokenTemplate()}
|
|
<wui-text variant="paragraph-600" color="fg-100">${this.text}</wui-text>
|
|
</button>
|
|
`}tokenTemplate(){return this.imageSrc?U`<wui-image src=${this.imageSrc}></wui-image>`:U`
|
|
<wui-icon-box
|
|
size="sm"
|
|
iconColor="fg-200"
|
|
backgroundColor="fg-300"
|
|
icon="networkPlaceholder"
|
|
></wui-icon-box>
|
|
`}};A.styles=[Q,j,X];D([M()],A.prototype,"imageSrc",void 0);D([M()],A.prototype,"text",void 0);A=D([K("wui-token-button")],A);export{r as S};
|