@markee_team/sdk 0.1.0-alpha.6 → 0.1.0-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -8
- package/dist/index.js +2 -2
- package/dist/modal.d.ts +2 -0
- package/dist/react.js +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -218,8 +218,8 @@ Then implement the agreed scope:
|
|
|
218
218
|
4. If a host wallet exists, pass its selected EIP-1193 provider through the wallet
|
|
219
219
|
adapter. For ConnectKit/wagmi use the active connector. Resolve connect after
|
|
220
220
|
selection, reject cancellation, and do not silently switch wallet providers.
|
|
221
|
-
Otherwise omit wallet.
|
|
222
|
-
|
|
221
|
+
Otherwise omit wallet. Without a connected app account, the modal shows only
|
|
222
|
+
Pay, opening Markee-hosted checkout for supported boards. Do not install
|
|
223
223
|
Privy or collect card details in the host app.
|
|
224
224
|
5. Apply theme options while preserving the built-in modal layout. Handle onEvent
|
|
225
225
|
if needed; show success only for a confirmed event. Let the SDK manage review,
|
|
@@ -236,12 +236,14 @@ bridging is not available. Transactions and card funding use real funds.
|
|
|
236
236
|
|
|
237
237
|
## Pay by card without an app wallet
|
|
238
238
|
|
|
239
|
-
|
|
239
|
+
Without a connected app wallet, the modal shows **Pay** as its only payment action
|
|
240
|
+
and hides wallet balances and wallet-management sections. For Sale boards on Base
|
|
241
|
+
with MARKEE rewards support this flow
|
|
240
242
|
when the Markee backend enables hosted checkout. No Privy provider, payment keys or
|
|
241
243
|
API configuration is needed in the integrating app. Omit the `wallet` adapter.
|
|
242
244
|
|
|
243
245
|
The SDK opens Markee, where the user signs in, receives a Privy embedded wallet,
|
|
244
|
-
funds it
|
|
246
|
+
funds it through Stripe (Base USDC converted to ETH) or MoonPay (Base ETH), and confirms
|
|
245
247
|
the Markee payment. The contract sends MARKEE directly to that user's paying
|
|
246
248
|
wallet. The host receives `onEvent({ type: 'confirmed', hash })` only after
|
|
247
249
|
server-side receipt verification. Card funding alone is not a successful payment.
|
|
@@ -249,9 +251,12 @@ server-side receipt verification. Card funding alone is not a successful payment
|
|
|
249
251
|
The checkout can resume after closing or refreshing. If a wallet submission has an
|
|
250
252
|
unknown result, it asks the user to check the existing transaction instead of
|
|
251
253
|
sending again. On browsers that block popups, it navigates to Markee in the same
|
|
252
|
-
tab. Reopen Pay
|
|
254
|
+
tab. Reopen Pay after returning to recover the confirmed result.
|
|
253
255
|
|
|
254
256
|
Card availability, fees, minimum purchase amounts and identity checks depend on
|
|
255
|
-
the funding provider and user eligibility. Any unused ETH remains in the
|
|
256
|
-
wallet.
|
|
257
|
-
wallet and
|
|
257
|
+
the funding provider and user eligibility. Any unused USDC or ETH remains in the
|
|
258
|
+
user's wallet. Conversion uses a capped approval and maximum 1% slippage, with
|
|
259
|
+
wallet confirmation and Markee-sponsored conversion gas. For Rent, incoming
|
|
260
|
+
bridging and automatic rewards forwarding to a different wallet are outside this
|
|
261
|
+
checkout flow. If hosted checkout is unavailable, Pay is disabled with an
|
|
262
|
+
availability message; the modal does not fall back to asking for a wallet.
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var N="https://markee-git-feature-markee-sdk-1hive.vercel.app/api/sdk/v1",m=class extends Error{constructor(t,a="MARKEE_ERROR",i){super(t);this.code=a;this.status=i;this.name="MarkeeError"}};async function C(){if(typeof window>"u")return[];let s=new Map,e=a=>{let i=a.detail;i?.provider?.request&&typeof i.info?.uuid=="string"&&s.set(i.info.uuid,{uuid:i.info.uuid,name:String(i.info.name).slice(0,80),provider:i.provider})};window.addEventListener("eip6963:announceProvider",e),window.dispatchEvent(new Event("eip6963:requestProvider")),await new Promise(a=>setTimeout(a,150)),window.removeEventListener("eip6963:announceProvider",e);let t=window.ethereum;return!s.size&&t?.request&&s.set("injected",{uuid:"injected",name:"Browser wallet",provider:t}),[...s.values()]}var k=s=>typeof s=="string"&&/^0x[\da-f]{40}$/i.test(s),E=s=>typeof s=="string"&&/^0x[\da-f]{64}$/i.test(s),x=class{constructor(e={}){this.options=e;let t=new URL(e.apiUrl??N);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new m("Use an HTTPS Markee API URL (HTTP is allowed on localhost).");this.apiUrl=t.href.replace(/\/$/,""),this.fetcher=e.fetch||globalThis.fetch.bind(globalThis)}apiUrl;fetcher;injected=null;sending=!1;inMemoryPending=[];adminMemory=null;communityReceipts={};async request(e,t,a){let i=await this.fetcher(`${this.apiUrl}/${e}`,{method:t===void 0?"GET":"POST",body:t===void 0?void 0:JSON.stringify(t),headers:t===void 0?void 0:{"Content-Type":"application/json"},credentials:"omit",signal:a||AbortSignal.timeout(55e3)}),r=await i.json().catch(()=>null);if(!i.ok)throw new m(r?.error||`Markee returned HTTP ${i.status}.`,r?.code,i.status);return r}async provider(){return this.options.wallet?this.options.wallet.getProvider():this.injected}async account(){let e=await this.provider();if(!e)return null;let t=await e.request({method:"eth_accounts"});return Array.isArray(t)&&k(t[0])?t[0]:null}async connect(e){let t=await this.provider();if(this.options.wallet)t||(t=await this.options.wallet.connect?.()||null);else{if(t=e||t,!t){let i=await C();if(i.length>1)throw new m("Select a browser wallet.","SELECT_WALLET");t=i[0]?.provider||null}this.injected=t}if(!t)throw new m("Connect a wallet in the app or install a browser wallet to continue.","NO_WALLET");let a=await t.request({method:"eth_requestAccounts"});if(!Array.isArray(a)||!k(a[0]))throw new m("The wallet did not return an account.");return a[0]}verifySite(e,t){return this.request("sites/verify",{placement:e,siteUrl:t})}siteRequests=new Map;registerSite(e){if(!this.options.siteUrl)return;let t=JSON.stringify([e,this.options.siteUrl]);if(this.siteRequests.has(t))return;let a=this.verifySite(e,this.options.siteUrl);this.siteRequests.set(t,a),a.then(i=>this.options.onSiteVerification?.(i),i=>this.options.onSiteVerification?.({verified:!1,url:this.options.siteUrl,message:i instanceof Error?i.message:"Site verification failed."})).catch(()=>{})}async snapshot(e,t,a,i){let r=new URLSearchParams({placement:JSON.stringify(e)});return t&&r.set("account",t),a!==void 0&&r.set("offset",String(a)),this.request(`snapshot?${r}`,void 0,i)}async prepare(e,t){let a=await this.account();if(!a)throw new m("Connect your wallet first.","NOT_CONNECTED");return this.request("prepare",{placement:e,account:a,action:t})}async ensureWallet(e,t){let a=await this.provider();if(!a||(await this.account())?.toLowerCase()!==e.toLowerCase())throw new m("Your wallet account changed. Review this action again.","ACCOUNT_CHANGED");let i=Number(await a.request({method:"eth_chainId"}));if(i!==t&&await a.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${t.toString(16)}`}]}),i=Number(await a.request({method:"eth_chainId"})),i!==t||(await this.account())?.toLowerCase()!==e.toLowerCase())throw new m("The wallet account or network changed. Review again.","WALLET_CHANGED");return a}async send(e){if(this.sending)throw new m("A wallet request is already in progress.");if(e.expiresAt<=Date.now())throw new m("This review expired. Prepare the action again.","REVIEW_EXPIRED");if(this.pending(e.placement,e.transaction.from))throw new m("A transaction is still pending for this wallet and placement. Check it before submitting again.","PENDING_TRANSACTION");this.sending=!0;try{let a=await this.ensureWallet(e.transaction.from,e.transaction.chainId);if(e.expiresAt<=Date.now())throw new m("This review expired. Prepare the action again.","REVIEW_EXPIRED");let{chainId:i,...r}=e.transaction,n=await a.request({method:"eth_sendTransaction",params:[r]});if(!E(n))throw new m("The wallet returned an unexpected transaction identifier. Check your wallet before retrying.");return this.persist([...this.records(),{preparation:e,hash:n}]),this.options.onEvent?.({type:"submitted",hash:n}),n}catch(a){throw this.options.onEvent?.({type:"error",message:a instanceof Error?a.message:String(a)}),a}finally{this.sending=!1}}async verify(e){let t=await this.request("verify",{id:e.preparation.id,hash:e.hash});return t.status!=="pending"&&(this.persist(this.records().filter(a=>a.hash!==e.hash)),t.status==="confirmed"&&this.options.onEvent?.({type:"confirmed",hash:t.hash})),t}async reconcile(e,t){if(!E(t))throw new m("Enter a valid replacement transaction hash.");let a=await this.request("verify",{id:e.preparation.id,hash:t});return a.status!=="pending"&&this.persist(this.records().filter(i=>i.hash!==e.hash)),a}storageKey(){return`markee:sdk:v1:pending:${this.apiUrl}`}records(){try{if(typeof localStorage>"u")return this.inMemoryPending;let e=JSON.parse(localStorage.getItem(this.storageKey())||"[]");return Array.isArray(e)?e.filter(t=>E(t?.hash)&&typeof t.preparation?.id=="string"&&k(t.preparation?.transaction?.from)&&t.preparation?.placement):[]}catch{return this.inMemoryPending}}persist(e){this.inMemoryPending=e;try{typeof localStorage<"u"&&localStorage.setItem(this.storageKey(),JSON.stringify(e))}catch{}}pending(e,t){return this.records().find(a=>JSON.stringify(a.preparation.placement).toLowerCase()===JSON.stringify(e).toLowerCase()&&a.preparation.transaction.from.toLowerCase()===t.toLowerCase())}async quote(e){return this.request(`community/quote?${new URLSearchParams({chainId:String(e.chainId),community:e.community})}`)}async authorize(e,t){let a=await this.account();if(!a)throw new m("Connect your community council wallet first.");return this.request(`community/${t}`,{action:"challenge",chainId:e.chainId,community:e.community,account:a})}async executeAuthorization(e,t,a){if(this.pendingAuthorization())throw new m("An earlier community authorization is still processing. Check its status first.");let i=t.typedData,n=await(await this.ensureWallet(a,i.domain.chainId)).request({method:"eth_signTypedData_v4",params:[a,JSON.stringify({...i,types:{...i.types,EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}]}})]});if(typeof n!="string"||!/^0x[\da-f]+$/i.test(n))throw new m("Wallet did not return a typed-data signature.");return this.saveAuthorization({kind:e,nonce:t.nonce,signature:n,account:a,community:i.domain.verifyingContract,chainId:i.domain.chainId}),this.resumeAuthorization()}pendingAuthorization(){try{let e=typeof localStorage>"u"?this.adminMemory:JSON.parse(localStorage.getItem(`${this.storageKey()}:admin`)||"null");return e&&["activate","claim"].includes(e.kind)&&k(e.account)&&k(e.community)&&typeof e.nonce=="string"&&typeof e.signature=="string"?e:null}catch{return this.adminMemory}}saveAuthorization(e){this.adminMemory=e;try{typeof localStorage<"u"&&localStorage.setItem(`${this.storageKey()}:admin`,JSON.stringify(e))}catch{}}async resumeAuthorization(){let e=this.pendingAuthorization();if(!e)throw new m("There is no pending community authorization.");let t=await this.request(`community/${e.kind}`,{action:"verify",nonce:e.nonce,signature:e.signature});if(t.status==="complete"&&t.result){let a=`${e.chainId}:${e.community.toLowerCase()}`;this.communityReceipts[a]=t.result;try{typeof localStorage<"u"&&localStorage.setItem(`${this.storageKey()}:community:${a}`,JSON.stringify(t.result))}catch{}}return(t.status==="complete"||t.status==="failed")&&this.saveAuthorization(null),t}communityReceipt(e){let t=`${e.chainId}:${e.community.toLowerCase()}`;try{let a=typeof localStorage>"u"?this.communityReceipts[t]:JSON.parse(localStorage.getItem(`${this.storageKey()}:community:${t}`)||"null");return a&&E(a.transactionHash)?a:null}catch{return this.communityReceipts[t]||null}}bridgeStatus(e,t,a,i){return this.request(`community/status?${new URLSearchParams({protocol:e,transactionHash:t,fromChainId:String(a),toChainId:String(i)})}`)}recordView(e,t,a){return this.request("views",{address:e,message:t,url:a})}};var R=(s,e)=>`markee:checkout:v1:${s.apiUrl}:${JSON.stringify(e)}`;function q(s,e){try{let t=JSON.parse(localStorage.getItem(R(s,e))||"null");return t&&typeof t.id=="string"&&/^[a-f0-9]{48}$/.test(t.id)&&/^[a-f0-9]{64}$/.test(t.readToken)&&/^[a-f0-9]{64}$/.test(t.writeToken)&&Number.isFinite(t.expiresAt)?t:null}catch{return null}}async function z(s,e){return s.request("checkout/status",{id:e.id,token:e.readToken})}function $(s,e){try{localStorage.removeItem(R(s,e))}catch{}}async function H(s,e,t){let a=window.open("about:blank","_blank","popup,width=520,height=780");a&&(a.opener=null);let i=q(s,e);try{if(i){let n=await z(s,i).catch(o=>{if(o instanceof m&&o.status===404)return $(s,e),i=null,null;throw o});if(n?.result?.status==="confirmed"||n?.result?.status==="reverted")return $(s,e),a?.close(),n.result;i&&n&&i.expiresAt<Date.now()&&["created","ready"].includes(n.status)&&($(s,e),i=null)}if(!i){i=await s.request("checkout/create",{placement:e,action:t,origin:window.location.origin});try{localStorage.setItem(R(s,e),JSON.stringify(i))}catch{}}let r=new URL(`/checkout/${i.id}`,s.apiUrl);if(r.hash=new URLSearchParams({token:i.writeToken}).toString(),a)a.location.replace(r.href);else throw window.location.assign(r.href),new Error("Continuing payment on Markee.");for(let n=0;n<1800;n++){let o=await z(s,i);if(o.result&&o.status==="confirmed")return $(s,e),o.result;if(o.status==="reverted")throw $(s,e),new Error("Payment reverted. Any unspent funds remain in your Markee wallet.");if(a.closed)throw new Error("Markee checkout closed. Choose Pay by card again to resume; funding alone does not complete payment.");await new Promise(d=>setTimeout(d,3e3))}throw new Error("Checkout is still pending. Reopen it to check the payment; do not pay again.")}catch(r){throw i||a?.close(),r}}function g(s,e=!1){let t=s.trim();if(!/^\d+(\.\d{0,18})?$/.test(t))throw new Error("Enter an ETH amount with up to 18 decimal places.");let[a,i=""]=t.split("."),r=BigInt(a)*10n**18n+BigInt(i.padEnd(18,"0"));if(!e&&r===0n||r>=2n**256n)throw new Error("Enter a positive amount.");return r.toString()}function p(s,e=6){let t=BigInt(s),a=t<0n?"-":"",i=t<0n?-t:t,r=(i%10n**18n).toString().padStart(18,"0").slice(0,e).replace(/0+$/,"");return i>0n&&i<10n**BigInt(18-e)?`${a}<0.${"0".repeat(e-1)}1`:`${a}${i/10n**18n}${r?`.${r}`:""}`}function S(s){return`${s.slice(0,6)}\u2026${s.slice(-4)}`}function l(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var F=`
|
|
1
|
+
var q="https://markee-git-feature-markee-sdk-1hive.vercel.app/api/sdk/v1",m=class extends Error{constructor(t,a="MARKEE_ERROR",i){super(t);this.code=a;this.status=i;this.name="MarkeeError"}};async function C(){if(typeof window>"u")return[];let s=new Map,e=a=>{let i=a.detail;i?.provider?.request&&typeof i.info?.uuid=="string"&&s.set(i.info.uuid,{uuid:i.info.uuid,name:String(i.info.name).slice(0,80),provider:i.provider})};window.addEventListener("eip6963:announceProvider",e),window.dispatchEvent(new Event("eip6963:requestProvider")),await new Promise(a=>setTimeout(a,150)),window.removeEventListener("eip6963:announceProvider",e);let t=window.ethereum;return!s.size&&t?.request&&s.set("injected",{uuid:"injected",name:"Browser wallet",provider:t}),[...s.values()]}var k=s=>typeof s=="string"&&/^0x[\da-f]{40}$/i.test(s),E=s=>typeof s=="string"&&/^0x[\da-f]{64}$/i.test(s),x=class{constructor(e={}){this.options=e;let t=new URL(e.apiUrl??q);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new m("Use an HTTPS Markee API URL (HTTP is allowed on localhost).");this.apiUrl=t.href.replace(/\/$/,""),this.fetcher=e.fetch||globalThis.fetch.bind(globalThis)}apiUrl;fetcher;injected=null;sending=!1;inMemoryPending=[];adminMemory=null;communityReceipts={};async request(e,t,a){let i=await this.fetcher(`${this.apiUrl}/${e}`,{method:t===void 0?"GET":"POST",body:t===void 0?void 0:JSON.stringify(t),headers:t===void 0?void 0:{"Content-Type":"application/json"},credentials:"omit",signal:a||AbortSignal.timeout(55e3)}),r=await i.json().catch(()=>null);if(!i.ok)throw new m(r?.error||`Markee returned HTTP ${i.status}.`,r?.code,i.status);return r}async provider(){return this.options.wallet?this.options.wallet.getProvider():this.injected}async account(){let e=await this.provider();if(!e)return null;let t=await e.request({method:"eth_accounts"});return Array.isArray(t)&&k(t[0])?t[0]:null}async connect(e){let t=await this.provider();if(this.options.wallet)t||(t=await this.options.wallet.connect?.()||null);else{if(t=e||t,!t){let i=await C();if(i.length>1)throw new m("Select a browser wallet.","SELECT_WALLET");t=i[0]?.provider||null}this.injected=t}if(!t)throw new m("Connect a wallet in the app or install a browser wallet to continue.","NO_WALLET");let a=await t.request({method:"eth_requestAccounts"});if(!Array.isArray(a)||!k(a[0]))throw new m("The wallet did not return an account.");return a[0]}verifySite(e,t){return this.request("sites/verify",{placement:e,siteUrl:t})}siteRequests=new Map;registerSite(e){if(!this.options.siteUrl)return;let t=JSON.stringify([e,this.options.siteUrl]);if(this.siteRequests.has(t))return;let a=this.verifySite(e,this.options.siteUrl);this.siteRequests.set(t,a),a.then(i=>this.options.onSiteVerification?.(i),i=>this.options.onSiteVerification?.({verified:!1,url:this.options.siteUrl,message:i instanceof Error?i.message:"Site verification failed."})).catch(()=>{})}async snapshot(e,t,a,i){let r=new URLSearchParams({placement:JSON.stringify(e)});return t&&r.set("account",t),a!==void 0&&r.set("offset",String(a)),this.request(`snapshot?${r}`,void 0,i)}async prepare(e,t){let a=await this.account();if(!a)throw new m("Connect your wallet first.","NOT_CONNECTED");return this.request("prepare",{placement:e,account:a,action:t})}async ensureWallet(e,t){let a=await this.provider();if(!a||(await this.account())?.toLowerCase()!==e.toLowerCase())throw new m("Your wallet account changed. Review this action again.","ACCOUNT_CHANGED");let i=Number(await a.request({method:"eth_chainId"}));if(i!==t&&await a.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${t.toString(16)}`}]}),i=Number(await a.request({method:"eth_chainId"})),i!==t||(await this.account())?.toLowerCase()!==e.toLowerCase())throw new m("The wallet account or network changed. Review again.","WALLET_CHANGED");return a}async send(e){if(this.sending)throw new m("A wallet request is already in progress.");if(e.expiresAt<=Date.now())throw new m("This review expired. Prepare the action again.","REVIEW_EXPIRED");if(this.pending(e.placement,e.transaction.from))throw new m("A transaction is still pending for this wallet and placement. Check it before submitting again.","PENDING_TRANSACTION");this.sending=!0;try{let a=await this.ensureWallet(e.transaction.from,e.transaction.chainId);if(e.expiresAt<=Date.now())throw new m("This review expired. Prepare the action again.","REVIEW_EXPIRED");let{chainId:i,...r}=e.transaction,n=await a.request({method:"eth_sendTransaction",params:[r]});if(!E(n))throw new m("The wallet returned an unexpected transaction identifier. Check your wallet before retrying.");return this.persist([...this.records(),{preparation:e,hash:n}]),this.options.onEvent?.({type:"submitted",hash:n}),n}catch(a){throw this.options.onEvent?.({type:"error",message:a instanceof Error?a.message:String(a)}),a}finally{this.sending=!1}}async verify(e){let t=await this.request("verify",{id:e.preparation.id,hash:e.hash});return t.status!=="pending"&&(this.persist(this.records().filter(a=>a.hash!==e.hash)),t.status==="confirmed"&&this.options.onEvent?.({type:"confirmed",hash:t.hash})),t}async reconcile(e,t){if(!E(t))throw new m("Enter a valid replacement transaction hash.");let a=await this.request("verify",{id:e.preparation.id,hash:t});return a.status!=="pending"&&this.persist(this.records().filter(i=>i.hash!==e.hash)),a}storageKey(){return`markee:sdk:v1:pending:${this.apiUrl}`}records(){try{if(typeof localStorage>"u")return this.inMemoryPending;let e=JSON.parse(localStorage.getItem(this.storageKey())||"[]");return Array.isArray(e)?e.filter(t=>E(t?.hash)&&typeof t.preparation?.id=="string"&&k(t.preparation?.transaction?.from)&&t.preparation?.placement):[]}catch{return this.inMemoryPending}}persist(e){this.inMemoryPending=e;try{typeof localStorage<"u"&&localStorage.setItem(this.storageKey(),JSON.stringify(e))}catch{}}pending(e,t){return this.records().find(a=>JSON.stringify(a.preparation.placement).toLowerCase()===JSON.stringify(e).toLowerCase()&&a.preparation.transaction.from.toLowerCase()===t.toLowerCase())}async quote(e){return this.request(`community/quote?${new URLSearchParams({chainId:String(e.chainId),community:e.community})}`)}async authorize(e,t){let a=await this.account();if(!a)throw new m("Connect your community council wallet first.");return this.request(`community/${t}`,{action:"challenge",chainId:e.chainId,community:e.community,account:a})}async executeAuthorization(e,t,a){if(this.pendingAuthorization())throw new m("An earlier community authorization is still processing. Check its status first.");let i=t.typedData,n=await(await this.ensureWallet(a,i.domain.chainId)).request({method:"eth_signTypedData_v4",params:[a,JSON.stringify({...i,types:{...i.types,EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}]}})]});if(typeof n!="string"||!/^0x[\da-f]+$/i.test(n))throw new m("Wallet did not return a typed-data signature.");return this.saveAuthorization({kind:e,nonce:t.nonce,signature:n,account:a,community:i.domain.verifyingContract,chainId:i.domain.chainId}),this.resumeAuthorization()}pendingAuthorization(){try{let e=typeof localStorage>"u"?this.adminMemory:JSON.parse(localStorage.getItem(`${this.storageKey()}:admin`)||"null");return e&&["activate","claim"].includes(e.kind)&&k(e.account)&&k(e.community)&&typeof e.nonce=="string"&&typeof e.signature=="string"?e:null}catch{return this.adminMemory}}saveAuthorization(e){this.adminMemory=e;try{typeof localStorage<"u"&&localStorage.setItem(`${this.storageKey()}:admin`,JSON.stringify(e))}catch{}}async resumeAuthorization(){let e=this.pendingAuthorization();if(!e)throw new m("There is no pending community authorization.");let t=await this.request(`community/${e.kind}`,{action:"verify",nonce:e.nonce,signature:e.signature});if(t.status==="complete"&&t.result){let a=`${e.chainId}:${e.community.toLowerCase()}`;this.communityReceipts[a]=t.result;try{typeof localStorage<"u"&&localStorage.setItem(`${this.storageKey()}:community:${a}`,JSON.stringify(t.result))}catch{}}return(t.status==="complete"||t.status==="failed")&&this.saveAuthorization(null),t}communityReceipt(e){let t=`${e.chainId}:${e.community.toLowerCase()}`;try{let a=typeof localStorage>"u"?this.communityReceipts[t]:JSON.parse(localStorage.getItem(`${this.storageKey()}:community:${t}`)||"null");return a&&E(a.transactionHash)?a:null}catch{return this.communityReceipts[t]||null}}bridgeStatus(e,t,a,i){return this.request(`community/status?${new URLSearchParams({protocol:e,transactionHash:t,fromChainId:String(a),toChainId:String(i)})}`)}recordView(e,t,a){return this.request("views",{address:e,message:t,url:a})}};var H=(s,e)=>`markee:checkout:v1:${s.apiUrl}:${JSON.stringify(e)}`;function N(s,e){try{let t=JSON.parse(localStorage.getItem(H(s,e))||"null");return t&&typeof t.id=="string"&&/^[a-f0-9]{48}$/.test(t.id)&&/^[a-f0-9]{64}$/.test(t.readToken)&&/^[a-f0-9]{64}$/.test(t.writeToken)&&Number.isFinite(t.expiresAt)?t:null}catch{return null}}async function z(s,e){return s.request("checkout/status",{id:e.id,token:e.readToken})}function $(s,e){try{localStorage.removeItem(H(s,e))}catch{}}async function R(s,e,t){let a=window.open("about:blank","_blank","popup,width=520,height=780");a&&(a.opener=null);let i=N(s,e);try{if(i){let n=await z(s,i).catch(o=>{if(o instanceof m&&o.status===404)return $(s,e),i=null,null;throw o});if(n?.result?.status==="confirmed"||n?.result?.status==="reverted")return $(s,e),a?.close(),n.result;i&&n&&i.expiresAt<Date.now()&&["created","ready"].includes(n.status)&&($(s,e),i=null)}if(!i){i=await s.request("checkout/create",{placement:e,action:t,origin:window.location.origin});try{localStorage.setItem(H(s,e),JSON.stringify(i))}catch{}}let r=new URL(`/checkout/${i.id}`,s.apiUrl);if(r.hash=new URLSearchParams({token:i.writeToken}).toString(),a)a.location.replace(r.href);else throw window.location.assign(r.href),new Error("Continuing payment on Markee.");for(let n=0;n<1800;n++){let o=await z(s,i);if(o.result&&o.status==="confirmed")return $(s,e),o.result;if(o.status==="reverted")throw $(s,e),new Error("Payment reverted. Any unspent funds remain in your Markee wallet.");if(a.closed)throw new Error("Markee checkout closed. Choose Pay by card again to resume; funding alone does not complete payment.");await new Promise(c=>setTimeout(c,3e3))}throw new Error("Checkout is still pending. Reopen it to check the payment; do not pay again.")}catch(r){throw i||a?.close(),r}}function g(s,e=!1){let t=s.trim();if(!/^\d+(\.\d{0,18})?$/.test(t))throw new Error("Enter an ETH amount with up to 18 decimal places.");let[a,i=""]=t.split("."),r=BigInt(a)*10n**18n+BigInt(i.padEnd(18,"0"));if(!e&&r===0n||r>=2n**256n)throw new Error("Enter a positive amount.");return r.toString()}function p(s,e=6){let t=BigInt(s),a=t<0n?"-":"",i=t<0n?-t:t,r=(i%10n**18n).toString().padStart(18,"0").slice(0,e).replace(/0+$/,"");return i>0n&&i<10n**BigInt(18-e)?`${a}<0.${"0".repeat(e-1)}1`:`${a}${i/10n**18n}${r?`.${r}`:""}`}function S(s){return`${s.slice(0,6)}\u2026${s.slice(-4)}`}function l(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var F=`
|
|
2
2
|
:host{all:initial;font-family:var(--markee-font-family);color:var(--markee-text);font-size:14px;line-height:1.5;color-scheme:var(--markee-color-scheme)}
|
|
3
3
|
|
|
4
4
|
*{box-sizing:border-box}
|
|
@@ -104,4 +104,4 @@ footer{padding:12px 18px}
|
|
|
104
104
|
@media(prefers-reduced-motion:reduce){*{animation:none!important;scroll-behavior:auto!important}
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
-
`;var W={background:"#fbfcff",surface:"#ffffff",text:"#181b21",muted:"#687080",border:"#dce1ea",inputBackground:"#ffffff",inputText:"#202737",primary:"#282e3e",primaryText:"#ffffff",accent:"#c9f1a7",accentText:"#2b3c20",accentSurface:"#f1f7ea",accentSurfaceText:"#4e6535",accentBorder:"#cde3b5",selected:"#e9edf7",selectedText:"#242c47",info:"#edf1f9",infoText:"#52617b",error:"#fff0f0",errorText:"#9c3540",success:"#edf7e6",successText:"#40602f",link:"#4762a5",focusRing:"#5871c8",overlay:"#17203888"},U={background:"#151923",surface:"#202633",text:"#f0f3f8",muted:"#a6b1c3",border:"#434f63",inputBackground:"#10151e",inputText:"#f0f3f8",primary:"#dde6fa",primaryText:"#182238",accent:"#c9f1a7",accentText:"#24361a",accentSurface:"#243221",accentSurfaceText:"#c4e5ad",accentBorder:"#526b40",selected:"#313d53",selectedText:"#edf3ff",info:"#243149",infoText:"#bdcff1",error:"#44262e",errorText:"#ffbdc5",success:"#233b2b",successText:"#b5e4bf",link:"#adc5ff",focusRing:"#a1b4ff",overlay:"#030711b8"},j='Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',K=s=>`--markee-${s.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`;function D(s,e){let t,a=(i={})=>{t?.(),t=void 0;let r=i.mode==="system"?window.matchMedia("(prefers-color-scheme: dark)"):void 0,n=()=>{let o=i.mode==="dark"||r?.matches?"dark":"light",d=o==="dark"?U:W;s.dataset.markeeTheme=o,s.style.setProperty("--markee-color-scheme",o);for(let u of Object.keys(d)){let w=i.colors?.[u];s.style.setProperty(K(u),w&&CSS.supports("color",w)?w:d[u])}s.style.setProperty("--markee-font-family",i.fontFamily&&CSS.supports("font-family",i.fontFamily)?i.fontFamily:j);let f=typeof i.radius=="number"&&Number.isFinite(i.radius)?Math.max(0,Math.min(48,i.radius)):22;s.style.setProperty("--markee-radius",`${f}px`),s.style.setProperty("--markee-card-radius",`${f*.64}px`),s.style.setProperty("--markee-control-radius",`${f*.45}px`),s.style.setProperty("--markee-small-radius",`${f*.32}px`)};n(),r&&(r.addEventListener("change",n),t=()=>r.removeEventListener("change",n))};return a(e),{set:a,destroy(){t?.(),t=void 0}}}var v=2628000n,T=10n**15n,A=(...s)=>s.reduce((e,t)=>e>t?e:t,0n);function M(s,e){let t=s.strategy==="rent",a=t?(BigInt(s.minimum)+T-1n)/T*T:e?1n:BigInt(s.minimum),i=s.entries.filter(u=>u.address.toLowerCase()!==e?.address.toLowerCase()),r=A(...i.map(u=>BigInt(u.score))),n=!!e&&e.address.toLowerCase()===s.top?.toLowerCase();if(!t){let u=BigInt(e?.totalFunds??"0");return{minimum:a,boost:A(a,r+T-u,n?u:0n),double:n&&u>0n}}let d=!!e&&s.wallet?.backedMarkee?.toLowerCase()===e.address.toLowerCase()?BigInt(s.wallet.flowRate):0n,f=A(BigInt(e?.aggregateRate??"0")-d);return{minimum:a,boost:A(a,(r-f)*v+T,n?d*v*2n:0n),double:n&&d>0n}}var P=s=>{let e=BigInt(s);return`${e/10n**18n}.${(e%10n**18n).toString().padStart(18,"0")}`.replace(/\.?0+$/,"")||"0"},c=(s,e,t="",a="")=>`<button type="button" class="btn ${t}" data-cmd="${s}" ${a}>${e}</button>`,B=(s,e)=>/^https:\/\//.test(s)?`<a href="${l(s)}" target="_blank" rel="noopener noreferrer">${l(e)} \u2197</a>`:"",L=class{constructor(e,t){this.client=e;this.options=t;if(typeof document>"u")throw new Error("Open the Markee modal in a browser.");e.registerSite(t.placement),this.previousFocus=document.activeElement,this.previousOverflow=document.body.style.overflow,document.body.style.overflow="hidden",this.host=document.createElement("div"),this.host.setAttribute("data-markee-modal",""),this.root=this.host.attachShadow({mode:"open"}),this.theme=D(this.host,t.theme??e.options.theme),document.body.appendChild(this.host),this.root.addEventListener("click",this.onClick),this.root.addEventListener("submit",this.onSubmit),this.root.addEventListener("keydown",this.onKey),this.root.addEventListener("input",()=>{this.captureDraft(),this.updateFields()}),e.request("checkout/config").then(a=>{this.cardAvailable=a.enabled,this.render()}).catch(()=>{}),this.render(),this.root.querySelector('[data-cmd="close"]')?.focus(),this.reload(),this.watchAccount()}host;root;theme;snapshot;cardAvailable=!1;account=null;tab="main";leaderboardOpen=!1;initialSelection=!1;renderedView="";form;review;authorization;adminResult;adminProcessing=!1;result;pending;wallets;busy=!1;error="";closed=!1;epoch=0;timer;accountTimer;watched;previousFocus;previousOverflow;abort=new AbortController;drafts=new Map;viewObserver;viewed=new Set;walletChanged=()=>{this.initialSelection=!1,this.review=void 0,this.authorization=void 0,this.form=void 0,this.result=void 0,this.error="Wallet changed. Refreshing this placement\u2026",this.reload()};close(){this.closed||(this.closed=!0,this.abort.abort(),clearTimeout(this.timer),clearTimeout(this.accountTimer),this.viewObserver?.disconnect(),this.theme.destroy(),this.watched?.removeListener?.("accountsChanged",this.walletChanged),this.watched?.removeListener?.("chainChanged",this.walletChanged),this.host.remove(),document.body.style.overflow=this.previousOverflow,this.previousFocus?.focus(),this.options.onClose?.())}setTheme(e){this.closed||this.theme.set(e)}async watchAccount(){try{let e=await this.client.provider();e!==this.watched&&(this.watched?.removeListener?.("accountsChanged",this.walletChanged),this.watched?.removeListener?.("chainChanged",this.walletChanged),this.watched=e||void 0,e?.on?.("accountsChanged",this.walletChanged),e?.on?.("chainChanged",this.walletChanged)),(await this.client.account())?.toLowerCase()!==this.account?.toLowerCase()&&!this.busy&&this.walletChanged()}catch{}this.closed||(this.accountTimer=setTimeout(()=>void this.watchAccount(),2e3))}async reload(e){let t=++this.epoch;try{let a=await this.client.account(),i=await this.client.snapshot(this.options.placement,a,e,this.abort.signal);if(this.closed||t!==this.epoch)return;if(this.account=a,this.snapshot=i,this.error="",this.form&&(this.form.entry=i.entries.find(n=>n.address.toLowerCase()===this.form.entry.address.toLowerCase())??this.form.entry),!this.initialSelection&&a){this.initialSelection=!0;let n=i.entries.find(o=>o.address.toLowerCase()===i.wallet?.backedMarkee?.toLowerCase())??i.entries.find(o=>o.owner.toLowerCase()===a.toLowerCase());n&&!this.form&&!this.drafts.get("create")?.message&&(this.form={kind:i.strategy==="rent"?"stream":"fund",entry:n})}this.options.placement.kind==="gardens-community"&&(this.adminResult=this.client.communityReceipt(this.options.placement)||void 0),this.pending=a?this.client.pending(this.options.placement,a):void 0;let r=this.client.pendingAuthorization();this.adminProcessing=!!r&&this.options.placement.kind==="gardens-community"&&r.account.toLowerCase()===a?.toLowerCase()&&r.community.toLowerCase()===this.options.placement.community.toLowerCase()&&r.chainId===this.options.placement.chainId,this.render(),this.pending&&this.poll()}catch(a){!this.closed&&t===this.epoch&&this.fail(a)}}fail(e){this.error=e instanceof Error?e.message:String(e),this.render()}async task(e){if(!this.busy){this.busy=!0,this.error="",this.render();try{await e()}catch(t){this.fail(t)}finally{this.busy=!1,this.render()}}}async connect(){if(!this.client.options.wallet){let e=await C();if(e.length>1){this.wallets=e,this.render();return}}this.host.style.visibility="hidden";try{await this.client.connect()}finally{this.host.style.visibility=""}await this.reload()}async prepare(e){if(this.pending)throw new Error("Check your pending transaction before preparing another action.");if(!this.account){await this.connect();return}this.review=await this.client.prepare(this.options.placement,e),this.authorization=void 0}async poll(){if(clearTimeout(this.timer),!(!this.pending||this.closed)){try{let e=this.pending,t=await this.client.verify(e);if(this.closed||this.pending?.hash!==e.hash)return;if(t.status!=="pending"){if(this.pending=void 0,this.result=t,this.error="",await this.reload(),t.createdMarkee&&this.snapshot?.strategy==="rent"){let a=this.snapshot.entries.find(r=>r.address.toLowerCase()===t.createdMarkee.toLowerCase()),i=e.preparation.action;if(i.kind==="create"){this.form={kind:"stream",entry:a||{address:t.createdMarkee,owner:e.preparation.transaction.from,message:i.message,name:i.name,score:"0",totalFunds:"0",aggregateRate:"0",legacyFloor:"0",moderated:!1,views:0}};let r=this.drafts.get("create")?.amount;r&&this.drafts.set(this.draftKey(),{amount:r})}}this.render();return}}catch(e){this.closed||this.fail(e)}!this.closed&&this.pending&&(this.timer=setTimeout(()=>void this.poll(),5e3))}}async applyAdmin(e){if(this.authorization=void 0,this.adminProcessing=e.status==="working"||e.status==="submitted",e.status==="complete"&&(this.adminResult=e.result,await this.reload()),e.status==="failed")throw new Error(e.error||"Community action failed.")}onClick=e=>{let t=e.target.closest("[data-cmd]");if(!t)return;let a=t.dataset.cmd;if(a==="close"){this.close();return}if(!this.busy){if(this.captureDraft(),a==="leaderboard"){this.leaderboardOpen=!this.leaderboardOpen,this.render();return}if(a==="create"){this.tab="main",this.form=void 0,this.review=void 0,this.render();return}if(a.startsWith("tab:")){this.tab=a.slice(4),this.review=void 0,this.authorization=void 0,this.render();return}if(a==="back"){this.review||this.authorization||this.wallets?(this.review=void 0,this.authorization=void 0,this.wallets=void 0):this.tab!=="main"?this.tab="main":this.form?.kind.startsWith("edit")?this.form={kind:this.snapshot.strategy==="rent"?"stream":"fund",entry:this.form.entry}:this.form=void 0,this.render();return}if(a.startsWith("preset:")&&this.snapshot){let i=this.root.querySelector("#amount");if(i){let r=M(this.snapshot,this.form?.entry);i.value=P((a==="preset:min"?r.minimum:r.boost).toString()),this.captureDraft(),this.updateFields()}return}if(a.startsWith("form:")){let[,i,r]=a.split(":"),n=this.snapshot?.entries.find(o=>o.address===r);n&&(this.form={kind:i,entry:n},this.tab="main"),this.render();return}if(a==="card"&&this.snapshot?.strategy==="sale"){this.captureDraft();let i=this.root.querySelector("#markee-action");if(!i||!i.reportValidity())return;let r=new FormData(i),n;try{let d=g(String(r.get("amount")||""));n=this.form?.kind==="fund"?{kind:"fund",markee:this.form.entry.address,amount:d}:{kind:"create",message:String(r.get("message")||""),name:String(r.get("name")||""),amount:d}}catch(d){this.error=d.message,this.render();return}let o=H(this.client,this.options.placement,n);this.task(async()=>{let d=await o;if(d.status!=="confirmed")throw new Error("Payment was not confirmed.");this.result=d,this.client.options.onEvent?.({type:"confirmed",hash:d.hash}),await this.reload()});return}this.task(async()=>{if(a==="connect")await this.connect();else if(a.startsWith("wallet:"))await this.client.connect(this.wallets[Number(a.slice(7))].provider),this.wallets=void 0,await this.reload();else if(a==="refresh")await this.reload();else if(a==="more")await this.reload(this.snapshot?.nextOffset??void 0);else if(a==="send"&&this.review){let i=this.review,r=await this.client.send(i);this.pending={preparation:i,hash:r},this.review=void 0,this.form=void 0,this.result=void 0,this.poll()}else if(a==="check")await this.poll();else if(["stop","withdraw-buffer","settle"].includes(a))await this.prepare({kind:a});else if(a.startsWith("claim-refund:")||a.startsWith("connect-refund:")||a.startsWith("claim-top:")){let[i,r]=a.split(":");await this.prepare({kind:i,markee:r})}else if(a==="activate"||a==="claim"){let i=this.options.placement;if(i.kind!=="gardens-community"||!this.account)return;let r=this.account;this.authorization={kind:a,account:r,value:await this.client.authorize(i,a)},this.review=void 0}else if(a==="sign"&&this.authorization){let i=this.authorization;try{await this.applyAdmin(await this.client.executeAuthorization(i.kind,i.value,i.account))}finally{this.client.pendingAuthorization()&&(this.authorization=void 0,this.adminProcessing=!0)}}else if(a==="admin-check")await this.applyAdmin(await this.client.resumeAuthorization());else if(a==="bridge"&&this.adminResult){let i=await this.client.bridgeStatus(this.adminResult.bridgeProtocol||"none",this.adminResult.transactionHash,this.snapshot.chainId,this.options.placement.chainId);this.error=`Treasury transfer status: ${i.status.replace(/_/g," ")}.`}})}};onSubmit=e=>{if(e.preventDefault(),this.busy)return;this.captureDraft();let t=e.target,a=new FormData(t),i=r=>String(a.get(r)||"");this.task(async()=>{if(t.dataset.form==="create")this.snapshot?.strategy==="rent"&&g(i("amount")),await this.prepare({kind:"create",message:i("message"),name:i("name"),...this.snapshot?.strategy==="sale"?{amount:g(i("amount"),!0)}:{}});else if(t.dataset.form==="balance")await this.prepare({kind:i("kind"),amount:g(i("amount"))});else if(this.form){let{kind:r,entry:n}=this.form;r==="fund"?await this.prepare({kind:r,markee:n.address,amount:g(i("amount"))}):r==="stream"?await this.prepare({kind:r,markee:n.address,monthlyAmount:g(i("amount"))}):r==="edit-message"?await this.prepare({kind:r,markee:n.address,message:i("message")}):await this.prepare({kind:r,markee:n.address,name:i("name")})}})};draftKey(){return this.tab!=="main"?this.tab:this.form?`${this.form.kind}:${this.form.entry.address}`:"create"}captureDraft(){let e=this.root.querySelector("form");e&&this.drafts.set(this.draftKey(),Object.fromEntries([...new FormData(e)].map(([t,a])=>[t,String(a)])))}onKey=e=>{let t=e;if(t.key==="Escape"&&(t.preventDefault(),this.close()),t.key!=="Tab"||this.host.style.visibility==="hidden")return;let a=[...this.root.querySelectorAll("button:not(:disabled),a[href],input,textarea,select")],i=a[0],r=a[a.length-1];t.shiftKey&&this.root.activeElement===i?(t.preventDefault(),r?.focus()):!t.shiftKey&&this.root.activeElement===r&&(t.preventDefault(),i?.focus())};field(e,t,a="",i="",r=!1){let n=e==="message"?this.snapshot?.maxMessageBytes:e==="name"?this.snapshot?.maxNameBytes:void 0,o=`${e==="name"?"":"required"} ${n===void 0?"":`data-byte-limit="${n}"`} aria-describedby="${e}-hint"`;return`<div class="field"><label for="${e}">${t}${n===void 0?"":`<span class="field-count" aria-hidden="true" data-count-for="${e}"></span>`}</label>${r?`<textarea id="${e}" name="${e}" ${o} placeholder="Your message on the sign">${l(a)}</textarea>`:`<input id="${e}" name="${e}" ${e==="amount"?'inputmode="decimal"':""} value="${l(a)}" ${o}>`}${i?`<small id="${e}-hint">${i}</small>`:""}</div>`}reviewHtml(){let e=this.review,t=e.action,a=t.kind==="create"||t.kind==="edit-message"?t.message:this.form?this.entryMessage(this.form.entry):void 0,i=e.review.lines.filter(r=>!r.startsWith("Message: "));return`<h2 class="review-title">${l(e.review.title)}</h2>${a?`<section class="message-card"><p class="message">${l(a)}</p></section>`:""}<section class="review"><ul>${i.map(r=>`<li>${l(r)}</li>`).join("")}</ul><div class="stat"><span>Estimated network fee</span><strong>${p(e.review.estimatedGasCost)} ETH</strong></div><div class="stat"><span>Wallet</span><strong class="mono">${S(e.transaction.from)}</strong></div></section><p class="note">${l(e.review.reward)}</p><p class="meta">This review expires in 5 minutes. Your wallet shows the final network fee.</p>`}authorizationHtml(){let e=this.authorization,t=e.value.typedData.message;return`<div class="eyebrow">Community authorization</div><h2>${e.kind==="activate"?"Activate this community\u2019s Markee":"Claim community revenue"}</h2><p>A signed authorization lets Markee\u2019s keeper execute this action. The server rechecks your current council role before submitting it.</p><div class="card stack">${["registryCommunity","recipient","leaderboardFactory"].filter(a=>t[a]).map(a=>`<div class="meta">${l(a)}<br><strong class="mono">${l(t[a])}</strong></div>`).join("")}${["claimAmount","gasCost","maxFeeAmount"].filter(a=>t[a]!==void 0).map(a=>`<div class="stat"><span>${a==="claimAmount"?"Revenue":a==="gasCost"?"Keeper network fee":"Maximum bridge fee"}</span><strong>${p(String(t[a]))} ETH</strong></div>`).join("")}</div><p class="note">${e.kind==="claim"?"Revenue is sent to the community council treasury. Bridged claims remain pending until destination delivery is confirmed.":"This creates the community board and its revenue vault on the Markee chain."}</p>`}entryMessage(e){return e.moderated===!1?e.message:e.moderated?"This message is hidden by moderation.":"Message unavailable while moderation loads."}entriesHtml(){let e=this.snapshot,t=[...e.entries].sort((r,n)=>BigInt(r.score)>BigInt(n.score)?-1:BigInt(r.score)<BigInt(n.score)?1:0),a=[...t.filter(r=>r.owner.toLowerCase()===this.account?.toLowerCase()),...t.filter(r=>r.owner.toLowerCase()!==this.account?.toLowerCase())],i=e.board&&[8453,11155111].includes(e.chainId)?`https://${e.chainId===8453?"www":"2staging"}.markee.xyz/markee/${e.board}`:"";return`<section class="leaderboard" aria-label="Markee leaderboard"><div class="row between">${c("leaderboard",`<span class="chevron" aria-hidden="true">${this.leaderboardOpen?"\u2303":"\u2304"}</span> Leaderboard`,"text-button",`aria-expanded="${this.leaderboardOpen}" aria-controls="markee-leaderboard"`)}${B(i,"Open in Markee")}</div>${this.leaderboardOpen?`<div class="leaderboard-list" id="markee-leaderboard">${a.map(r=>{let n=r.owner.toLowerCase()===this.account?.toLowerCase(),o=r.address.toLowerCase()===e.top?.toLowerCase(),d=r.address.toLowerCase()===this.form?.entry.address.toLowerCase();return`<article class="leaderboard-entry ${o?"winner":""} ${d?"selected-entry":""}"><div class="grow"><p class="message">${l(this.entryMessage(r))}</p><div class="row entry-caption">${o?'<span class="pill">Winner</span>':""}${n?'<span class="meta">Yours</span>':""}${r.moderated===!1&&r.name?`<span class="name">${l(r.name)}</span>`:""}</div></div><div class="entry-funding"><div class="meta mono">${e.strategy==="rent"?`${p((BigInt(r.score)*v).toString())} ETH/mo`:`${p(r.totalFunds)} ETH`}</div><span class="meta">${r.views===null?"Views unavailable":`${r.views.toLocaleString()} views`}</span>${c(`form:${e.strategy==="sale"?"fund":"stream"}:${r.address}`,d?"Selected":"Fund",`compact ${d?"primary":""}`,`aria-pressed="${d}" aria-label="${d?"Selected":"Fund"} message ${S(r.address)}"`)}</div></article>`}).join("")||'<p class="empty">No Markees yet. Create the first one.</p>'}${e.strategy==="rent"&&e.rankedTop&&e.rankedTop.toLowerCase()!==e.top?.toLowerCase()?`<p class="note">The ranking has changed. ${c(`claim-top:${e.rankedTop}`,"Refresh winner","compact")}</p>`:""}${e.nextOffset!==null?c("more","Browse more messages","full"):""}</div>`:""}</section>`}selectedMessageHtml(e){let t=this.snapshot,a=t.wallet,i=e.owner.toLowerCase()===this.account?.toLowerCase(),r=t.entries.find(d=>d.owner.toLowerCase()===this.account?.toLowerCase()),n=e.address.toLowerCase()===t.top?.toLowerCase(),o=e.address.toLowerCase()===a?.backedMarkee?.toLowerCase()&&BigInt(a?.flowRate??"0")>0n;return`<section class="message-card ${n?"winner":""}"><div class="row between"><span class="eyebrow">${i?"Your Markee":"Markee you\u2019re funding"}</span>${n?'<span class="pill">Winner</span>':""}</div><p class="message">${l(this.entryMessage(e))}</p>${e.moderated===!1&&e.name?`<p class="name">${l(e.name)}</p>`:""}<div class="row message-tools">${i?c(`form:edit-message:${e.address}`,"Edit message","text-button")+c(`form:edit-name:${e.address}`,"Edit name","text-button"):""}${!i&&r?c(`form:${t.strategy==="rent"?"stream":"fund"}:${r.address}`,"Back to your Markee","text-button"):""}${c("create","Create your own Markee","text-button")}${t.strategy==="rent"&&this.account?c(`claim-refund:${e.address}`,"Collect refund","text-button"):""}</div><div class="message-stats">${t.strategy==="rent"?`<span class="meta">${o?n?"\u25CF Active stream":a?.poolConnected?"\u25CF Stream refunded while not the winner":"\u25CF Connect your refund pool in Deposit manager":"No active stream from your wallet to this message"}</span><div class="stats-grid"><div><span class="stat-label">Ranking rate</span><strong>${p((BigInt(e.score)*v).toString())} ETH/mo</strong></div><div><span class="stat-label">Your rate</span><strong>${p((o?BigInt(a.flowRate)*v:0n).toString())} ETH/mo</strong></div>${a?`<div><span class="stat-label">ETHx balance</span><strong>${p(a.ethx)} ETHx</strong></div><div><span class="stat-label">Funds remaining</span><strong title="Across all of your ETHx flows">${a.runwaySeconds===null?"No net outflow":`${(Number(a.runwaySeconds)/86400).toFixed(1)} days`}</strong></div>`:""}</div>${BigInt(e.legacyFloor)>0n?`<p class="meta">Ranking includes a decaying legacy floor of ${p((BigInt(e.legacyFloor)*v).toString())} ETH/mo.</p>`:""}`:`<div class="stats-grid"><div><span class="stat-label">Total funded</span><strong>${p(e.totalFunds)} ETH</strong></div><div><span class="stat-label">Views</span><strong>${e.views===null?"Unavailable":e.views.toLocaleString()}</strong></div></div>`}</div></section>`}fundingHtml(e){let t=this.snapshot,a=t.wallet,i=t.strategy==="rent",r=M(t,e),n=!!e&&e.address.toLowerCase()===a?.backedMarkee?.toLowerCase(),o=i&&n?BigInt(a.flowRate)*v:0n,d=BigInt(t.minimum)>r.minimum?BigInt(t.minimum):r.minimum,f=o>d?o:d,u=!i&&e?1n:BigInt(t.minimum);return`<section class="funding-card"><label for="amount">${i?"Monthly streaming rate":"Payment amount"}</label><div class="amount-row"><div class="amount-value"><input id="amount" name="amount" inputmode="decimal" value="${l(P(f.toString()))}" required aria-describedby="amount-hint"><span class="mono">${i?"ETHx/mo":"ETH"}</span></div><div class="amount-presets">${c("preset:min","MIN","compact mono",'title="Use the minimum amount"')}${c("preset:boost",r.double?"2\xD7":"WIN","compact mono",'title="Suggest an amount using the loaded ranking"')}</div></div><div class="funding-caption"><span id="amount-hint">Minimum ${P(u.toString())} ${i?"ETH/mo":"ETH"}</span><span>${a?`Balance ${p(a.eth)} ETH`:"Connect to see your balance"}</span></div><div class="funding-tools">${c("tab:wallet",i?"Deposit manager \u2192":"Wallet & rewards \u2192","text-button")}<span class="meta">${i?a?.runwaySeconds!=null?`${(Number(a.runwaySeconds)/86400).toFixed(1)} days remaining`:a?`${p(a.ethx)} ETHx available`:"ETH funds your ETHx balance":"One-time payment"}</span></div></section><p class="meta funding-hint">${i?"Unspent rent is refunded while your message is not the winner. You can stop streaming at any time.":e?"Adding funds keeps the current message owner.":"The paying wallet will own this message."} Shortcuts use the loaded ranking; positions can change.</p>`}formHtml(){let e=this.snapshot,t=this.form;return t?.kind.startsWith("edit")?`<form id="markee-action" data-form="entry"><section class="message-card"><div class="eyebrow">Your Markee</div>${t.kind==="edit-message"?this.field("message","Markee message",t.entry.message,`${e.maxMessageBytes} UTF-8 bytes maximum.`,!0):this.field("name","Your name (optional)",t.entry.name,`${e.maxNameBytes} UTF-8 bytes maximum.`)}</section></form>`:`<form id="markee-action" data-form="${t?"entry":"create"}">${t?this.selectedMessageHtml(t.entry):`<section class="message-card editor-card">${this.field("message","Markee message","",`${e.maxMessageBytes} UTF-8 bytes maximum.`,!0)}${this.field("name","Your name (optional)","",`${e.maxNameBytes} UTF-8 bytes maximum.`)}</section>`}${this.fundingHtml(t?.entry)}${!t&&e.strategy==="rent"?'<p class="note">First create your message, then review and confirm its stream. Your chosen rate is kept for the next step.</p>':""}</form>`}updateFields(){for(let t of this.root.querySelectorAll("[data-byte-limit]")){let a=Number(t.dataset.byteLimit),i=new TextEncoder().encode(t.value).length;t.setCustomValidity(i>a?`Use at most ${a} UTF-8 bytes.`:"");let r=this.root.querySelector(`[data-count-for="${t.name}"]`);r&&(r.textContent=`${i}/${a}`)}let e=this.root.querySelector("#markee-action #amount");if(e&&this.snapshot){let t=M(this.snapshot,this.form?.entry),a;try{a=BigInt(g(e.value,this.snapshot.strategy==="sale"))}catch{}let i=this.snapshot.strategy==="sale"&&this.form?1n:BigInt(this.snapshot.minimum);e.setCustomValidity(a===void 0?"Enter a valid ETH amount.":a<i?`Use at least ${P(i.toString())} ETH${this.snapshot.strategy==="rent"?" per month":""}.`:""),this.root.querySelector('[data-cmd="preset:min"]')?.setAttribute("aria-pressed",String(a===t.minimum)),this.root.querySelector('[data-cmd="preset:boost"]')?.setAttribute("aria-pressed",String(a===t.boost))}}walletHtml(){let e=this.snapshot,t=e.wallet;if(!t)return'<p class="empty">Connect your wallet to see balances and manage your Markee.</p>'+c("connect","Connect app wallet","primary full");let a=`<h2>Your wallet</h2><p class="meta mono">${l(t.address)}</p><div class="grid"><div class="card"><span class="meta">Native ETH</span><div class="metric">${p(t.eth)}</div></div><div class="card"><span class="meta">MARKEE</span><div class="metric">${t.markee===null?"Unavailable":p(t.markee,2)}</div></div></div>`;return e.strategy==="sale"?a+'<p class="note">Payments reward the paying wallet when this board has RevNet enabled. Manage your messages from the leaderboard.</p>':(a+=`<div class="divider"></div><div class="card"><div class="stat"><span>Available ETHx</span><strong>${p(t.ethx)} ETHx</strong></div><div class="stat"><span>This board\u2019s monthly rate</span><strong>${p((BigInt(t.flowRate)*2628000n).toString())} ETH</strong></div><div class="stat"><span>Refund flow / month</span><strong>${p((BigInt(t.refundRate)*2628000n).toString())} ETHx</strong></div><div class="stat"><span>Runway across all ETHx flows</span><strong>${t.runwaySeconds===null?"No net outflow":`${(Number(t.runwaySeconds)/86400).toFixed(1)} days`}</strong></div><p class="meta">Snapshot at ${new Date(t.observedAt*1e3).toLocaleTimeString()}. Balances and rates can change.</p><div class="row">${BigInt(t.flowRate)>0n?c("stop","Stop stream","danger"):""}${t.backedMarkee&&!t.poolConnected?c(`connect-refund:${t.backedMarkee}`,"Connect refund pool","accent"):""}${c("refresh","Refresh balances")}</div></div><div class="divider"></div><h3>Manage ETHx</h3><form data-form="balance"><div class="grid"><div><label for="kind">Action</label><select id="kind" name="kind"><option value="wrap">Deposit ETH \u2192 ETHx</option><option value="unwrap">Withdraw ETHx \u2192 ETH</option></select></div>${this.field("amount","Amount","0.001")}</div><button type="submit" class="btn">Review balance change</button></form><div class="divider"></div><div class="card"><h3>Buffer and rewards</h3><div class="stat"><span>Refundable board buffer</span><strong>${p(t.withdrawableDeposit)} ETHx</strong></div><div class="stat"><span>Accrued rent to settle</span><strong>${p(t.pendingSettlement)} ETH</strong></div><p class="meta">Rewards come from actual rent spent, not the ETH deposited into your wallet.</p><div class="row">${BigInt(t.withdrawableDeposit)>0n?c("withdraw-buffer","Recover buffer"):""}${BigInt(t.pendingSettlement)>0n?c("settle",e.revnetEnabled?"Claim MARKEE":"Settle rent","primary"):""}${t.backedMarkee&&BigInt(t.poolClaimable)>0n?c(`claim-refund:${t.backedMarkee}`,"Collect pool refund"):""}</div></div>`,a)}communityHtml(){let e=this.snapshot.community;return e?`<h2>Community treasury</h2><p class="muted">Community council members can activate Markee and collect community revenue.</p><div class="card"><div class="stat"><span>Integration</span><strong>${e.integration.status==="active"?"Active":"Not activated"}</strong></div><div class="stat"><span>Available revenue</span><strong>${p(e.revenue.claimableAmount)} ETH</strong></div>${e.permissions?.councilSafe?`<p class="meta">Council treasury<br><span class="mono">${l(e.permissions.councilSafe)}</span></p>`:""}<div class="row">${this.adminProcessing?'<p class="note">A signed community action is processing. Check it before authorizing another.</p>'+c("admin-check","Check community action","primary"):this.account?e.integration.status!=="active"&&e.permissions?.canActivate?c("activate","Activate community Markee","primary"):e.permissions?.canClaim&&BigInt(e.revenue.claimableAmount)>0n?c("claim","Review revenue claim","primary"):'<span class="meta">No authorized action is currently available for this wallet.</span>':c("connect","Connect council wallet","primary")}</div></div>${this.adminResult?`<div class="success">Source transaction confirmed. ${B(this.adminResult.transactionUrl||"","View transaction")}${this.adminResult.bridged?"<p>Bridge delivery is tracked separately from the source transaction.</p>":""}${c("bridge","Check transfer status")}</div>`:""}`:""}title(){let e=this.snapshot;return this.wallets?"Connect your wallet":this.review?"Review payment":this.authorization?"Review authorization":this.pending?"Payment in progress":this.tab==="wallet"?e?.strategy==="rent"?"Deposit manager":"Wallet & rewards":this.tab==="community"||e&&!e.board?"Community treasury":this.form?.kind.startsWith("edit")?"Edit your Markee":this.form?this.form.entry.owner.toLowerCase()!==this.account?.toLowerCase()?"Fund a Markee":e?.strategy==="sale"?"Fund your Markee":BigInt(e?.wallet?.flowRate??"0")>0n?"Manage your Markee stream":"Stream to your Markee":"Change the Markee Sign"}footerHtml(){let e=this.snapshot,t="";if(this.wallets)t=c("back","Back");else if(this.review)t=c("back","Back")+c("send","Confirm in wallet","primary");else if(this.authorization)t=c("back","Back")+c("sign","Sign authorization","primary");else if(this.pending)t=c("check","Check transaction","primary");else if(e&&this.tab==="main"&&e.board){let a=this.form?.kind.startsWith("edit"),i=a?c("back","Cancel"):e.strategy==="rent"&&BigInt(e.wallet?.flowRate??"0")>0n?c("stop","Stop streaming","danger"):"";t=(this.cardAvailable&&e.strategy==="sale"&&e.chainId===8453&&e.placement.kind==="board"&&e.revnetEnabled&&e.token&&!a?c("card","Pay by card","primary"):"")+i+(this.account?`<button class="btn primary" type="submit" form="markee-action">${a?"Review change":!this.form&&e.strategy==="rent"?"Review creation":"Review payment info"}</button>`:c("connect","Connect wallet","primary"))}else e&&(t=c("tab:main","Back to Markee"));return`<footer><div class="footer-actions">${t}</div><div class="footer-meta"><span>Powered by Markee${this.account?` \xB7 ${S(this.account)}`:""}</span>${e?.community&&e.board&&this.tab!=="community"&&!this.review&&!this.authorization&&!this.pending?c("tab:community","Community treasury","text-button"):""}</div></footer>`}render(){if(this.closed)return;let e=this.root.activeElement,t=e?.dataset.cmd,a=e?.id,i=this.wallets?"wallets":this.review?`review:${this.review.id}`:this.authorization?`authorization:${this.authorization.value.nonce}`:this.pending?`pending:${this.pending.hash}`:`${this.tab}:${this.form?.kind??"create"}:${this.form?.entry.address??""}`,r=i===this.renderedView?this.root.querySelector(".content")?.scrollTop??0:0;this.renderedView=i;let n=!document.activeElement||document.activeElement===document.body||document.activeElement===this.host,o=this.snapshot,d="";this.wallets?d=`<h2>Choose your wallet</h2><div class="wallets">${this.wallets.map((h,b)=>c(`wallet:${b}`,l(h.name))).join("")}</div>`:this.review?d=this.reviewHtml():this.authorization?d=this.authorizationHtml():o?this.pending?d=`<h2>Waiting for confirmation</h2><p>Your transaction was sent. You can close this modal and come back to check it.</p><p class="meta mono">${l(this.pending.hash)}</p><p class="note">Do not send a second payment while this transaction is pending.</p>`:!o.board||this.tab==="community"?d=this.communityHtml():this.tab==="wallet"?d=this.walletHtml():d=`${this.form?.kind.startsWith("edit")?"":this.entriesHtml()}${this.formHtml()}`:d=this.error?c("refresh","Retry","primary"):'<div class="loading"><span class="spinner"></span>Loading Markee\u2026</div>';let f=this.result?`<div class="${this.result.status==="reverted"||this.result.settlement==="deferred"?"error":"success"}">${this.result.status==="reverted"?"Transaction reverted. No action was completed.":this.result.settlement==="deferred"?"The transaction confirmed, but reward settlement was deferred. Your claim remains available.":`Transaction confirmed.${this.result.tokensReceived&&BigInt(this.result.tokensReceived)>0n?` ${p(this.result.tokensReceived,2)} MARKEE delivered to your wallet.`:""}`} ${B(this.result.explorerUrl,"View receipt")}</div>`:"";this.root.innerHTML=`<style>${F}</style><div class="overlay"><section class="panel" role="dialog" aria-modal="true" aria-labelledby="markee-title"><header><div class="grow"><h1 id="markee-title">${l(this.title())}</h1><p class="header-caption">${l(o?.name||"Markee")}${o?` \xB7 ${o.strategy==="rent"?"For rent":"For sale"}${o.chainId===8453?" \xB7 Base":o.chainId===11155111?" \xB7 Sepolia testnet":""}`:""}</p></div><button class="close" data-cmd="close" aria-label="Close Markee">\xD7</button></header><main class="content" aria-busy="${this.busy}"><div role="status" aria-live="polite">${this.busy?'<p class="meta"><span class="spinner"></span>Working\u2026</p>':""}${this.error?`<div class="error">${l(this.error)}</div>`:""}${f}</div>${o?.warnings.map(h=>`<div class="note">${l(h)}</div>`).join("")||""}${d}</main>${this.footerHtml()}</section></div>`,this.busy&&this.root.querySelectorAll('button:not([data-cmd="close"])').forEach(h=>{h.disabled=!0});let u=this.drafts.get(this.draftKey());if(u)for(let h of this.root.querySelectorAll("input,textarea,select"))u[h.name]!==void 0&&(h.value=u[h.name]);this.updateFields();let w=this.root.querySelector(".content");w&&(w.scrollTop=r),this.viewObserver?.disconnect();let O=this.root.querySelector(".winner"),y=o?.entries.find(h=>h.address.toLowerCase()===o.top?.toLowerCase()),I=y?`${y.address}:${y.message}`:"";O&&y?.moderated===!1&&!this.viewed.has(I)&&typeof IntersectionObserver<"u"&&(this.viewObserver=new IntersectionObserver(h=>{h.some(b=>b.isIntersecting)&&(this.viewObserver?.disconnect(),this.viewed.add(I),this.client.recordView(y.address,y.message,window.location.origin).catch(()=>{this.viewed.delete(I)}))},{threshold:.5}),this.viewObserver.observe(O)),n&&((a?this.root.getElementById(a):t?[...this.root.querySelectorAll("[data-cmd]")].find(b=>b.dataset.cmd===t):null)??this.root.querySelector('[data-cmd="close"]'))?.focus({preventScroll:!0})}};function _(s={}){let e=new x(s),t,a=s.theme;return{client:e,open(i){return t?.close(),t=new L(e,{...i,theme:i.theme??a}),t},setTheme(i){a=i??{},t?.setTheme(a)},close(){t?.close(),t=void 0}}}export{N as DEFAULT_MARKEE_API_URL,x as MarkeeClient,m as MarkeeError,L as MarkeeModal,z as checkoutStatus,_ as createMarkee,C as discoverWallets,p as formatEth,H as openHostedCheckout,g as parseEth,q as savedCheckout};
|
|
107
|
+
`;var W={background:"#fbfcff",surface:"#ffffff",text:"#181b21",muted:"#687080",border:"#dce1ea",inputBackground:"#ffffff",inputText:"#202737",primary:"#282e3e",primaryText:"#ffffff",accent:"#c9f1a7",accentText:"#2b3c20",accentSurface:"#f1f7ea",accentSurfaceText:"#4e6535",accentBorder:"#cde3b5",selected:"#e9edf7",selectedText:"#242c47",info:"#edf1f9",infoText:"#52617b",error:"#fff0f0",errorText:"#9c3540",success:"#edf7e6",successText:"#40602f",link:"#4762a5",focusRing:"#5871c8",overlay:"#17203888"},U={background:"#151923",surface:"#202633",text:"#f0f3f8",muted:"#a6b1c3",border:"#434f63",inputBackground:"#10151e",inputText:"#f0f3f8",primary:"#dde6fa",primaryText:"#182238",accent:"#c9f1a7",accentText:"#24361a",accentSurface:"#243221",accentSurfaceText:"#c4e5ad",accentBorder:"#526b40",selected:"#313d53",selectedText:"#edf3ff",info:"#243149",infoText:"#bdcff1",error:"#44262e",errorText:"#ffbdc5",success:"#233b2b",successText:"#b5e4bf",link:"#adc5ff",focusRing:"#a1b4ff",overlay:"#030711b8"},j='Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',K=s=>`--markee-${s.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`;function D(s,e){let t,a=(i={})=>{t?.(),t=void 0;let r=i.mode==="system"?window.matchMedia("(prefers-color-scheme: dark)"):void 0,n=()=>{let o=i.mode==="dark"||r?.matches?"dark":"light",c=o==="dark"?U:W;s.dataset.markeeTheme=o,s.style.setProperty("--markee-color-scheme",o);for(let u of Object.keys(c)){let w=i.colors?.[u];s.style.setProperty(K(u),w&&CSS.supports("color",w)?w:c[u])}s.style.setProperty("--markee-font-family",i.fontFamily&&CSS.supports("font-family",i.fontFamily)?i.fontFamily:j);let f=typeof i.radius=="number"&&Number.isFinite(i.radius)?Math.max(0,Math.min(48,i.radius)):22;s.style.setProperty("--markee-radius",`${f}px`),s.style.setProperty("--markee-card-radius",`${f*.64}px`),s.style.setProperty("--markee-control-radius",`${f*.45}px`),s.style.setProperty("--markee-small-radius",`${f*.32}px`)};n(),r&&(r.addEventListener("change",n),t=()=>r.removeEventListener("change",n))};return a(e),{set:a,destroy(){t?.(),t=void 0}}}var v=2628000n,T=10n**15n,A=(...s)=>s.reduce((e,t)=>e>t?e:t,0n);function M(s,e){let t=s.strategy==="rent",a=t?(BigInt(s.minimum)+T-1n)/T*T:e?1n:BigInt(s.minimum),i=s.entries.filter(u=>u.address.toLowerCase()!==e?.address.toLowerCase()),r=A(...i.map(u=>BigInt(u.score))),n=!!e&&e.address.toLowerCase()===s.top?.toLowerCase();if(!t){let u=BigInt(e?.totalFunds??"0");return{minimum:a,boost:A(a,r+T-u,n?u:0n),double:n&&u>0n}}let c=!!e&&s.wallet?.backedMarkee?.toLowerCase()===e.address.toLowerCase()?BigInt(s.wallet.flowRate):0n,f=A(BigInt(e?.aggregateRate??"0")-c);return{minimum:a,boost:A(a,(r-f)*v+T,n?c*v*2n:0n),double:n&&c>0n}}var P=s=>{let e=BigInt(s);return`${e/10n**18n}.${(e%10n**18n).toString().padStart(18,"0")}`.replace(/\.?0+$/,"")||"0"},d=(s,e,t="",a="")=>`<button type="button" class="btn ${t}" data-cmd="${s}" ${a}>${e}</button>`,B=(s,e)=>/^https:\/\//.test(s)?`<a href="${l(s)}" target="_blank" rel="noopener noreferrer">${l(e)} \u2197</a>`:"",L=class{constructor(e,t){this.client=e;this.options=t;if(typeof document>"u")throw new Error("Open the Markee modal in a browser.");e.registerSite(t.placement),this.previousFocus=document.activeElement,this.previousOverflow=document.body.style.overflow,document.body.style.overflow="hidden",this.host=document.createElement("div"),this.host.setAttribute("data-markee-modal",""),this.root=this.host.attachShadow({mode:"open"}),this.theme=D(this.host,t.theme??e.options.theme),document.body.appendChild(this.host),this.root.addEventListener("click",this.onClick),this.root.addEventListener("submit",this.onSubmit),this.root.addEventListener("keydown",this.onKey),this.root.addEventListener("input",()=>{this.captureDraft(),this.updateFields()}),e.request("checkout/config").then(a=>{this.cardAvailable=a.enabled}).catch(()=>{}).finally(()=>{this.checkoutChecked=!0,this.render()}),this.render(),this.root.querySelector('[data-cmd="close"]')?.focus(),this.reload(),this.watchAccount()}host;root;theme;snapshot;cardAvailable=!1;checkoutChecked=!1;account=null;tab="main";leaderboardOpen=!1;initialSelection=!1;renderedView="";form;review;authorization;adminResult;adminProcessing=!1;result;pending;wallets;busy=!1;error="";closed=!1;epoch=0;timer;accountTimer;watched;previousFocus;previousOverflow;abort=new AbortController;drafts=new Map;viewObserver;viewed=new Set;walletChanged=()=>{this.initialSelection=!1,this.review=void 0,this.authorization=void 0,this.form=void 0,this.tab="main",this.result=void 0,this.error="Wallet changed. Refreshing this placement\u2026",this.reload()};close(){this.closed||(this.closed=!0,this.abort.abort(),clearTimeout(this.timer),clearTimeout(this.accountTimer),this.viewObserver?.disconnect(),this.theme.destroy(),this.watched?.removeListener?.("accountsChanged",this.walletChanged),this.watched?.removeListener?.("chainChanged",this.walletChanged),this.host.remove(),document.body.style.overflow=this.previousOverflow,this.previousFocus?.focus(),this.options.onClose?.())}setTheme(e){this.closed||this.theme.set(e)}async watchAccount(){try{let e=await this.client.provider();e!==this.watched&&(this.watched?.removeListener?.("accountsChanged",this.walletChanged),this.watched?.removeListener?.("chainChanged",this.walletChanged),this.watched=e||void 0,e?.on?.("accountsChanged",this.walletChanged),e?.on?.("chainChanged",this.walletChanged)),(await this.client.account())?.toLowerCase()!==this.account?.toLowerCase()&&!this.busy&&this.walletChanged()}catch{}this.closed||(this.accountTimer=setTimeout(()=>void this.watchAccount(),2e3))}async reload(e){let t=++this.epoch;try{let a=await this.client.account().catch(()=>null),i=await this.client.snapshot(this.options.placement,a,e,this.abort.signal);if(this.closed||t!==this.epoch)return;if(this.account=a,this.snapshot=i,this.error="",this.form&&(this.form.entry=i.entries.find(n=>n.address.toLowerCase()===this.form.entry.address.toLowerCase())??this.form.entry),!this.initialSelection&&a){this.initialSelection=!0;let n=i.entries.find(o=>o.address.toLowerCase()===i.wallet?.backedMarkee?.toLowerCase())??i.entries.find(o=>o.owner.toLowerCase()===a.toLowerCase());n&&!this.form&&!this.drafts.get("create")?.message&&(this.form={kind:i.strategy==="rent"?"stream":"fund",entry:n})}this.options.placement.kind==="gardens-community"&&(this.adminResult=this.client.communityReceipt(this.options.placement)||void 0),this.pending=a?this.client.pending(this.options.placement,a):void 0;let r=this.client.pendingAuthorization();this.adminProcessing=!!r&&this.options.placement.kind==="gardens-community"&&r.account.toLowerCase()===a?.toLowerCase()&&r.community.toLowerCase()===this.options.placement.community.toLowerCase()&&r.chainId===this.options.placement.chainId,this.render(),this.pending&&this.poll()}catch(a){!this.closed&&t===this.epoch&&this.fail(a)}}fail(e){this.error=e instanceof Error?e.message:String(e),this.render()}async task(e){if(!this.busy){this.busy=!0,this.error="",this.render();try{await e()}catch(t){this.fail(t)}finally{this.busy=!1,this.render()}}}async connect(){if(!this.client.options.wallet){let e=await C();if(e.length>1){this.wallets=e,this.render();return}}this.host.style.visibility="hidden";try{await this.client.connect()}finally{this.host.style.visibility=""}await this.reload()}async prepare(e){if(this.pending)throw new Error("Check your pending transaction before preparing another action.");if(!this.account){await this.connect();return}this.review=await this.client.prepare(this.options.placement,e),this.authorization=void 0}async poll(){if(clearTimeout(this.timer),!(!this.pending||this.closed)){try{let e=this.pending,t=await this.client.verify(e);if(this.closed||this.pending?.hash!==e.hash)return;if(t.status!=="pending"){if(this.pending=void 0,this.result=t,this.error="",await this.reload(),t.createdMarkee&&this.snapshot?.strategy==="rent"){let a=this.snapshot.entries.find(r=>r.address.toLowerCase()===t.createdMarkee.toLowerCase()),i=e.preparation.action;if(i.kind==="create"){this.form={kind:"stream",entry:a||{address:t.createdMarkee,owner:e.preparation.transaction.from,message:i.message,name:i.name,score:"0",totalFunds:"0",aggregateRate:"0",legacyFloor:"0",moderated:!1,views:0}};let r=this.drafts.get("create")?.amount;r&&this.drafts.set(this.draftKey(),{amount:r})}}this.render();return}}catch(e){this.closed||this.fail(e)}!this.closed&&this.pending&&(this.timer=setTimeout(()=>void this.poll(),5e3))}}async applyAdmin(e){if(this.authorization=void 0,this.adminProcessing=e.status==="working"||e.status==="submitted",e.status==="complete"&&(this.adminResult=e.result,await this.reload()),e.status==="failed")throw new Error(e.error||"Community action failed.")}onClick=e=>{let t=e.target.closest("[data-cmd]");if(!t)return;let a=t.dataset.cmd;if(a==="close"){this.close();return}if(!this.busy){if(this.captureDraft(),a==="leaderboard"){this.leaderboardOpen=!this.leaderboardOpen,this.render();return}if(a==="create"){this.tab="main",this.form=void 0,this.review=void 0,this.render();return}if(a.startsWith("tab:")){this.tab=a.slice(4),this.review=void 0,this.authorization=void 0,this.render();return}if(a==="back"){this.review||this.authorization||this.wallets?(this.review=void 0,this.authorization=void 0,this.wallets=void 0):this.tab!=="main"?this.tab="main":this.form?.kind.startsWith("edit")?this.form={kind:this.snapshot.strategy==="rent"?"stream":"fund",entry:this.form.entry}:this.form=void 0,this.render();return}if(a.startsWith("preset:")&&this.snapshot){let i=this.root.querySelector("#amount");if(i){let r=M(this.snapshot,this.form?.entry);i.value=P((a==="preset:min"?r.minimum:r.boost).toString()),this.captureDraft(),this.updateFields()}return}if(a.startsWith("form:")){let[,i,r]=a.split(":"),n=this.snapshot?.entries.find(o=>o.address===r);n&&(this.form={kind:i,entry:n},this.tab="main"),this.render();return}if(a==="card"&&this.hostedEligible()&&this.cardAvailable){this.captureDraft();let i=this.root.querySelector("#markee-action");if(!i||!i.reportValidity())return;let r=new FormData(i),n;try{let c=g(String(r.get("amount")||""));n=this.form?.kind==="fund"?{kind:"fund",markee:this.form.entry.address,amount:c}:{kind:"create",message:String(r.get("message")||""),name:String(r.get("name")||""),amount:c}}catch(c){this.error=c.message,this.render();return}let o=R(this.client,this.options.placement,n);this.task(async()=>{let c=await o;if(c.status!=="confirmed")throw new Error("Payment was not confirmed.");this.result=c,this.client.options.onEvent?.({type:"confirmed",hash:c.hash}),await this.reload()});return}this.task(async()=>{if(a==="connect")await this.connect();else if(a.startsWith("wallet:"))await this.client.connect(this.wallets[Number(a.slice(7))].provider),this.wallets=void 0,await this.reload();else if(a==="refresh")await this.reload();else if(a==="more")await this.reload(this.snapshot?.nextOffset??void 0);else if(a==="send"&&this.review){let i=this.review,r=await this.client.send(i);this.pending={preparation:i,hash:r},this.review=void 0,this.form=void 0,this.result=void 0,this.poll()}else if(a==="check")await this.poll();else if(["stop","withdraw-buffer","settle"].includes(a))await this.prepare({kind:a});else if(a.startsWith("claim-refund:")||a.startsWith("connect-refund:")||a.startsWith("claim-top:")){let[i,r]=a.split(":");await this.prepare({kind:i,markee:r})}else if(a==="activate"||a==="claim"){let i=this.options.placement;if(i.kind!=="gardens-community"||!this.account)return;let r=this.account;this.authorization={kind:a,account:r,value:await this.client.authorize(i,a)},this.review=void 0}else if(a==="sign"&&this.authorization){let i=this.authorization;try{await this.applyAdmin(await this.client.executeAuthorization(i.kind,i.value,i.account))}finally{this.client.pendingAuthorization()&&(this.authorization=void 0,this.adminProcessing=!0)}}else if(a==="admin-check")await this.applyAdmin(await this.client.resumeAuthorization());else if(a==="bridge"&&this.adminResult){let i=await this.client.bridgeStatus(this.adminResult.bridgeProtocol||"none",this.adminResult.transactionHash,this.snapshot.chainId,this.options.placement.chainId);this.error=`Treasury transfer status: ${i.status.replace(/_/g," ")}.`}})}};onSubmit=e=>{if(e.preventDefault(),this.busy)return;if(!this.account){this.root.querySelector('[data-cmd="card"]:not(:disabled)')?.click();return}this.captureDraft();let t=e.target,a=new FormData(t),i=r=>String(a.get(r)||"");this.task(async()=>{if(t.dataset.form==="create")this.snapshot?.strategy==="rent"&&g(i("amount")),await this.prepare({kind:"create",message:i("message"),name:i("name"),...this.snapshot?.strategy==="sale"?{amount:g(i("amount"),!0)}:{}});else if(t.dataset.form==="balance")await this.prepare({kind:i("kind"),amount:g(i("amount"))});else if(this.form){let{kind:r,entry:n}=this.form;r==="fund"?await this.prepare({kind:r,markee:n.address,amount:g(i("amount"))}):r==="stream"?await this.prepare({kind:r,markee:n.address,monthlyAmount:g(i("amount"))}):r==="edit-message"?await this.prepare({kind:r,markee:n.address,message:i("message")}):await this.prepare({kind:r,markee:n.address,name:i("name")})}})};draftKey(){return this.tab!=="main"?this.tab:this.form?`${this.form.kind}:${this.form.entry.address}`:"create"}captureDraft(){let e=this.root.querySelector("form");e&&this.drafts.set(this.draftKey(),Object.fromEntries([...new FormData(e)].map(([t,a])=>[t,String(a)])))}onKey=e=>{let t=e;if(t.key==="Escape"&&(t.preventDefault(),this.close()),t.key!=="Tab"||this.host.style.visibility==="hidden")return;let a=[...this.root.querySelectorAll("button:not(:disabled),a[href],input,textarea,select")],i=a[0],r=a[a.length-1];t.shiftKey&&this.root.activeElement===i?(t.preventDefault(),r?.focus()):!t.shiftKey&&this.root.activeElement===r&&(t.preventDefault(),i?.focus())};field(e,t,a="",i="",r=!1){let n=e==="message"?this.snapshot?.maxMessageBytes:e==="name"?this.snapshot?.maxNameBytes:void 0,o=`${e==="name"?"":"required"} ${n===void 0?"":`data-byte-limit="${n}"`} aria-describedby="${e}-hint"`;return`<div class="field"><label for="${e}">${t}${n===void 0?"":`<span class="field-count" aria-hidden="true" data-count-for="${e}"></span>`}</label>${r?`<textarea id="${e}" name="${e}" ${o} placeholder="Your message on the sign">${l(a)}</textarea>`:`<input id="${e}" name="${e}" ${e==="amount"?'inputmode="decimal"':""} value="${l(a)}" ${o}>`}${i?`<small id="${e}-hint">${i}</small>`:""}</div>`}reviewHtml(){let e=this.review,t=e.action,a=t.kind==="create"||t.kind==="edit-message"?t.message:this.form?this.entryMessage(this.form.entry):void 0,i=e.review.lines.filter(r=>!r.startsWith("Message: "));return`<h2 class="review-title">${l(e.review.title)}</h2>${a?`<section class="message-card"><p class="message">${l(a)}</p></section>`:""}<section class="review"><ul>${i.map(r=>`<li>${l(r)}</li>`).join("")}</ul><div class="stat"><span>Estimated network fee</span><strong>${p(e.review.estimatedGasCost)} ETH</strong></div><div class="stat"><span>Wallet</span><strong class="mono">${S(e.transaction.from)}</strong></div></section><p class="note">${l(e.review.reward)}</p><p class="meta">This review expires in 5 minutes. Your wallet shows the final network fee.</p>`}authorizationHtml(){let e=this.authorization,t=e.value.typedData.message;return`<div class="eyebrow">Community authorization</div><h2>${e.kind==="activate"?"Activate this community\u2019s Markee":"Claim community revenue"}</h2><p>A signed authorization lets Markee\u2019s keeper execute this action. The server rechecks your current council role before submitting it.</p><div class="card stack">${["registryCommunity","recipient","leaderboardFactory"].filter(a=>t[a]).map(a=>`<div class="meta">${l(a)}<br><strong class="mono">${l(t[a])}</strong></div>`).join("")}${["claimAmount","gasCost","maxFeeAmount"].filter(a=>t[a]!==void 0).map(a=>`<div class="stat"><span>${a==="claimAmount"?"Revenue":a==="gasCost"?"Keeper network fee":"Maximum bridge fee"}</span><strong>${p(String(t[a]))} ETH</strong></div>`).join("")}</div><p class="note">${e.kind==="claim"?"Revenue is sent to the community council treasury. Bridged claims remain pending until destination delivery is confirmed.":"This creates the community board and its revenue vault on the Markee chain."}</p>`}entryMessage(e){return e.moderated===!1?e.message:e.moderated?"This message is hidden by moderation.":"Message unavailable while moderation loads."}entriesHtml(){let e=this.snapshot,t=[...e.entries].sort((r,n)=>BigInt(r.score)>BigInt(n.score)?-1:BigInt(r.score)<BigInt(n.score)?1:0),a=[...t.filter(r=>r.owner.toLowerCase()===this.account?.toLowerCase()),...t.filter(r=>r.owner.toLowerCase()!==this.account?.toLowerCase())],i=e.board&&[8453,11155111].includes(e.chainId)?`https://${e.chainId===8453?"www":"2staging"}.markee.xyz/markee/${e.board}`:"";return`<section class="leaderboard" aria-label="Markee leaderboard"><div class="row between">${d("leaderboard",`<span class="chevron" aria-hidden="true">${this.leaderboardOpen?"\u2303":"\u2304"}</span> Leaderboard`,"text-button",`aria-expanded="${this.leaderboardOpen}" aria-controls="markee-leaderboard"`)}${B(i,"Open in Markee")}</div>${this.leaderboardOpen?`<div class="leaderboard-list" id="markee-leaderboard">${a.map(r=>{let n=r.owner.toLowerCase()===this.account?.toLowerCase(),o=r.address.toLowerCase()===e.top?.toLowerCase(),c=r.address.toLowerCase()===this.form?.entry.address.toLowerCase();return`<article class="leaderboard-entry ${o?"winner":""} ${c?"selected-entry":""}"><div class="grow"><p class="message">${l(this.entryMessage(r))}</p><div class="row entry-caption">${o?'<span class="pill">Winner</span>':""}${n?'<span class="meta">Yours</span>':""}${r.moderated===!1&&r.name?`<span class="name">${l(r.name)}</span>`:""}</div></div><div class="entry-funding"><div class="meta mono">${e.strategy==="rent"?`${p((BigInt(r.score)*v).toString())} ETH/mo`:`${p(r.totalFunds)} ETH`}</div><span class="meta">${r.views===null?"Views unavailable":`${r.views.toLocaleString()} views`}</span>${d(`form:${e.strategy==="sale"?"fund":"stream"}:${r.address}`,c?"Selected":"Fund",`compact ${c?"primary":""}`,`aria-pressed="${c}" aria-label="${c?"Selected":"Fund"} message ${S(r.address)}"`)}</div></article>`}).join("")||'<p class="empty">No Markees yet. Create the first one.</p>'}${e.strategy==="rent"&&e.rankedTop&&e.rankedTop.toLowerCase()!==e.top?.toLowerCase()?`<p class="note">The ranking has changed. ${d(`claim-top:${e.rankedTop}`,"Refresh winner","compact")}</p>`:""}${e.nextOffset!==null?d("more","Browse more messages","full"):""}</div>`:""}</section>`}selectedMessageHtml(e){let t=this.snapshot,a=t.wallet,i=e.owner.toLowerCase()===this.account?.toLowerCase(),r=t.entries.find(c=>c.owner.toLowerCase()===this.account?.toLowerCase()),n=e.address.toLowerCase()===t.top?.toLowerCase(),o=e.address.toLowerCase()===a?.backedMarkee?.toLowerCase()&&BigInt(a?.flowRate??"0")>0n;return`<section class="message-card ${n?"winner":""}"><div class="row between"><span class="eyebrow">${i?"Your Markee":"Markee you\u2019re funding"}</span>${n?'<span class="pill">Winner</span>':""}</div><p class="message">${l(this.entryMessage(e))}</p>${e.moderated===!1&&e.name?`<p class="name">${l(e.name)}</p>`:""}<div class="row message-tools">${i?d(`form:edit-message:${e.address}`,"Edit message","text-button")+d(`form:edit-name:${e.address}`,"Edit name","text-button"):""}${!i&&r?d(`form:${t.strategy==="rent"?"stream":"fund"}:${r.address}`,"Back to your Markee","text-button"):""}${d("create","Create your own Markee","text-button")}${t.strategy==="rent"&&this.account?d(`claim-refund:${e.address}`,"Collect refund","text-button"):""}</div><div class="message-stats">${t.strategy==="rent"?`<span class="meta">${this.account?o?n?"\u25CF Active stream":a?.poolConnected?"\u25CF Stream refunded while not the winner":"\u25CF Connect your refund pool in Deposit manager":"No active stream from your wallet to this message":"Live message ranking"}</span><div class="stats-grid"><div><span class="stat-label">Ranking rate</span><strong>${p((BigInt(e.score)*v).toString())} ETH/mo</strong></div>${this.account?`<div><span class="stat-label">Your rate</span><strong>${p((o?BigInt(a.flowRate)*v:0n).toString())} ETH/mo</strong></div>`:""}${a?`<div><span class="stat-label">ETHx balance</span><strong>${p(a.ethx)} ETHx</strong></div><div><span class="stat-label">Funds remaining</span><strong title="Across all of your ETHx flows">${a.runwaySeconds===null?"No net outflow":`${(Number(a.runwaySeconds)/86400).toFixed(1)} days`}</strong></div>`:""}</div>${BigInt(e.legacyFloor)>0n?`<p class="meta">Ranking includes a decaying legacy floor of ${p((BigInt(e.legacyFloor)*v).toString())} ETH/mo.</p>`:""}`:`<div class="stats-grid"><div><span class="stat-label">Total funded</span><strong>${p(e.totalFunds)} ETH</strong></div><div><span class="stat-label">Views</span><strong>${e.views===null?"Unavailable":e.views.toLocaleString()}</strong></div></div>`}</div></section>`}fundingHtml(e){let t=this.snapshot,a=t.wallet,i=t.strategy==="rent",r=M(t,e),n=!!e&&e.address.toLowerCase()===a?.backedMarkee?.toLowerCase(),o=i&&n?BigInt(a.flowRate)*v:0n,c=BigInt(t.minimum)>r.minimum?BigInt(t.minimum):r.minimum,f=o>c?o:c,u=!i&&e?1n:BigInt(t.minimum);return`<section class="funding-card"><label for="amount">${i?"Monthly streaming rate":"Payment amount"}</label><div class="amount-row"><div class="amount-value"><input id="amount" name="amount" inputmode="decimal" value="${l(P(f.toString()))}" required aria-describedby="amount-hint"><span class="mono">${i?"ETHx/mo":"ETH"}</span></div><div class="amount-presets">${d("preset:min","MIN","compact mono",'title="Use the minimum amount"')}${d("preset:boost",r.double?"2\xD7":"WIN","compact mono",'title="Suggest an amount using the loaded ranking"')}</div></div><div class="funding-caption"><span id="amount-hint">Minimum ${P(u.toString())} ${i?"ETH/mo":"ETH"}</span>${this.account&&a?`<span>Balance ${p(a.eth)} ETH</span>`:""}</div><div class="funding-tools">${this.account?d("tab:wallet",i?"Deposit manager \u2192":"Wallet & rewards \u2192","text-button"):""}<span class="meta">${i?a?.runwaySeconds!=null?`${(Number(a.runwaySeconds)/86400).toFixed(1)} days remaining`:a?`${p(a.ethx)} ETHx available`:"ETH funds your ETHx balance":"One-time payment"}</span></div></section><p class="meta funding-hint">${i?"Unspent rent is refunded while your message is not the winner. You can stop streaming at any time.":e?"Adding funds keeps the current message owner.":"The paying wallet will own this message."} Shortcuts use the loaded ranking; positions can change.</p>`}formHtml(){let e=this.snapshot,t=this.form;return t?.kind.startsWith("edit")?`<form id="markee-action" data-form="entry"><section class="message-card"><div class="eyebrow">Your Markee</div>${t.kind==="edit-message"?this.field("message","Markee message",t.entry.message,`${e.maxMessageBytes} UTF-8 bytes maximum.`,!0):this.field("name","Your name (optional)",t.entry.name,`${e.maxNameBytes} UTF-8 bytes maximum.`)}</section></form>`:`<form id="markee-action" data-form="${t?"entry":"create"}">${t?this.selectedMessageHtml(t.entry):`<section class="message-card editor-card">${this.field("message","Markee message","",`${e.maxMessageBytes} UTF-8 bytes maximum.`,!0)}${this.field("name","Your name (optional)","",`${e.maxNameBytes} UTF-8 bytes maximum.`)}</section>`}${this.fundingHtml(t?.entry)}${!t&&e.strategy==="rent"?'<p class="note">First create your message, then review and confirm its stream. Your chosen rate is kept for the next step.</p>':""}</form>`}updateFields(){for(let t of this.root.querySelectorAll("[data-byte-limit]")){let a=Number(t.dataset.byteLimit),i=new TextEncoder().encode(t.value).length;t.setCustomValidity(i>a?`Use at most ${a} UTF-8 bytes.`:"");let r=this.root.querySelector(`[data-count-for="${t.name}"]`);r&&(r.textContent=`${i}/${a}`)}let e=this.root.querySelector("#markee-action #amount");if(e&&this.snapshot){let t=M(this.snapshot,this.form?.entry),a;try{a=BigInt(g(e.value,this.snapshot.strategy==="sale"))}catch{}let i=this.snapshot.strategy==="sale"&&this.form?1n:BigInt(this.snapshot.minimum);e.setCustomValidity(a===void 0?"Enter a valid ETH amount.":a<i?`Use at least ${P(i.toString())} ETH${this.snapshot.strategy==="rent"?" per month":""}.`:""),this.root.querySelector('[data-cmd="preset:min"]')?.setAttribute("aria-pressed",String(a===t.minimum)),this.root.querySelector('[data-cmd="preset:boost"]')?.setAttribute("aria-pressed",String(a===t.boost))}}walletHtml(){let e=this.snapshot,t=e.wallet;if(!t)return'<p class="empty">Connect your wallet to see balances and manage your Markee.</p>'+d("connect","Connect app wallet","primary full");let a=`<h2>Your wallet</h2><p class="meta mono">${l(t.address)}</p><div class="grid"><div class="card"><span class="meta">Native ETH</span><div class="metric">${p(t.eth)}</div></div><div class="card"><span class="meta">MARKEE</span><div class="metric">${t.markee===null?"Unavailable":p(t.markee,2)}</div></div></div>`;return e.strategy==="sale"?a+'<p class="note">Payments reward the paying wallet when this board has RevNet enabled. Manage your messages from the leaderboard.</p>':(a+=`<div class="divider"></div><div class="card"><div class="stat"><span>Available ETHx</span><strong>${p(t.ethx)} ETHx</strong></div><div class="stat"><span>This board\u2019s monthly rate</span><strong>${p((BigInt(t.flowRate)*2628000n).toString())} ETH</strong></div><div class="stat"><span>Refund flow / month</span><strong>${p((BigInt(t.refundRate)*2628000n).toString())} ETHx</strong></div><div class="stat"><span>Runway across all ETHx flows</span><strong>${t.runwaySeconds===null?"No net outflow":`${(Number(t.runwaySeconds)/86400).toFixed(1)} days`}</strong></div><p class="meta">Snapshot at ${new Date(t.observedAt*1e3).toLocaleTimeString()}. Balances and rates can change.</p><div class="row">${BigInt(t.flowRate)>0n?d("stop","Stop stream","danger"):""}${t.backedMarkee&&!t.poolConnected?d(`connect-refund:${t.backedMarkee}`,"Connect refund pool","accent"):""}${d("refresh","Refresh balances")}</div></div><div class="divider"></div><h3>Manage ETHx</h3><form data-form="balance"><div class="grid"><div><label for="kind">Action</label><select id="kind" name="kind"><option value="wrap">Deposit ETH \u2192 ETHx</option><option value="unwrap">Withdraw ETHx \u2192 ETH</option></select></div>${this.field("amount","Amount","0.001")}</div><button type="submit" class="btn">Review balance change</button></form><div class="divider"></div><div class="card"><h3>Buffer and rewards</h3><div class="stat"><span>Refundable board buffer</span><strong>${p(t.withdrawableDeposit)} ETHx</strong></div><div class="stat"><span>Accrued rent to settle</span><strong>${p(t.pendingSettlement)} ETH</strong></div><p class="meta">Rewards come from actual rent spent, not the ETH deposited into your wallet.</p><div class="row">${BigInt(t.withdrawableDeposit)>0n?d("withdraw-buffer","Recover buffer"):""}${BigInt(t.pendingSettlement)>0n?d("settle",e.revnetEnabled?"Claim MARKEE":"Settle rent","primary"):""}${t.backedMarkee&&BigInt(t.poolClaimable)>0n?d(`claim-refund:${t.backedMarkee}`,"Collect pool refund"):""}</div></div>`,a)}communityHtml(){let e=this.snapshot.community;return e?`<h2>Community treasury</h2><p class="muted">Community council members can activate Markee and collect community revenue.</p><div class="card"><div class="stat"><span>Integration</span><strong>${e.integration.status==="active"?"Active":"Not activated"}</strong></div><div class="stat"><span>Available revenue</span><strong>${p(e.revenue.claimableAmount)} ETH</strong></div>${e.permissions?.councilSafe?`<p class="meta">Council treasury<br><span class="mono">${l(e.permissions.councilSafe)}</span></p>`:""}<div class="row">${this.adminProcessing?'<p class="note">A signed community action is processing. Check it before authorizing another.</p>'+d("admin-check","Check community action","primary"):this.account?e.integration.status!=="active"&&e.permissions?.canActivate?d("activate","Activate community Markee","primary"):e.permissions?.canClaim&&BigInt(e.revenue.claimableAmount)>0n?d("claim","Review revenue claim","primary"):'<span class="meta">No authorized action is currently available for this wallet.</span>':d("connect","Connect council wallet","primary")}</div></div>${this.adminResult?`<div class="success">Source transaction confirmed. ${B(this.adminResult.transactionUrl||"","View transaction")}${this.adminResult.bridged?"<p>Bridge delivery is tracked separately from the source transaction.</p>":""}${d("bridge","Check transfer status")}</div>`:""}`:""}title(){let e=this.snapshot;return this.wallets?"Connect your wallet":this.review?"Review payment":this.authorization?"Review authorization":this.pending?"Payment in progress":this.tab==="wallet"?e?.strategy==="rent"?"Deposit manager":"Wallet & rewards":this.tab==="community"||e&&!e.board?"Community treasury":this.form?.kind.startsWith("edit")?"Edit your Markee":this.form?this.form.entry.owner.toLowerCase()!==this.account?.toLowerCase()?"Fund a Markee":e?.strategy==="sale"?"Fund your Markee":BigInt(e?.wallet?.flowRate??"0")>0n?"Manage your Markee stream":"Stream to your Markee":"Change the Markee Sign"}hostedEligible(){let e=this.snapshot;return!!e&&e.strategy==="sale"&&e.chainId===8453&&e.placement.kind==="board"&&e.revnetEnabled&&!!e.token}footerHtml(){let e=this.snapshot,t="";if(this.wallets)t=d("back","Back");else if(this.review)t=d("back","Back")+d("send","Confirm in wallet","primary");else if(this.authorization)t=d("back","Back")+d("sign","Sign authorization","primary");else if(this.pending)t=d("check","Check transaction","primary");else if(e&&this.tab==="main"&&e.board){let a=this.form?.kind.startsWith("edit"),i=a?d("back","Cancel"):e.strategy==="rent"&&BigInt(e.wallet?.flowRate??"0")>0n?d("stop","Stop streaming","danger"):"";this.account?t=(this.cardAvailable&&e.strategy==="sale"&&e.chainId===8453&&e.placement.kind==="board"&&e.revnetEnabled&&e.token&&!a?d("card","Pay by card","primary"):"")+i+(this.account?`<button class="btn primary" type="submit" form="markee-action">${a?"Review change":!this.form&&e.strategy==="rent"?"Review creation":"Review payment info"}</button>`:d("connect","Connect wallet","primary")):t=d("card","Pay","primary",!this.checkoutChecked||!this.cardAvailable||!this.hostedEligible()?"disabled":"")}else e&&(t=d("tab:main","Back to Markee"));return`<footer><div class="footer-actions">${t}</div><div class="footer-meta"><span>Powered by Markee${this.account?` \xB7 ${S(this.account)}`:""}</span>${this.account&&e?.community&&e.board&&this.tab!=="community"&&!this.review&&!this.authorization&&!this.pending?d("tab:community","Community treasury","text-button"):""}</div></footer>`}render(){if(this.closed)return;let e=this.root.activeElement,t=e?.dataset.cmd,a=e?.id,i=this.wallets?"wallets":this.review?`review:${this.review.id}`:this.authorization?`authorization:${this.authorization.value.nonce}`:this.pending?`pending:${this.pending.hash}`:`${this.tab}:${this.form?.kind??"create"}:${this.form?.entry.address??""}`,r=i===this.renderedView?this.root.querySelector(".content")?.scrollTop??0:0;this.renderedView=i;let n=!document.activeElement||document.activeElement===document.body||document.activeElement===this.host,o=this.snapshot,c="";this.wallets?c=`<h2>Choose your wallet</h2><div class="wallets">${this.wallets.map((h,b)=>d(`wallet:${b}`,l(h.name))).join("")}</div>`:this.review?c=this.reviewHtml():this.authorization?c=this.authorizationHtml():o?this.pending?c=`<h2>Waiting for confirmation</h2><p>Your transaction was sent. You can close this modal and come back to check it.</p><p class="meta mono">${l(this.pending.hash)}</p><p class="note">Do not send a second payment while this transaction is pending.</p>`:!o.board||this.tab==="community"?c=this.communityHtml():this.tab==="wallet"?c=this.walletHtml():c=`${this.form?.kind.startsWith("edit")?"":this.entriesHtml()}${this.formHtml()}${this.account?"":`<p class="note">${this.checkoutChecked?this.hostedEligible()?this.cardAvailable?"Sign in and pay on Markee. Your payment wallet and rewards are managed there.":"Pay in Markee is temporarily unavailable. Please try again later.":"Pay in Markee is not supported for this board yet.":"Checking Markee checkout availability\u2026"}</p>`}`:c=this.error?d("refresh","Retry","primary"):'<div class="loading"><span class="spinner"></span>Loading Markee\u2026</div>';let f=this.result?`<div class="${this.result.status==="reverted"||this.result.settlement==="deferred"?"error":"success"}">${this.result.status==="reverted"?"Transaction reverted. No action was completed.":this.result.settlement==="deferred"?"The transaction confirmed, but reward settlement was deferred. Your claim remains available.":`Transaction confirmed.${this.result.tokensReceived&&BigInt(this.result.tokensReceived)>0n?` ${p(this.result.tokensReceived,2)} MARKEE delivered to your wallet.`:""}`} ${B(this.result.explorerUrl,"View receipt")}</div>`:"";this.root.innerHTML=`<style>${F}</style><div class="overlay"><section class="panel" role="dialog" aria-modal="true" aria-labelledby="markee-title"><header><div class="grow"><h1 id="markee-title">${l(this.title())}</h1><p class="header-caption">${l(o?.name||"Markee")}${o?` \xB7 ${o.strategy==="rent"?"For rent":"For sale"}${o.chainId===8453?" \xB7 Base":o.chainId===11155111?" \xB7 Sepolia testnet":""}`:""}</p></div><button class="close" data-cmd="close" aria-label="Close Markee">\xD7</button></header><main class="content" aria-busy="${this.busy}"><div role="status" aria-live="polite">${this.busy?'<p class="meta"><span class="spinner"></span>Working\u2026</p>':""}${this.error?`<div class="error">${l(this.error)}</div>`:""}${f}</div>${o?.warnings.map(h=>`<div class="note">${l(h)}</div>`).join("")||""}${c}</main>${this.footerHtml()}</section></div>`,this.busy&&this.root.querySelectorAll('button:not([data-cmd="close"])').forEach(h=>{h.disabled=!0});let u=this.drafts.get(this.draftKey());if(u)for(let h of this.root.querySelectorAll("input,textarea,select"))u[h.name]!==void 0&&(h.value=u[h.name]);this.updateFields();let w=this.root.querySelector(".content");w&&(w.scrollTop=r),this.viewObserver?.disconnect();let O=this.root.querySelector(".winner"),y=o?.entries.find(h=>h.address.toLowerCase()===o.top?.toLowerCase()),I=y?`${y.address}:${y.message}`:"";O&&y?.moderated===!1&&!this.viewed.has(I)&&typeof IntersectionObserver<"u"&&(this.viewObserver=new IntersectionObserver(h=>{h.some(b=>b.isIntersecting)&&(this.viewObserver?.disconnect(),this.viewed.add(I),this.client.recordView(y.address,y.message,window.location.origin).catch(()=>{this.viewed.delete(I)}))},{threshold:.5}),this.viewObserver.observe(O)),n&&((a?this.root.getElementById(a):t?[...this.root.querySelectorAll("[data-cmd]")].find(b=>b.dataset.cmd===t):null)??this.root.querySelector('[data-cmd="close"]'))?.focus({preventScroll:!0})}};function _(s={}){let e=new x(s),t,a=s.theme;return{client:e,open(i){return t?.close(),t=new L(e,{...i,theme:i.theme??a}),t},setTheme(i){a=i??{},t?.setTheme(a)},close(){t?.close(),t=void 0}}}export{q as DEFAULT_MARKEE_API_URL,x as MarkeeClient,m as MarkeeError,L as MarkeeModal,z as checkoutStatus,_ as createMarkee,C as discoverWallets,p as formatEth,R as openHostedCheckout,g as parseEth,N as savedCheckout};
|
package/dist/modal.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ export declare class MarkeeModal {
|
|
|
14
14
|
private theme;
|
|
15
15
|
private snapshot?;
|
|
16
16
|
private cardAvailable;
|
|
17
|
+
private checkoutChecked;
|
|
17
18
|
private account;
|
|
18
19
|
private tab;
|
|
19
20
|
private leaderboardOpen;
|
|
@@ -70,6 +71,7 @@ export declare class MarkeeModal {
|
|
|
70
71
|
private walletHtml;
|
|
71
72
|
private communityHtml;
|
|
72
73
|
private title;
|
|
74
|
+
private hostedEligible;
|
|
73
75
|
private footerHtml;
|
|
74
76
|
private render;
|
|
75
77
|
}
|
package/dist/react.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use client";import{createElement as W,useEffect as H,useRef as U}from"react";var K="https://markee-git-feature-markee-sdk-1hive.vercel.app/api/sdk/v1",m=class extends Error{constructor(t,a="MARKEE_ERROR",i){super(t);this.code=a;this.status=i;this.name="MarkeeError"}};async function L(){if(typeof window>"u")return[];let n=new Map,e=a=>{let i=a.detail;i?.provider?.request&&typeof i.info?.uuid=="string"&&n.set(i.info.uuid,{uuid:i.info.uuid,name:String(i.info.name).slice(0,80),provider:i.provider})};window.addEventListener("eip6963:announceProvider",e),window.dispatchEvent(new Event("eip6963:requestProvider")),await new Promise(a=>setTimeout(a,150)),window.removeEventListener("eip6963:announceProvider",e);let t=window.ethereum;return!n.size&&t?.request&&n.set("injected",{uuid:"injected",name:"Browser wallet",provider:t}),[...n.values()]}var x=n=>typeof n=="string"&&/^0x[\da-f]{40}$/i.test(n),E=n=>typeof n=="string"&&/^0x[\da-f]{64}$/i.test(n),b=class{constructor(e={}){this.options=e;let t=new URL(e.apiUrl??K);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new m("Use an HTTPS Markee API URL (HTTP is allowed on localhost).");this.apiUrl=t.href.replace(/\/$/,""),this.fetcher=e.fetch||globalThis.fetch.bind(globalThis)}apiUrl;fetcher;injected=null;sending=!1;inMemoryPending=[];adminMemory=null;communityReceipts={};async request(e,t,a){let i=await this.fetcher(`${this.apiUrl}/${e}`,{method:t===void 0?"GET":"POST",body:t===void 0?void 0:JSON.stringify(t),headers:t===void 0?void 0:{"Content-Type":"application/json"},credentials:"omit",signal:a||AbortSignal.timeout(55e3)}),r=await i.json().catch(()=>null);if(!i.ok)throw new m(r?.error||`Markee returned HTTP ${i.status}.`,r?.code,i.status);return r}async provider(){return this.options.wallet?this.options.wallet.getProvider():this.injected}async account(){let e=await this.provider();if(!e)return null;let t=await e.request({method:"eth_accounts"});return Array.isArray(t)&&x(t[0])?t[0]:null}async connect(e){let t=await this.provider();if(this.options.wallet)t||(t=await this.options.wallet.connect?.()||null);else{if(t=e||t,!t){let i=await L();if(i.length>1)throw new m("Select a browser wallet.","SELECT_WALLET");t=i[0]?.provider||null}this.injected=t}if(!t)throw new m("Connect a wallet in the app or install a browser wallet to continue.","NO_WALLET");let a=await t.request({method:"eth_requestAccounts"});if(!Array.isArray(a)||!x(a[0]))throw new m("The wallet did not return an account.");return a[0]}verifySite(e,t){return this.request("sites/verify",{placement:e,siteUrl:t})}siteRequests=new Map;registerSite(e){if(!this.options.siteUrl)return;let t=JSON.stringify([e,this.options.siteUrl]);if(this.siteRequests.has(t))return;let a=this.verifySite(e,this.options.siteUrl);this.siteRequests.set(t,a),a.then(i=>this.options.onSiteVerification?.(i),i=>this.options.onSiteVerification?.({verified:!1,url:this.options.siteUrl,message:i instanceof Error?i.message:"Site verification failed."})).catch(()=>{})}async snapshot(e,t,a,i){let r=new URLSearchParams({placement:JSON.stringify(e)});return t&&r.set("account",t),a!==void 0&&r.set("offset",String(a)),this.request(`snapshot?${r}`,void 0,i)}async prepare(e,t){let a=await this.account();if(!a)throw new m("Connect your wallet first.","NOT_CONNECTED");return this.request("prepare",{placement:e,account:a,action:t})}async ensureWallet(e,t){let a=await this.provider();if(!a||(await this.account())?.toLowerCase()!==e.toLowerCase())throw new m("Your wallet account changed. Review this action again.","ACCOUNT_CHANGED");let i=Number(await a.request({method:"eth_chainId"}));if(i!==t&&await a.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${t.toString(16)}`}]}),i=Number(await a.request({method:"eth_chainId"})),i!==t||(await this.account())?.toLowerCase()!==e.toLowerCase())throw new m("The wallet account or network changed. Review again.","WALLET_CHANGED");return a}async send(e){if(this.sending)throw new m("A wallet request is already in progress.");if(e.expiresAt<=Date.now())throw new m("This review expired. Prepare the action again.","REVIEW_EXPIRED");if(this.pending(e.placement,e.transaction.from))throw new m("A transaction is still pending for this wallet and placement. Check it before submitting again.","PENDING_TRANSACTION");this.sending=!0;try{let a=await this.ensureWallet(e.transaction.from,e.transaction.chainId);if(e.expiresAt<=Date.now())throw new m("This review expired. Prepare the action again.","REVIEW_EXPIRED");let{chainId:i,...r}=e.transaction,s=await a.request({method:"eth_sendTransaction",params:[r]});if(!E(s))throw new m("The wallet returned an unexpected transaction identifier. Check your wallet before retrying.");return this.persist([...this.records(),{preparation:e,hash:s}]),this.options.onEvent?.({type:"submitted",hash:s}),s}catch(a){throw this.options.onEvent?.({type:"error",message:a instanceof Error?a.message:String(a)}),a}finally{this.sending=!1}}async verify(e){let t=await this.request("verify",{id:e.preparation.id,hash:e.hash});return t.status!=="pending"&&(this.persist(this.records().filter(a=>a.hash!==e.hash)),t.status==="confirmed"&&this.options.onEvent?.({type:"confirmed",hash:t.hash})),t}async reconcile(e,t){if(!E(t))throw new m("Enter a valid replacement transaction hash.");let a=await this.request("verify",{id:e.preparation.id,hash:t});return a.status!=="pending"&&this.persist(this.records().filter(i=>i.hash!==e.hash)),a}storageKey(){return`markee:sdk:v1:pending:${this.apiUrl}`}records(){try{if(typeof localStorage>"u")return this.inMemoryPending;let e=JSON.parse(localStorage.getItem(this.storageKey())||"[]");return Array.isArray(e)?e.filter(t=>E(t?.hash)&&typeof t.preparation?.id=="string"&&x(t.preparation?.transaction?.from)&&t.preparation?.placement):[]}catch{return this.inMemoryPending}}persist(e){this.inMemoryPending=e;try{typeof localStorage<"u"&&localStorage.setItem(this.storageKey(),JSON.stringify(e))}catch{}}pending(e,t){return this.records().find(a=>JSON.stringify(a.preparation.placement).toLowerCase()===JSON.stringify(e).toLowerCase()&&a.preparation.transaction.from.toLowerCase()===t.toLowerCase())}async quote(e){return this.request(`community/quote?${new URLSearchParams({chainId:String(e.chainId),community:e.community})}`)}async authorize(e,t){let a=await this.account();if(!a)throw new m("Connect your community council wallet first.");return this.request(`community/${t}`,{action:"challenge",chainId:e.chainId,community:e.community,account:a})}async executeAuthorization(e,t,a){if(this.pendingAuthorization())throw new m("An earlier community authorization is still processing. Check its status first.");let i=t.typedData,s=await(await this.ensureWallet(a,i.domain.chainId)).request({method:"eth_signTypedData_v4",params:[a,JSON.stringify({...i,types:{...i.types,EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}]}})]});if(typeof s!="string"||!/^0x[\da-f]+$/i.test(s))throw new m("Wallet did not return a typed-data signature.");return this.saveAuthorization({kind:e,nonce:t.nonce,signature:s,account:a,community:i.domain.verifyingContract,chainId:i.domain.chainId}),this.resumeAuthorization()}pendingAuthorization(){try{let e=typeof localStorage>"u"?this.adminMemory:JSON.parse(localStorage.getItem(`${this.storageKey()}:admin`)||"null");return e&&["activate","claim"].includes(e.kind)&&x(e.account)&&x(e.community)&&typeof e.nonce=="string"&&typeof e.signature=="string"?e:null}catch{return this.adminMemory}}saveAuthorization(e){this.adminMemory=e;try{typeof localStorage<"u"&&localStorage.setItem(`${this.storageKey()}:admin`,JSON.stringify(e))}catch{}}async resumeAuthorization(){let e=this.pendingAuthorization();if(!e)throw new m("There is no pending community authorization.");let t=await this.request(`community/${e.kind}`,{action:"verify",nonce:e.nonce,signature:e.signature});if(t.status==="complete"&&t.result){let a=`${e.chainId}:${e.community.toLowerCase()}`;this.communityReceipts[a]=t.result;try{typeof localStorage<"u"&&localStorage.setItem(`${this.storageKey()}:community:${a}`,JSON.stringify(t.result))}catch{}}return(t.status==="complete"||t.status==="failed")&&this.saveAuthorization(null),t}communityReceipt(e){let t=`${e.chainId}:${e.community.toLowerCase()}`;try{let a=typeof localStorage>"u"?this.communityReceipts[t]:JSON.parse(localStorage.getItem(`${this.storageKey()}:community:${t}`)||"null");return a&&E(a.transactionHash)?a:null}catch{return this.communityReceipts[t]||null}}bridgeStatus(e,t,a,i){return this.request(`community/status?${new URLSearchParams({protocol:e,transactionHash:t,fromChainId:String(a),toChainId:String(i)})}`)}recordView(e,t,a){return this.request("views",{address:e,message:t,url:a})}};var z=(n,e)=>`markee:checkout:v1:${n.apiUrl}:${JSON.stringify(e)}`;function j(n,e){try{let t=JSON.parse(localStorage.getItem(z(n,e))||"null");return t&&typeof t.id=="string"&&/^[a-f0-9]{48}$/.test(t.id)&&/^[a-f0-9]{64}$/.test(t.readToken)&&/^[a-f0-9]{64}$/.test(t.writeToken)&&Number.isFinite(t.expiresAt)?t:null}catch{return null}}async function O(n,e){return n.request("checkout/status",{id:e.id,token:e.readToken})}function $(n,e){try{localStorage.removeItem(z(n,e))}catch{}}async function N(n,e,t){let a=window.open("about:blank","_blank","popup,width=520,height=780");a&&(a.opener=null);let i=j(n,e);try{if(i){let s=await O(n,i).catch(o=>{if(o instanceof m&&o.status===404)return $(n,e),i=null,null;throw o});if(s?.result?.status==="confirmed"||s?.result?.status==="reverted")return $(n,e),a?.close(),s.result;i&&s&&i.expiresAt<Date.now()&&["created","ready"].includes(s.status)&&($(n,e),i=null)}if(!i){i=await n.request("checkout/create",{placement:e,action:t,origin:window.location.origin});try{localStorage.setItem(z(n,e),JSON.stringify(i))}catch{}}let r=new URL(`/checkout/${i.id}`,n.apiUrl);if(r.hash=new URLSearchParams({token:i.writeToken}).toString(),a)a.location.replace(r.href);else throw window.location.assign(r.href),new Error("Continuing payment on Markee.");for(let s=0;s<1800;s++){let o=await O(n,i);if(o.result&&o.status==="confirmed")return $(n,e),o.result;if(o.status==="reverted")throw $(n,e),new Error("Payment reverted. Any unspent funds remain in your Markee wallet.");if(a.closed)throw new Error("Markee checkout closed. Choose Pay by card again to resume; funding alone does not complete payment.");await new Promise(d=>setTimeout(d,3e3))}throw new Error("Checkout is still pending. Reopen it to check the payment; do not pay again.")}catch(r){throw i||a?.close(),r}}function g(n,e=!1){let t=n.trim();if(!/^\d+(\.\d{0,18})?$/.test(t))throw new Error("Enter an ETH amount with up to 18 decimal places.");let[a,i=""]=t.split("."),r=BigInt(a)*10n**18n+BigInt(i.padEnd(18,"0"));if(!e&&r===0n||r>=2n**256n)throw new Error("Enter a positive amount.");return r.toString()}function u(n,e=6){let t=BigInt(n),a=t<0n?"-":"",i=t<0n?-t:t,r=(i%10n**18n).toString().padStart(18,"0").slice(0,e).replace(/0+$/,"");return i>0n&&i<10n**BigInt(18-e)?`${a}<0.${"0".repeat(e-1)}1`:`${a}${i/10n**18n}${r?`.${r}`:""}`}function C(n){return`${n.slice(0,6)}\u2026${n.slice(-4)}`}function l(n){return String(n).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var q=`
|
|
1
|
+
"use client";import{createElement as W,useEffect as H,useRef as U}from"react";var K="https://markee-git-feature-markee-sdk-1hive.vercel.app/api/sdk/v1",m=class extends Error{constructor(t,a="MARKEE_ERROR",i){super(t);this.code=a;this.status=i;this.name="MarkeeError"}};async function L(){if(typeof window>"u")return[];let n=new Map,e=a=>{let i=a.detail;i?.provider?.request&&typeof i.info?.uuid=="string"&&n.set(i.info.uuid,{uuid:i.info.uuid,name:String(i.info.name).slice(0,80),provider:i.provider})};window.addEventListener("eip6963:announceProvider",e),window.dispatchEvent(new Event("eip6963:requestProvider")),await new Promise(a=>setTimeout(a,150)),window.removeEventListener("eip6963:announceProvider",e);let t=window.ethereum;return!n.size&&t?.request&&n.set("injected",{uuid:"injected",name:"Browser wallet",provider:t}),[...n.values()]}var x=n=>typeof n=="string"&&/^0x[\da-f]{40}$/i.test(n),E=n=>typeof n=="string"&&/^0x[\da-f]{64}$/i.test(n),b=class{constructor(e={}){this.options=e;let t=new URL(e.apiUrl??K);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new m("Use an HTTPS Markee API URL (HTTP is allowed on localhost).");this.apiUrl=t.href.replace(/\/$/,""),this.fetcher=e.fetch||globalThis.fetch.bind(globalThis)}apiUrl;fetcher;injected=null;sending=!1;inMemoryPending=[];adminMemory=null;communityReceipts={};async request(e,t,a){let i=await this.fetcher(`${this.apiUrl}/${e}`,{method:t===void 0?"GET":"POST",body:t===void 0?void 0:JSON.stringify(t),headers:t===void 0?void 0:{"Content-Type":"application/json"},credentials:"omit",signal:a||AbortSignal.timeout(55e3)}),r=await i.json().catch(()=>null);if(!i.ok)throw new m(r?.error||`Markee returned HTTP ${i.status}.`,r?.code,i.status);return r}async provider(){return this.options.wallet?this.options.wallet.getProvider():this.injected}async account(){let e=await this.provider();if(!e)return null;let t=await e.request({method:"eth_accounts"});return Array.isArray(t)&&x(t[0])?t[0]:null}async connect(e){let t=await this.provider();if(this.options.wallet)t||(t=await this.options.wallet.connect?.()||null);else{if(t=e||t,!t){let i=await L();if(i.length>1)throw new m("Select a browser wallet.","SELECT_WALLET");t=i[0]?.provider||null}this.injected=t}if(!t)throw new m("Connect a wallet in the app or install a browser wallet to continue.","NO_WALLET");let a=await t.request({method:"eth_requestAccounts"});if(!Array.isArray(a)||!x(a[0]))throw new m("The wallet did not return an account.");return a[0]}verifySite(e,t){return this.request("sites/verify",{placement:e,siteUrl:t})}siteRequests=new Map;registerSite(e){if(!this.options.siteUrl)return;let t=JSON.stringify([e,this.options.siteUrl]);if(this.siteRequests.has(t))return;let a=this.verifySite(e,this.options.siteUrl);this.siteRequests.set(t,a),a.then(i=>this.options.onSiteVerification?.(i),i=>this.options.onSiteVerification?.({verified:!1,url:this.options.siteUrl,message:i instanceof Error?i.message:"Site verification failed."})).catch(()=>{})}async snapshot(e,t,a,i){let r=new URLSearchParams({placement:JSON.stringify(e)});return t&&r.set("account",t),a!==void 0&&r.set("offset",String(a)),this.request(`snapshot?${r}`,void 0,i)}async prepare(e,t){let a=await this.account();if(!a)throw new m("Connect your wallet first.","NOT_CONNECTED");return this.request("prepare",{placement:e,account:a,action:t})}async ensureWallet(e,t){let a=await this.provider();if(!a||(await this.account())?.toLowerCase()!==e.toLowerCase())throw new m("Your wallet account changed. Review this action again.","ACCOUNT_CHANGED");let i=Number(await a.request({method:"eth_chainId"}));if(i!==t&&await a.request({method:"wallet_switchEthereumChain",params:[{chainId:`0x${t.toString(16)}`}]}),i=Number(await a.request({method:"eth_chainId"})),i!==t||(await this.account())?.toLowerCase()!==e.toLowerCase())throw new m("The wallet account or network changed. Review again.","WALLET_CHANGED");return a}async send(e){if(this.sending)throw new m("A wallet request is already in progress.");if(e.expiresAt<=Date.now())throw new m("This review expired. Prepare the action again.","REVIEW_EXPIRED");if(this.pending(e.placement,e.transaction.from))throw new m("A transaction is still pending for this wallet and placement. Check it before submitting again.","PENDING_TRANSACTION");this.sending=!0;try{let a=await this.ensureWallet(e.transaction.from,e.transaction.chainId);if(e.expiresAt<=Date.now())throw new m("This review expired. Prepare the action again.","REVIEW_EXPIRED");let{chainId:i,...r}=e.transaction,s=await a.request({method:"eth_sendTransaction",params:[r]});if(!E(s))throw new m("The wallet returned an unexpected transaction identifier. Check your wallet before retrying.");return this.persist([...this.records(),{preparation:e,hash:s}]),this.options.onEvent?.({type:"submitted",hash:s}),s}catch(a){throw this.options.onEvent?.({type:"error",message:a instanceof Error?a.message:String(a)}),a}finally{this.sending=!1}}async verify(e){let t=await this.request("verify",{id:e.preparation.id,hash:e.hash});return t.status!=="pending"&&(this.persist(this.records().filter(a=>a.hash!==e.hash)),t.status==="confirmed"&&this.options.onEvent?.({type:"confirmed",hash:t.hash})),t}async reconcile(e,t){if(!E(t))throw new m("Enter a valid replacement transaction hash.");let a=await this.request("verify",{id:e.preparation.id,hash:t});return a.status!=="pending"&&this.persist(this.records().filter(i=>i.hash!==e.hash)),a}storageKey(){return`markee:sdk:v1:pending:${this.apiUrl}`}records(){try{if(typeof localStorage>"u")return this.inMemoryPending;let e=JSON.parse(localStorage.getItem(this.storageKey())||"[]");return Array.isArray(e)?e.filter(t=>E(t?.hash)&&typeof t.preparation?.id=="string"&&x(t.preparation?.transaction?.from)&&t.preparation?.placement):[]}catch{return this.inMemoryPending}}persist(e){this.inMemoryPending=e;try{typeof localStorage<"u"&&localStorage.setItem(this.storageKey(),JSON.stringify(e))}catch{}}pending(e,t){return this.records().find(a=>JSON.stringify(a.preparation.placement).toLowerCase()===JSON.stringify(e).toLowerCase()&&a.preparation.transaction.from.toLowerCase()===t.toLowerCase())}async quote(e){return this.request(`community/quote?${new URLSearchParams({chainId:String(e.chainId),community:e.community})}`)}async authorize(e,t){let a=await this.account();if(!a)throw new m("Connect your community council wallet first.");return this.request(`community/${t}`,{action:"challenge",chainId:e.chainId,community:e.community,account:a})}async executeAuthorization(e,t,a){if(this.pendingAuthorization())throw new m("An earlier community authorization is still processing. Check its status first.");let i=t.typedData,s=await(await this.ensureWallet(a,i.domain.chainId)).request({method:"eth_signTypedData_v4",params:[a,JSON.stringify({...i,types:{...i.types,EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"}]}})]});if(typeof s!="string"||!/^0x[\da-f]+$/i.test(s))throw new m("Wallet did not return a typed-data signature.");return this.saveAuthorization({kind:e,nonce:t.nonce,signature:s,account:a,community:i.domain.verifyingContract,chainId:i.domain.chainId}),this.resumeAuthorization()}pendingAuthorization(){try{let e=typeof localStorage>"u"?this.adminMemory:JSON.parse(localStorage.getItem(`${this.storageKey()}:admin`)||"null");return e&&["activate","claim"].includes(e.kind)&&x(e.account)&&x(e.community)&&typeof e.nonce=="string"&&typeof e.signature=="string"?e:null}catch{return this.adminMemory}}saveAuthorization(e){this.adminMemory=e;try{typeof localStorage<"u"&&localStorage.setItem(`${this.storageKey()}:admin`,JSON.stringify(e))}catch{}}async resumeAuthorization(){let e=this.pendingAuthorization();if(!e)throw new m("There is no pending community authorization.");let t=await this.request(`community/${e.kind}`,{action:"verify",nonce:e.nonce,signature:e.signature});if(t.status==="complete"&&t.result){let a=`${e.chainId}:${e.community.toLowerCase()}`;this.communityReceipts[a]=t.result;try{typeof localStorage<"u"&&localStorage.setItem(`${this.storageKey()}:community:${a}`,JSON.stringify(t.result))}catch{}}return(t.status==="complete"||t.status==="failed")&&this.saveAuthorization(null),t}communityReceipt(e){let t=`${e.chainId}:${e.community.toLowerCase()}`;try{let a=typeof localStorage>"u"?this.communityReceipts[t]:JSON.parse(localStorage.getItem(`${this.storageKey()}:community:${t}`)||"null");return a&&E(a.transactionHash)?a:null}catch{return this.communityReceipts[t]||null}}bridgeStatus(e,t,a,i){return this.request(`community/status?${new URLSearchParams({protocol:e,transactionHash:t,fromChainId:String(a),toChainId:String(i)})}`)}recordView(e,t,a){return this.request("views",{address:e,message:t,url:a})}};var I=(n,e)=>`markee:checkout:v1:${n.apiUrl}:${JSON.stringify(e)}`;function j(n,e){try{let t=JSON.parse(localStorage.getItem(I(n,e))||"null");return t&&typeof t.id=="string"&&/^[a-f0-9]{48}$/.test(t.id)&&/^[a-f0-9]{64}$/.test(t.readToken)&&/^[a-f0-9]{64}$/.test(t.writeToken)&&Number.isFinite(t.expiresAt)?t:null}catch{return null}}async function O(n,e){return n.request("checkout/status",{id:e.id,token:e.readToken})}function $(n,e){try{localStorage.removeItem(I(n,e))}catch{}}async function N(n,e,t){let a=window.open("about:blank","_blank","popup,width=520,height=780");a&&(a.opener=null);let i=j(n,e);try{if(i){let s=await O(n,i).catch(o=>{if(o instanceof m&&o.status===404)return $(n,e),i=null,null;throw o});if(s?.result?.status==="confirmed"||s?.result?.status==="reverted")return $(n,e),a?.close(),s.result;i&&s&&i.expiresAt<Date.now()&&["created","ready"].includes(s.status)&&($(n,e),i=null)}if(!i){i=await n.request("checkout/create",{placement:e,action:t,origin:window.location.origin});try{localStorage.setItem(I(n,e),JSON.stringify(i))}catch{}}let r=new URL(`/checkout/${i.id}`,n.apiUrl);if(r.hash=new URLSearchParams({token:i.writeToken}).toString(),a)a.location.replace(r.href);else throw window.location.assign(r.href),new Error("Continuing payment on Markee.");for(let s=0;s<1800;s++){let o=await O(n,i);if(o.result&&o.status==="confirmed")return $(n,e),o.result;if(o.status==="reverted")throw $(n,e),new Error("Payment reverted. Any unspent funds remain in your Markee wallet.");if(a.closed)throw new Error("Markee checkout closed. Choose Pay by card again to resume; funding alone does not complete payment.");await new Promise(d=>setTimeout(d,3e3))}throw new Error("Checkout is still pending. Reopen it to check the payment; do not pay again.")}catch(r){throw i||a?.close(),r}}function g(n,e=!1){let t=n.trim();if(!/^\d+(\.\d{0,18})?$/.test(t))throw new Error("Enter an ETH amount with up to 18 decimal places.");let[a,i=""]=t.split("."),r=BigInt(a)*10n**18n+BigInt(i.padEnd(18,"0"));if(!e&&r===0n||r>=2n**256n)throw new Error("Enter a positive amount.");return r.toString()}function u(n,e=6){let t=BigInt(n),a=t<0n?"-":"",i=t<0n?-t:t,r=(i%10n**18n).toString().padStart(18,"0").slice(0,e).replace(/0+$/,"");return i>0n&&i<10n**BigInt(18-e)?`${a}<0.${"0".repeat(e-1)}1`:`${a}${i/10n**18n}${r?`.${r}`:""}`}function C(n){return`${n.slice(0,6)}\u2026${n.slice(-4)}`}function l(n){return String(n).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var q=`
|
|
2
2
|
:host{all:initial;font-family:var(--markee-font-family);color:var(--markee-text);font-size:14px;line-height:1.5;color-scheme:var(--markee-color-scheme)}
|
|
3
3
|
|
|
4
4
|
*{box-sizing:border-box}
|
|
@@ -104,4 +104,4 @@ footer{padding:12px 18px}
|
|
|
104
104
|
@media(prefers-reduced-motion:reduce){*{animation:none!important;scroll-behavior:auto!important}
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
-
`;var _={background:"#fbfcff",surface:"#ffffff",text:"#181b21",muted:"#687080",border:"#dce1ea",inputBackground:"#ffffff",inputText:"#202737",primary:"#282e3e",primaryText:"#ffffff",accent:"#c9f1a7",accentText:"#2b3c20",accentSurface:"#f1f7ea",accentSurfaceText:"#4e6535",accentBorder:"#cde3b5",selected:"#e9edf7",selectedText:"#242c47",info:"#edf1f9",infoText:"#52617b",error:"#fff0f0",errorText:"#9c3540",success:"#edf7e6",successText:"#40602f",link:"#4762a5",focusRing:"#5871c8",overlay:"#17203888"},V={background:"#151923",surface:"#202633",text:"#f0f3f8",muted:"#a6b1c3",border:"#434f63",inputBackground:"#10151e",inputText:"#f0f3f8",primary:"#dde6fa",primaryText:"#182238",accent:"#c9f1a7",accentText:"#24361a",accentSurface:"#243221",accentSurfaceText:"#c4e5ad",accentBorder:"#526b40",selected:"#313d53",selectedText:"#edf3ff",info:"#243149",infoText:"#bdcff1",error:"#44262e",errorText:"#ffbdc5",success:"#233b2b",successText:"#b5e4bf",link:"#adc5ff",focusRing:"#a1b4ff",overlay:"#030711b8"},J='Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',Y=n=>`--markee-${n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`;function F(n,e){let t,a=(i={})=>{t?.(),t=void 0;let r=i.mode==="system"?window.matchMedia("(prefers-color-scheme: dark)"):void 0,s=()=>{let o=i.mode==="dark"||r?.matches?"dark":"light",d=o==="dark"?V:_;n.dataset.markeeTheme=o,n.style.setProperty("--markee-color-scheme",o);for(let p of Object.keys(d)){let w=i.colors?.[p];n.style.setProperty(Y(p),w&&CSS.supports("color",w)?w:d[p])}n.style.setProperty("--markee-font-family",i.fontFamily&&CSS.supports("font-family",i.fontFamily)?i.fontFamily:J);let f=typeof i.radius=="number"&&Number.isFinite(i.radius)?Math.max(0,Math.min(48,i.radius)):22;n.style.setProperty("--markee-radius",`${f}px`),n.style.setProperty("--markee-card-radius",`${f*.64}px`),n.style.setProperty("--markee-control-radius",`${f*.45}px`),n.style.setProperty("--markee-small-radius",`${f*.32}px`)};s(),r&&(r.addEventListener("change",s),t=()=>r.removeEventListener("change",s))};return a(e),{set:a,destroy(){t?.(),t=void 0}}}var v=2628000n,T=10n**15n,S=(...n)=>n.reduce((e,t)=>e>t?e:t,0n);function A(n,e){let t=n.strategy==="rent",a=t?(BigInt(n.minimum)+T-1n)/T*T:e?1n:BigInt(n.minimum),i=n.entries.filter(p=>p.address.toLowerCase()!==e?.address.toLowerCase()),r=S(...i.map(p=>BigInt(p.score))),s=!!e&&e.address.toLowerCase()===n.top?.toLowerCase();if(!t){let p=BigInt(e?.totalFunds??"0");return{minimum:a,boost:S(a,r+T-p,s?p:0n),double:s&&p>0n}}let d=!!e&&n.wallet?.backedMarkee?.toLowerCase()===e.address.toLowerCase()?BigInt(n.wallet.flowRate):0n,f=S(BigInt(e?.aggregateRate??"0")-d);return{minimum:a,boost:S(a,(r-f)*v+T,s?d*v*2n:0n),double:s&&d>0n}}var M=n=>{let e=BigInt(n);return`${e/10n**18n}.${(e%10n**18n).toString().padStart(18,"0")}`.replace(/\.?0+$/,"")||"0"},c=(n,e,t="",a="")=>`<button type="button" class="btn ${t}" data-cmd="${n}" ${a}>${e}</button>`,I=(n,e)=>/^https:\/\//.test(n)?`<a href="${l(n)}" target="_blank" rel="noopener noreferrer">${l(e)} \u2197</a>`:"",R=class{constructor(e,t){this.client=e;this.options=t;if(typeof document>"u")throw new Error("Open the Markee modal in a browser.");e.registerSite(t.placement),this.previousFocus=document.activeElement,this.previousOverflow=document.body.style.overflow,document.body.style.overflow="hidden",this.host=document.createElement("div"),this.host.setAttribute("data-markee-modal",""),this.root=this.host.attachShadow({mode:"open"}),this.theme=F(this.host,t.theme??e.options.theme),document.body.appendChild(this.host),this.root.addEventListener("click",this.onClick),this.root.addEventListener("submit",this.onSubmit),this.root.addEventListener("keydown",this.onKey),this.root.addEventListener("input",()=>{this.captureDraft(),this.updateFields()}),e.request("checkout/config").then(a=>{this.cardAvailable=a.enabled,this.render()}).catch(()=>{}),this.render(),this.root.querySelector('[data-cmd="close"]')?.focus(),this.reload(),this.watchAccount()}host;root;theme;snapshot;cardAvailable=!1;account=null;tab="main";leaderboardOpen=!1;initialSelection=!1;renderedView="";form;review;authorization;adminResult;adminProcessing=!1;result;pending;wallets;busy=!1;error="";closed=!1;epoch=0;timer;accountTimer;watched;previousFocus;previousOverflow;abort=new AbortController;drafts=new Map;viewObserver;viewed=new Set;walletChanged=()=>{this.initialSelection=!1,this.review=void 0,this.authorization=void 0,this.form=void 0,this.result=void 0,this.error="Wallet changed. Refreshing this placement\u2026",this.reload()};close(){this.closed||(this.closed=!0,this.abort.abort(),clearTimeout(this.timer),clearTimeout(this.accountTimer),this.viewObserver?.disconnect(),this.theme.destroy(),this.watched?.removeListener?.("accountsChanged",this.walletChanged),this.watched?.removeListener?.("chainChanged",this.walletChanged),this.host.remove(),document.body.style.overflow=this.previousOverflow,this.previousFocus?.focus(),this.options.onClose?.())}setTheme(e){this.closed||this.theme.set(e)}async watchAccount(){try{let e=await this.client.provider();e!==this.watched&&(this.watched?.removeListener?.("accountsChanged",this.walletChanged),this.watched?.removeListener?.("chainChanged",this.walletChanged),this.watched=e||void 0,e?.on?.("accountsChanged",this.walletChanged),e?.on?.("chainChanged",this.walletChanged)),(await this.client.account())?.toLowerCase()!==this.account?.toLowerCase()&&!this.busy&&this.walletChanged()}catch{}this.closed||(this.accountTimer=setTimeout(()=>void this.watchAccount(),2e3))}async reload(e){let t=++this.epoch;try{let a=await this.client.account(),i=await this.client.snapshot(this.options.placement,a,e,this.abort.signal);if(this.closed||t!==this.epoch)return;if(this.account=a,this.snapshot=i,this.error="",this.form&&(this.form.entry=i.entries.find(s=>s.address.toLowerCase()===this.form.entry.address.toLowerCase())??this.form.entry),!this.initialSelection&&a){this.initialSelection=!0;let s=i.entries.find(o=>o.address.toLowerCase()===i.wallet?.backedMarkee?.toLowerCase())??i.entries.find(o=>o.owner.toLowerCase()===a.toLowerCase());s&&!this.form&&!this.drafts.get("create")?.message&&(this.form={kind:i.strategy==="rent"?"stream":"fund",entry:s})}this.options.placement.kind==="gardens-community"&&(this.adminResult=this.client.communityReceipt(this.options.placement)||void 0),this.pending=a?this.client.pending(this.options.placement,a):void 0;let r=this.client.pendingAuthorization();this.adminProcessing=!!r&&this.options.placement.kind==="gardens-community"&&r.account.toLowerCase()===a?.toLowerCase()&&r.community.toLowerCase()===this.options.placement.community.toLowerCase()&&r.chainId===this.options.placement.chainId,this.render(),this.pending&&this.poll()}catch(a){!this.closed&&t===this.epoch&&this.fail(a)}}fail(e){this.error=e instanceof Error?e.message:String(e),this.render()}async task(e){if(!this.busy){this.busy=!0,this.error="",this.render();try{await e()}catch(t){this.fail(t)}finally{this.busy=!1,this.render()}}}async connect(){if(!this.client.options.wallet){let e=await L();if(e.length>1){this.wallets=e,this.render();return}}this.host.style.visibility="hidden";try{await this.client.connect()}finally{this.host.style.visibility=""}await this.reload()}async prepare(e){if(this.pending)throw new Error("Check your pending transaction before preparing another action.");if(!this.account){await this.connect();return}this.review=await this.client.prepare(this.options.placement,e),this.authorization=void 0}async poll(){if(clearTimeout(this.timer),!(!this.pending||this.closed)){try{let e=this.pending,t=await this.client.verify(e);if(this.closed||this.pending?.hash!==e.hash)return;if(t.status!=="pending"){if(this.pending=void 0,this.result=t,this.error="",await this.reload(),t.createdMarkee&&this.snapshot?.strategy==="rent"){let a=this.snapshot.entries.find(r=>r.address.toLowerCase()===t.createdMarkee.toLowerCase()),i=e.preparation.action;if(i.kind==="create"){this.form={kind:"stream",entry:a||{address:t.createdMarkee,owner:e.preparation.transaction.from,message:i.message,name:i.name,score:"0",totalFunds:"0",aggregateRate:"0",legacyFloor:"0",moderated:!1,views:0}};let r=this.drafts.get("create")?.amount;r&&this.drafts.set(this.draftKey(),{amount:r})}}this.render();return}}catch(e){this.closed||this.fail(e)}!this.closed&&this.pending&&(this.timer=setTimeout(()=>void this.poll(),5e3))}}async applyAdmin(e){if(this.authorization=void 0,this.adminProcessing=e.status==="working"||e.status==="submitted",e.status==="complete"&&(this.adminResult=e.result,await this.reload()),e.status==="failed")throw new Error(e.error||"Community action failed.")}onClick=e=>{let t=e.target.closest("[data-cmd]");if(!t)return;let a=t.dataset.cmd;if(a==="close"){this.close();return}if(!this.busy){if(this.captureDraft(),a==="leaderboard"){this.leaderboardOpen=!this.leaderboardOpen,this.render();return}if(a==="create"){this.tab="main",this.form=void 0,this.review=void 0,this.render();return}if(a.startsWith("tab:")){this.tab=a.slice(4),this.review=void 0,this.authorization=void 0,this.render();return}if(a==="back"){this.review||this.authorization||this.wallets?(this.review=void 0,this.authorization=void 0,this.wallets=void 0):this.tab!=="main"?this.tab="main":this.form?.kind.startsWith("edit")?this.form={kind:this.snapshot.strategy==="rent"?"stream":"fund",entry:this.form.entry}:this.form=void 0,this.render();return}if(a.startsWith("preset:")&&this.snapshot){let i=this.root.querySelector("#amount");if(i){let r=A(this.snapshot,this.form?.entry);i.value=M((a==="preset:min"?r.minimum:r.boost).toString()),this.captureDraft(),this.updateFields()}return}if(a.startsWith("form:")){let[,i,r]=a.split(":"),s=this.snapshot?.entries.find(o=>o.address===r);s&&(this.form={kind:i,entry:s},this.tab="main"),this.render();return}if(a==="card"&&this.snapshot?.strategy==="sale"){this.captureDraft();let i=this.root.querySelector("#markee-action");if(!i||!i.reportValidity())return;let r=new FormData(i),s;try{let d=g(String(r.get("amount")||""));s=this.form?.kind==="fund"?{kind:"fund",markee:this.form.entry.address,amount:d}:{kind:"create",message:String(r.get("message")||""),name:String(r.get("name")||""),amount:d}}catch(d){this.error=d.message,this.render();return}let o=N(this.client,this.options.placement,s);this.task(async()=>{let d=await o;if(d.status!=="confirmed")throw new Error("Payment was not confirmed.");this.result=d,this.client.options.onEvent?.({type:"confirmed",hash:d.hash}),await this.reload()});return}this.task(async()=>{if(a==="connect")await this.connect();else if(a.startsWith("wallet:"))await this.client.connect(this.wallets[Number(a.slice(7))].provider),this.wallets=void 0,await this.reload();else if(a==="refresh")await this.reload();else if(a==="more")await this.reload(this.snapshot?.nextOffset??void 0);else if(a==="send"&&this.review){let i=this.review,r=await this.client.send(i);this.pending={preparation:i,hash:r},this.review=void 0,this.form=void 0,this.result=void 0,this.poll()}else if(a==="check")await this.poll();else if(["stop","withdraw-buffer","settle"].includes(a))await this.prepare({kind:a});else if(a.startsWith("claim-refund:")||a.startsWith("connect-refund:")||a.startsWith("claim-top:")){let[i,r]=a.split(":");await this.prepare({kind:i,markee:r})}else if(a==="activate"||a==="claim"){let i=this.options.placement;if(i.kind!=="gardens-community"||!this.account)return;let r=this.account;this.authorization={kind:a,account:r,value:await this.client.authorize(i,a)},this.review=void 0}else if(a==="sign"&&this.authorization){let i=this.authorization;try{await this.applyAdmin(await this.client.executeAuthorization(i.kind,i.value,i.account))}finally{this.client.pendingAuthorization()&&(this.authorization=void 0,this.adminProcessing=!0)}}else if(a==="admin-check")await this.applyAdmin(await this.client.resumeAuthorization());else if(a==="bridge"&&this.adminResult){let i=await this.client.bridgeStatus(this.adminResult.bridgeProtocol||"none",this.adminResult.transactionHash,this.snapshot.chainId,this.options.placement.chainId);this.error=`Treasury transfer status: ${i.status.replace(/_/g," ")}.`}})}};onSubmit=e=>{if(e.preventDefault(),this.busy)return;this.captureDraft();let t=e.target,a=new FormData(t),i=r=>String(a.get(r)||"");this.task(async()=>{if(t.dataset.form==="create")this.snapshot?.strategy==="rent"&&g(i("amount")),await this.prepare({kind:"create",message:i("message"),name:i("name"),...this.snapshot?.strategy==="sale"?{amount:g(i("amount"),!0)}:{}});else if(t.dataset.form==="balance")await this.prepare({kind:i("kind"),amount:g(i("amount"))});else if(this.form){let{kind:r,entry:s}=this.form;r==="fund"?await this.prepare({kind:r,markee:s.address,amount:g(i("amount"))}):r==="stream"?await this.prepare({kind:r,markee:s.address,monthlyAmount:g(i("amount"))}):r==="edit-message"?await this.prepare({kind:r,markee:s.address,message:i("message")}):await this.prepare({kind:r,markee:s.address,name:i("name")})}})};draftKey(){return this.tab!=="main"?this.tab:this.form?`${this.form.kind}:${this.form.entry.address}`:"create"}captureDraft(){let e=this.root.querySelector("form");e&&this.drafts.set(this.draftKey(),Object.fromEntries([...new FormData(e)].map(([t,a])=>[t,String(a)])))}onKey=e=>{let t=e;if(t.key==="Escape"&&(t.preventDefault(),this.close()),t.key!=="Tab"||this.host.style.visibility==="hidden")return;let a=[...this.root.querySelectorAll("button:not(:disabled),a[href],input,textarea,select")],i=a[0],r=a[a.length-1];t.shiftKey&&this.root.activeElement===i?(t.preventDefault(),r?.focus()):!t.shiftKey&&this.root.activeElement===r&&(t.preventDefault(),i?.focus())};field(e,t,a="",i="",r=!1){let s=e==="message"?this.snapshot?.maxMessageBytes:e==="name"?this.snapshot?.maxNameBytes:void 0,o=`${e==="name"?"":"required"} ${s===void 0?"":`data-byte-limit="${s}"`} aria-describedby="${e}-hint"`;return`<div class="field"><label for="${e}">${t}${s===void 0?"":`<span class="field-count" aria-hidden="true" data-count-for="${e}"></span>`}</label>${r?`<textarea id="${e}" name="${e}" ${o} placeholder="Your message on the sign">${l(a)}</textarea>`:`<input id="${e}" name="${e}" ${e==="amount"?'inputmode="decimal"':""} value="${l(a)}" ${o}>`}${i?`<small id="${e}-hint">${i}</small>`:""}</div>`}reviewHtml(){let e=this.review,t=e.action,a=t.kind==="create"||t.kind==="edit-message"?t.message:this.form?this.entryMessage(this.form.entry):void 0,i=e.review.lines.filter(r=>!r.startsWith("Message: "));return`<h2 class="review-title">${l(e.review.title)}</h2>${a?`<section class="message-card"><p class="message">${l(a)}</p></section>`:""}<section class="review"><ul>${i.map(r=>`<li>${l(r)}</li>`).join("")}</ul><div class="stat"><span>Estimated network fee</span><strong>${u(e.review.estimatedGasCost)} ETH</strong></div><div class="stat"><span>Wallet</span><strong class="mono">${C(e.transaction.from)}</strong></div></section><p class="note">${l(e.review.reward)}</p><p class="meta">This review expires in 5 minutes. Your wallet shows the final network fee.</p>`}authorizationHtml(){let e=this.authorization,t=e.value.typedData.message;return`<div class="eyebrow">Community authorization</div><h2>${e.kind==="activate"?"Activate this community\u2019s Markee":"Claim community revenue"}</h2><p>A signed authorization lets Markee\u2019s keeper execute this action. The server rechecks your current council role before submitting it.</p><div class="card stack">${["registryCommunity","recipient","leaderboardFactory"].filter(a=>t[a]).map(a=>`<div class="meta">${l(a)}<br><strong class="mono">${l(t[a])}</strong></div>`).join("")}${["claimAmount","gasCost","maxFeeAmount"].filter(a=>t[a]!==void 0).map(a=>`<div class="stat"><span>${a==="claimAmount"?"Revenue":a==="gasCost"?"Keeper network fee":"Maximum bridge fee"}</span><strong>${u(String(t[a]))} ETH</strong></div>`).join("")}</div><p class="note">${e.kind==="claim"?"Revenue is sent to the community council treasury. Bridged claims remain pending until destination delivery is confirmed.":"This creates the community board and its revenue vault on the Markee chain."}</p>`}entryMessage(e){return e.moderated===!1?e.message:e.moderated?"This message is hidden by moderation.":"Message unavailable while moderation loads."}entriesHtml(){let e=this.snapshot,t=[...e.entries].sort((r,s)=>BigInt(r.score)>BigInt(s.score)?-1:BigInt(r.score)<BigInt(s.score)?1:0),a=[...t.filter(r=>r.owner.toLowerCase()===this.account?.toLowerCase()),...t.filter(r=>r.owner.toLowerCase()!==this.account?.toLowerCase())],i=e.board&&[8453,11155111].includes(e.chainId)?`https://${e.chainId===8453?"www":"2staging"}.markee.xyz/markee/${e.board}`:"";return`<section class="leaderboard" aria-label="Markee leaderboard"><div class="row between">${c("leaderboard",`<span class="chevron" aria-hidden="true">${this.leaderboardOpen?"\u2303":"\u2304"}</span> Leaderboard`,"text-button",`aria-expanded="${this.leaderboardOpen}" aria-controls="markee-leaderboard"`)}${I(i,"Open in Markee")}</div>${this.leaderboardOpen?`<div class="leaderboard-list" id="markee-leaderboard">${a.map(r=>{let s=r.owner.toLowerCase()===this.account?.toLowerCase(),o=r.address.toLowerCase()===e.top?.toLowerCase(),d=r.address.toLowerCase()===this.form?.entry.address.toLowerCase();return`<article class="leaderboard-entry ${o?"winner":""} ${d?"selected-entry":""}"><div class="grow"><p class="message">${l(this.entryMessage(r))}</p><div class="row entry-caption">${o?'<span class="pill">Winner</span>':""}${s?'<span class="meta">Yours</span>':""}${r.moderated===!1&&r.name?`<span class="name">${l(r.name)}</span>`:""}</div></div><div class="entry-funding"><div class="meta mono">${e.strategy==="rent"?`${u((BigInt(r.score)*v).toString())} ETH/mo`:`${u(r.totalFunds)} ETH`}</div><span class="meta">${r.views===null?"Views unavailable":`${r.views.toLocaleString()} views`}</span>${c(`form:${e.strategy==="sale"?"fund":"stream"}:${r.address}`,d?"Selected":"Fund",`compact ${d?"primary":""}`,`aria-pressed="${d}" aria-label="${d?"Selected":"Fund"} message ${C(r.address)}"`)}</div></article>`}).join("")||'<p class="empty">No Markees yet. Create the first one.</p>'}${e.strategy==="rent"&&e.rankedTop&&e.rankedTop.toLowerCase()!==e.top?.toLowerCase()?`<p class="note">The ranking has changed. ${c(`claim-top:${e.rankedTop}`,"Refresh winner","compact")}</p>`:""}${e.nextOffset!==null?c("more","Browse more messages","full"):""}</div>`:""}</section>`}selectedMessageHtml(e){let t=this.snapshot,a=t.wallet,i=e.owner.toLowerCase()===this.account?.toLowerCase(),r=t.entries.find(d=>d.owner.toLowerCase()===this.account?.toLowerCase()),s=e.address.toLowerCase()===t.top?.toLowerCase(),o=e.address.toLowerCase()===a?.backedMarkee?.toLowerCase()&&BigInt(a?.flowRate??"0")>0n;return`<section class="message-card ${s?"winner":""}"><div class="row between"><span class="eyebrow">${i?"Your Markee":"Markee you\u2019re funding"}</span>${s?'<span class="pill">Winner</span>':""}</div><p class="message">${l(this.entryMessage(e))}</p>${e.moderated===!1&&e.name?`<p class="name">${l(e.name)}</p>`:""}<div class="row message-tools">${i?c(`form:edit-message:${e.address}`,"Edit message","text-button")+c(`form:edit-name:${e.address}`,"Edit name","text-button"):""}${!i&&r?c(`form:${t.strategy==="rent"?"stream":"fund"}:${r.address}`,"Back to your Markee","text-button"):""}${c("create","Create your own Markee","text-button")}${t.strategy==="rent"&&this.account?c(`claim-refund:${e.address}`,"Collect refund","text-button"):""}</div><div class="message-stats">${t.strategy==="rent"?`<span class="meta">${o?s?"\u25CF Active stream":a?.poolConnected?"\u25CF Stream refunded while not the winner":"\u25CF Connect your refund pool in Deposit manager":"No active stream from your wallet to this message"}</span><div class="stats-grid"><div><span class="stat-label">Ranking rate</span><strong>${u((BigInt(e.score)*v).toString())} ETH/mo</strong></div><div><span class="stat-label">Your rate</span><strong>${u((o?BigInt(a.flowRate)*v:0n).toString())} ETH/mo</strong></div>${a?`<div><span class="stat-label">ETHx balance</span><strong>${u(a.ethx)} ETHx</strong></div><div><span class="stat-label">Funds remaining</span><strong title="Across all of your ETHx flows">${a.runwaySeconds===null?"No net outflow":`${(Number(a.runwaySeconds)/86400).toFixed(1)} days`}</strong></div>`:""}</div>${BigInt(e.legacyFloor)>0n?`<p class="meta">Ranking includes a decaying legacy floor of ${u((BigInt(e.legacyFloor)*v).toString())} ETH/mo.</p>`:""}`:`<div class="stats-grid"><div><span class="stat-label">Total funded</span><strong>${u(e.totalFunds)} ETH</strong></div><div><span class="stat-label">Views</span><strong>${e.views===null?"Unavailable":e.views.toLocaleString()}</strong></div></div>`}</div></section>`}fundingHtml(e){let t=this.snapshot,a=t.wallet,i=t.strategy==="rent",r=A(t,e),s=!!e&&e.address.toLowerCase()===a?.backedMarkee?.toLowerCase(),o=i&&s?BigInt(a.flowRate)*v:0n,d=BigInt(t.minimum)>r.minimum?BigInt(t.minimum):r.minimum,f=o>d?o:d,p=!i&&e?1n:BigInt(t.minimum);return`<section class="funding-card"><label for="amount">${i?"Monthly streaming rate":"Payment amount"}</label><div class="amount-row"><div class="amount-value"><input id="amount" name="amount" inputmode="decimal" value="${l(M(f.toString()))}" required aria-describedby="amount-hint"><span class="mono">${i?"ETHx/mo":"ETH"}</span></div><div class="amount-presets">${c("preset:min","MIN","compact mono",'title="Use the minimum amount"')}${c("preset:boost",r.double?"2\xD7":"WIN","compact mono",'title="Suggest an amount using the loaded ranking"')}</div></div><div class="funding-caption"><span id="amount-hint">Minimum ${M(p.toString())} ${i?"ETH/mo":"ETH"}</span><span>${a?`Balance ${u(a.eth)} ETH`:"Connect to see your balance"}</span></div><div class="funding-tools">${c("tab:wallet",i?"Deposit manager \u2192":"Wallet & rewards \u2192","text-button")}<span class="meta">${i?a?.runwaySeconds!=null?`${(Number(a.runwaySeconds)/86400).toFixed(1)} days remaining`:a?`${u(a.ethx)} ETHx available`:"ETH funds your ETHx balance":"One-time payment"}</span></div></section><p class="meta funding-hint">${i?"Unspent rent is refunded while your message is not the winner. You can stop streaming at any time.":e?"Adding funds keeps the current message owner.":"The paying wallet will own this message."} Shortcuts use the loaded ranking; positions can change.</p>`}formHtml(){let e=this.snapshot,t=this.form;return t?.kind.startsWith("edit")?`<form id="markee-action" data-form="entry"><section class="message-card"><div class="eyebrow">Your Markee</div>${t.kind==="edit-message"?this.field("message","Markee message",t.entry.message,`${e.maxMessageBytes} UTF-8 bytes maximum.`,!0):this.field("name","Your name (optional)",t.entry.name,`${e.maxNameBytes} UTF-8 bytes maximum.`)}</section></form>`:`<form id="markee-action" data-form="${t?"entry":"create"}">${t?this.selectedMessageHtml(t.entry):`<section class="message-card editor-card">${this.field("message","Markee message","",`${e.maxMessageBytes} UTF-8 bytes maximum.`,!0)}${this.field("name","Your name (optional)","",`${e.maxNameBytes} UTF-8 bytes maximum.`)}</section>`}${this.fundingHtml(t?.entry)}${!t&&e.strategy==="rent"?'<p class="note">First create your message, then review and confirm its stream. Your chosen rate is kept for the next step.</p>':""}</form>`}updateFields(){for(let t of this.root.querySelectorAll("[data-byte-limit]")){let a=Number(t.dataset.byteLimit),i=new TextEncoder().encode(t.value).length;t.setCustomValidity(i>a?`Use at most ${a} UTF-8 bytes.`:"");let r=this.root.querySelector(`[data-count-for="${t.name}"]`);r&&(r.textContent=`${i}/${a}`)}let e=this.root.querySelector("#markee-action #amount");if(e&&this.snapshot){let t=A(this.snapshot,this.form?.entry),a;try{a=BigInt(g(e.value,this.snapshot.strategy==="sale"))}catch{}let i=this.snapshot.strategy==="sale"&&this.form?1n:BigInt(this.snapshot.minimum);e.setCustomValidity(a===void 0?"Enter a valid ETH amount.":a<i?`Use at least ${M(i.toString())} ETH${this.snapshot.strategy==="rent"?" per month":""}.`:""),this.root.querySelector('[data-cmd="preset:min"]')?.setAttribute("aria-pressed",String(a===t.minimum)),this.root.querySelector('[data-cmd="preset:boost"]')?.setAttribute("aria-pressed",String(a===t.boost))}}walletHtml(){let e=this.snapshot,t=e.wallet;if(!t)return'<p class="empty">Connect your wallet to see balances and manage your Markee.</p>'+c("connect","Connect app wallet","primary full");let a=`<h2>Your wallet</h2><p class="meta mono">${l(t.address)}</p><div class="grid"><div class="card"><span class="meta">Native ETH</span><div class="metric">${u(t.eth)}</div></div><div class="card"><span class="meta">MARKEE</span><div class="metric">${t.markee===null?"Unavailable":u(t.markee,2)}</div></div></div>`;return e.strategy==="sale"?a+'<p class="note">Payments reward the paying wallet when this board has RevNet enabled. Manage your messages from the leaderboard.</p>':(a+=`<div class="divider"></div><div class="card"><div class="stat"><span>Available ETHx</span><strong>${u(t.ethx)} ETHx</strong></div><div class="stat"><span>This board\u2019s monthly rate</span><strong>${u((BigInt(t.flowRate)*2628000n).toString())} ETH</strong></div><div class="stat"><span>Refund flow / month</span><strong>${u((BigInt(t.refundRate)*2628000n).toString())} ETHx</strong></div><div class="stat"><span>Runway across all ETHx flows</span><strong>${t.runwaySeconds===null?"No net outflow":`${(Number(t.runwaySeconds)/86400).toFixed(1)} days`}</strong></div><p class="meta">Snapshot at ${new Date(t.observedAt*1e3).toLocaleTimeString()}. Balances and rates can change.</p><div class="row">${BigInt(t.flowRate)>0n?c("stop","Stop stream","danger"):""}${t.backedMarkee&&!t.poolConnected?c(`connect-refund:${t.backedMarkee}`,"Connect refund pool","accent"):""}${c("refresh","Refresh balances")}</div></div><div class="divider"></div><h3>Manage ETHx</h3><form data-form="balance"><div class="grid"><div><label for="kind">Action</label><select id="kind" name="kind"><option value="wrap">Deposit ETH \u2192 ETHx</option><option value="unwrap">Withdraw ETHx \u2192 ETH</option></select></div>${this.field("amount","Amount","0.001")}</div><button type="submit" class="btn">Review balance change</button></form><div class="divider"></div><div class="card"><h3>Buffer and rewards</h3><div class="stat"><span>Refundable board buffer</span><strong>${u(t.withdrawableDeposit)} ETHx</strong></div><div class="stat"><span>Accrued rent to settle</span><strong>${u(t.pendingSettlement)} ETH</strong></div><p class="meta">Rewards come from actual rent spent, not the ETH deposited into your wallet.</p><div class="row">${BigInt(t.withdrawableDeposit)>0n?c("withdraw-buffer","Recover buffer"):""}${BigInt(t.pendingSettlement)>0n?c("settle",e.revnetEnabled?"Claim MARKEE":"Settle rent","primary"):""}${t.backedMarkee&&BigInt(t.poolClaimable)>0n?c(`claim-refund:${t.backedMarkee}`,"Collect pool refund"):""}</div></div>`,a)}communityHtml(){let e=this.snapshot.community;return e?`<h2>Community treasury</h2><p class="muted">Community council members can activate Markee and collect community revenue.</p><div class="card"><div class="stat"><span>Integration</span><strong>${e.integration.status==="active"?"Active":"Not activated"}</strong></div><div class="stat"><span>Available revenue</span><strong>${u(e.revenue.claimableAmount)} ETH</strong></div>${e.permissions?.councilSafe?`<p class="meta">Council treasury<br><span class="mono">${l(e.permissions.councilSafe)}</span></p>`:""}<div class="row">${this.adminProcessing?'<p class="note">A signed community action is processing. Check it before authorizing another.</p>'+c("admin-check","Check community action","primary"):this.account?e.integration.status!=="active"&&e.permissions?.canActivate?c("activate","Activate community Markee","primary"):e.permissions?.canClaim&&BigInt(e.revenue.claimableAmount)>0n?c("claim","Review revenue claim","primary"):'<span class="meta">No authorized action is currently available for this wallet.</span>':c("connect","Connect council wallet","primary")}</div></div>${this.adminResult?`<div class="success">Source transaction confirmed. ${I(this.adminResult.transactionUrl||"","View transaction")}${this.adminResult.bridged?"<p>Bridge delivery is tracked separately from the source transaction.</p>":""}${c("bridge","Check transfer status")}</div>`:""}`:""}title(){let e=this.snapshot;return this.wallets?"Connect your wallet":this.review?"Review payment":this.authorization?"Review authorization":this.pending?"Payment in progress":this.tab==="wallet"?e?.strategy==="rent"?"Deposit manager":"Wallet & rewards":this.tab==="community"||e&&!e.board?"Community treasury":this.form?.kind.startsWith("edit")?"Edit your Markee":this.form?this.form.entry.owner.toLowerCase()!==this.account?.toLowerCase()?"Fund a Markee":e?.strategy==="sale"?"Fund your Markee":BigInt(e?.wallet?.flowRate??"0")>0n?"Manage your Markee stream":"Stream to your Markee":"Change the Markee Sign"}footerHtml(){let e=this.snapshot,t="";if(this.wallets)t=c("back","Back");else if(this.review)t=c("back","Back")+c("send","Confirm in wallet","primary");else if(this.authorization)t=c("back","Back")+c("sign","Sign authorization","primary");else if(this.pending)t=c("check","Check transaction","primary");else if(e&&this.tab==="main"&&e.board){let a=this.form?.kind.startsWith("edit"),i=a?c("back","Cancel"):e.strategy==="rent"&&BigInt(e.wallet?.flowRate??"0")>0n?c("stop","Stop streaming","danger"):"";t=(this.cardAvailable&&e.strategy==="sale"&&e.chainId===8453&&e.placement.kind==="board"&&e.revnetEnabled&&e.token&&!a?c("card","Pay by card","primary"):"")+i+(this.account?`<button class="btn primary" type="submit" form="markee-action">${a?"Review change":!this.form&&e.strategy==="rent"?"Review creation":"Review payment info"}</button>`:c("connect","Connect wallet","primary"))}else e&&(t=c("tab:main","Back to Markee"));return`<footer><div class="footer-actions">${t}</div><div class="footer-meta"><span>Powered by Markee${this.account?` \xB7 ${C(this.account)}`:""}</span>${e?.community&&e.board&&this.tab!=="community"&&!this.review&&!this.authorization&&!this.pending?c("tab:community","Community treasury","text-button"):""}</div></footer>`}render(){if(this.closed)return;let e=this.root.activeElement,t=e?.dataset.cmd,a=e?.id,i=this.wallets?"wallets":this.review?`review:${this.review.id}`:this.authorization?`authorization:${this.authorization.value.nonce}`:this.pending?`pending:${this.pending.hash}`:`${this.tab}:${this.form?.kind??"create"}:${this.form?.entry.address??""}`,r=i===this.renderedView?this.root.querySelector(".content")?.scrollTop??0:0;this.renderedView=i;let s=!document.activeElement||document.activeElement===document.body||document.activeElement===this.host,o=this.snapshot,d="";this.wallets?d=`<h2>Choose your wallet</h2><div class="wallets">${this.wallets.map((h,k)=>c(`wallet:${k}`,l(h.name))).join("")}</div>`:this.review?d=this.reviewHtml():this.authorization?d=this.authorizationHtml():o?this.pending?d=`<h2>Waiting for confirmation</h2><p>Your transaction was sent. You can close this modal and come back to check it.</p><p class="meta mono">${l(this.pending.hash)}</p><p class="note">Do not send a second payment while this transaction is pending.</p>`:!o.board||this.tab==="community"?d=this.communityHtml():this.tab==="wallet"?d=this.walletHtml():d=`${this.form?.kind.startsWith("edit")?"":this.entriesHtml()}${this.formHtml()}`:d=this.error?c("refresh","Retry","primary"):'<div class="loading"><span class="spinner"></span>Loading Markee\u2026</div>';let f=this.result?`<div class="${this.result.status==="reverted"||this.result.settlement==="deferred"?"error":"success"}">${this.result.status==="reverted"?"Transaction reverted. No action was completed.":this.result.settlement==="deferred"?"The transaction confirmed, but reward settlement was deferred. Your claim remains available.":`Transaction confirmed.${this.result.tokensReceived&&BigInt(this.result.tokensReceived)>0n?` ${u(this.result.tokensReceived,2)} MARKEE delivered to your wallet.`:""}`} ${I(this.result.explorerUrl,"View receipt")}</div>`:"";this.root.innerHTML=`<style>${q}</style><div class="overlay"><section class="panel" role="dialog" aria-modal="true" aria-labelledby="markee-title"><header><div class="grow"><h1 id="markee-title">${l(this.title())}</h1><p class="header-caption">${l(o?.name||"Markee")}${o?` \xB7 ${o.strategy==="rent"?"For rent":"For sale"}${o.chainId===8453?" \xB7 Base":o.chainId===11155111?" \xB7 Sepolia testnet":""}`:""}</p></div><button class="close" data-cmd="close" aria-label="Close Markee">\xD7</button></header><main class="content" aria-busy="${this.busy}"><div role="status" aria-live="polite">${this.busy?'<p class="meta"><span class="spinner"></span>Working\u2026</p>':""}${this.error?`<div class="error">${l(this.error)}</div>`:""}${f}</div>${o?.warnings.map(h=>`<div class="note">${l(h)}</div>`).join("")||""}${d}</main>${this.footerHtml()}</section></div>`,this.busy&&this.root.querySelectorAll('button:not([data-cmd="close"])').forEach(h=>{h.disabled=!0});let p=this.drafts.get(this.draftKey());if(p)for(let h of this.root.querySelectorAll("input,textarea,select"))p[h.name]!==void 0&&(h.value=p[h.name]);this.updateFields();let w=this.root.querySelector(".content");w&&(w.scrollTop=r),this.viewObserver?.disconnect();let B=this.root.querySelector(".winner"),y=o?.entries.find(h=>h.address.toLowerCase()===o.top?.toLowerCase()),P=y?`${y.address}:${y.message}`:"";B&&y?.moderated===!1&&!this.viewed.has(P)&&typeof IntersectionObserver<"u"&&(this.viewObserver=new IntersectionObserver(h=>{h.some(k=>k.isIntersecting)&&(this.viewObserver?.disconnect(),this.viewed.add(P),this.client.recordView(y.address,y.message,window.location.origin).catch(()=>{this.viewed.delete(P)}))},{threshold:.5}),this.viewObserver.observe(B)),s&&((a?this.root.getElementById(a):t?[...this.root.querySelectorAll("[data-cmd]")].find(k=>k.dataset.cmd===t):null)??this.root.querySelector('[data-cmd="close"]'))?.focus({preventScroll:!0})}};function D(n={}){let e=new b(n),t,a=n.theme;return{client:e,open(i){return t?.close(),t=new R(e,{...i,theme:i.theme??a}),t},setTheme(i){a=i??{},t?.setTheme(a)},close(){t?.close(),t=void 0}}}function pe(n){let e=U(n);e.current=n;let t=U(),a=JSON.stringify(n.placement);return H(()=>{if(!n.siteUrl)return;new b({apiUrl:n.apiUrl,fetch:n.fetch,siteUrl:n.siteUrl,onSiteVerification:r=>e.current.onSiteVerification?.(r)}).registerSite(n.placement)},[n.siteUrl,n.apiUrl,n.fetch,a]),H(()=>{if(!n.open)return;let i=D({apiUrl:n.apiUrl,fetch:n.fetch,theme:e.current.theme,wallet:n.wallet?{getProvider:()=>e.current.wallet.getProvider(),connect:()=>{let s=e.current.wallet?.connect;return s?s():Promise.reject(new Error("Connect the app wallet first."))}}:void 0,onEvent:s=>e.current.onEvent?.(s)});t.current=i;let r=!1;return i.open({placement:n.placement,onClose:()=>{r||e.current.onClose()}}),()=>{r=!0,i.close(),t.current=void 0}},[n.open,n.apiUrl,n.fetch,!!n.wallet,a]),H(()=>{t.current?.setTheme(n.theme)},[n.theme]),n.placement.kind==="board"?W("span",{hidden:!0,"data-markee-address":n.placement.address}):null}function he({children:n="Open Markee",onClick:e,...t}){return W("button",{...t,type:"button",onClick:e},n)}export{he as MarkeeButton,pe as MarkeeModal};
|
|
107
|
+
`;var _={background:"#fbfcff",surface:"#ffffff",text:"#181b21",muted:"#687080",border:"#dce1ea",inputBackground:"#ffffff",inputText:"#202737",primary:"#282e3e",primaryText:"#ffffff",accent:"#c9f1a7",accentText:"#2b3c20",accentSurface:"#f1f7ea",accentSurfaceText:"#4e6535",accentBorder:"#cde3b5",selected:"#e9edf7",selectedText:"#242c47",info:"#edf1f9",infoText:"#52617b",error:"#fff0f0",errorText:"#9c3540",success:"#edf7e6",successText:"#40602f",link:"#4762a5",focusRing:"#5871c8",overlay:"#17203888"},V={background:"#151923",surface:"#202633",text:"#f0f3f8",muted:"#a6b1c3",border:"#434f63",inputBackground:"#10151e",inputText:"#f0f3f8",primary:"#dde6fa",primaryText:"#182238",accent:"#c9f1a7",accentText:"#24361a",accentSurface:"#243221",accentSurfaceText:"#c4e5ad",accentBorder:"#526b40",selected:"#313d53",selectedText:"#edf3ff",info:"#243149",infoText:"#bdcff1",error:"#44262e",errorText:"#ffbdc5",success:"#233b2b",successText:"#b5e4bf",link:"#adc5ff",focusRing:"#a1b4ff",overlay:"#030711b8"},J='Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',Y=n=>`--markee-${n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`;function F(n,e){let t,a=(i={})=>{t?.(),t=void 0;let r=i.mode==="system"?window.matchMedia("(prefers-color-scheme: dark)"):void 0,s=()=>{let o=i.mode==="dark"||r?.matches?"dark":"light",d=o==="dark"?V:_;n.dataset.markeeTheme=o,n.style.setProperty("--markee-color-scheme",o);for(let p of Object.keys(d)){let w=i.colors?.[p];n.style.setProperty(Y(p),w&&CSS.supports("color",w)?w:d[p])}n.style.setProperty("--markee-font-family",i.fontFamily&&CSS.supports("font-family",i.fontFamily)?i.fontFamily:J);let f=typeof i.radius=="number"&&Number.isFinite(i.radius)?Math.max(0,Math.min(48,i.radius)):22;n.style.setProperty("--markee-radius",`${f}px`),n.style.setProperty("--markee-card-radius",`${f*.64}px`),n.style.setProperty("--markee-control-radius",`${f*.45}px`),n.style.setProperty("--markee-small-radius",`${f*.32}px`)};s(),r&&(r.addEventListener("change",s),t=()=>r.removeEventListener("change",s))};return a(e),{set:a,destroy(){t?.(),t=void 0}}}var v=2628000n,T=10n**15n,S=(...n)=>n.reduce((e,t)=>e>t?e:t,0n);function M(n,e){let t=n.strategy==="rent",a=t?(BigInt(n.minimum)+T-1n)/T*T:e?1n:BigInt(n.minimum),i=n.entries.filter(p=>p.address.toLowerCase()!==e?.address.toLowerCase()),r=S(...i.map(p=>BigInt(p.score))),s=!!e&&e.address.toLowerCase()===n.top?.toLowerCase();if(!t){let p=BigInt(e?.totalFunds??"0");return{minimum:a,boost:S(a,r+T-p,s?p:0n),double:s&&p>0n}}let d=!!e&&n.wallet?.backedMarkee?.toLowerCase()===e.address.toLowerCase()?BigInt(n.wallet.flowRate):0n,f=S(BigInt(e?.aggregateRate??"0")-d);return{minimum:a,boost:S(a,(r-f)*v+T,s?d*v*2n:0n),double:s&&d>0n}}var A=n=>{let e=BigInt(n);return`${e/10n**18n}.${(e%10n**18n).toString().padStart(18,"0")}`.replace(/\.?0+$/,"")||"0"},c=(n,e,t="",a="")=>`<button type="button" class="btn ${t}" data-cmd="${n}" ${a}>${e}</button>`,z=(n,e)=>/^https:\/\//.test(n)?`<a href="${l(n)}" target="_blank" rel="noopener noreferrer">${l(e)} \u2197</a>`:"",R=class{constructor(e,t){this.client=e;this.options=t;if(typeof document>"u")throw new Error("Open the Markee modal in a browser.");e.registerSite(t.placement),this.previousFocus=document.activeElement,this.previousOverflow=document.body.style.overflow,document.body.style.overflow="hidden",this.host=document.createElement("div"),this.host.setAttribute("data-markee-modal",""),this.root=this.host.attachShadow({mode:"open"}),this.theme=F(this.host,t.theme??e.options.theme),document.body.appendChild(this.host),this.root.addEventListener("click",this.onClick),this.root.addEventListener("submit",this.onSubmit),this.root.addEventListener("keydown",this.onKey),this.root.addEventListener("input",()=>{this.captureDraft(),this.updateFields()}),e.request("checkout/config").then(a=>{this.cardAvailable=a.enabled}).catch(()=>{}).finally(()=>{this.checkoutChecked=!0,this.render()}),this.render(),this.root.querySelector('[data-cmd="close"]')?.focus(),this.reload(),this.watchAccount()}host;root;theme;snapshot;cardAvailable=!1;checkoutChecked=!1;account=null;tab="main";leaderboardOpen=!1;initialSelection=!1;renderedView="";form;review;authorization;adminResult;adminProcessing=!1;result;pending;wallets;busy=!1;error="";closed=!1;epoch=0;timer;accountTimer;watched;previousFocus;previousOverflow;abort=new AbortController;drafts=new Map;viewObserver;viewed=new Set;walletChanged=()=>{this.initialSelection=!1,this.review=void 0,this.authorization=void 0,this.form=void 0,this.tab="main",this.result=void 0,this.error="Wallet changed. Refreshing this placement\u2026",this.reload()};close(){this.closed||(this.closed=!0,this.abort.abort(),clearTimeout(this.timer),clearTimeout(this.accountTimer),this.viewObserver?.disconnect(),this.theme.destroy(),this.watched?.removeListener?.("accountsChanged",this.walletChanged),this.watched?.removeListener?.("chainChanged",this.walletChanged),this.host.remove(),document.body.style.overflow=this.previousOverflow,this.previousFocus?.focus(),this.options.onClose?.())}setTheme(e){this.closed||this.theme.set(e)}async watchAccount(){try{let e=await this.client.provider();e!==this.watched&&(this.watched?.removeListener?.("accountsChanged",this.walletChanged),this.watched?.removeListener?.("chainChanged",this.walletChanged),this.watched=e||void 0,e?.on?.("accountsChanged",this.walletChanged),e?.on?.("chainChanged",this.walletChanged)),(await this.client.account())?.toLowerCase()!==this.account?.toLowerCase()&&!this.busy&&this.walletChanged()}catch{}this.closed||(this.accountTimer=setTimeout(()=>void this.watchAccount(),2e3))}async reload(e){let t=++this.epoch;try{let a=await this.client.account().catch(()=>null),i=await this.client.snapshot(this.options.placement,a,e,this.abort.signal);if(this.closed||t!==this.epoch)return;if(this.account=a,this.snapshot=i,this.error="",this.form&&(this.form.entry=i.entries.find(s=>s.address.toLowerCase()===this.form.entry.address.toLowerCase())??this.form.entry),!this.initialSelection&&a){this.initialSelection=!0;let s=i.entries.find(o=>o.address.toLowerCase()===i.wallet?.backedMarkee?.toLowerCase())??i.entries.find(o=>o.owner.toLowerCase()===a.toLowerCase());s&&!this.form&&!this.drafts.get("create")?.message&&(this.form={kind:i.strategy==="rent"?"stream":"fund",entry:s})}this.options.placement.kind==="gardens-community"&&(this.adminResult=this.client.communityReceipt(this.options.placement)||void 0),this.pending=a?this.client.pending(this.options.placement,a):void 0;let r=this.client.pendingAuthorization();this.adminProcessing=!!r&&this.options.placement.kind==="gardens-community"&&r.account.toLowerCase()===a?.toLowerCase()&&r.community.toLowerCase()===this.options.placement.community.toLowerCase()&&r.chainId===this.options.placement.chainId,this.render(),this.pending&&this.poll()}catch(a){!this.closed&&t===this.epoch&&this.fail(a)}}fail(e){this.error=e instanceof Error?e.message:String(e),this.render()}async task(e){if(!this.busy){this.busy=!0,this.error="",this.render();try{await e()}catch(t){this.fail(t)}finally{this.busy=!1,this.render()}}}async connect(){if(!this.client.options.wallet){let e=await L();if(e.length>1){this.wallets=e,this.render();return}}this.host.style.visibility="hidden";try{await this.client.connect()}finally{this.host.style.visibility=""}await this.reload()}async prepare(e){if(this.pending)throw new Error("Check your pending transaction before preparing another action.");if(!this.account){await this.connect();return}this.review=await this.client.prepare(this.options.placement,e),this.authorization=void 0}async poll(){if(clearTimeout(this.timer),!(!this.pending||this.closed)){try{let e=this.pending,t=await this.client.verify(e);if(this.closed||this.pending?.hash!==e.hash)return;if(t.status!=="pending"){if(this.pending=void 0,this.result=t,this.error="",await this.reload(),t.createdMarkee&&this.snapshot?.strategy==="rent"){let a=this.snapshot.entries.find(r=>r.address.toLowerCase()===t.createdMarkee.toLowerCase()),i=e.preparation.action;if(i.kind==="create"){this.form={kind:"stream",entry:a||{address:t.createdMarkee,owner:e.preparation.transaction.from,message:i.message,name:i.name,score:"0",totalFunds:"0",aggregateRate:"0",legacyFloor:"0",moderated:!1,views:0}};let r=this.drafts.get("create")?.amount;r&&this.drafts.set(this.draftKey(),{amount:r})}}this.render();return}}catch(e){this.closed||this.fail(e)}!this.closed&&this.pending&&(this.timer=setTimeout(()=>void this.poll(),5e3))}}async applyAdmin(e){if(this.authorization=void 0,this.adminProcessing=e.status==="working"||e.status==="submitted",e.status==="complete"&&(this.adminResult=e.result,await this.reload()),e.status==="failed")throw new Error(e.error||"Community action failed.")}onClick=e=>{let t=e.target.closest("[data-cmd]");if(!t)return;let a=t.dataset.cmd;if(a==="close"){this.close();return}if(!this.busy){if(this.captureDraft(),a==="leaderboard"){this.leaderboardOpen=!this.leaderboardOpen,this.render();return}if(a==="create"){this.tab="main",this.form=void 0,this.review=void 0,this.render();return}if(a.startsWith("tab:")){this.tab=a.slice(4),this.review=void 0,this.authorization=void 0,this.render();return}if(a==="back"){this.review||this.authorization||this.wallets?(this.review=void 0,this.authorization=void 0,this.wallets=void 0):this.tab!=="main"?this.tab="main":this.form?.kind.startsWith("edit")?this.form={kind:this.snapshot.strategy==="rent"?"stream":"fund",entry:this.form.entry}:this.form=void 0,this.render();return}if(a.startsWith("preset:")&&this.snapshot){let i=this.root.querySelector("#amount");if(i){let r=M(this.snapshot,this.form?.entry);i.value=A((a==="preset:min"?r.minimum:r.boost).toString()),this.captureDraft(),this.updateFields()}return}if(a.startsWith("form:")){let[,i,r]=a.split(":"),s=this.snapshot?.entries.find(o=>o.address===r);s&&(this.form={kind:i,entry:s},this.tab="main"),this.render();return}if(a==="card"&&this.hostedEligible()&&this.cardAvailable){this.captureDraft();let i=this.root.querySelector("#markee-action");if(!i||!i.reportValidity())return;let r=new FormData(i),s;try{let d=g(String(r.get("amount")||""));s=this.form?.kind==="fund"?{kind:"fund",markee:this.form.entry.address,amount:d}:{kind:"create",message:String(r.get("message")||""),name:String(r.get("name")||""),amount:d}}catch(d){this.error=d.message,this.render();return}let o=N(this.client,this.options.placement,s);this.task(async()=>{let d=await o;if(d.status!=="confirmed")throw new Error("Payment was not confirmed.");this.result=d,this.client.options.onEvent?.({type:"confirmed",hash:d.hash}),await this.reload()});return}this.task(async()=>{if(a==="connect")await this.connect();else if(a.startsWith("wallet:"))await this.client.connect(this.wallets[Number(a.slice(7))].provider),this.wallets=void 0,await this.reload();else if(a==="refresh")await this.reload();else if(a==="more")await this.reload(this.snapshot?.nextOffset??void 0);else if(a==="send"&&this.review){let i=this.review,r=await this.client.send(i);this.pending={preparation:i,hash:r},this.review=void 0,this.form=void 0,this.result=void 0,this.poll()}else if(a==="check")await this.poll();else if(["stop","withdraw-buffer","settle"].includes(a))await this.prepare({kind:a});else if(a.startsWith("claim-refund:")||a.startsWith("connect-refund:")||a.startsWith("claim-top:")){let[i,r]=a.split(":");await this.prepare({kind:i,markee:r})}else if(a==="activate"||a==="claim"){let i=this.options.placement;if(i.kind!=="gardens-community"||!this.account)return;let r=this.account;this.authorization={kind:a,account:r,value:await this.client.authorize(i,a)},this.review=void 0}else if(a==="sign"&&this.authorization){let i=this.authorization;try{await this.applyAdmin(await this.client.executeAuthorization(i.kind,i.value,i.account))}finally{this.client.pendingAuthorization()&&(this.authorization=void 0,this.adminProcessing=!0)}}else if(a==="admin-check")await this.applyAdmin(await this.client.resumeAuthorization());else if(a==="bridge"&&this.adminResult){let i=await this.client.bridgeStatus(this.adminResult.bridgeProtocol||"none",this.adminResult.transactionHash,this.snapshot.chainId,this.options.placement.chainId);this.error=`Treasury transfer status: ${i.status.replace(/_/g," ")}.`}})}};onSubmit=e=>{if(e.preventDefault(),this.busy)return;if(!this.account){this.root.querySelector('[data-cmd="card"]:not(:disabled)')?.click();return}this.captureDraft();let t=e.target,a=new FormData(t),i=r=>String(a.get(r)||"");this.task(async()=>{if(t.dataset.form==="create")this.snapshot?.strategy==="rent"&&g(i("amount")),await this.prepare({kind:"create",message:i("message"),name:i("name"),...this.snapshot?.strategy==="sale"?{amount:g(i("amount"),!0)}:{}});else if(t.dataset.form==="balance")await this.prepare({kind:i("kind"),amount:g(i("amount"))});else if(this.form){let{kind:r,entry:s}=this.form;r==="fund"?await this.prepare({kind:r,markee:s.address,amount:g(i("amount"))}):r==="stream"?await this.prepare({kind:r,markee:s.address,monthlyAmount:g(i("amount"))}):r==="edit-message"?await this.prepare({kind:r,markee:s.address,message:i("message")}):await this.prepare({kind:r,markee:s.address,name:i("name")})}})};draftKey(){return this.tab!=="main"?this.tab:this.form?`${this.form.kind}:${this.form.entry.address}`:"create"}captureDraft(){let e=this.root.querySelector("form");e&&this.drafts.set(this.draftKey(),Object.fromEntries([...new FormData(e)].map(([t,a])=>[t,String(a)])))}onKey=e=>{let t=e;if(t.key==="Escape"&&(t.preventDefault(),this.close()),t.key!=="Tab"||this.host.style.visibility==="hidden")return;let a=[...this.root.querySelectorAll("button:not(:disabled),a[href],input,textarea,select")],i=a[0],r=a[a.length-1];t.shiftKey&&this.root.activeElement===i?(t.preventDefault(),r?.focus()):!t.shiftKey&&this.root.activeElement===r&&(t.preventDefault(),i?.focus())};field(e,t,a="",i="",r=!1){let s=e==="message"?this.snapshot?.maxMessageBytes:e==="name"?this.snapshot?.maxNameBytes:void 0,o=`${e==="name"?"":"required"} ${s===void 0?"":`data-byte-limit="${s}"`} aria-describedby="${e}-hint"`;return`<div class="field"><label for="${e}">${t}${s===void 0?"":`<span class="field-count" aria-hidden="true" data-count-for="${e}"></span>`}</label>${r?`<textarea id="${e}" name="${e}" ${o} placeholder="Your message on the sign">${l(a)}</textarea>`:`<input id="${e}" name="${e}" ${e==="amount"?'inputmode="decimal"':""} value="${l(a)}" ${o}>`}${i?`<small id="${e}-hint">${i}</small>`:""}</div>`}reviewHtml(){let e=this.review,t=e.action,a=t.kind==="create"||t.kind==="edit-message"?t.message:this.form?this.entryMessage(this.form.entry):void 0,i=e.review.lines.filter(r=>!r.startsWith("Message: "));return`<h2 class="review-title">${l(e.review.title)}</h2>${a?`<section class="message-card"><p class="message">${l(a)}</p></section>`:""}<section class="review"><ul>${i.map(r=>`<li>${l(r)}</li>`).join("")}</ul><div class="stat"><span>Estimated network fee</span><strong>${u(e.review.estimatedGasCost)} ETH</strong></div><div class="stat"><span>Wallet</span><strong class="mono">${C(e.transaction.from)}</strong></div></section><p class="note">${l(e.review.reward)}</p><p class="meta">This review expires in 5 minutes. Your wallet shows the final network fee.</p>`}authorizationHtml(){let e=this.authorization,t=e.value.typedData.message;return`<div class="eyebrow">Community authorization</div><h2>${e.kind==="activate"?"Activate this community\u2019s Markee":"Claim community revenue"}</h2><p>A signed authorization lets Markee\u2019s keeper execute this action. The server rechecks your current council role before submitting it.</p><div class="card stack">${["registryCommunity","recipient","leaderboardFactory"].filter(a=>t[a]).map(a=>`<div class="meta">${l(a)}<br><strong class="mono">${l(t[a])}</strong></div>`).join("")}${["claimAmount","gasCost","maxFeeAmount"].filter(a=>t[a]!==void 0).map(a=>`<div class="stat"><span>${a==="claimAmount"?"Revenue":a==="gasCost"?"Keeper network fee":"Maximum bridge fee"}</span><strong>${u(String(t[a]))} ETH</strong></div>`).join("")}</div><p class="note">${e.kind==="claim"?"Revenue is sent to the community council treasury. Bridged claims remain pending until destination delivery is confirmed.":"This creates the community board and its revenue vault on the Markee chain."}</p>`}entryMessage(e){return e.moderated===!1?e.message:e.moderated?"This message is hidden by moderation.":"Message unavailable while moderation loads."}entriesHtml(){let e=this.snapshot,t=[...e.entries].sort((r,s)=>BigInt(r.score)>BigInt(s.score)?-1:BigInt(r.score)<BigInt(s.score)?1:0),a=[...t.filter(r=>r.owner.toLowerCase()===this.account?.toLowerCase()),...t.filter(r=>r.owner.toLowerCase()!==this.account?.toLowerCase())],i=e.board&&[8453,11155111].includes(e.chainId)?`https://${e.chainId===8453?"www":"2staging"}.markee.xyz/markee/${e.board}`:"";return`<section class="leaderboard" aria-label="Markee leaderboard"><div class="row between">${c("leaderboard",`<span class="chevron" aria-hidden="true">${this.leaderboardOpen?"\u2303":"\u2304"}</span> Leaderboard`,"text-button",`aria-expanded="${this.leaderboardOpen}" aria-controls="markee-leaderboard"`)}${z(i,"Open in Markee")}</div>${this.leaderboardOpen?`<div class="leaderboard-list" id="markee-leaderboard">${a.map(r=>{let s=r.owner.toLowerCase()===this.account?.toLowerCase(),o=r.address.toLowerCase()===e.top?.toLowerCase(),d=r.address.toLowerCase()===this.form?.entry.address.toLowerCase();return`<article class="leaderboard-entry ${o?"winner":""} ${d?"selected-entry":""}"><div class="grow"><p class="message">${l(this.entryMessage(r))}</p><div class="row entry-caption">${o?'<span class="pill">Winner</span>':""}${s?'<span class="meta">Yours</span>':""}${r.moderated===!1&&r.name?`<span class="name">${l(r.name)}</span>`:""}</div></div><div class="entry-funding"><div class="meta mono">${e.strategy==="rent"?`${u((BigInt(r.score)*v).toString())} ETH/mo`:`${u(r.totalFunds)} ETH`}</div><span class="meta">${r.views===null?"Views unavailable":`${r.views.toLocaleString()} views`}</span>${c(`form:${e.strategy==="sale"?"fund":"stream"}:${r.address}`,d?"Selected":"Fund",`compact ${d?"primary":""}`,`aria-pressed="${d}" aria-label="${d?"Selected":"Fund"} message ${C(r.address)}"`)}</div></article>`}).join("")||'<p class="empty">No Markees yet. Create the first one.</p>'}${e.strategy==="rent"&&e.rankedTop&&e.rankedTop.toLowerCase()!==e.top?.toLowerCase()?`<p class="note">The ranking has changed. ${c(`claim-top:${e.rankedTop}`,"Refresh winner","compact")}</p>`:""}${e.nextOffset!==null?c("more","Browse more messages","full"):""}</div>`:""}</section>`}selectedMessageHtml(e){let t=this.snapshot,a=t.wallet,i=e.owner.toLowerCase()===this.account?.toLowerCase(),r=t.entries.find(d=>d.owner.toLowerCase()===this.account?.toLowerCase()),s=e.address.toLowerCase()===t.top?.toLowerCase(),o=e.address.toLowerCase()===a?.backedMarkee?.toLowerCase()&&BigInt(a?.flowRate??"0")>0n;return`<section class="message-card ${s?"winner":""}"><div class="row between"><span class="eyebrow">${i?"Your Markee":"Markee you\u2019re funding"}</span>${s?'<span class="pill">Winner</span>':""}</div><p class="message">${l(this.entryMessage(e))}</p>${e.moderated===!1&&e.name?`<p class="name">${l(e.name)}</p>`:""}<div class="row message-tools">${i?c(`form:edit-message:${e.address}`,"Edit message","text-button")+c(`form:edit-name:${e.address}`,"Edit name","text-button"):""}${!i&&r?c(`form:${t.strategy==="rent"?"stream":"fund"}:${r.address}`,"Back to your Markee","text-button"):""}${c("create","Create your own Markee","text-button")}${t.strategy==="rent"&&this.account?c(`claim-refund:${e.address}`,"Collect refund","text-button"):""}</div><div class="message-stats">${t.strategy==="rent"?`<span class="meta">${this.account?o?s?"\u25CF Active stream":a?.poolConnected?"\u25CF Stream refunded while not the winner":"\u25CF Connect your refund pool in Deposit manager":"No active stream from your wallet to this message":"Live message ranking"}</span><div class="stats-grid"><div><span class="stat-label">Ranking rate</span><strong>${u((BigInt(e.score)*v).toString())} ETH/mo</strong></div>${this.account?`<div><span class="stat-label">Your rate</span><strong>${u((o?BigInt(a.flowRate)*v:0n).toString())} ETH/mo</strong></div>`:""}${a?`<div><span class="stat-label">ETHx balance</span><strong>${u(a.ethx)} ETHx</strong></div><div><span class="stat-label">Funds remaining</span><strong title="Across all of your ETHx flows">${a.runwaySeconds===null?"No net outflow":`${(Number(a.runwaySeconds)/86400).toFixed(1)} days`}</strong></div>`:""}</div>${BigInt(e.legacyFloor)>0n?`<p class="meta">Ranking includes a decaying legacy floor of ${u((BigInt(e.legacyFloor)*v).toString())} ETH/mo.</p>`:""}`:`<div class="stats-grid"><div><span class="stat-label">Total funded</span><strong>${u(e.totalFunds)} ETH</strong></div><div><span class="stat-label">Views</span><strong>${e.views===null?"Unavailable":e.views.toLocaleString()}</strong></div></div>`}</div></section>`}fundingHtml(e){let t=this.snapshot,a=t.wallet,i=t.strategy==="rent",r=M(t,e),s=!!e&&e.address.toLowerCase()===a?.backedMarkee?.toLowerCase(),o=i&&s?BigInt(a.flowRate)*v:0n,d=BigInt(t.minimum)>r.minimum?BigInt(t.minimum):r.minimum,f=o>d?o:d,p=!i&&e?1n:BigInt(t.minimum);return`<section class="funding-card"><label for="amount">${i?"Monthly streaming rate":"Payment amount"}</label><div class="amount-row"><div class="amount-value"><input id="amount" name="amount" inputmode="decimal" value="${l(A(f.toString()))}" required aria-describedby="amount-hint"><span class="mono">${i?"ETHx/mo":"ETH"}</span></div><div class="amount-presets">${c("preset:min","MIN","compact mono",'title="Use the minimum amount"')}${c("preset:boost",r.double?"2\xD7":"WIN","compact mono",'title="Suggest an amount using the loaded ranking"')}</div></div><div class="funding-caption"><span id="amount-hint">Minimum ${A(p.toString())} ${i?"ETH/mo":"ETH"}</span>${this.account&&a?`<span>Balance ${u(a.eth)} ETH</span>`:""}</div><div class="funding-tools">${this.account?c("tab:wallet",i?"Deposit manager \u2192":"Wallet & rewards \u2192","text-button"):""}<span class="meta">${i?a?.runwaySeconds!=null?`${(Number(a.runwaySeconds)/86400).toFixed(1)} days remaining`:a?`${u(a.ethx)} ETHx available`:"ETH funds your ETHx balance":"One-time payment"}</span></div></section><p class="meta funding-hint">${i?"Unspent rent is refunded while your message is not the winner. You can stop streaming at any time.":e?"Adding funds keeps the current message owner.":"The paying wallet will own this message."} Shortcuts use the loaded ranking; positions can change.</p>`}formHtml(){let e=this.snapshot,t=this.form;return t?.kind.startsWith("edit")?`<form id="markee-action" data-form="entry"><section class="message-card"><div class="eyebrow">Your Markee</div>${t.kind==="edit-message"?this.field("message","Markee message",t.entry.message,`${e.maxMessageBytes} UTF-8 bytes maximum.`,!0):this.field("name","Your name (optional)",t.entry.name,`${e.maxNameBytes} UTF-8 bytes maximum.`)}</section></form>`:`<form id="markee-action" data-form="${t?"entry":"create"}">${t?this.selectedMessageHtml(t.entry):`<section class="message-card editor-card">${this.field("message","Markee message","",`${e.maxMessageBytes} UTF-8 bytes maximum.`,!0)}${this.field("name","Your name (optional)","",`${e.maxNameBytes} UTF-8 bytes maximum.`)}</section>`}${this.fundingHtml(t?.entry)}${!t&&e.strategy==="rent"?'<p class="note">First create your message, then review and confirm its stream. Your chosen rate is kept for the next step.</p>':""}</form>`}updateFields(){for(let t of this.root.querySelectorAll("[data-byte-limit]")){let a=Number(t.dataset.byteLimit),i=new TextEncoder().encode(t.value).length;t.setCustomValidity(i>a?`Use at most ${a} UTF-8 bytes.`:"");let r=this.root.querySelector(`[data-count-for="${t.name}"]`);r&&(r.textContent=`${i}/${a}`)}let e=this.root.querySelector("#markee-action #amount");if(e&&this.snapshot){let t=M(this.snapshot,this.form?.entry),a;try{a=BigInt(g(e.value,this.snapshot.strategy==="sale"))}catch{}let i=this.snapshot.strategy==="sale"&&this.form?1n:BigInt(this.snapshot.minimum);e.setCustomValidity(a===void 0?"Enter a valid ETH amount.":a<i?`Use at least ${A(i.toString())} ETH${this.snapshot.strategy==="rent"?" per month":""}.`:""),this.root.querySelector('[data-cmd="preset:min"]')?.setAttribute("aria-pressed",String(a===t.minimum)),this.root.querySelector('[data-cmd="preset:boost"]')?.setAttribute("aria-pressed",String(a===t.boost))}}walletHtml(){let e=this.snapshot,t=e.wallet;if(!t)return'<p class="empty">Connect your wallet to see balances and manage your Markee.</p>'+c("connect","Connect app wallet","primary full");let a=`<h2>Your wallet</h2><p class="meta mono">${l(t.address)}</p><div class="grid"><div class="card"><span class="meta">Native ETH</span><div class="metric">${u(t.eth)}</div></div><div class="card"><span class="meta">MARKEE</span><div class="metric">${t.markee===null?"Unavailable":u(t.markee,2)}</div></div></div>`;return e.strategy==="sale"?a+'<p class="note">Payments reward the paying wallet when this board has RevNet enabled. Manage your messages from the leaderboard.</p>':(a+=`<div class="divider"></div><div class="card"><div class="stat"><span>Available ETHx</span><strong>${u(t.ethx)} ETHx</strong></div><div class="stat"><span>This board\u2019s monthly rate</span><strong>${u((BigInt(t.flowRate)*2628000n).toString())} ETH</strong></div><div class="stat"><span>Refund flow / month</span><strong>${u((BigInt(t.refundRate)*2628000n).toString())} ETHx</strong></div><div class="stat"><span>Runway across all ETHx flows</span><strong>${t.runwaySeconds===null?"No net outflow":`${(Number(t.runwaySeconds)/86400).toFixed(1)} days`}</strong></div><p class="meta">Snapshot at ${new Date(t.observedAt*1e3).toLocaleTimeString()}. Balances and rates can change.</p><div class="row">${BigInt(t.flowRate)>0n?c("stop","Stop stream","danger"):""}${t.backedMarkee&&!t.poolConnected?c(`connect-refund:${t.backedMarkee}`,"Connect refund pool","accent"):""}${c("refresh","Refresh balances")}</div></div><div class="divider"></div><h3>Manage ETHx</h3><form data-form="balance"><div class="grid"><div><label for="kind">Action</label><select id="kind" name="kind"><option value="wrap">Deposit ETH \u2192 ETHx</option><option value="unwrap">Withdraw ETHx \u2192 ETH</option></select></div>${this.field("amount","Amount","0.001")}</div><button type="submit" class="btn">Review balance change</button></form><div class="divider"></div><div class="card"><h3>Buffer and rewards</h3><div class="stat"><span>Refundable board buffer</span><strong>${u(t.withdrawableDeposit)} ETHx</strong></div><div class="stat"><span>Accrued rent to settle</span><strong>${u(t.pendingSettlement)} ETH</strong></div><p class="meta">Rewards come from actual rent spent, not the ETH deposited into your wallet.</p><div class="row">${BigInt(t.withdrawableDeposit)>0n?c("withdraw-buffer","Recover buffer"):""}${BigInt(t.pendingSettlement)>0n?c("settle",e.revnetEnabled?"Claim MARKEE":"Settle rent","primary"):""}${t.backedMarkee&&BigInt(t.poolClaimable)>0n?c(`claim-refund:${t.backedMarkee}`,"Collect pool refund"):""}</div></div>`,a)}communityHtml(){let e=this.snapshot.community;return e?`<h2>Community treasury</h2><p class="muted">Community council members can activate Markee and collect community revenue.</p><div class="card"><div class="stat"><span>Integration</span><strong>${e.integration.status==="active"?"Active":"Not activated"}</strong></div><div class="stat"><span>Available revenue</span><strong>${u(e.revenue.claimableAmount)} ETH</strong></div>${e.permissions?.councilSafe?`<p class="meta">Council treasury<br><span class="mono">${l(e.permissions.councilSafe)}</span></p>`:""}<div class="row">${this.adminProcessing?'<p class="note">A signed community action is processing. Check it before authorizing another.</p>'+c("admin-check","Check community action","primary"):this.account?e.integration.status!=="active"&&e.permissions?.canActivate?c("activate","Activate community Markee","primary"):e.permissions?.canClaim&&BigInt(e.revenue.claimableAmount)>0n?c("claim","Review revenue claim","primary"):'<span class="meta">No authorized action is currently available for this wallet.</span>':c("connect","Connect council wallet","primary")}</div></div>${this.adminResult?`<div class="success">Source transaction confirmed. ${z(this.adminResult.transactionUrl||"","View transaction")}${this.adminResult.bridged?"<p>Bridge delivery is tracked separately from the source transaction.</p>":""}${c("bridge","Check transfer status")}</div>`:""}`:""}title(){let e=this.snapshot;return this.wallets?"Connect your wallet":this.review?"Review payment":this.authorization?"Review authorization":this.pending?"Payment in progress":this.tab==="wallet"?e?.strategy==="rent"?"Deposit manager":"Wallet & rewards":this.tab==="community"||e&&!e.board?"Community treasury":this.form?.kind.startsWith("edit")?"Edit your Markee":this.form?this.form.entry.owner.toLowerCase()!==this.account?.toLowerCase()?"Fund a Markee":e?.strategy==="sale"?"Fund your Markee":BigInt(e?.wallet?.flowRate??"0")>0n?"Manage your Markee stream":"Stream to your Markee":"Change the Markee Sign"}hostedEligible(){let e=this.snapshot;return!!e&&e.strategy==="sale"&&e.chainId===8453&&e.placement.kind==="board"&&e.revnetEnabled&&!!e.token}footerHtml(){let e=this.snapshot,t="";if(this.wallets)t=c("back","Back");else if(this.review)t=c("back","Back")+c("send","Confirm in wallet","primary");else if(this.authorization)t=c("back","Back")+c("sign","Sign authorization","primary");else if(this.pending)t=c("check","Check transaction","primary");else if(e&&this.tab==="main"&&e.board){let a=this.form?.kind.startsWith("edit"),i=a?c("back","Cancel"):e.strategy==="rent"&&BigInt(e.wallet?.flowRate??"0")>0n?c("stop","Stop streaming","danger"):"";this.account?t=(this.cardAvailable&&e.strategy==="sale"&&e.chainId===8453&&e.placement.kind==="board"&&e.revnetEnabled&&e.token&&!a?c("card","Pay by card","primary"):"")+i+(this.account?`<button class="btn primary" type="submit" form="markee-action">${a?"Review change":!this.form&&e.strategy==="rent"?"Review creation":"Review payment info"}</button>`:c("connect","Connect wallet","primary")):t=c("card","Pay","primary",!this.checkoutChecked||!this.cardAvailable||!this.hostedEligible()?"disabled":"")}else e&&(t=c("tab:main","Back to Markee"));return`<footer><div class="footer-actions">${t}</div><div class="footer-meta"><span>Powered by Markee${this.account?` \xB7 ${C(this.account)}`:""}</span>${this.account&&e?.community&&e.board&&this.tab!=="community"&&!this.review&&!this.authorization&&!this.pending?c("tab:community","Community treasury","text-button"):""}</div></footer>`}render(){if(this.closed)return;let e=this.root.activeElement,t=e?.dataset.cmd,a=e?.id,i=this.wallets?"wallets":this.review?`review:${this.review.id}`:this.authorization?`authorization:${this.authorization.value.nonce}`:this.pending?`pending:${this.pending.hash}`:`${this.tab}:${this.form?.kind??"create"}:${this.form?.entry.address??""}`,r=i===this.renderedView?this.root.querySelector(".content")?.scrollTop??0:0;this.renderedView=i;let s=!document.activeElement||document.activeElement===document.body||document.activeElement===this.host,o=this.snapshot,d="";this.wallets?d=`<h2>Choose your wallet</h2><div class="wallets">${this.wallets.map((h,k)=>c(`wallet:${k}`,l(h.name))).join("")}</div>`:this.review?d=this.reviewHtml():this.authorization?d=this.authorizationHtml():o?this.pending?d=`<h2>Waiting for confirmation</h2><p>Your transaction was sent. You can close this modal and come back to check it.</p><p class="meta mono">${l(this.pending.hash)}</p><p class="note">Do not send a second payment while this transaction is pending.</p>`:!o.board||this.tab==="community"?d=this.communityHtml():this.tab==="wallet"?d=this.walletHtml():d=`${this.form?.kind.startsWith("edit")?"":this.entriesHtml()}${this.formHtml()}${this.account?"":`<p class="note">${this.checkoutChecked?this.hostedEligible()?this.cardAvailable?"Sign in and pay on Markee. Your payment wallet and rewards are managed there.":"Pay in Markee is temporarily unavailable. Please try again later.":"Pay in Markee is not supported for this board yet.":"Checking Markee checkout availability\u2026"}</p>`}`:d=this.error?c("refresh","Retry","primary"):'<div class="loading"><span class="spinner"></span>Loading Markee\u2026</div>';let f=this.result?`<div class="${this.result.status==="reverted"||this.result.settlement==="deferred"?"error":"success"}">${this.result.status==="reverted"?"Transaction reverted. No action was completed.":this.result.settlement==="deferred"?"The transaction confirmed, but reward settlement was deferred. Your claim remains available.":`Transaction confirmed.${this.result.tokensReceived&&BigInt(this.result.tokensReceived)>0n?` ${u(this.result.tokensReceived,2)} MARKEE delivered to your wallet.`:""}`} ${z(this.result.explorerUrl,"View receipt")}</div>`:"";this.root.innerHTML=`<style>${q}</style><div class="overlay"><section class="panel" role="dialog" aria-modal="true" aria-labelledby="markee-title"><header><div class="grow"><h1 id="markee-title">${l(this.title())}</h1><p class="header-caption">${l(o?.name||"Markee")}${o?` \xB7 ${o.strategy==="rent"?"For rent":"For sale"}${o.chainId===8453?" \xB7 Base":o.chainId===11155111?" \xB7 Sepolia testnet":""}`:""}</p></div><button class="close" data-cmd="close" aria-label="Close Markee">\xD7</button></header><main class="content" aria-busy="${this.busy}"><div role="status" aria-live="polite">${this.busy?'<p class="meta"><span class="spinner"></span>Working\u2026</p>':""}${this.error?`<div class="error">${l(this.error)}</div>`:""}${f}</div>${o?.warnings.map(h=>`<div class="note">${l(h)}</div>`).join("")||""}${d}</main>${this.footerHtml()}</section></div>`,this.busy&&this.root.querySelectorAll('button:not([data-cmd="close"])').forEach(h=>{h.disabled=!0});let p=this.drafts.get(this.draftKey());if(p)for(let h of this.root.querySelectorAll("input,textarea,select"))p[h.name]!==void 0&&(h.value=p[h.name]);this.updateFields();let w=this.root.querySelector(".content");w&&(w.scrollTop=r),this.viewObserver?.disconnect();let B=this.root.querySelector(".winner"),y=o?.entries.find(h=>h.address.toLowerCase()===o.top?.toLowerCase()),P=y?`${y.address}:${y.message}`:"";B&&y?.moderated===!1&&!this.viewed.has(P)&&typeof IntersectionObserver<"u"&&(this.viewObserver=new IntersectionObserver(h=>{h.some(k=>k.isIntersecting)&&(this.viewObserver?.disconnect(),this.viewed.add(P),this.client.recordView(y.address,y.message,window.location.origin).catch(()=>{this.viewed.delete(P)}))},{threshold:.5}),this.viewObserver.observe(B)),s&&((a?this.root.getElementById(a):t?[...this.root.querySelectorAll("[data-cmd]")].find(k=>k.dataset.cmd===t):null)??this.root.querySelector('[data-cmd="close"]'))?.focus({preventScroll:!0})}};function D(n={}){let e=new b(n),t,a=n.theme;return{client:e,open(i){return t?.close(),t=new R(e,{...i,theme:i.theme??a}),t},setTheme(i){a=i??{},t?.setTheme(a)},close(){t?.close(),t=void 0}}}function pe(n){let e=U(n);e.current=n;let t=U(),a=JSON.stringify(n.placement);return H(()=>{if(!n.siteUrl)return;new b({apiUrl:n.apiUrl,fetch:n.fetch,siteUrl:n.siteUrl,onSiteVerification:r=>e.current.onSiteVerification?.(r)}).registerSite(n.placement)},[n.siteUrl,n.apiUrl,n.fetch,a]),H(()=>{if(!n.open)return;let i=D({apiUrl:n.apiUrl,fetch:n.fetch,theme:e.current.theme,wallet:n.wallet?{getProvider:()=>e.current.wallet.getProvider(),connect:()=>{let s=e.current.wallet?.connect;return s?s():Promise.reject(new Error("Connect the app wallet first."))}}:void 0,onEvent:s=>e.current.onEvent?.(s)});t.current=i;let r=!1;return i.open({placement:n.placement,onClose:()=>{r||e.current.onClose()}}),()=>{r=!0,i.close(),t.current=void 0}},[n.open,n.apiUrl,n.fetch,!!n.wallet,a]),H(()=>{t.current?.setTheme(n.theme)},[n.theme]),n.placement.kind==="board"?W("span",{hidden:!0,"data-markee-address":n.placement.address}):null}function he({children:n="Open Markee",onClick:e,...t}){return W("button",{...t,type:"button",onClick:e},n)}export{he as MarkeeButton,pe as MarkeeModal};
|