@ic-pay/icpay-widget 0.1.100 → 1.1.3
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.d.ts +1 -0
- package/dist/index.global.js +46 -46
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +15 -15
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var De=Object.defineProperty;var
|
|
1
|
+
var De=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var s=(o,a,e,t)=>{for(var i=t>1?void 0:t?Ke(a,e):a,n=o.length-1,r;n>=0;n--)(r=o[n])&&(i=(t?r(a,e,i):r(i))||i);return t&&i&&De(a,e,i),i};import{css as ze}from"lit";var $=ze`
|
|
2
2
|
:host {
|
|
3
3
|
--icpay-primary: #f9fafb;
|
|
4
4
|
--icpay-secondary: #e5e7eb;
|
|
@@ -56,7 +56,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
56
56
|
0%, 100% { opacity: 1; }
|
|
57
57
|
50% { opacity: 0.7; }
|
|
58
58
|
}
|
|
59
|
-
`;function ie(o,a){if(!o||!a)return;let e=a.primaryColor||void 0,t=a.secondaryColor||void 0,i=(K,z)=>{z&&o.style.setProperty(K,z)};i("--icpay-primary",e),i("--icpay-secondary",t);let n=K=>{if(!K)return null;let z=K.replace("#",""),H=z.length===3?z.split("").map(Te=>Te+Te).join(""):z,V=parseInt(H,16),te=V>>16&255,Re=V>>8&255,Be=V&255;return{r:te,g:Re,b:Be}},c=(K=>{let z=n(K);if(!z)return 0;let H=V=>{let te=V/255;return te<=.03928?te/12.92:Math.pow((te+.055)/1.055,2.4)};return .2126*H(z.r)+.7152*H(z.g)+.0722*H(z.b)})(e||t)>.6,d=a.surfaceColor||(c?"#f3f4f6":"#1f2937"),p=a.surfaceAltColor||(c?"#e5e7eb":"#374151"),E=a.borderColor||(c?"#d1d5db":"#4b5563"),ue=a.textColor||(c?"#111827":"#f9fafb"),be=a.accentColor||t||e||(c?"#6b7280":"#9ca3af"),me=a.mutedTextColor||(c?"#6b7280":"#9ca3af");i("--icpay-accent",be),i("--icpay-text",ue),i("--icpay-muted",me),i("--icpay-surface",d),i("--icpay-surface-alt",p),i("--icpay-border",E)}import{Icpay as Ne}from"@ic-pay/icpay-sdk";var Ue=typeof window<"u";function ve(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}function h(o){if(!Ue)return{client:{},quoteUsd:async()=>({tokenAmountDecimals:"0"}),sendUsd:async()=>({transactionId:"0",status:"pending"}),startOnrampUsd:async()=>({transactionId:"0",status:"pending",metadata:{onramp:{sessionId:null}}}),notifyIntentUntilComplete:()=>({stop:()=>{}})};ve(o.debug||!1,"Creating SDK with config:",o);let a={publishableKey:o.publishableKey};o.enableEvents!==void 0?a.enableEvents=o.enableEvents:a.enableEvents=!0,o.apiUrl&&(a.apiUrl=o.apiUrl),o.icHost&&(a.icHost=o.icHost),o.actorProvider&&(a.actorProvider=o.actorProvider),o.connectedWallet&&(a.connectedWallet=o.connectedWallet),o.debug!==void 0&&(a.debug=o.debug),ve(o.debug||!1,"Filtered SDK config:",a);try{let l=function(c,d,p){return t.notifyPaymentIntentOnRamp({paymentIntentId:c,intervalMs:d,orderId:p})};var e=l;ve(o.debug||!1,"typeof Icpay:",typeof Ne);let t=new Ne(a);if(Ue){let c=t,d=p=>{c.addEventListener(p,E=>{window.dispatchEvent(new CustomEvent(p,{detail:E?.detail??E}))})};["icpay-sdk-error","icpay-sdk-transaction-created","icpay-sdk-transaction-updated","icpay-sdk-transaction-completed","icpay-sdk-transaction-failed","icpay-sdk-method-start","icpay-sdk-method-success","icpay-sdk-method-error"].forEach(d)}async function i(c,d){return t.calculateTokenAmountFromUSD({usdAmount:c,ledgerCanisterId:d})}async function n(c,d,p){return t.sendFundsUsd({usdAmount:c,ledgerCanisterId:d,metadata:p})}async function r(c,d,p){return t.sendFundsUsd({usdAmount:c,ledgerCanisterId:d,metadata:p,onrampPayment:!0})}return{client:t,quoteUsd:i,sendUsd:n,startOnrampUsd:r,notifyIntentUntilComplete:l}}catch(t){throw ve(o.debug||!1,"Error creating SDK:",t),t}}import{LitElement as et,html as se,css as tt}from"lit";import{customElement as it,property as nt,state as U}from"lit/decorators.js";import{IcpayError as Pe}from"@ic-pay/icpay-sdk";var C={WALLET_NOT_CONNECTED:"WALLET_NOT_CONNECTED",WALLET_USER_CANCELLED:"WALLET_USER_CANCELLED",WALLET_SIGNATURE_REJECTED:"WALLET_SIGNATURE_REJECTED",INSUFFICIENT_BALANCE:"INSUFFICIENT_BALANCE",NETWORK_ERROR:"NETWORK_ERROR",API_ERROR:"API_ERROR",LEDGER_NOT_FOUND:"LEDGER_NOT_FOUND",TRANSACTION_FAILED:"TRANSACTION_FAILED",TRANSACTION_TIMEOUT:"TRANSACTION_TIMEOUT",UNKNOWN_ERROR:"UNKNOWN_ERROR"},ze={onError:o=>{console.error("[ICPay Widget] Error:",o)},onUserCancelled:()=>{console.log("[ICPay Widget] User cancelled the action")},onInsufficientBalance:o=>{console.warn("[ICPay Widget] Insufficient balance:",o.message)},onWalletError:o=>{console.warn("[ICPay Widget] Wallet error:",o.message)},onNetworkError:o=>{console.error("[ICPay Widget] Network error:",o.message)}};function L(o,a=ze){o instanceof Pe?(a.onError(o),o.isUserCancelled()?a.onUserCancelled?.():o.isBalanceError()?a.onInsufficientBalance?.(o):o.isWalletError()?a.onWalletError?.(o):o.isNetworkError()&&a.onNetworkError?.(o)):(console.error("[ICPay Widget] Unknown error:",o),a.onError(new Pe({code:C.UNKNOWN_ERROR,message:o instanceof Error?o.message:"An unknown error occurred",details:o})))}var He={[C.WALLET_NOT_CONNECTED]:"Please connect your wallet to continue",[C.WALLET_USER_CANCELLED]:"User have rejected the transfer",[C.WALLET_SIGNATURE_REJECTED]:"User have rejected the transfer",[C.INSUFFICIENT_BALANCE]:"Insufficient balance for this transaction",[C.NETWORK_ERROR]:"Network error. Please try again",[C.API_ERROR]:"Service temporarily unavailable",[C.LEDGER_NOT_FOUND]:"Selected token is not supported",[C.TRANSACTION_FAILED]:"Transaction failed. Please try again",[C.TRANSACTION_TIMEOUT]:"Transaction timed out. Please try again",[C.UNKNOWN_ERROR]:"Something went wrong. Please try again"};function O(o){return He[o.code]||o.message||"An error occurred"}function A(o){return!o.isUserCancelled()}function W(o){if(o.userAction)return o.userAction;switch(o.code){case C.WALLET_NOT_CONNECTED:return"Connect Wallet";case C.INSUFFICIENT_BALANCE:return"Add Funds";case C.NETWORK_ERROR:case C.API_ERROR:return"Try Again";default:return null}}function T(o){return o.isUserCancelled()?"info":o.isBalanceError()||o.isWalletError()?"warning":"error"}import{LitElement as je,html as S,css as Ve}from"lit";import{customElement as Ge,property as q,state as j}from"lit/decorators.js";function g(o,a,e){o&&(e!==void 0?console.log(a,e):console.log(a))}var Ye=[{key:"wallet",label:"Connect Wallet",tooltip:"Awaiting wallet connection",status:"pending"},{key:"init",label:"Initialising ICPay",tooltip:"Initializing payment",status:"pending"},{key:"await",label:"Awaiting payment confirmation",tooltip:"Preparing payment",status:"pending"},{key:"transfer",label:"Transferring funds",tooltip:"Submitting payment",status:"pending"},{key:"verify",label:"Verifying payment",tooltip:"Confirming payment",status:"pending"},{key:"confirm",label:"Payment confirmed",tooltip:"Payment completed",status:"pending"}],m=class extends je{constructor(){super(...arguments);this.open=!1;this.steps=Ye;this.amount=0;this.currency="";this.ledgerSymbol="";this.debug=!1;this.activeIndex=0;this.completed=!1;this.failed=!1;this.errorMessage=null;this.showSuccess=!1;this.showConfetti=!1;this.currentSteps=[];this.currentAmount=0;this.currentCurrency="";this.currentLedgerSymbol="";this.confirmLoadingStartedAt=null;this.progressionTimer=null;this.onMethodStart=e=>{let t=e?.detail?.name||"",i=e?.detail?.type||"";if(g(this.debug,"ICPay Progress: Method start event received:",e.detail),t==="sendFunds"||t==="sendFundsUsd"||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order"){if(this.open=!0,this.activeIndex=0,this.completed=!1,this.failed=!1,this.errorMessage=null,this.showSuccess=!1,this.showConfetti=!1,this.currentSteps=this.currentSteps.map(n=>({...n,status:"pending"})),i==="onramp"){let n=this.getStepIndexByKey("wallet");n>=0&&(this.currentSteps[n]={...this.currentSteps[n],label:"Transak Started",tooltip:"Awaiting Transak information"})}this.setLoadingByKey("wallet"),e?.detail?.amount!==void 0&&(this.currentAmount=e.detail.amount,this.amount=e.detail.amount,g(this.debug,"ICPay Progress: Amount updated to:",e.detail.amount)),e?.detail?.currency&&(this.currentCurrency=e.detail.currency,this.currency=e.detail.currency,g(this.debug,"ICPay Progress: Currency updated to:",e.detail.currency)),e?.detail?.ledgerSymbol&&(this.currentLedgerSymbol=e.detail.ledgerSymbol,this.ledgerSymbol=e.detail.ledgerSymbol,g(this.debug,"ICPay Progress: Current state after method start:",{activeIndex:this.activeIndex,currentAmount:this.currentAmount,currentCurrency:this.currentCurrency,currentLedgerSymbol:this.currentLedgerSymbol})),g(this.debug,"ICPay Progress: Waiting for wallet confirmation before starting progression"),this.requestUpdate()}!this.failed&&!this.completed&&(t==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.setLoadingByKey("transfer")):t==="notifyLedgerTransaction"&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")))};this.onMethodSuccess=e=>{let t=e?.detail?.name||"";(t==="sendFunds"||t==="sendFundsUsd"||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order")&&this.dispatchEvent(new CustomEvent("icpay-progress-method-success",{detail:{methodName:t,step:this.activeIndex},bubbles:!0})),!this.failed&&!this.completed&&(t==="getLedgerBalance"?(this.completeByKey("wallet"),this.completeByKey("init"),this.setLoadingByKey("await")):t==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")):t==="notifyLedgerTransaction"&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.completeByKey("verify"),this.setLoadingByKey("confirm")))};this.onTransactionCreated=e=>{let t=e?.detail?.transactionId||e?.detail?.id;g(this.debug,"ICPay Progress: Transaction created event received:",e.detail),!this.failed&&!this.completed&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.setLoadingByKey("transfer")),this.dispatchEvent(new CustomEvent("icpay-progress-transaction-created",{detail:{transactionId:t,step:this.activeIndex},bubbles:!0}))};this.onTransactionUpdated=e=>{let t=e?.detail?.status||"pending",i=e?.detail?.transactionId||e?.detail?.id;g(this.debug,"ICPay Progress: Transaction updated event received:",e.detail),!this.failed&&this.completed,this.dispatchEvent(new CustomEvent("icpay-progress-transaction-updated",{detail:{status:t,transactionId:i,step:this.activeIndex},bubbles:!0}))};this.onTransactionCompleted=e=>{let t=e?.detail?.transactionId||e?.detail?.id,i=e?.detail?.status||"completed";g(this.debug,"ICPay Progress: Transaction completed event received:",e.detail),g(this.debug,"ICPay Progress: Current state when transaction completed:",{activeIndex:this.activeIndex,completed:this.completed,failed:this.failed,showSuccess:this.showSuccess}),this.completeByKey("transfer"),this.completeByKey("await"),this.completeByKey("init"),this.completeByKey("verify"),this.completeByKey("confirm"),this.completed=!0,this.showSuccess=!0,this.showConfetti=!0,this.dispatchEvent(new CustomEvent("icpay-progress-completed",{detail:{transactionId:t,status:i,amount:this.currentAmount||this.amount,currency:this.currentCurrency||this.currency,ledgerSymbol:this.currentLedgerSymbol||this.ledgerSymbol},bubbles:!0})),setTimeout(()=>{this.showConfetti=!1},3e3)};this.onTransactionFailed=e=>{let t=e?.detail?.message||e?.detail?.error?.message||"Transaction failed",i=e?.detail?.error?.code||e?.detail?.code||"UNKNOWN_ERROR",n=e?.detail?.transactionId||e?.detail?.id;g(this.debug,"ICPay Progress: Transaction failed event received:",e.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(t),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",t),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:t,errorCode:i,transactionId:n,step:this.activeIndex},bubbles:!0}))};this.onTransactionMismatched=e=>{let t=e?.detail?.requestedAmount,i=e?.detail?.paidAmount,n=e?.detail?.transactionId||e?.detail?.id;this.failed=!0;let r=t!=null?String(t):"unknown",l=i!=null?String(i):"unknown";this.errorMessage=`Amount mismatch. Requested ${r}, paid ${l}.`,this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:this.errorMessage,errorCode:"MISMATCHED_AMOUNT",transactionId:n,step:this.activeIndex,requestedAmount:t,paidAmount:i},bubbles:!0}))};this.onMethodError=e=>{let t=e?.detail?.name||"",i=e?.detail?.error?.message||e?.detail?.message||"An error occurred",n=e?.detail?.error?.code||e?.detail?.code||"METHOD_ERROR";g(this.debug,"ICPay Progress: Method error event received:",e.detail),(t?.startsWith("sendFunds")||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order")&&(this.failed=!0,this.errorMessage=this.transformErrorMessage(i),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",i),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-error",{detail:{methodName:t,errorMessage:i,errorCode:n,step:this.activeIndex},bubbles:!0})))};this.onSDKError=e=>{let t=e?.detail?.message||"SDK error occurred",i=e?.detail?.code||"SDK_ERROR";g(this.debug,"ICPay Progress: SDK error event received:",e.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(t),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",t),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-sdk-error",{detail:{errorMessage:t,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWalletConnected=e=>{let t=e?.detail?.walletType||"unknown";g(this.debug,"ICPay Progress: Wallet connected event received:",e.detail),this.completeByKey("wallet"),this.setLoadingByKey("init"),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-connected",{detail:{walletType:t,step:this.activeIndex},bubbles:!0}))};this.onWalletDisconnected=e=>{let t=e?.detail?.walletType||"unknown";g(this.debug,"ICPay Progress: Wallet disconnected event received:",e.detail),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-disconnected",{detail:{walletType:t,step:this.activeIndex},bubbles:!0}))};this.onBalanceCheck=e=>{let t=e?.detail?.hasBalance||!1,i=e?.detail?.balance||0;g(this.debug,"ICPay Progress: Balance check event received:",e.detail),t||(this.failed=!0,this.errorMessage="Insufficient balance for transaction",this.updateStepStatus(this.activeIndex,"error","Insufficient balance for transaction"),this.stopAutomaticProgression(),this.dispatchEvent(new CustomEvent("icpay-progress-insufficient-balance",{detail:{balance:i,required:this.currentAmount||this.amount,step:this.activeIndex},bubbles:!0})))};this.onLedgerVerified=e=>{let t=e?.detail?.ledgerId||e?.detail?.canisterId,i=e?.detail?.symbol||"unknown";g(this.debug,"ICPay Progress: Ledger verified event received:",e.detail),i&&i!=="unknown"&&(this.currentLedgerSymbol=i,this.ledgerSymbol=i),this.dispatchEvent(new CustomEvent("icpay-progress-ledger-verified",{detail:{ledgerId:t,symbol:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetPayment=e=>{let t=e?.detail?.amount,i=e?.detail?.currency,n=e?.detail?.ledgerSymbol;if(g(this.debug,"ICPay Progress: Widget payment event received:",e.detail),t!==void 0&&(this.currentAmount=t,this.amount=t),i&&(this.currentCurrency=i,this.currency=i),n&&(this.currentLedgerSymbol=n,this.ledgerSymbol=n),!this.failed){for(let r=this.activeIndex;r<this.currentSteps.length;r++)this.updateStepStatus(r,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-payment",{detail:{amount:t,currency:i,ledgerSymbol:n,step:this.activeIndex},bubbles:!0}))};this.onWidgetError=e=>{let t=e?.detail?.message||"Widget error occurred",i=e?.detail?.code||"WIDGET_ERROR";g(this.debug,"ICPay Progress: Widget error event received:",e.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(t),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",t),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-widget-error",{detail:{errorMessage:t,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetUnlock=e=>{let t=e?.detail?.amount,i=e?.detail?.currency;if(g(this.debug,"ICPay Progress: Widget unlock event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-unlock",{detail:{amount:t,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetTip=e=>{let t=e?.detail?.amount,i=e?.detail?.currency;if(g(this.debug,"ICPay Progress: Widget tip event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-tip",{detail:{amount:t,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetDonation=e=>{let t=e?.detail?.amount,i=e?.detail?.currency;if(g(this.debug,"ICPay Progress: Widget donation event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-donation",{detail:{amount:t,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetCoffee=e=>{let t=e?.detail?.amount,i=e?.detail?.currency;if(g(this.debug,"ICPay Progress: Widget coffee event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-coffee",{detail:{amount:t,currency:i,step:this.activeIndex},bubbles:!0}))}}connectedCallback(){super.connectedCallback();try{ie(this,this.theme)}catch{}this.currentSteps=[...this.steps],this.currentAmount=this.amount,this.currentCurrency=this.currency,this.currentLedgerSymbol=this.ledgerSymbol,this.attachSDKEventListeners()}disconnectedCallback(){super.disconnectedCallback(),this.detachSDKEventListeners(),this.stopAutomaticProgression()}updated(e){if(e.has("theme"))try{ie(this,this.theme)}catch{}}attachSDKEventListeners(){window.addEventListener("icpay-sdk-method-start",this.onMethodStart),window.addEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.addEventListener("icpay-sdk-method-error",this.onMethodError),window.addEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.addEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.addEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.addEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.addEventListener("icpay-sdk-error",this.onSDKError),window.addEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.addEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.addEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.addEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.addEventListener("icpay-pay",this.onWidgetPayment),window.addEventListener("icpay-error",this.onWidgetError),window.addEventListener("icpay-unlock",this.onWidgetUnlock),window.addEventListener("icpay-tip",this.onWidgetTip),window.addEventListener("icpay-donation",this.onWidgetDonation),window.addEventListener("icpay-coffee",this.onWidgetCoffee)}detachSDKEventListeners(){window.removeEventListener("icpay-sdk-method-start",this.onMethodStart),window.removeEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.removeEventListener("icpay-sdk-method-error",this.onMethodError),window.removeEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.removeEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.removeEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.removeEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.removeEventListener("icpay-sdk-error",this.onSDKError),window.removeEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.removeEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.removeEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.removeEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.removeEventListener("icpay-pay",this.onWidgetPayment),window.removeEventListener("icpay-error",this.onWidgetError),window.removeEventListener("icpay-unlock",this.onWidgetUnlock),window.removeEventListener("icpay-tip",this.onWidgetTip),window.removeEventListener("icpay-donation",this.onWidgetDonation),window.removeEventListener("icpay-coffee",this.onWidgetCoffee)}startAutomaticProgression(){this.progressionTimer&&clearInterval(this.progressionTimer),this.activeIndex=1,this.updateStepStatus(this.activeIndex,"loading"),g(this.debug,"ICPay Progress: Starting automatic progression from step:",this.activeIndex),this.progressionTimer=setInterval(()=>{if(this.failed||this.completed){this.stopAutomaticProgression();return}g(this.debug,"ICPay Progress: Processing step:",this.activeIndex),this.updateStepStatus(this.activeIndex,"completed"),this.activeIndex<this.currentSteps.length-1?(this.activeIndex++,this.updateStepStatus(this.activeIndex,"loading"),g(this.debug,"ICPay Progress: Auto-progressed to step:",this.activeIndex)):(this.stopAutomaticProgression(),g(this.debug,"ICPay Progress: All steps completed, waiting for transaction completion")),this.requestUpdate()},3e3)}stopAutomaticProgression(){this.progressionTimer&&(clearInterval(this.progressionTimer),this.progressionTimer=null)}updateStepStatus(e,t,i){if(e>=0&&e<this.currentSteps.length){let n=this.currentSteps[e],r=n.status;n.status=t,t==="completed"&&(n.timestamp=this.getCurrentTime()),t==="error"&&i&&(n.errorMessage=this.transformErrorMessage(i)),g(this.debug,`ICPay Progress: Step ${e} (${n.label}) status changed from ${r} to ${t}`),this.requestUpdate()}}getCurrentTime(){return new Date().toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}progressPercent(){if(this.failed)return 0;if(this.showSuccess)return 100;let t=this.currentSteps.filter(i=>i.status==="completed").length/this.currentSteps.length*100;return Math.max(0,Math.min(100,t))}verticalPercent(){if(this.failed)return 0;if(this.showSuccess)return 100;let t=this.currentSteps.filter(i=>i.status==="completed").length/this.currentSteps.length*100;return Math.max(0,Math.min(100,t))}getStepIcon(e){switch(e.status){case"loading":return S`<div class="spinner"></div>`;case"completed":return"\u2713";case"error":return"\u2717";default:return"\u25CB"}}getStepIndexByKey(e){return this.currentSteps.findIndex(t=>t.key===e)}setLoadingByKey(e){let t=this.getStepIndexByKey(e);t>=0&&(this.activeIndex=t,this.updateStepStatus(t,"loading"),e==="confirm"&&(this.confirmLoadingStartedAt=Date.now()))}completeByKey(e){let t=this.getStepIndexByKey(e);t>=0&&(this.updateStepStatus(t,"completed"),this.activeIndex=t)}transformErrorMessage(e){let t=String(e||"").toLowerCase();return t.includes("user rejected")||t.includes("user cancelled")||t.includes("user canceled")||t.includes("signature rejected")?"User have rejected the transfer":e}renderConfetti(){if(!this.showConfetti)return"";let e=Array.from({length:50},(i,n)=>n),t=["#0066FF","#ef4444","#10b981","#f59e0b","#8b5cf6"];return S`
|
|
59
|
+
`;function ie(o,a){if(!o||!a)return;let e=a.primaryColor||void 0,t=a.secondaryColor||void 0,i=(z,F)=>{F&&o.style.setProperty(z,F)};i("--icpay-primary",e),i("--icpay-secondary",t);let n=z=>{if(!z)return null;let F=z.replace("#",""),H=F.length===3?F.split("").map(Te=>Te+Te).join(""):F,V=parseInt(H,16),te=V>>16&255,Re=V>>8&255,Be=V&255;return{r:te,g:Re,b:Be}},c=(z=>{let F=n(z);if(!F)return 0;let H=V=>{let te=V/255;return te<=.03928?te/12.92:Math.pow((te+.055)/1.055,2.4)};return .2126*H(F.r)+.7152*H(F.g)+.0722*H(F.b)})(e||t)>.6,d=a.surfaceColor||(c?"#f3f4f6":"#1f2937"),p=a.surfaceAltColor||(c?"#e5e7eb":"#374151"),E=a.borderColor||(c?"#d1d5db":"#4b5563"),ue=a.textColor||(c?"#111827":"#f9fafb"),be=a.accentColor||t||e||(c?"#6b7280":"#9ca3af"),me=a.mutedTextColor||(c?"#6b7280":"#9ca3af");i("--icpay-accent",be),i("--icpay-text",ue),i("--icpay-muted",me),i("--icpay-surface",d),i("--icpay-surface-alt",p),i("--icpay-border",E)}import{Icpay as Ne}from"@ic-pay/icpay-sdk";var Ue=typeof window<"u";function ve(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}function h(o){if(!Ue)return{client:{},quoteUsd:async()=>({tokenAmountDecimals:"0"}),sendUsd:async()=>({transactionId:"0",status:"pending"}),startOnrampUsd:async()=>({transactionId:"0",status:"pending",metadata:{onramp:{sessionId:null}}}),notifyIntentUntilComplete:()=>({stop:()=>{}})};ve(o.debug||!1,"Creating SDK with config:",o);let a={publishableKey:o.publishableKey};o.enableEvents!==void 0?a.enableEvents=o.enableEvents:a.enableEvents=!0,o.apiUrl&&(a.apiUrl=o.apiUrl),o.icHost&&(a.icHost=o.icHost),o.actorProvider&&(a.actorProvider=o.actorProvider),o.connectedWallet&&(a.connectedWallet=o.connectedWallet),o.onrampDisabled!==void 0&&(a.onrampDisabled=o.onrampDisabled),o.debug!==void 0&&(a.debug=o.debug),ve(o.debug||!1,"Filtered SDK config:",a);try{let l=function(c,d,p){return t.notifyPaymentIntentOnRamp({paymentIntentId:c,intervalMs:d,orderId:p})};var e=l;ve(o.debug||!1,"typeof Icpay:",typeof Ne);let t=new Ne(a);if(Ue){let c=t,d=p=>{c.addEventListener(p,E=>{window.dispatchEvent(new CustomEvent(p,{detail:E?.detail??E}))})};["icpay-sdk-error","icpay-sdk-transaction-created","icpay-sdk-transaction-updated","icpay-sdk-transaction-completed","icpay-sdk-transaction-failed","icpay-sdk-method-start","icpay-sdk-method-success","icpay-sdk-method-error"].forEach(d)}async function i(c,d){return t.calculateTokenAmountFromUSD({usdAmount:c,ledgerCanisterId:d})}async function n(c,d,p){return t.createPaymentUsd({usdAmount:c,ledgerCanisterId:d,metadata:p})}async function r(c,d,p){return t.createPaymentUsd({usdAmount:c,ledgerCanisterId:d,metadata:p,onrampPayment:!0})}return{client:t,quoteUsd:i,sendUsd:n,startOnrampUsd:r,notifyIntentUntilComplete:l}}catch(t){throw ve(o.debug||!1,"Error creating SDK:",t),t}}import{LitElement as et,html as se,css as tt}from"lit";import{customElement as it,property as nt,state as U}from"lit/decorators.js";import{IcpayError as Pe}from"@ic-pay/icpay-sdk";var C={WALLET_NOT_CONNECTED:"WALLET_NOT_CONNECTED",WALLET_USER_CANCELLED:"WALLET_USER_CANCELLED",WALLET_SIGNATURE_REJECTED:"WALLET_SIGNATURE_REJECTED",INSUFFICIENT_BALANCE:"INSUFFICIENT_BALANCE",NETWORK_ERROR:"NETWORK_ERROR",API_ERROR:"API_ERROR",LEDGER_NOT_FOUND:"LEDGER_NOT_FOUND",TRANSACTION_FAILED:"TRANSACTION_FAILED",TRANSACTION_TIMEOUT:"TRANSACTION_TIMEOUT",UNKNOWN_ERROR:"UNKNOWN_ERROR"},Fe={onError:o=>{console.error("[ICPay Widget] Error:",o)},onUserCancelled:()=>{console.log("[ICPay Widget] User cancelled the action")},onInsufficientBalance:o=>{console.warn("[ICPay Widget] Insufficient balance:",o.message)},onWalletError:o=>{console.warn("[ICPay Widget] Wallet error:",o.message)},onNetworkError:o=>{console.error("[ICPay Widget] Network error:",o.message)}};function L(o,a=Fe){o instanceof Pe?(a.onError(o),o.isUserCancelled()?a.onUserCancelled?.():o.isBalanceError()?a.onInsufficientBalance?.(o):o.isWalletError()?a.onWalletError?.(o):o.isNetworkError()&&a.onNetworkError?.(o)):(console.error("[ICPay Widget] Unknown error:",o),a.onError(new Pe({code:C.UNKNOWN_ERROR,message:o instanceof Error?o.message:"An unknown error occurred",details:o})))}var He={[C.WALLET_NOT_CONNECTED]:"Please connect your wallet to continue",[C.WALLET_USER_CANCELLED]:"User have rejected the transfer",[C.WALLET_SIGNATURE_REJECTED]:"User have rejected the transfer",[C.INSUFFICIENT_BALANCE]:"Insufficient balance for this transaction",[C.NETWORK_ERROR]:"Network error. Please try again",[C.API_ERROR]:"Service temporarily unavailable",[C.LEDGER_NOT_FOUND]:"Selected token is not supported",[C.TRANSACTION_FAILED]:"Transaction failed. Please try again",[C.TRANSACTION_TIMEOUT]:"Transaction timed out. Please try again",[C.UNKNOWN_ERROR]:"Something went wrong. Please try again"};function O(o){return He[o.code]||o.message||"An error occurred"}function A(o){return!o.isUserCancelled()}function W(o){if(o.userAction)return o.userAction;switch(o.code){case C.WALLET_NOT_CONNECTED:return"Connect Wallet";case C.INSUFFICIENT_BALANCE:return"Add Funds";case C.NETWORK_ERROR:case C.API_ERROR:return"Try Again";default:return null}}function T(o){return o.isUserCancelled()?"info":o.isBalanceError()||o.isWalletError()?"warning":"error"}import{LitElement as je,html as S,css as Ve}from"lit";import{customElement as Ge,property as q,state as j}from"lit/decorators.js";function g(o,a,e){o&&(e!==void 0?console.log(a,e):console.log(a))}var Ye=[{key:"wallet",label:"Connect Wallet",tooltip:"Awaiting wallet connection",status:"pending"},{key:"init",label:"Initialising ICPay",tooltip:"Initializing payment",status:"pending"},{key:"await",label:"Awaiting payment confirmation",tooltip:"Preparing payment",status:"pending"},{key:"transfer",label:"Transferring funds",tooltip:"Submitting payment",status:"pending"},{key:"verify",label:"Verifying payment",tooltip:"Confirming payment",status:"pending"},{key:"confirm",label:"Payment confirmed",tooltip:"Payment completed",status:"pending"}],m=class extends je{constructor(){super(...arguments);this.open=!1;this.steps=Ye;this.amount=0;this.currency="";this.ledgerSymbol="";this.debug=!1;this.activeIndex=0;this.completed=!1;this.failed=!1;this.errorMessage=null;this.showSuccess=!1;this.showConfetti=!1;this.currentSteps=[];this.currentAmount=0;this.currentCurrency="";this.currentLedgerSymbol="";this.confirmLoadingStartedAt=null;this.progressionTimer=null;this.onMethodStart=e=>{let t=e?.detail?.name||"",i=e?.detail?.type||"";if(g(this.debug,"ICPay Progress: Method start event received:",e.detail),t==="createPayment"||t==="createPaymentUsd"||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order"){if(this.open=!0,this.activeIndex=0,this.completed=!1,this.failed=!1,this.errorMessage=null,this.showSuccess=!1,this.showConfetti=!1,this.currentSteps=this.currentSteps.map(n=>({...n,status:"pending"})),i==="onramp"){let n=this.getStepIndexByKey("wallet");n>=0&&(this.currentSteps[n]={...this.currentSteps[n],label:"Transak Started",tooltip:"Awaiting Transak information"})}this.setLoadingByKey("wallet"),e?.detail?.amount!==void 0&&(this.currentAmount=e.detail.amount,this.amount=e.detail.amount,g(this.debug,"ICPay Progress: Amount updated to:",e.detail.amount)),e?.detail?.currency&&(this.currentCurrency=e.detail.currency,this.currency=e.detail.currency,g(this.debug,"ICPay Progress: Currency updated to:",e.detail.currency)),e?.detail?.ledgerSymbol&&(this.currentLedgerSymbol=e.detail.ledgerSymbol,this.ledgerSymbol=e.detail.ledgerSymbol,g(this.debug,"ICPay Progress: Current state after method start:",{activeIndex:this.activeIndex,currentAmount:this.currentAmount,currentCurrency:this.currentCurrency,currentLedgerSymbol:this.currentLedgerSymbol})),g(this.debug,"ICPay Progress: Waiting for wallet confirmation before starting progression"),this.requestUpdate()}!this.failed&&!this.completed&&(t==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.setLoadingByKey("transfer")):t==="notifyLedgerTransaction"&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")))};this.onMethodSuccess=e=>{let t=e?.detail?.name||"";(t==="createPayment"||t==="createPaymentUsd"||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order")&&this.dispatchEvent(new CustomEvent("icpay-progress-method-success",{detail:{methodName:t,step:this.activeIndex},bubbles:!0})),!this.failed&&!this.completed&&(t==="getLedgerBalance"?(this.completeByKey("wallet"),this.completeByKey("init"),this.setLoadingByKey("await")):t==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")):t==="notifyLedgerTransaction"&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.completeByKey("transfer"),this.completeByKey("verify"),this.setLoadingByKey("confirm")))};this.onTransactionCreated=e=>{let t=e?.detail?.transactionId||e?.detail?.id;g(this.debug,"ICPay Progress: Transaction created event received:",e.detail),!this.failed&&!this.completed&&(this.completeByKey("wallet"),this.completeByKey("init"),this.completeByKey("await"),this.setLoadingByKey("transfer")),this.dispatchEvent(new CustomEvent("icpay-progress-transaction-created",{detail:{transactionId:t,step:this.activeIndex},bubbles:!0}))};this.onTransactionUpdated=e=>{let t=e?.detail?.status||"pending",i=e?.detail?.transactionId||e?.detail?.id;g(this.debug,"ICPay Progress: Transaction updated event received:",e.detail),!this.failed&&this.completed,this.dispatchEvent(new CustomEvent("icpay-progress-transaction-updated",{detail:{status:t,transactionId:i,step:this.activeIndex},bubbles:!0}))};this.onTransactionCompleted=e=>{let t=e?.detail?.transactionId||e?.detail?.id,i=e?.detail?.status||"completed";g(this.debug,"ICPay Progress: Transaction completed event received:",e.detail),g(this.debug,"ICPay Progress: Current state when transaction completed:",{activeIndex:this.activeIndex,completed:this.completed,failed:this.failed,showSuccess:this.showSuccess}),this.completeByKey("transfer"),this.completeByKey("await"),this.completeByKey("init"),this.completeByKey("verify"),this.completeByKey("confirm"),this.completed=!0,this.showSuccess=!0,this.showConfetti=!0,this.dispatchEvent(new CustomEvent("icpay-progress-completed",{detail:{transactionId:t,status:i,amount:this.currentAmount||this.amount,currency:this.currentCurrency||this.currency,ledgerSymbol:this.currentLedgerSymbol||this.ledgerSymbol},bubbles:!0})),setTimeout(()=>{this.showConfetti=!1},3e3)};this.onTransactionFailed=e=>{let t=e?.detail?.message||e?.detail?.error?.message||"Transaction failed",i=e?.detail?.error?.code||e?.detail?.code||"UNKNOWN_ERROR",n=e?.detail?.transactionId||e?.detail?.id;g(this.debug,"ICPay Progress: Transaction failed event received:",e.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(t),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",t),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:t,errorCode:i,transactionId:n,step:this.activeIndex},bubbles:!0}))};this.onTransactionMismatched=e=>{let t=e?.detail?.requestedAmount,i=e?.detail?.paidAmount,n=e?.detail?.transactionId||e?.detail?.id;this.failed=!0;let r=t!=null?String(t):"unknown",l=i!=null?String(i):"unknown";this.errorMessage=`Amount mismatch. Requested ${r}, paid ${l}.`,this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:this.errorMessage,errorCode:"MISMATCHED_AMOUNT",transactionId:n,step:this.activeIndex,requestedAmount:t,paidAmount:i},bubbles:!0}))};this.onMethodError=e=>{let t=e?.detail?.name||"",i=e?.detail?.error?.message||e?.detail?.message||"An error occurred",n=e?.detail?.error?.code||e?.detail?.code||"METHOD_ERROR";g(this.debug,"ICPay Progress: Method error event received:",e.detail),(t?.startsWith("createPayment")||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order")&&(this.failed=!0,this.errorMessage=this.transformErrorMessage(i),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",i),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-error",{detail:{methodName:t,errorMessage:i,errorCode:n,step:this.activeIndex},bubbles:!0})))};this.onSDKError=e=>{let t=e?.detail?.message||"SDK error occurred",i=e?.detail?.code||"SDK_ERROR";g(this.debug,"ICPay Progress: SDK error event received:",e.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(t),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",t),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-sdk-error",{detail:{errorMessage:t,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWalletConnected=e=>{let t=e?.detail?.walletType||"unknown";g(this.debug,"ICPay Progress: Wallet connected event received:",e.detail),this.completeByKey("wallet"),this.setLoadingByKey("init"),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-connected",{detail:{walletType:t,step:this.activeIndex},bubbles:!0}))};this.onWalletDisconnected=e=>{let t=e?.detail?.walletType||"unknown";g(this.debug,"ICPay Progress: Wallet disconnected event received:",e.detail),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-disconnected",{detail:{walletType:t,step:this.activeIndex},bubbles:!0}))};this.onBalanceCheck=e=>{let t=e?.detail?.hasBalance||!1,i=e?.detail?.balance||0;g(this.debug,"ICPay Progress: Balance check event received:",e.detail),t||(this.failed=!0,this.errorMessage="Insufficient balance for transaction",this.updateStepStatus(this.activeIndex,"error","Insufficient balance for transaction"),this.stopAutomaticProgression(),this.dispatchEvent(new CustomEvent("icpay-progress-insufficient-balance",{detail:{balance:i,required:this.currentAmount||this.amount,step:this.activeIndex},bubbles:!0})))};this.onLedgerVerified=e=>{let t=e?.detail?.ledgerId||e?.detail?.canisterId,i=e?.detail?.symbol||"unknown";g(this.debug,"ICPay Progress: Ledger verified event received:",e.detail),i&&i!=="unknown"&&(this.currentLedgerSymbol=i,this.ledgerSymbol=i),this.dispatchEvent(new CustomEvent("icpay-progress-ledger-verified",{detail:{ledgerId:t,symbol:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetPayment=e=>{let t=e?.detail?.amount,i=e?.detail?.currency,n=e?.detail?.ledgerSymbol;if(g(this.debug,"ICPay Progress: Widget payment event received:",e.detail),t!==void 0&&(this.currentAmount=t,this.amount=t),i&&(this.currentCurrency=i,this.currency=i),n&&(this.currentLedgerSymbol=n,this.ledgerSymbol=n),!this.failed){for(let r=this.activeIndex;r<this.currentSteps.length;r++)this.updateStepStatus(r,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-payment",{detail:{amount:t,currency:i,ledgerSymbol:n,step:this.activeIndex},bubbles:!0}))};this.onWidgetError=e=>{let t=e?.detail?.message||"Widget error occurred",i=e?.detail?.code||"WIDGET_ERROR";g(this.debug,"ICPay Progress: Widget error event received:",e.detail),this.failed=!0,this.errorMessage=this.transformErrorMessage(t),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",t),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-widget-error",{detail:{errorMessage:t,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetUnlock=e=>{let t=e?.detail?.amount,i=e?.detail?.currency;if(g(this.debug,"ICPay Progress: Widget unlock event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-unlock",{detail:{amount:t,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetTip=e=>{let t=e?.detail?.amount,i=e?.detail?.currency;if(g(this.debug,"ICPay Progress: Widget tip event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-tip",{detail:{amount:t,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetDonation=e=>{let t=e?.detail?.amount,i=e?.detail?.currency;if(g(this.debug,"ICPay Progress: Widget donation event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-donation",{detail:{amount:t,currency:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetCoffee=e=>{let t=e?.detail?.amount,i=e?.detail?.currency;if(g(this.debug,"ICPay Progress: Widget coffee event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-coffee",{detail:{amount:t,currency:i,step:this.activeIndex},bubbles:!0}))}}connectedCallback(){super.connectedCallback();try{ie(this,this.theme)}catch{}this.currentSteps=[...this.steps],this.currentAmount=this.amount,this.currentCurrency=this.currency,this.currentLedgerSymbol=this.ledgerSymbol,this.attachSDKEventListeners()}disconnectedCallback(){super.disconnectedCallback(),this.detachSDKEventListeners(),this.stopAutomaticProgression()}updated(e){if(e.has("theme"))try{ie(this,this.theme)}catch{}}attachSDKEventListeners(){window.addEventListener("icpay-sdk-method-start",this.onMethodStart),window.addEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.addEventListener("icpay-sdk-method-error",this.onMethodError),window.addEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.addEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.addEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.addEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.addEventListener("icpay-sdk-error",this.onSDKError),window.addEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.addEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.addEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.addEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.addEventListener("icpay-pay",this.onWidgetPayment),window.addEventListener("icpay-error",this.onWidgetError),window.addEventListener("icpay-unlock",this.onWidgetUnlock),window.addEventListener("icpay-tip",this.onWidgetTip),window.addEventListener("icpay-donation",this.onWidgetDonation),window.addEventListener("icpay-coffee",this.onWidgetCoffee)}detachSDKEventListeners(){window.removeEventListener("icpay-sdk-method-start",this.onMethodStart),window.removeEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.removeEventListener("icpay-sdk-method-error",this.onMethodError),window.removeEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.removeEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.removeEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.removeEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.removeEventListener("icpay-sdk-error",this.onSDKError),window.removeEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.removeEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.removeEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.removeEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.removeEventListener("icpay-pay",this.onWidgetPayment),window.removeEventListener("icpay-error",this.onWidgetError),window.removeEventListener("icpay-unlock",this.onWidgetUnlock),window.removeEventListener("icpay-tip",this.onWidgetTip),window.removeEventListener("icpay-donation",this.onWidgetDonation),window.removeEventListener("icpay-coffee",this.onWidgetCoffee)}startAutomaticProgression(){this.progressionTimer&&clearInterval(this.progressionTimer),this.activeIndex=1,this.updateStepStatus(this.activeIndex,"loading"),g(this.debug,"ICPay Progress: Starting automatic progression from step:",this.activeIndex),this.progressionTimer=setInterval(()=>{if(this.failed||this.completed){this.stopAutomaticProgression();return}g(this.debug,"ICPay Progress: Processing step:",this.activeIndex),this.updateStepStatus(this.activeIndex,"completed"),this.activeIndex<this.currentSteps.length-1?(this.activeIndex++,this.updateStepStatus(this.activeIndex,"loading"),g(this.debug,"ICPay Progress: Auto-progressed to step:",this.activeIndex)):(this.stopAutomaticProgression(),g(this.debug,"ICPay Progress: All steps completed, waiting for transaction completion")),this.requestUpdate()},3e3)}stopAutomaticProgression(){this.progressionTimer&&(clearInterval(this.progressionTimer),this.progressionTimer=null)}updateStepStatus(e,t,i){if(e>=0&&e<this.currentSteps.length){let n=this.currentSteps[e],r=n.status;n.status=t,t==="completed"&&(n.timestamp=this.getCurrentTime()),t==="error"&&i&&(n.errorMessage=this.transformErrorMessage(i)),g(this.debug,`ICPay Progress: Step ${e} (${n.label}) status changed from ${r} to ${t}`),this.requestUpdate()}}getCurrentTime(){return new Date().toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}progressPercent(){if(this.failed)return 0;if(this.showSuccess)return 100;let t=this.currentSteps.filter(i=>i.status==="completed").length/this.currentSteps.length*100;return Math.max(0,Math.min(100,t))}verticalPercent(){if(this.failed)return 0;if(this.showSuccess)return 100;let t=this.currentSteps.filter(i=>i.status==="completed").length/this.currentSteps.length*100;return Math.max(0,Math.min(100,t))}getStepIcon(e){switch(e.status){case"loading":return S`<div class="spinner"></div>`;case"completed":return"\u2713";case"error":return"\u2717";default:return"\u25CB"}}getStepIndexByKey(e){return this.currentSteps.findIndex(t=>t.key===e)}setLoadingByKey(e){let t=this.getStepIndexByKey(e);t>=0&&(this.activeIndex=t,this.updateStepStatus(t,"loading"),e==="confirm"&&(this.confirmLoadingStartedAt=Date.now()))}completeByKey(e){let t=this.getStepIndexByKey(e);t>=0&&(this.updateStepStatus(t,"completed"),this.activeIndex=t)}transformErrorMessage(e){let t=String(e||"").toLowerCase();return t.includes("user rejected")||t.includes("user cancelled")||t.includes("user canceled")||t.includes("signature rejected")?"User have rejected the transfer":e}renderConfetti(){if(!this.showConfetti)return"";let e=Array.from({length:50},(i,n)=>n),t=["#0066FF","#ef4444","#10b981","#f59e0b","#8b5cf6"];return S`
|
|
60
60
|
<div class="confetti">
|
|
61
61
|
${e.map(i=>S`
|
|
62
62
|
<div
|
|
@@ -507,7 +507,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
507
507
|
`}
|
|
508
508
|
</div>
|
|
509
509
|
</div>
|
|
510
|
-
`}var Se=typeof window<"u",re=null;function G(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var v=class extends et{constructor(){super(...arguments);this.selectedSymbol="ICP";this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;re||(re=(await import("@windoge98/plug-n-play")).PNP);let i=new re(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),Se&&(G(this.config?.debug||!1,"Premium content connected",{config:this.config}),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="pay"&&this.onPay()},0)}}async loadVerifiedLedgers(){if(!(!Se||!this.config?.publishableKey))try{let t=await h(this.config).client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||this.availableLedgers[0]?.symbol||"ICP")}catch(e){console.warn("Failed to load verified ledgers:",e),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}async onPay(){if(Se&&!(this.processing||this.unlocked)){G(this.config?.debug||!1,"Premium content payment started",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config.priceUsd,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){G(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{re||(re=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new re(this.config?.plugNPlay||{});let r=this.pnp.getEnabledWallets();if(G(this.config?.debug||!1,"Available wallets",r),!r?.length)throw new Error("No wallets available");this.pendingAction="pay",this.showWalletModal=!0;return}catch(r){G(this.config?.debug||!1,"Wallet connection error:",r),this.errorMessage=r instanceof Error?r.message:"Wallet connection failed",this.errorSeverity="error";return}}G(this.config?.debug||!1,"Creating SDK for payment");let e=h(this.config),i=this.cryptoOptions.find(r=>r.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);G(this.config?.debug||!1,"Payment details",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,canisterId:i});let n=await e.sendUsd(this.config.priceUsd,i,{context:"premium-content"});G(this.config?.debug||!1,"Payment completed",{resp:n}),this.unlocked=!0,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:n.transactionId,status:n.status}),this.dispatchEvent(new CustomEvent("icpay-unlock",{detail:{amount:this.config.priceUsd,tx:n},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"
|
|
510
|
+
`}var Se=typeof window<"u",re=null;function G(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var v=class extends et{constructor(){super(...arguments);this.selectedSymbol="ICP";this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;re||(re=(await import("@windoge98/plug-n-play")).PNP);let i=new re(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),Se&&(G(this.config?.debug||!1,"Premium content connected",{config:this.config}),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="pay"&&this.onPay()},0)}}async loadVerifiedLedgers(){if(!(!Se||!this.config?.publishableKey))try{let t=await h(this.config).client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||this.availableLedgers[0]?.symbol||"ICP")}catch(e){console.warn("Failed to load verified ledgers:",e),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}async onPay(){if(Se&&!(this.processing||this.unlocked)){G(this.config?.debug||!1,"Premium content payment started",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config.priceUsd,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){G(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{re||(re=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new re(this.config?.plugNPlay||{});let r=this.pnp.getEnabledWallets();if(G(this.config?.debug||!1,"Available wallets",r),!r?.length)throw new Error("No wallets available");this.pendingAction="pay",this.showWalletModal=!0;return}catch(r){G(this.config?.debug||!1,"Wallet connection error:",r),this.errorMessage=r instanceof Error?r.message:"Wallet connection failed",this.errorSeverity="error";return}}G(this.config?.debug||!1,"Creating SDK for payment");let e=h(this.config),i=this.cryptoOptions.find(r=>r.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);G(this.config?.debug||!1,"Payment details",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,canisterId:i});let n=await e.sendUsd(this.config.priceUsd,i,{context:"premium-content"});G(this.config?.debug||!1,"Payment completed",{resp:n}),this.unlocked=!0,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:n.transactionId,status:n.status}),this.dispatchEvent(new CustomEvent("icpay-unlock",{detail:{amount:this.config.priceUsd,tx:n},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let e=h(this.config),i=this.cryptoOptions.find(d=>d.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),n=await e.startOnrampUsd(this.config.priceUsd,i,{context:"premium:onramp"}),r=n?.metadata?.onramp?.sessionId||n?.metadata?.onramp?.session_id||null,l=n?.metadata?.paymentIntentId||n?.paymentIntentId||null,c=n?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=l,r?(this.onrampSessionId=r,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(e){this.onrampSessionId=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let i=h(this.config),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}select(e){this.selectedSymbol=e}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}async connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");let t=await this.pnp.connect(e);if(!!!(t&&(t.connected===!0||t.principal||t.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}this.config={...this.config,connectedWallet:t,actorProvider:(r,l)=>this.pnp.getActor({canisterId:r,idl:l,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let n=this.pendingAction;this.pendingAction=null,n==="pay"&&setTimeout(()=>this.onPay(),0)}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?se`
|
|
511
511
|
<div class="icpay-card icpay-section">
|
|
512
512
|
${this.config?.progressBar?.enabled!==!1?se`
|
|
513
513
|
<icpay-progress-bar
|
|
@@ -551,7 +551,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
551
551
|
`:""}
|
|
552
552
|
</div>
|
|
553
553
|
`:""}
|
|
554
|
-
${(()=>{let t=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return B({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1,creditCardTooltip:(()=>{let n=Number(this.config?.priceUsd||0);return n>0&&n<5&&this.config?.onramp?.enabled!==!1?`Note: Minimum card amount is $5. You will pay about $${(5-n).toFixed(2)} more.`:null})()})})()}
|
|
554
|
+
${(()=>{let t=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return B({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let n=Number(this.config?.priceUsd||0);return n>0&&n<5&&this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-n).toFixed(2)} more.`:null})()})})()}
|
|
555
555
|
|
|
556
556
|
${this.showOnrampModal?N({visible:this.showOnrampModal,sessionId:this.onrampSessionId,errorMessage:this.onrampErrorMessage,apiKey:this.config?.onramp?.apiKey,environment:this.config?.onramp?.environment||"STAGING",width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0}}):null}
|
|
557
557
|
</div>
|
|
@@ -606,7 +606,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
606
606
|
border-color: rgba(239, 68, 68, 0.3);
|
|
607
607
|
color: #ef4444;
|
|
608
608
|
}
|
|
609
|
-
`],s([nt({type:Object})],v.prototype,"config",2),s([U()],v.prototype,"selectedSymbol",2),s([U()],v.prototype,"unlocked",2),s([U()],v.prototype,"succeeded",2),s([U()],v.prototype,"processing",2),s([U()],v.prototype,"availableLedgers",2),s([U()],v.prototype,"errorMessage",2),s([U()],v.prototype,"errorSeverity",2),s([U()],v.prototype,"errorAction",2),s([U()],v.prototype,"walletConnected",2),s([U()],v.prototype,"pendingAction",2),s([U()],v.prototype,"showWalletModal",2),s([U()],v.prototype,"showOnrampModal",2),s([U()],v.prototype,"onrampSessionId",2),s([U()],v.prototype,"onrampPaymentIntentId",2),s([U()],v.prototype,"onrampErrorMessage",2),v=s([it("icpay-premium-content")],v);import{LitElement as st,html as ee,css as rt}from"lit";import{customElement as ot,property as at,state as k}from"lit/decorators.js";var Ee=typeof window<"u",ae=null;function Y(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var f=class extends st{constructor(){super(...arguments);this.selectedAmount=1;this.selectedSymbol="ICP";this.total=0;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;ae||(ae=(await import("@windoge98/plug-n-play")).PNP);let i=new ae(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[1,5,10]}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),Ee&&(Y(this.config?.debug||!1,"Tip jar connected",{config:this.config}),this.config&&this.config.defaultAmountUsd&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers(),this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol))}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="tip"&&this.tip()},0)}}async loadVerifiedLedgers(){if(!(!Ee||!this.config?.publishableKey))try{let t=await h(this.config).client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.config?.cryptoOptions&&this.config.cryptoOptions.length===1&&(this.selectedSymbol=this.config.cryptoOptions[0].symbol),!this.selectedSymbol&&this.availableLedgers.length>0&&(this.selectedSymbol=this.config?.defaultSymbol||this.availableLedgers[0].symbol)}catch(e){console.warn("Failed to load verified ledgers:",e),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectAmount(e){this.selectedAmount=e}selectSymbol(e){this.selectedSymbol=e}get fillPercentage(){return Math.min(this.total/50*100,100)}async tip(){if(Ee&&(Y(this.config?.debug||!1,"Tip button clicked!",{config:this.config,processing:this.processing}),!this.processing)){this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"tip",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="tip",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Y(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{ae||(ae=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new ae(this.config?.plugNPlay||{});let r=this.pnp.getEnabledWallets();if(Y(this.config?.debug||!1,"Available wallets",r),!r?.length)throw new Error("No wallets available");this.pendingAction="tip",this.showWalletModal=!0;return}catch(r){Y(this.config?.debug||!1,"Wallet connection error:",r),this.errorMessage=r instanceof Error?r.message:"Wallet connection failed",this.errorSeverity="error";return}}Y(this.config?.debug||!1,"Creating SDK for payment");let e=h(this.config),i=this.cryptoOptions.find(r=>r.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);Y(this.config?.debug||!1,"Tip payment details",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,canisterId:i});let n=await e.sendUsd(this.selectedAmount,i,{context:"tip-jar"});Y(this.config?.debug||!1,"Tip payment completed",{resp:n}),this.total+=this.selectedAmount,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:n.transactionId,status:n.status,total:this.total}),this.dispatchEvent(new CustomEvent("icpay-tip",{detail:{amount:this.selectedAmount,tx:n},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"
|
|
609
|
+
`],s([nt({type:Object})],v.prototype,"config",2),s([U()],v.prototype,"selectedSymbol",2),s([U()],v.prototype,"unlocked",2),s([U()],v.prototype,"succeeded",2),s([U()],v.prototype,"processing",2),s([U()],v.prototype,"availableLedgers",2),s([U()],v.prototype,"errorMessage",2),s([U()],v.prototype,"errorSeverity",2),s([U()],v.prototype,"errorAction",2),s([U()],v.prototype,"walletConnected",2),s([U()],v.prototype,"pendingAction",2),s([U()],v.prototype,"showWalletModal",2),s([U()],v.prototype,"showOnrampModal",2),s([U()],v.prototype,"onrampSessionId",2),s([U()],v.prototype,"onrampPaymentIntentId",2),s([U()],v.prototype,"onrampErrorMessage",2),v=s([it("icpay-premium-content")],v);import{LitElement as st,html as ee,css as rt}from"lit";import{customElement as ot,property as at,state as k}from"lit/decorators.js";var Ee=typeof window<"u",ae=null;function Y(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var f=class extends st{constructor(){super(...arguments);this.selectedAmount=1;this.selectedSymbol="ICP";this.total=0;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;ae||(ae=(await import("@windoge98/plug-n-play")).PNP);let i=new ae(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[1,5,10]}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),Ee&&(Y(this.config?.debug||!1,"Tip jar connected",{config:this.config}),this.config&&this.config.defaultAmountUsd&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers(),this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol))}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="tip"&&this.tip()},0)}}async loadVerifiedLedgers(){if(!(!Ee||!this.config?.publishableKey))try{let t=await h(this.config).client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.config?.cryptoOptions&&this.config.cryptoOptions.length===1&&(this.selectedSymbol=this.config.cryptoOptions[0].symbol),!this.selectedSymbol&&this.availableLedgers.length>0&&(this.selectedSymbol=this.config?.defaultSymbol||this.availableLedgers[0].symbol)}catch(e){console.warn("Failed to load verified ledgers:",e),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectAmount(e){this.selectedAmount=e}selectSymbol(e){this.selectedSymbol=e}get fillPercentage(){return Math.min(this.total/50*100,100)}async tip(){if(Ee&&(Y(this.config?.debug||!1,"Tip button clicked!",{config:this.config,processing:this.processing}),!this.processing)){this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"tip",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="tip",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Y(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{ae||(ae=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new ae(this.config?.plugNPlay||{});let r=this.pnp.getEnabledWallets();if(Y(this.config?.debug||!1,"Available wallets",r),!r?.length)throw new Error("No wallets available");this.pendingAction="tip",this.showWalletModal=!0;return}catch(r){Y(this.config?.debug||!1,"Wallet connection error:",r),this.errorMessage=r instanceof Error?r.message:"Wallet connection failed",this.errorSeverity="error";return}}Y(this.config?.debug||!1,"Creating SDK for payment");let e=h(this.config),i=this.cryptoOptions.find(r=>r.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);Y(this.config?.debug||!1,"Tip payment details",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,canisterId:i});let n=await e.sendUsd(this.selectedAmount,i,{context:"tip-jar"});Y(this.config?.debug||!1,"Tip payment completed",{resp:n}),this.total+=this.selectedAmount,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:n.transactionId,status:n.status,total:this.total}),this.dispatchEvent(new CustomEvent("icpay-tip",{detail:{amount:this.selectedAmount,tx:n},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let e=h(this.config),i=this.cryptoOptions.find(d=>d.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),n=await e.startOnrampUsd(this.selectedAmount,i,{context:"tip:onramp"}),r=n?.metadata?.onramp?.sessionId||n?.metadata?.onramp?.session_id||null,l=n?.metadata?.paymentIntentId||n?.paymentIntentId||null,c=n?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=l,r?(this.onrampSessionId=r,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(e){this.onrampSessionId=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let i=h(this.config),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}async connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");let t=await this.pnp.connect(e);if(!!!(t&&(t.connected===!0||t.principal||t.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}this.config={...this.config,connectedWallet:t,actorProvider:(r,l)=>this.pnp.getActor({canisterId:r,idl:l,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let n=this.pendingAction;this.pendingAction=null,n==="tip"&&setTimeout(()=>this.tip(),0)}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){if(!this.config)return ee`<div class="icpay-card icpay-section">Loading...</div>`;let t=(this.cryptoOptions?.length||0)>1,i=this.config?.showLedgerDropdown,n=i==="dropdown"?"dropdown":i==="none"?"none":"buttons",r=n!=="none"&&(t||n==="dropdown"),l=n==="dropdown"?"dropdown":t?"buttons":"none";return ee`
|
|
610
610
|
<div class="icpay-card icpay-section" style="text-align:center;">
|
|
611
611
|
${this.config?.progressBar?.enabled!==!1?ee`
|
|
612
612
|
<icpay-progress-bar
|
|
@@ -687,7 +687,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
687
687
|
border-color: rgba(239, 68, 68, 0.3);
|
|
688
688
|
color: #ef4444;
|
|
689
689
|
}
|
|
690
|
-
`],s([at({type:Object})],f.prototype,"config",2),s([k()],f.prototype,"selectedAmount",2),s([k()],f.prototype,"selectedSymbol",2),s([k()],f.prototype,"total",2),s([k()],f.prototype,"processing",2),s([k()],f.prototype,"succeeded",2),s([k()],f.prototype,"availableLedgers",2),s([k()],f.prototype,"errorMessage",2),s([k()],f.prototype,"errorSeverity",2),s([k()],f.prototype,"errorAction",2),s([k()],f.prototype,"walletConnected",2),s([k()],f.prototype,"pendingAction",2),s([k()],f.prototype,"showWalletModal",2),s([k()],f.prototype,"showOnrampModal",2),s([k()],f.prototype,"onrampSessionId",2),s([k()],f.prototype,"onrampPaymentIntentId",2),s([k()],f.prototype,"onrampErrorMessage",2),f=s([ot("icpay-tip-jar")],f);import{LitElement as lt,html as fe,css as ct}from"lit";import{customElement as dt,property as we,state as P}from"lit/decorators.js";var ke=typeof window<"u",le=null;function Z(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var u=class extends lt{constructor(){super(...arguments);this.title="Article Title";this.preview="";this.lockedContent="";this.selectedSymbol="ICP";this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}get obfuscatedLockedContent(){try{return(this.lockedContent||"").replace(/[^\s]/g,"x")}catch{return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;le||(le=(await import("@windoge98/plug-n-play")).PNP);let i=new le(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"
|
|
690
|
+
`],s([at({type:Object})],f.prototype,"config",2),s([k()],f.prototype,"selectedAmount",2),s([k()],f.prototype,"selectedSymbol",2),s([k()],f.prototype,"total",2),s([k()],f.prototype,"processing",2),s([k()],f.prototype,"succeeded",2),s([k()],f.prototype,"availableLedgers",2),s([k()],f.prototype,"errorMessage",2),s([k()],f.prototype,"errorSeverity",2),s([k()],f.prototype,"errorAction",2),s([k()],f.prototype,"walletConnected",2),s([k()],f.prototype,"pendingAction",2),s([k()],f.prototype,"showWalletModal",2),s([k()],f.prototype,"showOnrampModal",2),s([k()],f.prototype,"onrampSessionId",2),s([k()],f.prototype,"onrampPaymentIntentId",2),s([k()],f.prototype,"onrampErrorMessage",2),f=s([ot("icpay-tip-jar")],f);import{LitElement as lt,html as fe,css as ct}from"lit";import{customElement as dt,property as we,state as P}from"lit/decorators.js";var ke=typeof window<"u",le=null;function Z(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var u=class extends lt{constructor(){super(...arguments);this.title="Article Title";this.preview="";this.lockedContent="";this.selectedSymbol="ICP";this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}get obfuscatedLockedContent(){try{return(this.lockedContent||"").replace(/[^\s]/g,"x")}catch{return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;le||(le=(await import("@windoge98/plug-n-play")).PNP);let i=new le(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let e=h(this.config),i=this.cryptoOptions.find(d=>d.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),n=await e.startOnrampUsd(this.config.priceUsd,i,{context:"article:onramp"}),r=n?.metadata?.onramp?.sessionId||n?.metadata?.onramp?.session_id||null,l=n?.metadata?.paymentIntentId||n?.paymentIntentId||null,c=n?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=l,r?(this.onrampSessionId=r,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(e){this.onrampSessionId=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let i=h(this.config),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),ke&&(Z(this.config?.debug||!1,"Article paywall connected",{config:this.config}),this.config&&(typeof this.config.title=="string"&&(this.title=this.config.title),typeof this.config.preview=="string"&&(this.preview=this.config.preview),typeof this.config.lockedContent=="string"&&(this.lockedContent=this.config.lockedContent)),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(e){if(e.has("config")&&this.config&&(typeof this.config.title=="string"&&(this.title=this.config.title),typeof this.config.preview=="string"&&(this.preview=this.config.preview),typeof this.config.lockedContent=="string"&&(this.lockedContent=this.config.lockedContent)),e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="unlock"&&this.unlock()},0)}}async loadVerifiedLedgers(){if(!(!ke||!this.config?.publishableKey))try{let t=await h(this.config).client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||this.availableLedgers[0]?.symbol||"ICP")}catch(e){console.warn("Failed to load verified ledgers:",e),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectSymbol(e){this.selectedSymbol=e}async unlock(){if(ke&&!(this.processing||this.unlocked)){Z(this.config?.debug||!1,"Article paywall unlock started",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"unlock",type:"sendUsd",amount:this.config.priceUsd,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="unlock",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Z(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{le||(le=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new le(this.config?.plugNPlay||{});let r=this.pnp.getEnabledWallets();if(Z(this.config?.debug||!1,"Available wallets",r),!r?.length)throw new Error("No wallets available");this.pendingAction="unlock",this.showWalletModal=!0;return}catch(r){Z(this.config?.debug||!1,"Wallet connection error:",r),this.errorMessage=r instanceof Error?r.message:"Wallet connection failed",this.errorSeverity="error";return}}Z(this.config?.debug||!1,"Creating SDK for payment");let e=h(this.config),i=this.cryptoOptions.find(r=>r.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);Z(this.config?.debug||!1,"Article payment details",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,canisterId:i});let n=await e.sendUsd(this.config.priceUsd,i,{context:"article"});Z(this.config?.debug||!1,"Article payment completed",{resp:n}),this.unlocked=!0,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:n.transactionId,status:n.status}),this.dispatchEvent(new CustomEvent("icpay-unlock",{detail:{amount:this.config.priceUsd,tx:n},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}async connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");let t=await this.pnp.connect(e);if(!!!(t&&(t.connected===!0||t.principal||t.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}this.config={...this.config,connectedWallet:t,actorProvider:(r,l)=>this.pnp.getActor({canisterId:r,idl:l,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let n=this.pendingAction;this.pendingAction=null,n==="unlock"&&setTimeout(()=>this.unlock(),0)}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?fe`
|
|
691
691
|
<div class="icpay-card icpay-section">
|
|
692
692
|
${this.config?.progressBar?.enabled!==!1?fe`
|
|
693
693
|
<icpay-progress-bar
|
|
@@ -729,7 +729,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
729
729
|
`:""}
|
|
730
730
|
</div>
|
|
731
731
|
`:""}
|
|
732
|
-
${(()=>{let t=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return B({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1,creditCardTooltip:(()=>{let n=Number(this.config?.priceUsd||0);return n>0&&n<5&&this.config?.onramp?.enabled!==!1?`Note: Minimum card amount is $5. You will pay about $${(5-n).toFixed(2)} more.`:null})()})})()}
|
|
732
|
+
${(()=>{let t=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return B({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let n=Number(this.config?.priceUsd||0);return n>0&&n<5&&this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-n).toFixed(2)} more.`:null})()})})()}
|
|
733
733
|
|
|
734
734
|
${this.showOnrampModal?N({visible:this.showOnrampModal,sessionId:this.onrampSessionId,errorMessage:this.onrampErrorMessage,apiKey:this.config?.onramp?.apiKey,environment:this.config?.onramp?.environment||"STAGING",width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0}}):null}
|
|
735
735
|
</div>
|
|
@@ -765,7 +765,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
765
765
|
border-color: rgba(239, 68, 68, 0.3);
|
|
766
766
|
color: #ef4444;
|
|
767
767
|
}
|
|
768
|
-
`],s([we({type:Object})],u.prototype,"config",2),s([we({type:String})],u.prototype,"title",2),s([we({type:String})],u.prototype,"preview",2),s([we({type:String})],u.prototype,"lockedContent",2),s([P()],u.prototype,"selectedSymbol",2),s([P()],u.prototype,"unlocked",2),s([P()],u.prototype,"succeeded",2),s([P()],u.prototype,"processing",2),s([P()],u.prototype,"availableLedgers",2),s([P()],u.prototype,"errorMessage",2),s([P()],u.prototype,"errorSeverity",2),s([P()],u.prototype,"errorAction",2),s([P()],u.prototype,"walletConnected",2),s([P()],u.prototype,"pendingAction",2),s([P()],u.prototype,"showWalletModal",2),s([P()],u.prototype,"showOnrampModal",2),s([P()],u.prototype,"onrampSessionId",2),s([P()],u.prototype,"onrampPaymentIntentId",2),s([P()],u.prototype,"onrampErrorMessage",2),u=s([dt("icpay-article-paywall")],u);import{LitElement as pt,html as ce,css as ht}from"lit";import{customElement as gt,property as ut,state as D}from"lit/decorators.js";var Me=typeof window<"u",Ie=null;function J(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var w=class extends pt{constructor(){super(...arguments);this.selectedIndex=0;this.selectedSymbol="ICP";this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),Me&&(J(this.config?.debug||!1,"Coffee shop connected",{config:this.config}),this.config&&typeof this.config.defaultItemIndex=="number"&&(this.selectedIndex=this.config.defaultItemIndex),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="order"&&this.order()},0)}}async loadVerifiedLedgers(){if(!(!Me||!this.config?.publishableKey))try{let t=await h(this.config).client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.availableLedgers.length>0&&!this.selectedSymbol&&(this.selectedSymbol=this.availableLedgers[0].symbol)}catch(e){console.warn("Failed to load verified ledgers:",e),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectItem(e){this.selectedIndex=e}selectSymbol(e){this.selectedSymbol=e}get selectedItem(){return this.config?.items?.[this.selectedIndex]||{name:"Loading...",priceUsd:0}}async order(){if(Me&&!this.processing){J(this.config?.debug||!1,"Coffee order started",{selectedItem:this.selectedItem,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"order",type:"sendUsd",amount:this.selectedItem.priceUsd,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="order",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){J(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{Ie||(Ie=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new Ie(this.config?.plugNPlay||{});let r=this.pnp.getEnabledWallets();if(J(this.config?.debug||!1,"Available wallets",r),!r?.length)throw new Error("No wallets available");this.pendingAction="order",this.showWalletModal=!0;return}catch(r){J(this.config?.debug||!1,"Wallet connection error:",r),this.errorMessage=r instanceof Error?r.message:"Wallet connection failed",this.errorSeverity="error";return}}J(this.config?.debug||!1,"Creating SDK for payment");let e=h(this.config),i=this.cryptoOptions.find(r=>r.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);J(this.config?.debug||!1,"Coffee order payment details",{item:this.selectedItem.name,priceUsd:this.selectedItem.priceUsd,selectedSymbol:this.selectedSymbol,canisterId:i});let n=await e.sendUsd(this.selectedItem.priceUsd,i,{context:"coffee",item:this.selectedItem.name});J(this.config?.debug||!1,"Coffee order payment completed",{resp:n}),this.config.onSuccess&&this.config.onSuccess({id:n.transactionId,status:n.status,item:this.selectedItem.name}),this.dispatchEvent(new CustomEvent("icpay-coffee",{detail:{item:this.selectedItem,tx:n},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"
|
|
768
|
+
`],s([we({type:Object})],u.prototype,"config",2),s([we({type:String})],u.prototype,"title",2),s([we({type:String})],u.prototype,"preview",2),s([we({type:String})],u.prototype,"lockedContent",2),s([P()],u.prototype,"selectedSymbol",2),s([P()],u.prototype,"unlocked",2),s([P()],u.prototype,"succeeded",2),s([P()],u.prototype,"processing",2),s([P()],u.prototype,"availableLedgers",2),s([P()],u.prototype,"errorMessage",2),s([P()],u.prototype,"errorSeverity",2),s([P()],u.prototype,"errorAction",2),s([P()],u.prototype,"walletConnected",2),s([P()],u.prototype,"pendingAction",2),s([P()],u.prototype,"showWalletModal",2),s([P()],u.prototype,"showOnrampModal",2),s([P()],u.prototype,"onrampSessionId",2),s([P()],u.prototype,"onrampPaymentIntentId",2),s([P()],u.prototype,"onrampErrorMessage",2),u=s([dt("icpay-article-paywall")],u);import{LitElement as pt,html as ce,css as ht}from"lit";import{customElement as gt,property as ut,state as D}from"lit/decorators.js";var Me=typeof window<"u",Ie=null;function J(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var w=class extends pt{constructor(){super(...arguments);this.selectedIndex=0;this.selectedSymbol="ICP";this.processing=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),Me&&(J(this.config?.debug||!1,"Coffee shop connected",{config:this.config}),this.config&&typeof this.config.defaultItemIndex=="number"&&(this.selectedIndex=this.config.defaultItemIndex),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="order"&&this.order()},0)}}async loadVerifiedLedgers(){if(!(!Me||!this.config?.publishableKey))try{let t=await h(this.config).client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.availableLedgers.length>0&&!this.selectedSymbol&&(this.selectedSymbol=this.availableLedgers[0].symbol)}catch(e){console.warn("Failed to load verified ledgers:",e),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectItem(e){this.selectedIndex=e}selectSymbol(e){this.selectedSymbol=e}get selectedItem(){return this.config?.items?.[this.selectedIndex]||{name:"Loading...",priceUsd:0}}async order(){if(Me&&!this.processing){J(this.config?.debug||!1,"Coffee order started",{selectedItem:this.selectedItem,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"order",type:"sendUsd",amount:this.selectedItem.priceUsd,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="order",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){J(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{Ie||(Ie=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new Ie(this.config?.plugNPlay||{});let r=this.pnp.getEnabledWallets();if(J(this.config?.debug||!1,"Available wallets",r),!r?.length)throw new Error("No wallets available");this.pendingAction="order",this.showWalletModal=!0;return}catch(r){J(this.config?.debug||!1,"Wallet connection error:",r),this.errorMessage=r instanceof Error?r.message:"Wallet connection failed",this.errorSeverity="error";return}}J(this.config?.debug||!1,"Creating SDK for payment");let e=h(this.config),i=this.cryptoOptions.find(r=>r.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);J(this.config?.debug||!1,"Coffee order payment details",{item:this.selectedItem.name,priceUsd:this.selectedItem.priceUsd,selectedSymbol:this.selectedSymbol,canisterId:i});let n=await e.sendUsd(this.selectedItem.priceUsd,i,{context:"coffee",item:this.selectedItem.name});J(this.config?.debug||!1,"Coffee order payment completed",{resp:n}),this.config.onSuccess&&this.config.onSuccess({id:n.transactionId,status:n.status,item:this.selectedItem.name}),this.dispatchEvent(new CustomEvent("icpay-coffee",{detail:{item:this.selectedItem,tx:n},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let e=h(this.config),i=this.cryptoOptions.find(d=>d.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),n=await e.startOnrampUsd(this.selectedItem.priceUsd,i,{context:"coffee:onramp",item:this.selectedItem.name}),r=n?.metadata?.onramp?.sessionId||n?.metadata?.onramp?.session_id||null,l=n?.metadata?.paymentIntentId||n?.paymentIntentId||null,c=n?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=l,r?(this.onrampSessionId=r,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(e){this.onrampSessionId=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let i=h(this.config),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}async connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");let t=await this.pnp.connect(e);if(!!!(t&&(t.connected===!0||t.principal||t.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}this.config={...this.config,connectedWallet:t,actorProvider:(r,l)=>this.pnp.getActor({canisterId:r,idl:l,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let n=this.pendingAction;this.pendingAction=null,n==="order"&&setTimeout(()=>this.order(),0)}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?ce`
|
|
769
769
|
<div class="icpay-card icpay-section">
|
|
770
770
|
${this.config?.progressBar?.enabled!==!1?ce`
|
|
771
771
|
<icpay-progress-bar
|
|
@@ -810,7 +810,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
810
810
|
`:""}
|
|
811
811
|
</div>
|
|
812
812
|
`:""}
|
|
813
|
-
${(()=>{let t=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return B({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1,creditCardTooltip:(()=>{let n=this.config?.defaultItemIndex??0,r=Number(this.config?.items?.[n]?.priceUsd||0);return r>0&&r<5&&this.config?.onramp?.enabled!==!1?`Note: Minimum card amount is $5. You will pay about $${(5-r).toFixed(2)} more.`:null})()})})()}
|
|
813
|
+
${(()=>{let t=(this.pnp?.getEnabledWallets?.()||[]).map(i=>({id:this.getWalletId(i),label:this.getWalletLabel(i),icon:this.getWalletIcon(i)}));return B({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,onSelect:i=>this.connectWithWallet(i),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let n=this.config?.defaultItemIndex??0,r=Number(this.config?.items?.[n]?.priceUsd||0);return r>0&&r<5&&this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-r).toFixed(2)} more.`:null})()})})()}
|
|
814
814
|
|
|
815
815
|
${this.showOnrampModal?N({visible:this.showOnrampModal,sessionId:this.onrampSessionId,errorMessage:this.onrampErrorMessage,apiKey:this.config?.onramp?.apiKey,environment:this.config?.onramp?.environment||"STAGING",width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0}}):null}
|
|
816
816
|
</div>
|
|
@@ -845,7 +845,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
845
845
|
border-color: rgba(239, 68, 68, 0.3);
|
|
846
846
|
color: #ef4444;
|
|
847
847
|
}
|
|
848
|
-
`],s([ut({type:Object})],w.prototype,"config",2),s([D()],w.prototype,"selectedIndex",2),s([D()],w.prototype,"selectedSymbol",2),s([D()],w.prototype,"processing",2),s([D()],w.prototype,"availableLedgers",2),s([D()],w.prototype,"errorMessage",2),s([D()],w.prototype,"errorSeverity",2),s([D()],w.prototype,"errorAction",2),s([D()],w.prototype,"walletConnected",2),s([D()],w.prototype,"pendingAction",2),s([D()],w.prototype,"showWalletModal",2),s([D()],w.prototype,"showOnrampModal",2),s([D()],w.prototype,"onrampSessionId",2),s([D()],w.prototype,"onrampPaymentIntentId",2),s([D()],w.prototype,"onrampErrorMessage",2),w=s([gt("icpay-coffee-shop")],w);import{LitElement as mt,html as de,css as ft}from"lit";import{customElement as yt,property as bt,state as M}from"lit/decorators.js";var Ce=typeof window<"u",pe=null;function X(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var y=class extends mt{constructor(){super(...arguments);this.selectedAmount=10;this.selectedSymbol="ICP";this.raised=0;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;pe||(pe=(await import("@windoge98/plug-n-play")).PNP);let i=new pe(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[10,25,50,100,250,500]}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),Ce&&(X(this.config?.debug||!1,"Donation thermometer connected",{config:this.config}),this.config&&typeof this.config.defaultAmountUsd=="number"&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="donate"&&this.donate()},0)}}async loadVerifiedLedgers(){if(!(!Ce||!this.config?.publishableKey))try{let t=await h(this.config).client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.availableLedgers.length>0&&!this.selectedSymbol&&(this.selectedSymbol=this.availableLedgers[0].symbol)}catch(e){console.warn("Failed to load verified ledgers:",e),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectAmount(e){this.selectedAmount=e}selectSymbol(e){this.selectedSymbol=e}get fillPercentage(){let e=Number(this.config?.goalUsd??1e3),t=e>0?e:1e3;return Math.min(this.raised/t*100,100)}async donate(){if(Ce&&!this.processing){X(this.config?.debug||!1,"Donation started",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"donate",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="donate",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){X(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{pe||(pe=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new pe(this.config?.plugNPlay||{});let r=this.pnp.getEnabledWallets();if(X(this.config?.debug||!1,"Available wallets",r),!r?.length)throw new Error("No wallets available");this.pendingAction="donate",this.showWalletModal=!0;return}catch(r){X(this.config?.debug||!1,"Wallet connection error:",r),this.errorMessage=r instanceof Error?r.message:"Wallet connection failed",this.errorSeverity="error";return}}X(this.config?.debug||!1,"Creating SDK for payment");let e=h(this.config),i=this.cryptoOptions.find(r=>r.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);X(this.config?.debug||!1,"Donation payment details",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,canisterId:i});let n=await e.sendUsd(this.selectedAmount,i,{context:"donation"});X(this.config?.debug||!1,"Donation payment completed",{resp:n}),this.raised+=this.selectedAmount,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:n.transactionId,status:n.status,raised:this.raised}),this.dispatchEvent(new CustomEvent("icpay-donation",{detail:{amount:this.selectedAmount,tx:n},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"
|
|
848
|
+
`],s([ut({type:Object})],w.prototype,"config",2),s([D()],w.prototype,"selectedIndex",2),s([D()],w.prototype,"selectedSymbol",2),s([D()],w.prototype,"processing",2),s([D()],w.prototype,"availableLedgers",2),s([D()],w.prototype,"errorMessage",2),s([D()],w.prototype,"errorSeverity",2),s([D()],w.prototype,"errorAction",2),s([D()],w.prototype,"walletConnected",2),s([D()],w.prototype,"pendingAction",2),s([D()],w.prototype,"showWalletModal",2),s([D()],w.prototype,"showOnrampModal",2),s([D()],w.prototype,"onrampSessionId",2),s([D()],w.prototype,"onrampPaymentIntentId",2),s([D()],w.prototype,"onrampErrorMessage",2),w=s([gt("icpay-coffee-shop")],w);import{LitElement as mt,html as de,css as ft}from"lit";import{customElement as yt,property as bt,state as M}from"lit/decorators.js";var Ce=typeof window<"u",pe=null;function X(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var y=class extends mt{constructor(){super(...arguments);this.selectedAmount=10;this.selectedSymbol="ICP";this.raised=0;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.pnp=null;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;pe||(pe=(await import("@windoge98/plug-n-play")).PNP);let i=new pe(this.config?.plugNPlay||{});this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[10,25,50,100,250,500]}get cryptoOptions(){return this.config.cryptoOptions?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),Ce&&(X(this.config?.debug||!1,"Donation thermometer connected",{config:this.config}),this.config&&typeof this.config.defaultAmountUsd=="number"&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP(),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers())}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="donate"&&this.donate()},0)}}async loadVerifiedLedgers(){if(!(!Ce||!this.config?.publishableKey))try{let t=await h(this.config).client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.availableLedgers.length>0&&!this.selectedSymbol&&(this.selectedSymbol=this.availableLedgers[0].symbol)}catch(e){console.warn("Failed to load verified ledgers:",e),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol="ICP")}}selectAmount(e){this.selectedAmount=e}selectSymbol(e){this.selectedSymbol=e}get fillPercentage(){let e=Number(this.config?.goalUsd??1e3),t=e>0?e:1e3;return Math.min(this.raised/t*100,100)}async donate(){if(Ce&&!this.processing){X(this.config?.debug||!1,"Donation started",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet}),this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"donate",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="donate",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){X(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{pe||(pe=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new pe(this.config?.plugNPlay||{});let r=this.pnp.getEnabledWallets();if(X(this.config?.debug||!1,"Available wallets",r),!r?.length)throw new Error("No wallets available");this.pendingAction="donate",this.showWalletModal=!0;return}catch(r){X(this.config?.debug||!1,"Wallet connection error:",r),this.errorMessage=r instanceof Error?r.message:"Wallet connection failed",this.errorSeverity="error";return}}X(this.config?.debug||!1,"Creating SDK for payment");let e=h(this.config),i=this.cryptoOptions.find(r=>r.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol);X(this.config?.debug||!1,"Donation payment details",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,canisterId:i});let n=await e.sendUsd(this.selectedAmount,i,{context:"donation"});X(this.config?.debug||!1,"Donation payment completed",{resp:n}),this.raised+=this.selectedAmount,this.succeeded=!0,this.config.onSuccess&&this.config.onSuccess({id:n.transactionId,status:n.status,raised:this.raised}),this.dispatchEvent(new CustomEvent("icpay-donation",{detail:{amount:this.selectedAmount,tx:n},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let e=h(this.config),i=this.cryptoOptions.find(d=>d.symbol===this.selectedSymbol).canisterId||await e.client.getLedgerCanisterIdBySymbol(this.selectedSymbol),n=await e.startOnrampUsd(this.selectedAmount,i,{context:"donation:onramp"}),r=n?.metadata?.onramp?.sessionId||n?.metadata?.onramp?.session_id||null,l=n?.metadata?.paymentIntentId||n?.paymentIntentId||null,c=n?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=l,r?(this.onrampSessionId=r,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=c||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(e){this.onrampSessionId=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let i=h(this.config),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}async connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");let t=await this.pnp.connect(e);if(!!!(t&&(t.connected===!0||t.principal||t.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}this.config={...this.config,connectedWallet:t,actorProvider:(r,l)=>this.pnp.getActor({canisterId:r,idl:l,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let n=this.pendingAction;this.pendingAction=null,n==="donate"&&setTimeout(()=>this.donate(),0)}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}render(){return this.config?de`
|
|
849
849
|
<div class="icpay-card icpay-section" style="text-align:center;">
|
|
850
850
|
${this.config?.progressBar?.enabled!==!1?de`
|
|
851
851
|
<icpay-progress-bar
|
|
@@ -924,7 +924,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
924
924
|
border-color: rgba(239, 68, 68, 0.3);
|
|
925
925
|
color: #ef4444;
|
|
926
926
|
}
|
|
927
|
-
`],s([bt({type:Object})],y.prototype,"config",2),s([M()],y.prototype,"selectedAmount",2),s([M()],y.prototype,"selectedSymbol",2),s([M()],y.prototype,"raised",2),s([M()],y.prototype,"processing",2),s([M()],y.prototype,"succeeded",2),s([M()],y.prototype,"availableLedgers",2),s([M()],y.prototype,"errorMessage",2),s([M()],y.prototype,"errorSeverity",2),s([M()],y.prototype,"errorAction",2),s([M()],y.prototype,"walletConnected",2),s([M()],y.prototype,"pendingAction",2),s([M()],y.prototype,"showWalletModal",2),s([M()],y.prototype,"showOnrampModal",2),s([M()],y.prototype,"onrampSessionId",2),s([M()],y.prototype,"onrampPaymentIntentId",2),s([M()],y.prototype,"onrampErrorMessage",2),y=s([yt("icpay-donation-thermometer")],y);import{LitElement as vt,html as he,css as wt}from"lit";import{customElement as xt,property as St,state as F}from"lit/decorators.js";var Le=typeof window<"u",Oe=null;function ye(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var x=class extends vt{constructor(){super(...arguments);this.selectedSymbol=null;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.onrampPollTimer=null;this.transakMessageHandlerBound=null;this.pnp=null;this.sdk=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}getSdk(){return this.sdk||(this.sdk=h(this.config)),this.sdk}get cryptoOptions(){return this.config?.cryptoOptions?.length?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),Le&&(ye(this.config?.debug||!1,"Pay button connected",{config:this.config}),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers(),this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol))}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="pay"&&this.pay()},0)}e.has("config")&&(this.sdk=null)}async loadVerifiedLedgers(){if(!(!Le||!this.config?.publishableKey))try{let t=await this.getSdk().client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||(this.availableLedgers[0]?.symbol??"ICP"))}catch(e){this.dispatchEvent(new CustomEvent("icpay-error",{detail:{message:"Failed to load verified ledgers",cause:e},bubbles:!0})),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||"ICP")}}selectSymbol(e){this.selectedSymbol=e}async ensureWallet(){if(this.config.useOwnWallet)return this.config.actorProvider?!0:(this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0})),!1);if(this.walletConnected)return!0;try{Oe||(Oe=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new Oe(this.config?.plugNPlay||{});let e=this.pnp.getEnabledWallets();if(ye(this.config?.debug||!1,"Available wallets",e),!e?.length)throw new Error("No wallets available");return this.pendingAction="pay",this.showWalletModal=!0,!1}catch(e){return this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error",!1}}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}async connectWithWallet(e){if(this.pnp)try{if(ye(this.config?.debug||!1,"Connecting to wallet",{walletId:e}),!e)throw new Error("No wallet ID provided");let t=await this.pnp.connect(e);if(ye(this.config?.debug||!1,"Wallet connect result",t),!!!(t&&(t.connected===!0||t.principal||t.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}this.config={...this.config,connectedWallet:t,actorProvider:(r,l)=>this.pnp.getActor({canisterId:r,idl:l,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let n=this.pendingAction;this.pendingAction=null,n==="pay"&&setTimeout(()=>this.pay(),0)}catch(t){ye(this.config?.debug||!1,"Wallet connection error",t),this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}renderWalletModal(){if(!this.showWalletModal||!this.pnp)return null;let t=(this.pnp.getEnabledWallets()||[]).map(p=>({id:this.getWalletId(p),label:this.getWalletLabel(p),icon:this.getWalletIcon(p)})),i=this.config?.onramp?.enabled!==!1,n=5,r=Number(this.config?.amountUsd??0),l=i&&r>0&&r<n,c=Math.max(0,n-r),d=l?`Note: Minimum card amount is $${n}. You will pay about $${c.toFixed(2)} more.`:null;return B({visible:this.showWalletModal,wallets:t,isConnecting:!1,onSelect:p=>this.connectWithWallet(p),onClose:()=>{this.showWalletModal=!1},onCreditCard:i?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:i,creditCardTooltip:d})}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"sendFundsUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let e=Number(this.config?.amountUsd??0),t=this.getSdk(),i=this.selectedSymbol||"ICP",r=this.cryptoOptions.find(E=>E.symbol===i)?.canisterId||await t.client.getLedgerCanisterIdBySymbol(i),l=await t.startOnrampUsd(e,r,{context:"pay-button:onramp"}),c=l?.metadata?.onramp?.sessionId||l?.metadata?.onramp?.session_id||null,d=l?.metadata?.onramp?.errorMessage||null;this.onrampErrorMessage=d||null;let p=l?.metadata?.paymentIntentId||l?.paymentIntentId||null;this.onrampPaymentIntentId=p,c?(this.onrampSessionId=c,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.showOnrampModal=!0)}catch(e){this.onrampSessionId=null,this.onrampErrorMessage=e?.message||null,this.showOnrampModal=!0,L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"getLedgerBalance"}}))}catch{}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"sendFundsToLedger"}}))}catch{}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"notifyLedgerTransaction"}}))}catch{}this.showOnrampModal=!1,this.startOnrampPolling(n||void 0)}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let i=this.getSdk(),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1},r=l=>{n()};try{window.addEventListener("icpay-sdk-transaction-completed",r,{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}async pay(){if(!(!Le||this.processing)){this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config?.amountUsd,currency:this.selectedSymbol||this.config?.defaultSymbol}}))}catch{}this.processing=!0;try{if(!await this.ensureWallet())return;let t=this.getSdk(),i=this.selectedSymbol||"ICP",r=this.cryptoOptions.find(p=>p.symbol===i)?.canisterId||await t.client.getLedgerCanisterIdBySymbol(i),l=Number(this.config?.amountUsd??0),c={context:"pay-button"},d=await t.sendUsd(l,r,c);this.config.onSuccess&&this.config.onSuccess({id:d.transactionId,status:d.status}),this.succeeded=!0,this.dispatchEvent(new CustomEvent("icpay-pay",{detail:{amount:l,tx:d},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}render(){if(!this.config)return he`<div class="icpay-card icpay-section">Loading...</div>`;let t=(this.cryptoOptions?.length||0)>1,i=this.config?.showLedgerDropdown,n=i==="dropdown"?"dropdown":i==="none"?"none":"buttons",r=n!=="none"&&(t||n==="dropdown"),l=n==="dropdown"?"dropdown":t?"buttons":"none",c=this.selectedSymbol||this.config?.defaultSymbol||"ICP",d=typeof this.config?.amountUsd=="number"?`${Number(this.config.amountUsd).toFixed(2)}`:"",E=(this.config?.buttonLabel||(typeof this.config?.amountUsd=="number"?"Pay ${amount} with {symbol}":"Pay with {symbol}")).replace("{amount}",d||"$0.00").replace("{symbol}",c),be=this.config?.progressBar?.enabled!==!1;return he`
|
|
927
|
+
`],s([bt({type:Object})],y.prototype,"config",2),s([M()],y.prototype,"selectedAmount",2),s([M()],y.prototype,"selectedSymbol",2),s([M()],y.prototype,"raised",2),s([M()],y.prototype,"processing",2),s([M()],y.prototype,"succeeded",2),s([M()],y.prototype,"availableLedgers",2),s([M()],y.prototype,"errorMessage",2),s([M()],y.prototype,"errorSeverity",2),s([M()],y.prototype,"errorAction",2),s([M()],y.prototype,"walletConnected",2),s([M()],y.prototype,"pendingAction",2),s([M()],y.prototype,"showWalletModal",2),s([M()],y.prototype,"showOnrampModal",2),s([M()],y.prototype,"onrampSessionId",2),s([M()],y.prototype,"onrampPaymentIntentId",2),s([M()],y.prototype,"onrampErrorMessage",2),y=s([yt("icpay-donation-thermometer")],y);import{LitElement as vt,html as he,css as wt}from"lit";import{customElement as xt,property as St,state as K}from"lit/decorators.js";var Le=typeof window<"u",Oe=null;function ye(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var x=class extends vt{constructor(){super(...arguments);this.selectedSymbol=null;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.onrampPollTimer=null;this.transakMessageHandlerBound=null;this.pnp=null;this.sdk=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}getSdk(){return this.sdk||(this.sdk=h(this.config)),this.sdk}get cryptoOptions(){return this.config?.cryptoOptions?.length?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),Le&&(ye(this.config?.debug||!1,"Pay button connected",{config:this.config}),this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers(),this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol))}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="pay"&&this.pay()},0)}e.has("config")&&(this.sdk=null)}async loadVerifiedLedgers(){if(!(!Le||!this.config?.publishableKey))try{let t=await this.getSdk().client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||(this.availableLedgers[0]?.symbol??"ICP"))}catch(e){this.dispatchEvent(new CustomEvent("icpay-error",{detail:{message:"Failed to load verified ledgers",cause:e},bubbles:!0})),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||"ICP")}}selectSymbol(e){this.selectedSymbol=e}async ensureWallet(){if(this.config.useOwnWallet)return this.config.actorProvider?!0:(this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0})),!1);if(this.walletConnected)return!0;try{Oe||(Oe=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new Oe(this.config?.plugNPlay||{});let e=this.pnp.getEnabledWallets();if(ye(this.config?.debug||!1,"Available wallets",e),!e?.length)throw new Error("No wallets available");return this.pendingAction="pay",this.showWalletModal=!0,!1}catch(e){return this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error",!1}}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}async connectWithWallet(e){if(this.pnp)try{if(ye(this.config?.debug||!1,"Connecting to wallet",{walletId:e}),!e)throw new Error("No wallet ID provided");let t=await this.pnp.connect(e);if(ye(this.config?.debug||!1,"Wallet connect result",t),!!!(t&&(t.connected===!0||t.principal||t.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}this.config={...this.config,connectedWallet:t,actorProvider:(r,l)=>this.pnp.getActor({canisterId:r,idl:l,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let n=this.pendingAction;this.pendingAction=null,n==="pay"&&setTimeout(()=>this.pay(),0)}catch(t){ye(this.config?.debug||!1,"Wallet connection error",t),this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}renderWalletModal(){if(!this.showWalletModal||!this.pnp)return null;let t=(this.pnp.getEnabledWallets()||[]).map(p=>({id:this.getWalletId(p),label:this.getWalletLabel(p),icon:this.getWalletIcon(p)})),i=this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0,n=5,r=Number(this.config?.amountUsd??0),l=i&&r>0&&r<n,c=Math.max(0,n-r),d=l?`Note: Minimum card amount is $${n}. You will pay about $${c.toFixed(2)} more.`:null;return B({visible:this.showWalletModal,wallets:t,isConnecting:!1,onSelect:p=>this.connectWithWallet(p),onClose:()=>{this.showWalletModal=!1},onCreditCard:i?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:i,creditCardTooltip:d})}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let e=Number(this.config?.amountUsd??0),t=this.getSdk(),i=this.selectedSymbol||"ICP",r=this.cryptoOptions.find(E=>E.symbol===i)?.canisterId||await t.client.getLedgerCanisterIdBySymbol(i),l=await t.startOnrampUsd(e,r,{context:"pay-button:onramp"}),c=l?.metadata?.onramp?.sessionId||l?.metadata?.onramp?.session_id||null,d=l?.metadata?.onramp?.errorMessage||null;this.onrampErrorMessage=d||null;let p=l?.metadata?.paymentIntentId||l?.paymentIntentId||null;this.onrampPaymentIntentId=p,c?(this.onrampSessionId=c,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.showOnrampModal=!0)}catch(e){this.onrampSessionId=null,this.onrampErrorMessage=e?.message||null,this.showOnrampModal=!0,L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"getLedgerBalance"}}))}catch{}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"sendFundsToLedger"}}))}catch{}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-success",{detail:{name:"notifyLedgerTransaction"}}))}catch{}this.showOnrampModal=!1,this.startOnrampPolling(n||void 0)}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let i=this.getSdk(),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1},r=l=>{n()};try{window.addEventListener("icpay-sdk-transaction-completed",r,{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}async pay(){if(!(!Le||this.processing)){this.errorMessage=null,this.errorSeverity=null,this.errorAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config?.amountUsd,currency:this.selectedSymbol||this.config?.defaultSymbol}}))}catch{}this.processing=!0;try{if(!await this.ensureWallet())return;let t=this.getSdk(),i=this.selectedSymbol||"ICP",r=this.cryptoOptions.find(p=>p.symbol===i)?.canisterId||await t.client.getLedgerCanisterIdBySymbol(i),l=Number(this.config?.amountUsd??0),c={context:"pay-button"},d=await t.sendUsd(l,r,c);this.config.onSuccess&&this.config.onSuccess({id:d.transactionId,status:d.status}),this.succeeded=!0,this.dispatchEvent(new CustomEvent("icpay-pay",{detail:{amount:l,tx:d},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}render(){if(!this.config)return he`<div class="icpay-card icpay-section">Loading...</div>`;let t=(this.cryptoOptions?.length||0)>1,i=this.config?.showLedgerDropdown,n=i==="dropdown"?"dropdown":i==="none"?"none":"buttons",r=n!=="none"&&(t||n==="dropdown"),l=n==="dropdown"?"dropdown":t?"buttons":"none",c=this.selectedSymbol||this.config?.defaultSymbol||"ICP",d=typeof this.config?.amountUsd=="number"?`${Number(this.config.amountUsd).toFixed(2)}`:"",E=(this.config?.buttonLabel||(typeof this.config?.amountUsd=="number"?"Pay ${amount} with {symbol}":"Pay with {symbol}")).replace("{amount}",d||"$0.00").replace("{symbol}",c),be=this.config?.progressBar?.enabled!==!1;return he`
|
|
928
928
|
<div class="icpay-card icpay-section">
|
|
929
929
|
${be?he`
|
|
930
930
|
<icpay-progress-bar
|
|
@@ -969,7 +969,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
969
969
|
.error-message.info { background: rgba(59,130,246,0.1); border-color: rgba(59,130,246,0.3); color: #3b82f6; }
|
|
970
970
|
.error-message.warning { background: rgba(245,158,11,0.1); border-color: rgba(245,158,11,0.3); color: #f59e0b; }
|
|
971
971
|
.error-message.error { background: rgba(239,68,68,0.1); border-color: rgba(239,68,68,0.3); color: #ef4444; }
|
|
972
|
-
`],s([St({type:Object})],x.prototype,"config",2),s([
|
|
972
|
+
`],s([St({type:Object})],x.prototype,"config",2),s([K()],x.prototype,"selectedSymbol",2),s([K()],x.prototype,"processing",2),s([K()],x.prototype,"succeeded",2),s([K()],x.prototype,"availableLedgers",2),s([K()],x.prototype,"errorMessage",2),s([K()],x.prototype,"errorSeverity",2),s([K()],x.prototype,"errorAction",2),s([K()],x.prototype,"walletConnected",2),s([K()],x.prototype,"pendingAction",2),s([K()],x.prototype,"showWalletModal",2),s([K()],x.prototype,"showOnrampModal",2),s([K()],x.prototype,"onrampSessionId",2),s([K()],x.prototype,"onrampPaymentIntentId",2),s([K()],x.prototype,"onrampErrorMessage",2),x=s([xt("icpay-pay-button")],x);import{LitElement as Et,html as ge,css as kt}from"lit";import{customElement as Mt,property as It,state as I}from"lit/decorators.js";var Ae=typeof window<"u",We=null;function Ct(o,a,e){o&&(e!==void 0?console.log(`[ICPay Widget] ${a}`,e):console.log(`[ICPay Widget] ${a}`))}var b=class extends Et{constructor(){super(...arguments);this.amountUsd=0;this.hasUserAmount=!1;this.selectedSymbol=null;this.processing=!1;this.succeeded=!1;this.availableLedgers=[];this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.showOnrampModal=!1;this.onrampSessionId=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.pnp=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null}get cryptoOptions(){return this.config?.cryptoOptions?.length?this.config.cryptoOptions:this.availableLedgers}connectedCallback(){super.connectedCallback(),Ae&&(Ct(this.config?.debug||!1,"Amount input connected",{config:this.config}),this.amountUsd=Number(this.config?.defaultAmountUsd??0),this.hasUserAmount=!1,this.config?.cryptoOptions&&this.config.cryptoOptions.length>0||this.loadVerifiedLedgers(),this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol))}updated(e){if(e.has("config")&&(!this.hasUserAmount&&typeof this.config?.defaultAmountUsd=="number"&&(this.amountUsd===0||this.amountUsd==null||Number.isNaN(this.amountUsd))&&(this.amountUsd=Number(this.config.defaultAmountUsd)),!this.selectedSymbol&&this.config?.defaultSymbol&&(this.selectedSymbol=this.config.defaultSymbol),!(this.config?.cryptoOptions&&this.config.cryptoOptions.length>0)&&this.availableLedgers.length===0&&this.loadVerifiedLedgers(),this.pendingAction&&this.config?.actorProvider)){let t=this.pendingAction;this.pendingAction=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}setTimeout(()=>{t==="pay"&&this.pay()},0)}}async loadVerifiedLedgers(){if(!(!Ae||!this.config?.publishableKey))try{let t=await h(this.config).client.getVerifiedLedgers();this.availableLedgers=t.map(i=>({symbol:i.symbol,label:i.name,canisterId:i.canisterId})),this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||(this.availableLedgers[0]?.symbol??"ICP"))}catch(e){this.dispatchEvent(new CustomEvent("icpay-error",{detail:{message:"Failed to load verified ledgers",cause:e},bubbles:!0})),this.availableLedgers=[{symbol:"ICP",label:"ICP",canisterId:"ryjl3-tyaaa-aaaaa-aaaba-cai"}],this.selectedSymbol||(this.selectedSymbol=this.config?.defaultSymbol||"ICP")}}onInputChange(e){let t=Number(this.config?.stepUsd??.5),i=Math.max(0,Number(e.target.value||0)),n=Math.round(i/t)*t;this.amountUsd=Number(n.toFixed(2)),this.hasUserAmount=!0}selectSymbol(e){this.selectedSymbol=e}isValidAmount(){let e=Number(this.config?.minUsd??.5),t=this.config?.maxUsd!==void 0?Number(this.config.maxUsd):1/0;return this.amountUsd>=e&&this.amountUsd<=t}async ensureWallet(){if(this.config.useOwnWallet)return this.config.actorProvider?!0:(this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0})),!1);if(this.walletConnected)return!0;try{if(We||(We=(await import("@windoge98/plug-n-play")).PNP),this.pnp=new We(this.config?.plugNPlay||{}),!this.pnp.getEnabledWallets()?.length)throw new Error("No wallets available");return this.pendingAction="pay",this.showWalletModal=!0,!1}catch(e){return this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error",!1}}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}async connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");let t=await this.pnp.connect(e);if(!!!(t&&(t.connected===!0||t.principal||t.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}this.config={...this.config,connectedWallet:t,actorProvider:(r,l)=>this.pnp.getActor({canisterId:r,idl:l,requiresSigning:!0,anon:!1})},this.showWalletModal=!1;let n=this.pendingAction;this.pendingAction=null,n==="pay"&&setTimeout(()=>this.pay(),0)}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,i=t?.event_id||t?.eventId||t?.id;if(!(!i||typeof i!="string")&&i==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let e=h(this.config),t=this.selectedSymbol||"ICP",n=this.cryptoOptions.find(E=>E.symbol===t)?.canisterId||await e.client.getLedgerCanisterIdBySymbol(t),r=Number(this.amountUsd),l=await e.startOnrampUsd(r,n,{context:"amount-input:onramp"}),c=l?.metadata?.onramp?.sessionId||l?.metadata?.onramp?.session_id||null,d=l?.metadata?.paymentIntentId||l?.paymentIntentId||null,p=l?.metadata?.onramp?.errorMessage||null;this.onrampPaymentIntentId=d,c?(this.onrampSessionId=c,this.onrampErrorMessage=null,this.showOnrampModal=!0,this.attachTransakMessageListener()):(this.onrampSessionId=null,this.onrampErrorMessage=p||"Failed to obtain onramp sessionId",this.showOnrampModal=!0)}catch(e){this.onrampSessionId=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let i=h(this.config),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=i.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}async pay(){if(!(!Ae||this.processing)){if(this.errorMessage=null,this.errorSeverity=null,this.errorAction=null,!this.isValidAmount()){this.errorMessage="Please enter a valid amount",this.errorSeverity="warning";return}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.amountUsd,currency:this.selectedSymbol||this.config?.defaultSymbol}}))}catch{}this.processing=!0;try{if(!await this.ensureWallet())return;let t=h(this.config),i=this.selectedSymbol||"ICP",r=this.cryptoOptions.find(p=>p.symbol===i)?.canisterId||await t.client.getLedgerCanisterIdBySymbol(i),l=Number(this.amountUsd),c={context:"amount-input"},d=await t.sendUsd(l,r,c);this.config.onSuccess&&this.config.onSuccess({id:d.transactionId,status:d.status,amountUsd:l}),this.succeeded=!0,this.dispatchEvent(new CustomEvent("icpay-amount-pay",{detail:{amount:l,tx:d},bubbles:!0}))}catch(e){L(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),A(t)&&(this.errorMessage=O(t),this.errorSeverity=T(t),this.errorAction=W(t))}})}finally{this.processing=!1}}}render(){if(!this.config)return ge`<div class="icpay-card icpay-section">Loading...</div>`;let e=this.config?.placeholder||"Enter amount in USD",i=(this.config?.buttonLabel||"Pay ${amount} with {symbol}").replace("{amount}",this.amountUsd?`${Number(this.amountUsd).toFixed(2)}`:"$0.00").replace("{symbol}",this.selectedSymbol||this.config?.defaultSymbol||"ICP"),n=this.cryptoOptions.find(z=>z.symbol===(this.selectedSymbol||""))?.label||this.cryptoOptions[0]?.label||this.config?.defaultSymbol||"ICP",r=this.config?.progressBar?.mode||"modal",l=this.config?.showLedgerDropdown,c=l==="buttons"?"buttons":l==="none"?"none":"dropdown",p=(this.cryptoOptions?.length||0)>1,E=c!=="none"&&(p||c==="dropdown"),ue=c==="dropdown"?"dropdown":p?"buttons":"none",me=this.config?.progressBar?.enabled!==!1&&(r==="modal"?!0:this.processing);return ge`
|
|
973
973
|
<div class="icpay-card icpay-section">
|
|
974
974
|
${me?ge`
|
|
975
975
|
<icpay-progress-bar
|
|
@@ -984,7 +984,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
984
984
|
<div class="top-row ${E?"with-selector":""}">
|
|
985
985
|
<div class="amount-field">
|
|
986
986
|
<span class="currency-prefix">$</span>
|
|
987
|
-
<input type="number" min="0" step="${Number(this.config?.stepUsd??.5)}" .value=${String(this.amountUsd||"")} placeholder="${e}" @input=${
|
|
987
|
+
<input type="number" min="0" step="${Number(this.config?.stepUsd??.5)}" .value=${String(this.amountUsd||"")} placeholder="${e}" @input=${z=>this.onInputChange(z)} />
|
|
988
988
|
</div>
|
|
989
989
|
${E?ge`
|
|
990
990
|
<icpay-token-selector
|
|
@@ -993,7 +993,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
993
993
|
.defaultSymbol=${this.config?.defaultSymbol||"ICP"}
|
|
994
994
|
mode=${ue}
|
|
995
995
|
.showLabel=${!1}
|
|
996
|
-
@icpay-token-change=${
|
|
996
|
+
@icpay-token-change=${z=>this.selectSymbol(z.detail.symbol)}
|
|
997
997
|
></icpay-token-selector>
|
|
998
998
|
`:null}
|
|
999
999
|
</div>
|
|
@@ -1011,7 +1011,7 @@ var De=Object.defineProperty;var Fe=Object.getOwnPropertyDescriptor;var s=(o,a,e
|
|
|
1011
1011
|
${this.errorAction?ge`<button style="margin-left: 8px; padding: 4px 8px; background: transparent; border: 1px solid currentColor; border-radius: 4px; font-size: 12px; cursor: pointer;">${this.errorAction}</button>`:""}
|
|
1012
1012
|
</div>
|
|
1013
1013
|
`:""}
|
|
1014
|
-
${(()=>{let
|
|
1014
|
+
${(()=>{let F=(this.pnp?.getEnabledWallets?.()||[]).map(H=>({id:this.getWalletId(H),label:this.getWalletLabel(H),icon:this.getWalletIcon(H)}));return B({visible:!!(this.showWalletModal&&this.pnp),wallets:F,isConnecting:!1,onSelect:H=>this.connectWithWallet(H),onClose:()=>{this.showWalletModal=!1},onCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let V=Number(this.amountUsd||0);return V>0&&V<5&&this.config?.onramp?.enabled!==!1&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-V).toFixed(2)} more.`:null})()})})()}
|
|
1015
1015
|
|
|
1016
1016
|
${this.showOnrampModal?N({visible:this.showOnrampModal,sessionId:this.onrampSessionId,errorMessage:this.onrampErrorMessage,apiKey:this.config?.onramp?.apiKey,environment:this.config?.onramp?.environment||"STAGING",width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0}}):null}
|
|
1017
1017
|
</div>
|