@markee_team/sdk 0.1.0-alpha.1 → 0.1.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -5
- package/dist/client.d.ts +3 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/modal.d.ts +1 -1
- package/dist/react.js +2 -2
- package/dist/types.d.ts +2 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
# @markee_team/sdk
|
|
2
2
|
|
|
3
|
-
An ESM JavaScript SDK with a self-contained, Shadow DOM modal and an optional React entry point. The
|
|
3
|
+
An ESM JavaScript SDK with a self-contained, Shadow DOM modal and an optional React entry point. The SDK knows the Markee API endpoint; the host only supplies its placement and, optionally, its current wallet provider. No Alchemy, Redis, Privy, or bridge-provider key belongs in the consuming app.
|
|
4
4
|
|
|
5
|
-
This is an experimental `0.1.0-alpha.
|
|
5
|
+
This is an experimental `0.1.0-alpha.3` release for wallet-funded For Sale and For Rent flows. Hosted card checkout and incoming cross-chain funding are not included.
|
|
6
6
|
|
|
7
7
|
Install the alpha:
|
|
8
8
|
|
|
@@ -25,7 +25,6 @@ npm run build --prefix packages/sdk
|
|
|
25
25
|
import { createMarkee } from '@markee_team/sdk';
|
|
26
26
|
|
|
27
27
|
const markee = createMarkee({
|
|
28
|
-
apiUrl: 'https://YOUR-MARKEE-API/api/sdk/v1',
|
|
29
28
|
// Optional. Reuse the wallet selected by your application's wallet connector.
|
|
30
29
|
wallet: {
|
|
31
30
|
getProvider: async () => appWalletProvider ?? null,
|
|
@@ -55,7 +54,6 @@ import { MarkeeModal } from '@markee_team/sdk/react';
|
|
|
55
54
|
<MarkeeModal
|
|
56
55
|
open={open}
|
|
57
56
|
onClose={() => setOpen(false)}
|
|
58
|
-
apiUrl="https://YOUR-MARKEE-API/api/sdk/v1"
|
|
59
57
|
wallet={walletAdapter}
|
|
60
58
|
placement={{ kind: 'gardens-community', chainId: 100, community: communityAddress }}
|
|
61
59
|
/>;
|
|
@@ -92,7 +90,7 @@ const theme: MarkeeTheme = {
|
|
|
92
90
|
|
|
93
91
|
// React: <MarkeeModal {...modalProps} theme={theme} />
|
|
94
92
|
// JavaScript:
|
|
95
|
-
const markee = createMarkee({
|
|
93
|
+
const markee = createMarkee({ theme });
|
|
96
94
|
markee.setTheme({ mode: 'dark' });
|
|
97
95
|
markee.setTheme(); // Reset to the default light theme.
|
|
98
96
|
```
|
|
@@ -138,3 +136,78 @@ Community activation supports the current council Safe, a current Safe owner, or
|
|
|
138
136
|
- API failures are explicit. Without moderation data, message text is withheld. No mock balances or fabricated rewards are returned by production handlers.
|
|
139
137
|
|
|
140
138
|
Backend configuration, endpoint details, and verification evidence: [`docs/sdk/implementation.md`](https://github.com/1Hive/markee/blob/feature/markee-sdk/docs/sdk/implementation.md).
|
|
139
|
+
|
|
140
|
+
## API endpoint
|
|
141
|
+
|
|
142
|
+
No API URL configuration is required. This alpha uses the Markee staging API at `https://markee-git-feature-markee-sdk-1hive.vercel.app/api/sdk/v1`. For local development or testing only, pass an optional `apiUrl` override to `createMarkee`, `MarkeeClient`, or the React modal. The current default is also exported as `DEFAULT_MARKEE_API_URL`.
|
|
143
|
+
|
|
144
|
+
## LLM implementation prompt
|
|
145
|
+
|
|
146
|
+
Copy this prompt into your coding assistant. It gathers missing requirements before implementing the integration.
|
|
147
|
+
|
|
148
|
+
```text
|
|
149
|
+
Integrate @markee_team/sdk@0.1.0-alpha.3 into this app. Inspect the app first and
|
|
150
|
+
follow its existing framework, styling, and wallet patterns.
|
|
151
|
+
|
|
152
|
+
Before changing code, inspect what is already available, then ask me the unanswered
|
|
153
|
+
questions below in one concise group. Do not ask again for facts already provided.
|
|
154
|
+
Wait for answers about strategy, placement, and intended scope before implementing.
|
|
155
|
+
|
|
156
|
+
1. Do you want For Rent (recurring streaming payments), For Sale (one-time
|
|
157
|
+
funding), or both?
|
|
158
|
+
2. Is this a proof of concept or an integration with your own Markee placement?
|
|
159
|
+
For your own placement, what are the chain ID and board address, or the Gardens
|
|
160
|
+
community address and chain ID? If unknown, ask for the existing Markee/Gardens
|
|
161
|
+
link so we can identify and verify the placement. Never invent an address or
|
|
162
|
+
assume a board supports the chosen strategy. Offer demo boards only with consent;
|
|
163
|
+
explain that they use real Base funds, not a sandbox. If no placement exists,
|
|
164
|
+
identify that prerequisite instead of silently substituting a demo board.
|
|
165
|
+
3. Where should Markee appear (page/component), what should open the modal, and
|
|
166
|
+
what should the button say? Is the placement fixed or selected per community?
|
|
167
|
+
4. Should we reuse the app's existing connected wallet or use SDK wallet discovery?
|
|
168
|
+
Inspect the installed connector first. If a new host wallet connector is needed,
|
|
169
|
+
ask which one; do not install ConnectKit automatically.
|
|
170
|
+
5. Should the modal match the app's theme, or use specific light/dark/system mode,
|
|
171
|
+
brand colors, font, and corner radius? Suggest the existing app theme by default.
|
|
172
|
+
6. After a confirmed transaction, should the app show a message, refresh data,
|
|
173
|
+
navigate, or notify an existing callback? Are there accessibility, mobile, or
|
|
174
|
+
framework constraints not evident from the code?
|
|
175
|
+
|
|
176
|
+
Explain that this alpha uses a built-in staging API and supports wallet-funded
|
|
177
|
+
flows; card checkout and incoming bridging are unavailable. If either is required,
|
|
178
|
+
ask whether to proceed with the supported scope instead of promising those features.
|
|
179
|
+
Summarize the agreed requirements and implement only the selected flows.
|
|
180
|
+
|
|
181
|
+
- Install @markee_team/sdk@0.1.0-alpha.3. The SDK knows its API endpoint. Do not
|
|
182
|
+
request an API URL, build an API proxy, or add RPC/database/provider keys.
|
|
183
|
+
- For React 18/19, import MarkeeModal from @markee_team/sdk/react in a client
|
|
184
|
+
component and supply open, onClose, and placement. For other apps, import
|
|
185
|
+
createMarkee from @markee_team/sdk, call createMarkee(), then open({ placement }).
|
|
186
|
+
Close the instance on teardown. Reuse the built-in modal UI.
|
|
187
|
+
- Use the agreed placement and strategy. Only if I explicitly choose a demo, use
|
|
188
|
+
the corresponding existing Base board below (do not add both unless requested):
|
|
189
|
+
For Sale: { kind: 'board', chainId: 8453,
|
|
190
|
+
address: '0x2768BC6e90266248BD8bCF5401C36D8049CdF671' }
|
|
191
|
+
For Rent: { kind: 'board', chainId: 8453,
|
|
192
|
+
address: '0x82cbe3BdFC4e01940D186Ac5EA151355647DE0d3' }
|
|
193
|
+
- Wallet integration is optional. Reuse the app's selected EIP-1193 provider via
|
|
194
|
+
wallet.getProvider(): Promise<provider | null> and optional
|
|
195
|
+
wallet.connect(): Promise<provider>. For ConnectKit/wagmi, use the active
|
|
196
|
+
connector's provider, resolve connect after selection, and reject cancellation.
|
|
197
|
+
Do not create a second wallet context or silently select another injected wallet.
|
|
198
|
+
If there is no existing wallet integration, omit wallet for SDK wallet discovery.
|
|
199
|
+
- Match the app using theme: mode ('light', 'dark', 'system'), fontFamily, radius,
|
|
200
|
+
and semantic colors such as primary and primaryText. Preserve the built-in
|
|
201
|
+
layout and its isolated Shadow DOM styles.
|
|
202
|
+
- Optionally handle onEvent and show success only for a confirmed event. Let the
|
|
203
|
+
SDK handle payment review, chain switching, submission, and verification.
|
|
204
|
+
Do not advertise card checkout or incoming bridging: this alpha lacks those
|
|
205
|
+
features. The demo boards use real Base funds.
|
|
206
|
+
- Run typecheck/build and verify the selected modal flows load without API configuration,
|
|
207
|
+
open/close correctly, and match the theme. Verify host wallet reuse if available.
|
|
208
|
+
Do not sign or submit transactions during automated verification. Report changed
|
|
209
|
+
files, checks, and remaining limitations.
|
|
210
|
+
|
|
211
|
+
This alpha automatically uses Markee's temporary staging backend. Read the installed
|
|
212
|
+
package README for exact types and configuration details.
|
|
213
|
+
```
|
package/dist/client.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { Action, Address, AdminOperation, AdminResult, Authorization, BridgeStatus, ClaimQuote, EIP1193Provider, Hex, Placement, PreparedAction, SDKOptions, Snapshot, TransactionResult } from './types.js';
|
|
2
|
+
/** Markee-hosted API for the alpha release. */
|
|
3
|
+
export declare const DEFAULT_MARKEE_API_URL = "https://markee-git-feature-markee-sdk-1hive.vercel.app/api/sdk/v1";
|
|
2
4
|
export declare class MarkeeError extends Error {
|
|
3
5
|
code: string;
|
|
4
6
|
status?: number | undefined;
|
|
@@ -31,7 +33,7 @@ export declare class MarkeeClient {
|
|
|
31
33
|
private inMemoryPending;
|
|
32
34
|
private adminMemory;
|
|
33
35
|
private communityReceipts;
|
|
34
|
-
constructor(options
|
|
36
|
+
constructor(options?: SDKOptions);
|
|
35
37
|
request<T>(path: string, body?: unknown, signal?: AbortSignal): Promise<T>;
|
|
36
38
|
provider(): Promise<EIP1193Provider | null>;
|
|
37
39
|
account(): Promise<Address | null>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export * from './types.js';
|
|
2
|
-
export { MarkeeClient, MarkeeError, discoverWallets } from './client.js';
|
|
2
|
+
export { MarkeeClient, MarkeeError, discoverWallets, DEFAULT_MARKEE_API_URL } from './client.js';
|
|
3
3
|
export type { PendingTransaction, DiscoveredWallet } from './client.js';
|
|
4
4
|
export { createMarkee, MarkeeModal } from './modal.js';
|
|
5
5
|
export type { ModalOptions } from './modal.js';
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var p=class extends Error{constructor(t,a="MARKEE_ERROR",i){super(t);this.code=a;this.status=i;this.name="MarkeeError"}};async function E(){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 x=s=>typeof s=="string"&&/^0x[\da-f]{40}$/i.test(s),T=s=>typeof s=="string"&&/^0x[\da-f]{64}$/i.test(s),k=class{constructor(e){this.options=e;let t=new URL(e.apiUrl);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new p("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 p(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 E();if(i.length>1)throw new p("Select a browser wallet.","SELECT_WALLET");t=i[0]?.provider||null}this.injected=t}if(!t)throw new p("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 p("The wallet did not return an account.");return a[0]}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 p("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 p("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 p("The wallet account or network changed. Review again.","WALLET_CHANGED");return a}async send(e){if(this.sending)throw new p("A wallet request is already in progress.");if(e.expiresAt<=Date.now())throw new p("This review expired. Prepare the action again.","REVIEW_EXPIRED");if(this.pending(e.placement,e.transaction.from))throw new p("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 p("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(!T(n))throw new p("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(!T(t))throw new p("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=>T(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 p("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 p("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 p("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)&&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 p("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&&T(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})}};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 m(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 C(s){return`${s.slice(0,6)}\u2026${s.slice(-4)}`}function l(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var
|
|
1
|
+
var H="https://markee-git-feature-markee-sdk-1hive.vercel.app/api/sdk/v1",p=class extends Error{constructor(t,a="MARKEE_ERROR",i){super(t);this.code=a;this.status=i;this.name="MarkeeError"}};async function E(){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 x=s=>typeof s=="string"&&/^0x[\da-f]{40}$/i.test(s),T=s=>typeof s=="string"&&/^0x[\da-f]{64}$/i.test(s),k=class{constructor(e={}){this.options=e;let t=new URL(e.apiUrl??H);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new p("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 p(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 E();if(i.length>1)throw new p("Select a browser wallet.","SELECT_WALLET");t=i[0]?.provider||null}this.injected=t}if(!t)throw new p("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 p("The wallet did not return an account.");return a[0]}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 p("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 p("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 p("The wallet account or network changed. Review again.","WALLET_CHANGED");return a}async send(e){if(this.sending)throw new p("A wallet request is already in progress.");if(e.expiresAt<=Date.now())throw new p("This review expired. Prepare the action again.","REVIEW_EXPIRED");if(this.pending(e.placement,e.transaction.from))throw new p("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 p("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(!T(n))throw new p("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(!T(t))throw new p("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=>T(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 p("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 p("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 p("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)&&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 p("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&&T(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})}};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 m(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 C(s){return`${s.slice(0,6)}\u2026${s.slice(-4)}`}function l(s){return String(s).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var R=`
|
|
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 B={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"},O={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"},N='Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',F=s=>`--markee-${s.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`;function R(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 d=i.mode==="dark"||r?.matches?"dark":"light",c=d==="dark"?O:B;s.dataset.markeeTheme=d,s.style.setProperty("--markee-color-scheme",d);for(let u of Object.keys(c)){let w=i.colors?.[u];s.style.setProperty(F(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:N);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,$=10n**15n,S=(...s)=>s.reduce((e,t)=>e>t?e:t,0n);function A(s,e){let t=s.strategy==="rent",a=t?(BigInt(s.minimum)+$-1n)/$*$:e?1n:BigInt(s.minimum),i=s.entries.filter(u=>u.address.toLowerCase()!==e?.address.toLowerCase()),r=S(...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:S(a,r+$-u,n?u:0n),double:n&&u>0n}}let c=!!e&&s.wallet?.backedMarkee?.toLowerCase()===e.address.toLowerCase()?BigInt(s.wallet.flowRate):0n,f=S(BigInt(e?.aggregateRate??"0")-c);return{minimum:a,boost:S(a,(r-f)*v+$,n?c*v*2n:0n),double:n&&c>0n}}var M=s=>{let e=BigInt(s);return`${e/10n**18n}.${(e%10n**18n).toString().padStart(18,"0")}`.replace(/\.?0+$/,"")||"0"},o=(s,e,t="",a="")=>`<button type="button" class="btn ${t}" data-cmd="${s}" ${a}>${e}</button>`,z=(s,e)=>/^https:\/\//.test(s)?`<a href="${l(s)}" target="_blank" rel="noopener noreferrer">${l(e)} \u2197</a>`:"",P=class{constructor(e,t){this.client=e;this.options=t;if(typeof document>"u")throw new Error("Open the Markee modal in a browser.");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=R(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()}),this.render(),this.root.querySelector('[data-cmd="close"]')?.focus(),this.reload(),this.watchAccount()}host;root;theme;snapshot;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(d=>d.address.toLowerCase()===i.wallet?.backedMarkee?.toLowerCase())??i.entries.find(d=>d.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 E();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(":"),n=this.snapshot?.entries.find(d=>d.address===r);n&&(this.form={kind:i,entry:n},this.tab="main"),this.render();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,d=`${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}" ${d} placeholder="Your message on the sign">${l(a)}</textarea>`:`<input id="${e}" name="${e}" ${e==="amount"?'inputmode="decimal"':""} value="${l(a)}" ${d}>`}${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>${m(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>${m(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">${o("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 n=r.owner.toLowerCase()===this.account?.toLowerCase(),d=r.address.toLowerCase()===e.top?.toLowerCase(),c=r.address.toLowerCase()===this.form?.entry.address.toLowerCase();return`<article class="leaderboard-entry ${d?"winner":""} ${c?"selected-entry":""}"><div class="grow"><p class="message">${l(this.entryMessage(r))}</p><div class="row entry-caption">${d?'<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"?`${m((BigInt(r.score)*v).toString())} ETH/mo`:`${m(r.totalFunds)} ETH`}</div><span class="meta">${r.views===null?"Views unavailable":`${r.views.toLocaleString()} views`}</span>${o(`form:${e.strategy==="sale"?"fund":"stream"}:${r.address}`,c?"Selected":"Fund",`compact ${c?"primary":""}`,`aria-pressed="${c}" aria-label="${c?"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. ${o(`claim-top:${e.rankedTop}`,"Refresh winner","compact")}</p>`:""}${e.nextOffset!==null?o("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(),d=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?o(`form:edit-message:${e.address}`,"Edit message","text-button")+o(`form:edit-name:${e.address}`,"Edit name","text-button"):""}${!i&&r?o(`form:${t.strategy==="rent"?"stream":"fund"}:${r.address}`,"Back to your Markee","text-button"):""}${o("create","Create your own Markee","text-button")}${t.strategy==="rent"&&this.account?o(`claim-refund:${e.address}`,"Collect refund","text-button"):""}</div><div class="message-stats">${t.strategy==="rent"?`<span class="meta">${d?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>${m((BigInt(e.score)*v).toString())} ETH/mo</strong></div><div><span class="stat-label">Your rate</span><strong>${m((d?BigInt(a.flowRate)*v:0n).toString())} ETH/mo</strong></div>${a?`<div><span class="stat-label">ETHx balance</span><strong>${m(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 ${m((BigInt(e.legacyFloor)*v).toString())} ETH/mo.</p>`:""}`:`<div class="stats-grid"><div><span class="stat-label">Total funded</span><strong>${m(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),n=!!e&&e.address.toLowerCase()===a?.backedMarkee?.toLowerCase(),d=i&&n?BigInt(a.flowRate)*v:0n,c=BigInt(t.minimum)>r.minimum?BigInt(t.minimum):r.minimum,f=d>c?d: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(M(f.toString()))}" required aria-describedby="amount-hint"><span class="mono">${i?"ETHx/mo":"ETH"}</span></div><div class="amount-presets">${o("preset:min","MIN","compact mono",'title="Use the minimum amount"')}${o("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(u.toString())} ${i?"ETH/mo":"ETH"}</span><span>${a?`Balance ${m(a.eth)} ETH`:"Connect to see your balance"}</span></div><div class="funding-tools">${o("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?`${m(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.":"Your connected 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>'+o("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">${m(t.eth)}</div></div><div class="card"><span class="meta">MARKEE</span><div class="metric">${t.markee===null?"Unavailable":m(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>${m(t.ethx)} ETHx</strong></div><div class="stat"><span>This board\u2019s monthly rate</span><strong>${m((BigInt(t.flowRate)*2628000n).toString())} ETH</strong></div><div class="stat"><span>Refund flow / month</span><strong>${m((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?o("stop","Stop stream","danger"):""}${t.backedMarkee&&!t.poolConnected?o(`connect-refund:${t.backedMarkee}`,"Connect refund pool","accent"):""}${o("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>${m(t.withdrawableDeposit)} ETHx</strong></div><div class="stat"><span>Accrued rent to settle</span><strong>${m(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?o("withdraw-buffer","Recover buffer"):""}${BigInt(t.pendingSettlement)>0n?o("settle",e.revnetEnabled?"Claim MARKEE":"Settle rent","primary"):""}${t.backedMarkee&&BigInt(t.poolClaimable)>0n?o(`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>${m(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>'+o("admin-check","Check community action","primary"):this.account?e.integration.status!=="active"&&e.permissions?.canActivate?o("activate","Activate community Markee","primary"):e.permissions?.canClaim&&BigInt(e.revenue.claimableAmount)>0n?o("claim","Review revenue claim","primary"):'<span class="meta">No authorized action is currently available for this wallet.</span>':o("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>":""}${o("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=o("back","Back");else if(this.review)t=o("back","Back")+o("send","Confirm in wallet","primary");else if(this.authorization)t=o("back","Back")+o("sign","Sign authorization","primary");else if(this.pending)t=o("check","Check transaction","primary");else if(e&&this.tab==="main"&&e.board){let a=this.form?.kind.startsWith("edit");t=(a?o("back","Cancel"):e.strategy==="rent"&&BigInt(e.wallet?.flowRate??"0")>0n?o("stop","Stop streaming","danger"):"")+(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>`:o("connect","Connect wallet","primary"))}else e&&(t=o("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?o("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,d=this.snapshot,c="";this.wallets?c=`<h2>Choose your wallet</h2><div class="wallets">${this.wallets.map((h,b)=>o(`wallet:${b}`,l(h.name))).join("")}</div>`:this.review?c=this.reviewHtml():this.authorization?c=this.authorizationHtml():d?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>`:!d.board||this.tab==="community"?c=this.communityHtml():this.tab==="wallet"?c=this.walletHtml():c=`${this.form?.kind.startsWith("edit")?"":this.entriesHtml()}${this.formHtml()}`:c=this.error?o("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?` ${m(this.result.tokensReceived,2)} MARKEE delivered to your wallet.`:""}`} ${z(this.result.explorerUrl,"View receipt")}</div>`:"";this.root.innerHTML=`<style>${H}</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(d?.name||"Markee")}${d?` \xB7 ${d.strategy==="rent"?"For rent":"For sale"}${d.chainId===8453?" \xB7 Base":d.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>${d?.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 I=this.root.querySelector(".winner"),y=d?.entries.find(h=>h.address.toLowerCase()===d.top?.toLowerCase()),L=y?`${y.address}:${y.message}`:"";I&&y?.moderated===!1&&!this.viewed.has(L)&&typeof IntersectionObserver<"u"&&(this.viewObserver=new IntersectionObserver(h=>{h.some(b=>b.isIntersecting)&&(this.viewObserver?.disconnect(),this.viewed.add(L),this.client.recordView(y.address,y.message,window.location.origin).catch(()=>{this.viewed.delete(L)}))},{threshold:.5}),this.viewObserver.observe(I)),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 q(s){let e=new k(s),t,a=s.theme;return{client:e,open(i){return t?.close(),t=new P(e,{...i,theme:i.theme??a}),t},setTheme(i){a=i??{},t?.setTheme(a)},close(){t?.close(),t=void 0}}}export{k as MarkeeClient,p as MarkeeError,P as MarkeeModal,q as createMarkee,E as discoverWallets,m as formatEth,g as parseEth};
|
|
107
|
+
`;var O={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"},F={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"},N='Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',D=s=>`--markee-${s.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`;function B(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 d=i.mode==="dark"||r?.matches?"dark":"light",c=d==="dark"?F:O;s.dataset.markeeTheme=d,s.style.setProperty("--markee-color-scheme",d);for(let u of Object.keys(c)){let w=i.colors?.[u];s.style.setProperty(D(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:N);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,$=10n**15n,S=(...s)=>s.reduce((e,t)=>e>t?e:t,0n);function A(s,e){let t=s.strategy==="rent",a=t?(BigInt(s.minimum)+$-1n)/$*$:e?1n:BigInt(s.minimum),i=s.entries.filter(u=>u.address.toLowerCase()!==e?.address.toLowerCase()),r=S(...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:S(a,r+$-u,n?u:0n),double:n&&u>0n}}let c=!!e&&s.wallet?.backedMarkee?.toLowerCase()===e.address.toLowerCase()?BigInt(s.wallet.flowRate):0n,f=S(BigInt(e?.aggregateRate??"0")-c);return{minimum:a,boost:S(a,(r-f)*v+$,n?c*v*2n:0n),double:n&&c>0n}}var M=s=>{let e=BigInt(s);return`${e/10n**18n}.${(e%10n**18n).toString().padStart(18,"0")}`.replace(/\.?0+$/,"")||"0"},o=(s,e,t="",a="")=>`<button type="button" class="btn ${t}" data-cmd="${s}" ${a}>${e}</button>`,z=(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.");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=B(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()}),this.render(),this.root.querySelector('[data-cmd="close"]')?.focus(),this.reload(),this.watchAccount()}host;root;theme;snapshot;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(d=>d.address.toLowerCase()===i.wallet?.backedMarkee?.toLowerCase())??i.entries.find(d=>d.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 E();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(":"),n=this.snapshot?.entries.find(d=>d.address===r);n&&(this.form={kind:i,entry:n},this.tab="main"),this.render();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,d=`${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}" ${d} placeholder="Your message on the sign">${l(a)}</textarea>`:`<input id="${e}" name="${e}" ${e==="amount"?'inputmode="decimal"':""} value="${l(a)}" ${d}>`}${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>${m(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>${m(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">${o("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 n=r.owner.toLowerCase()===this.account?.toLowerCase(),d=r.address.toLowerCase()===e.top?.toLowerCase(),c=r.address.toLowerCase()===this.form?.entry.address.toLowerCase();return`<article class="leaderboard-entry ${d?"winner":""} ${c?"selected-entry":""}"><div class="grow"><p class="message">${l(this.entryMessage(r))}</p><div class="row entry-caption">${d?'<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"?`${m((BigInt(r.score)*v).toString())} ETH/mo`:`${m(r.totalFunds)} ETH`}</div><span class="meta">${r.views===null?"Views unavailable":`${r.views.toLocaleString()} views`}</span>${o(`form:${e.strategy==="sale"?"fund":"stream"}:${r.address}`,c?"Selected":"Fund",`compact ${c?"primary":""}`,`aria-pressed="${c}" aria-label="${c?"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. ${o(`claim-top:${e.rankedTop}`,"Refresh winner","compact")}</p>`:""}${e.nextOffset!==null?o("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(),d=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?o(`form:edit-message:${e.address}`,"Edit message","text-button")+o(`form:edit-name:${e.address}`,"Edit name","text-button"):""}${!i&&r?o(`form:${t.strategy==="rent"?"stream":"fund"}:${r.address}`,"Back to your Markee","text-button"):""}${o("create","Create your own Markee","text-button")}${t.strategy==="rent"&&this.account?o(`claim-refund:${e.address}`,"Collect refund","text-button"):""}</div><div class="message-stats">${t.strategy==="rent"?`<span class="meta">${d?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>${m((BigInt(e.score)*v).toString())} ETH/mo</strong></div><div><span class="stat-label">Your rate</span><strong>${m((d?BigInt(a.flowRate)*v:0n).toString())} ETH/mo</strong></div>${a?`<div><span class="stat-label">ETHx balance</span><strong>${m(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 ${m((BigInt(e.legacyFloor)*v).toString())} ETH/mo.</p>`:""}`:`<div class="stats-grid"><div><span class="stat-label">Total funded</span><strong>${m(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),n=!!e&&e.address.toLowerCase()===a?.backedMarkee?.toLowerCase(),d=i&&n?BigInt(a.flowRate)*v:0n,c=BigInt(t.minimum)>r.minimum?BigInt(t.minimum):r.minimum,f=d>c?d: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(M(f.toString()))}" required aria-describedby="amount-hint"><span class="mono">${i?"ETHx/mo":"ETH"}</span></div><div class="amount-presets">${o("preset:min","MIN","compact mono",'title="Use the minimum amount"')}${o("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(u.toString())} ${i?"ETH/mo":"ETH"}</span><span>${a?`Balance ${m(a.eth)} ETH`:"Connect to see your balance"}</span></div><div class="funding-tools">${o("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?`${m(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.":"Your connected 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>'+o("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">${m(t.eth)}</div></div><div class="card"><span class="meta">MARKEE</span><div class="metric">${t.markee===null?"Unavailable":m(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>${m(t.ethx)} ETHx</strong></div><div class="stat"><span>This board\u2019s monthly rate</span><strong>${m((BigInt(t.flowRate)*2628000n).toString())} ETH</strong></div><div class="stat"><span>Refund flow / month</span><strong>${m((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?o("stop","Stop stream","danger"):""}${t.backedMarkee&&!t.poolConnected?o(`connect-refund:${t.backedMarkee}`,"Connect refund pool","accent"):""}${o("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>${m(t.withdrawableDeposit)} ETHx</strong></div><div class="stat"><span>Accrued rent to settle</span><strong>${m(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?o("withdraw-buffer","Recover buffer"):""}${BigInt(t.pendingSettlement)>0n?o("settle",e.revnetEnabled?"Claim MARKEE":"Settle rent","primary"):""}${t.backedMarkee&&BigInt(t.poolClaimable)>0n?o(`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>${m(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>'+o("admin-check","Check community action","primary"):this.account?e.integration.status!=="active"&&e.permissions?.canActivate?o("activate","Activate community Markee","primary"):e.permissions?.canClaim&&BigInt(e.revenue.claimableAmount)>0n?o("claim","Review revenue claim","primary"):'<span class="meta">No authorized action is currently available for this wallet.</span>':o("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>":""}${o("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=o("back","Back");else if(this.review)t=o("back","Back")+o("send","Confirm in wallet","primary");else if(this.authorization)t=o("back","Back")+o("sign","Sign authorization","primary");else if(this.pending)t=o("check","Check transaction","primary");else if(e&&this.tab==="main"&&e.board){let a=this.form?.kind.startsWith("edit");t=(a?o("back","Cancel"):e.strategy==="rent"&&BigInt(e.wallet?.flowRate??"0")>0n?o("stop","Stop streaming","danger"):"")+(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>`:o("connect","Connect wallet","primary"))}else e&&(t=o("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?o("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,d=this.snapshot,c="";this.wallets?c=`<h2>Choose your wallet</h2><div class="wallets">${this.wallets.map((h,b)=>o(`wallet:${b}`,l(h.name))).join("")}</div>`:this.review?c=this.reviewHtml():this.authorization?c=this.authorizationHtml():d?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>`:!d.board||this.tab==="community"?c=this.communityHtml():this.tab==="wallet"?c=this.walletHtml():c=`${this.form?.kind.startsWith("edit")?"":this.entriesHtml()}${this.formHtml()}`:c=this.error?o("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?` ${m(this.result.tokensReceived,2)} MARKEE delivered to your wallet.`:""}`} ${z(this.result.explorerUrl,"View receipt")}</div>`:"";this.root.innerHTML=`<style>${R}</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(d?.name||"Markee")}${d?` \xB7 ${d.strategy==="rent"?"For rent":"For sale"}${d.chainId===8453?" \xB7 Base":d.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>${d?.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 I=this.root.querySelector(".winner"),y=d?.entries.find(h=>h.address.toLowerCase()===d.top?.toLowerCase()),P=y?`${y.address}:${y.message}`:"";I&&y?.moderated===!1&&!this.viewed.has(P)&&typeof IntersectionObserver<"u"&&(this.viewObserver=new IntersectionObserver(h=>{h.some(b=>b.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(I)),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 q(s={}){let e=new k(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{H as DEFAULT_MARKEE_API_URL,k as MarkeeClient,p as MarkeeError,L as MarkeeModal,q as createMarkee,E as discoverWallets,m as formatEth,g as parseEth};
|
package/dist/modal.d.ts
CHANGED
|
@@ -72,7 +72,7 @@ export declare class MarkeeModal {
|
|
|
72
72
|
private footerHtml;
|
|
73
73
|
private render;
|
|
74
74
|
}
|
|
75
|
-
export declare function createMarkee(options
|
|
75
|
+
export declare function createMarkee(options?: SDKOptions): {
|
|
76
76
|
client: MarkeeClient;
|
|
77
77
|
open(options: ModalOptions): MarkeeModal;
|
|
78
78
|
setTheme(next?: MarkeeTheme): void;
|
package/dist/react.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use client";import{createElement as
|
|
1
|
+
"use client";import{createElement as K,useEffect as O,useRef as N}from"react";var F="https://markee-git-feature-markee-sdk-1hive.vercel.app/api/sdk/v1",p=class extends Error{constructor(t,a="MARKEE_ERROR",i){super(t);this.code=a;this.status=i;this.name="MarkeeError"}};async function P(){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),$=n=>typeof n=="string"&&/^0x[\da-f]{64}$/i.test(n),T=class{constructor(e={}){this.options=e;let t=new URL(e.apiUrl??F);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw new p("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 p(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 P();if(i.length>1)throw new p("Select a browser wallet.","SELECT_WALLET");t=i[0]?.provider||null}this.injected=t}if(!t)throw new p("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 p("The wallet did not return an account.");return a[0]}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 p("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 p("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 p("The wallet account or network changed. Review again.","WALLET_CHANGED");return a}async send(e){if(this.sending)throw new p("A wallet request is already in progress.");if(e.expiresAt<=Date.now())throw new p("This review expired. Prepare the action again.","REVIEW_EXPIRED");if(this.pending(e.placement,e.transaction.from))throw new p("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 p("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(!$(s))throw new p("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(!$(t))throw new p("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=>$(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 p("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 p("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 p("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 p("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&&$(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})}};function v(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 m(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 E(n){return`${n.slice(0,6)}\u2026${n.slice(-4)}`}function l(n){return String(n).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var H=`
|
|
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 F={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"},D={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"},q='Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',W=n=>`--markee-${n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`;function R(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 d=i.mode==="dark"||r?.matches?"dark":"light",c=d==="dark"?D:F;n.dataset.markeeTheme=d,n.style.setProperty("--markee-color-scheme",d);for(let u of Object.keys(c)){let w=i.colors?.[u];n.style.setProperty(W(u),w&&CSS.supports("color",w)?w:c[u])}n.style.setProperty("--markee-font-family",i.fontFamily&&CSS.supports("font-family",i.fontFamily)?i.fontFamily:q);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 g=2628000n,k=10n**15n,C=(...n)=>n.reduce((e,t)=>e>t?e:t,0n);function S(n,e){let t=n.strategy==="rent",a=t?(BigInt(n.minimum)+k-1n)/k*k:e?1n:BigInt(n.minimum),i=n.entries.filter(u=>u.address.toLowerCase()!==e?.address.toLowerCase()),r=C(...i.map(u=>BigInt(u.score))),s=!!e&&e.address.toLowerCase()===n.top?.toLowerCase();if(!t){let u=BigInt(e?.totalFunds??"0");return{minimum:a,boost:C(a,r+k-u,s?u:0n),double:s&&u>0n}}let c=!!e&&n.wallet?.backedMarkee?.toLowerCase()===e.address.toLowerCase()?BigInt(n.wallet.flowRate):0n,f=C(BigInt(e?.aggregateRate??"0")-c);return{minimum:a,boost:C(a,(r-f)*g+k,s?c*g*2n:0n),double:s&&c>0n}}var A=n=>{let e=BigInt(n);return`${e/10n**18n}.${(e%10n**18n).toString().padStart(18,"0")}`.replace(/\.?0+$/,"")||"0"},o=(n,e,t="",a="")=>`<button type="button" class="btn ${t}" data-cmd="${n}" ${a}>${e}</button>`,L=(n,e)=>/^https:\/\//.test(n)?`<a href="${l(n)}" target="_blank" rel="noopener noreferrer">${l(e)} \u2197</a>`:"",z=class{constructor(e,t){this.client=e;this.options=t;if(typeof document>"u")throw new Error("Open the Markee modal in a browser.");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=R(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()}),this.render(),this.root.querySelector('[data-cmd="close"]')?.focus(),this.reload(),this.watchAccount()}host;root;theme;snapshot;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(d=>d.address.toLowerCase()===i.wallet?.backedMarkee?.toLowerCase())??i.entries.find(d=>d.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 P();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=S(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(d=>d.address===r);s&&(this.form={kind:i,entry:s},this.tab="main"),this.render();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"&&v(i("amount")),await this.prepare({kind:"create",message:i("message"),name:i("name"),...this.snapshot?.strategy==="sale"?{amount:v(i("amount"),!0)}:{}});else if(t.dataset.form==="balance")await this.prepare({kind:i("kind"),amount:v(i("amount"))});else if(this.form){let{kind:r,entry:s}=this.form;r==="fund"?await this.prepare({kind:r,markee:s.address,amount:v(i("amount"))}):r==="stream"?await this.prepare({kind:r,markee:s.address,monthlyAmount:v(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,d=`${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}" ${d} placeholder="Your message on the sign">${l(a)}</textarea>`:`<input id="${e}" name="${e}" ${e==="amount"?'inputmode="decimal"':""} value="${l(a)}" ${d}>`}${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>${m(e.review.estimatedGasCost)} ETH</strong></div><div class="stat"><span>Wallet</span><strong class="mono">${E(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>${m(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">${o("leaderboard",`<span class="chevron" aria-hidden="true">${this.leaderboardOpen?"\u2303":"\u2304"}</span> Leaderboard`,"text-button",`aria-expanded="${this.leaderboardOpen}" aria-controls="markee-leaderboard"`)}${L(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(),d=r.address.toLowerCase()===e.top?.toLowerCase(),c=r.address.toLowerCase()===this.form?.entry.address.toLowerCase();return`<article class="leaderboard-entry ${d?"winner":""} ${c?"selected-entry":""}"><div class="grow"><p class="message">${l(this.entryMessage(r))}</p><div class="row entry-caption">${d?'<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"?`${m((BigInt(r.score)*g).toString())} ETH/mo`:`${m(r.totalFunds)} ETH`}</div><span class="meta">${r.views===null?"Views unavailable":`${r.views.toLocaleString()} views`}</span>${o(`form:${e.strategy==="sale"?"fund":"stream"}:${r.address}`,c?"Selected":"Fund",`compact ${c?"primary":""}`,`aria-pressed="${c}" aria-label="${c?"Selected":"Fund"} message ${E(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. ${o(`claim-top:${e.rankedTop}`,"Refresh winner","compact")}</p>`:""}${e.nextOffset!==null?o("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()),s=e.address.toLowerCase()===t.top?.toLowerCase(),d=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?o(`form:edit-message:${e.address}`,"Edit message","text-button")+o(`form:edit-name:${e.address}`,"Edit name","text-button"):""}${!i&&r?o(`form:${t.strategy==="rent"?"stream":"fund"}:${r.address}`,"Back to your Markee","text-button"):""}${o("create","Create your own Markee","text-button")}${t.strategy==="rent"&&this.account?o(`claim-refund:${e.address}`,"Collect refund","text-button"):""}</div><div class="message-stats">${t.strategy==="rent"?`<span class="meta">${d?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>${m((BigInt(e.score)*g).toString())} ETH/mo</strong></div><div><span class="stat-label">Your rate</span><strong>${m((d?BigInt(a.flowRate)*g:0n).toString())} ETH/mo</strong></div>${a?`<div><span class="stat-label">ETHx balance</span><strong>${m(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 ${m((BigInt(e.legacyFloor)*g).toString())} ETH/mo.</p>`:""}`:`<div class="stats-grid"><div><span class="stat-label">Total funded</span><strong>${m(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=S(t,e),s=!!e&&e.address.toLowerCase()===a?.backedMarkee?.toLowerCase(),d=i&&s?BigInt(a.flowRate)*g:0n,c=BigInt(t.minimum)>r.minimum?BigInt(t.minimum):r.minimum,f=d>c?d: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(A(f.toString()))}" required aria-describedby="amount-hint"><span class="mono">${i?"ETHx/mo":"ETH"}</span></div><div class="amount-presets">${o("preset:min","MIN","compact mono",'title="Use the minimum amount"')}${o("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(u.toString())} ${i?"ETH/mo":"ETH"}</span><span>${a?`Balance ${m(a.eth)} ETH`:"Connect to see your balance"}</span></div><div class="funding-tools">${o("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?`${m(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.":"Your connected 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=S(this.snapshot,this.form?.entry),a;try{a=BigInt(v(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>'+o("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">${m(t.eth)}</div></div><div class="card"><span class="meta">MARKEE</span><div class="metric">${t.markee===null?"Unavailable":m(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>${m(t.ethx)} ETHx</strong></div><div class="stat"><span>This board\u2019s monthly rate</span><strong>${m((BigInt(t.flowRate)*2628000n).toString())} ETH</strong></div><div class="stat"><span>Refund flow / month</span><strong>${m((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?o("stop","Stop stream","danger"):""}${t.backedMarkee&&!t.poolConnected?o(`connect-refund:${t.backedMarkee}`,"Connect refund pool","accent"):""}${o("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>${m(t.withdrawableDeposit)} ETHx</strong></div><div class="stat"><span>Accrued rent to settle</span><strong>${m(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?o("withdraw-buffer","Recover buffer"):""}${BigInt(t.pendingSettlement)>0n?o("settle",e.revnetEnabled?"Claim MARKEE":"Settle rent","primary"):""}${t.backedMarkee&&BigInt(t.poolClaimable)>0n?o(`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>${m(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>'+o("admin-check","Check community action","primary"):this.account?e.integration.status!=="active"&&e.permissions?.canActivate?o("activate","Activate community Markee","primary"):e.permissions?.canClaim&&BigInt(e.revenue.claimableAmount)>0n?o("claim","Review revenue claim","primary"):'<span class="meta">No authorized action is currently available for this wallet.</span>':o("connect","Connect council wallet","primary")}</div></div>${this.adminResult?`<div class="success">Source transaction confirmed. ${L(this.adminResult.transactionUrl||"","View transaction")}${this.adminResult.bridged?"<p>Bridge delivery is tracked separately from the source transaction.</p>":""}${o("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=o("back","Back");else if(this.review)t=o("back","Back")+o("send","Confirm in wallet","primary");else if(this.authorization)t=o("back","Back")+o("sign","Sign authorization","primary");else if(this.pending)t=o("check","Check transaction","primary");else if(e&&this.tab==="main"&&e.board){let a=this.form?.kind.startsWith("edit");t=(a?o("back","Cancel"):e.strategy==="rent"&&BigInt(e.wallet?.flowRate??"0")>0n?o("stop","Stop streaming","danger"):"")+(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>`:o("connect","Connect wallet","primary"))}else e&&(t=o("tab:main","Back to Markee"));return`<footer><div class="footer-actions">${t}</div><div class="footer-meta"><span>Powered by Markee${this.account?` \xB7 ${E(this.account)}`:""}</span>${e?.community&&e.board&&this.tab!=="community"&&!this.review&&!this.authorization&&!this.pending?o("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,d=this.snapshot,c="";this.wallets?c=`<h2>Choose your wallet</h2><div class="wallets">${this.wallets.map((h,b)=>o(`wallet:${b}`,l(h.name))).join("")}</div>`:this.review?c=this.reviewHtml():this.authorization?c=this.authorizationHtml():d?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>`:!d.board||this.tab==="community"?c=this.communityHtml():this.tab==="wallet"?c=this.walletHtml():c=`${this.form?.kind.startsWith("edit")?"":this.entriesHtml()}${this.formHtml()}`:c=this.error?o("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?` ${m(this.result.tokensReceived,2)} MARKEE delivered to your wallet.`:""}`} ${L(this.result.explorerUrl,"View receipt")}</div>`:"";this.root.innerHTML=`<style>${H}</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(d?.name||"Markee")}${d?` \xB7 ${d.strategy==="rent"?"For rent":"For sale"}${d.chainId===8453?" \xB7 Base":d.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>${d?.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 I=this.root.querySelector(".winner"),y=d?.entries.find(h=>h.address.toLowerCase()===d.top?.toLowerCase()),M=y?`${y.address}:${y.message}`:"";I&&y?.moderated===!1&&!this.viewed.has(M)&&typeof IntersectionObserver<"u"&&(this.viewObserver=new IntersectionObserver(h=>{h.some(b=>b.isIntersecting)&&(this.viewObserver?.disconnect(),this.viewed.add(M),this.client.recordView(y.address,y.message,window.location.origin).catch(()=>{this.viewed.delete(M)}))},{threshold:.5}),this.viewObserver.observe(I)),s&&((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 B(n){let e=new T(n),t,a=n.theme;return{client:e,open(i){return t?.close(),t=new z(e,{...i,theme:i.theme??a}),t},setTheme(i){a=i??{},t?.setTheme(a)},close(){t?.close(),t=void 0}}}function ie(n){let e=N(n);e.current=n;let t=N(),a=JSON.stringify(n.placement);return O(()=>{if(!n.open)return;let i=B({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]),O(()=>{t.current?.setTheme(n.theme)},[n.theme]),null}function re({children:n="Open Markee",onClick:e,...t}){return j("button",{...t,type:"button",onClick:e},n)}export{re as MarkeeButton,ie as MarkeeModal};
|
|
107
|
+
`;var D={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"},q={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"},W='Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',U=n=>`--markee-${n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`;function R(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 d=i.mode==="dark"||r?.matches?"dark":"light",c=d==="dark"?q:D;n.dataset.markeeTheme=d,n.style.setProperty("--markee-color-scheme",d);for(let u of Object.keys(c)){let w=i.colors?.[u];n.style.setProperty(U(u),w&&CSS.supports("color",w)?w:c[u])}n.style.setProperty("--markee-font-family",i.fontFamily&&CSS.supports("font-family",i.fontFamily)?i.fontFamily:W);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 g=2628000n,k=10n**15n,C=(...n)=>n.reduce((e,t)=>e>t?e:t,0n);function S(n,e){let t=n.strategy==="rent",a=t?(BigInt(n.minimum)+k-1n)/k*k:e?1n:BigInt(n.minimum),i=n.entries.filter(u=>u.address.toLowerCase()!==e?.address.toLowerCase()),r=C(...i.map(u=>BigInt(u.score))),s=!!e&&e.address.toLowerCase()===n.top?.toLowerCase();if(!t){let u=BigInt(e?.totalFunds??"0");return{minimum:a,boost:C(a,r+k-u,s?u:0n),double:s&&u>0n}}let c=!!e&&n.wallet?.backedMarkee?.toLowerCase()===e.address.toLowerCase()?BigInt(n.wallet.flowRate):0n,f=C(BigInt(e?.aggregateRate??"0")-c);return{minimum:a,boost:C(a,(r-f)*g+k,s?c*g*2n:0n),double:s&&c>0n}}var A=n=>{let e=BigInt(n);return`${e/10n**18n}.${(e%10n**18n).toString().padStart(18,"0")}`.replace(/\.?0+$/,"")||"0"},o=(n,e,t="",a="")=>`<button type="button" class="btn ${t}" data-cmd="${n}" ${a}>${e}</button>`,L=(n,e)=>/^https:\/\//.test(n)?`<a href="${l(n)}" target="_blank" rel="noopener noreferrer">${l(e)} \u2197</a>`:"",z=class{constructor(e,t){this.client=e;this.options=t;if(typeof document>"u")throw new Error("Open the Markee modal in a browser.");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=R(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()}),this.render(),this.root.querySelector('[data-cmd="close"]')?.focus(),this.reload(),this.watchAccount()}host;root;theme;snapshot;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(d=>d.address.toLowerCase()===i.wallet?.backedMarkee?.toLowerCase())??i.entries.find(d=>d.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 P();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=S(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(d=>d.address===r);s&&(this.form={kind:i,entry:s},this.tab="main"),this.render();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"&&v(i("amount")),await this.prepare({kind:"create",message:i("message"),name:i("name"),...this.snapshot?.strategy==="sale"?{amount:v(i("amount"),!0)}:{}});else if(t.dataset.form==="balance")await this.prepare({kind:i("kind"),amount:v(i("amount"))});else if(this.form){let{kind:r,entry:s}=this.form;r==="fund"?await this.prepare({kind:r,markee:s.address,amount:v(i("amount"))}):r==="stream"?await this.prepare({kind:r,markee:s.address,monthlyAmount:v(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,d=`${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}" ${d} placeholder="Your message on the sign">${l(a)}</textarea>`:`<input id="${e}" name="${e}" ${e==="amount"?'inputmode="decimal"':""} value="${l(a)}" ${d}>`}${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>${m(e.review.estimatedGasCost)} ETH</strong></div><div class="stat"><span>Wallet</span><strong class="mono">${E(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>${m(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">${o("leaderboard",`<span class="chevron" aria-hidden="true">${this.leaderboardOpen?"\u2303":"\u2304"}</span> Leaderboard`,"text-button",`aria-expanded="${this.leaderboardOpen}" aria-controls="markee-leaderboard"`)}${L(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(),d=r.address.toLowerCase()===e.top?.toLowerCase(),c=r.address.toLowerCase()===this.form?.entry.address.toLowerCase();return`<article class="leaderboard-entry ${d?"winner":""} ${c?"selected-entry":""}"><div class="grow"><p class="message">${l(this.entryMessage(r))}</p><div class="row entry-caption">${d?'<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"?`${m((BigInt(r.score)*g).toString())} ETH/mo`:`${m(r.totalFunds)} ETH`}</div><span class="meta">${r.views===null?"Views unavailable":`${r.views.toLocaleString()} views`}</span>${o(`form:${e.strategy==="sale"?"fund":"stream"}:${r.address}`,c?"Selected":"Fund",`compact ${c?"primary":""}`,`aria-pressed="${c}" aria-label="${c?"Selected":"Fund"} message ${E(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. ${o(`claim-top:${e.rankedTop}`,"Refresh winner","compact")}</p>`:""}${e.nextOffset!==null?o("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()),s=e.address.toLowerCase()===t.top?.toLowerCase(),d=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?o(`form:edit-message:${e.address}`,"Edit message","text-button")+o(`form:edit-name:${e.address}`,"Edit name","text-button"):""}${!i&&r?o(`form:${t.strategy==="rent"?"stream":"fund"}:${r.address}`,"Back to your Markee","text-button"):""}${o("create","Create your own Markee","text-button")}${t.strategy==="rent"&&this.account?o(`claim-refund:${e.address}`,"Collect refund","text-button"):""}</div><div class="message-stats">${t.strategy==="rent"?`<span class="meta">${d?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>${m((BigInt(e.score)*g).toString())} ETH/mo</strong></div><div><span class="stat-label">Your rate</span><strong>${m((d?BigInt(a.flowRate)*g:0n).toString())} ETH/mo</strong></div>${a?`<div><span class="stat-label">ETHx balance</span><strong>${m(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 ${m((BigInt(e.legacyFloor)*g).toString())} ETH/mo.</p>`:""}`:`<div class="stats-grid"><div><span class="stat-label">Total funded</span><strong>${m(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=S(t,e),s=!!e&&e.address.toLowerCase()===a?.backedMarkee?.toLowerCase(),d=i&&s?BigInt(a.flowRate)*g:0n,c=BigInt(t.minimum)>r.minimum?BigInt(t.minimum):r.minimum,f=d>c?d: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(A(f.toString()))}" required aria-describedby="amount-hint"><span class="mono">${i?"ETHx/mo":"ETH"}</span></div><div class="amount-presets">${o("preset:min","MIN","compact mono",'title="Use the minimum amount"')}${o("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(u.toString())} ${i?"ETH/mo":"ETH"}</span><span>${a?`Balance ${m(a.eth)} ETH`:"Connect to see your balance"}</span></div><div class="funding-tools">${o("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?`${m(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.":"Your connected 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=S(this.snapshot,this.form?.entry),a;try{a=BigInt(v(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>'+o("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">${m(t.eth)}</div></div><div class="card"><span class="meta">MARKEE</span><div class="metric">${t.markee===null?"Unavailable":m(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>${m(t.ethx)} ETHx</strong></div><div class="stat"><span>This board\u2019s monthly rate</span><strong>${m((BigInt(t.flowRate)*2628000n).toString())} ETH</strong></div><div class="stat"><span>Refund flow / month</span><strong>${m((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?o("stop","Stop stream","danger"):""}${t.backedMarkee&&!t.poolConnected?o(`connect-refund:${t.backedMarkee}`,"Connect refund pool","accent"):""}${o("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>${m(t.withdrawableDeposit)} ETHx</strong></div><div class="stat"><span>Accrued rent to settle</span><strong>${m(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?o("withdraw-buffer","Recover buffer"):""}${BigInt(t.pendingSettlement)>0n?o("settle",e.revnetEnabled?"Claim MARKEE":"Settle rent","primary"):""}${t.backedMarkee&&BigInt(t.poolClaimable)>0n?o(`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>${m(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>'+o("admin-check","Check community action","primary"):this.account?e.integration.status!=="active"&&e.permissions?.canActivate?o("activate","Activate community Markee","primary"):e.permissions?.canClaim&&BigInt(e.revenue.claimableAmount)>0n?o("claim","Review revenue claim","primary"):'<span class="meta">No authorized action is currently available for this wallet.</span>':o("connect","Connect council wallet","primary")}</div></div>${this.adminResult?`<div class="success">Source transaction confirmed. ${L(this.adminResult.transactionUrl||"","View transaction")}${this.adminResult.bridged?"<p>Bridge delivery is tracked separately from the source transaction.</p>":""}${o("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=o("back","Back");else if(this.review)t=o("back","Back")+o("send","Confirm in wallet","primary");else if(this.authorization)t=o("back","Back")+o("sign","Sign authorization","primary");else if(this.pending)t=o("check","Check transaction","primary");else if(e&&this.tab==="main"&&e.board){let a=this.form?.kind.startsWith("edit");t=(a?o("back","Cancel"):e.strategy==="rent"&&BigInt(e.wallet?.flowRate??"0")>0n?o("stop","Stop streaming","danger"):"")+(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>`:o("connect","Connect wallet","primary"))}else e&&(t=o("tab:main","Back to Markee"));return`<footer><div class="footer-actions">${t}</div><div class="footer-meta"><span>Powered by Markee${this.account?` \xB7 ${E(this.account)}`:""}</span>${e?.community&&e.board&&this.tab!=="community"&&!this.review&&!this.authorization&&!this.pending?o("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,d=this.snapshot,c="";this.wallets?c=`<h2>Choose your wallet</h2><div class="wallets">${this.wallets.map((h,b)=>o(`wallet:${b}`,l(h.name))).join("")}</div>`:this.review?c=this.reviewHtml():this.authorization?c=this.authorizationHtml():d?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>`:!d.board||this.tab==="community"?c=this.communityHtml():this.tab==="wallet"?c=this.walletHtml():c=`${this.form?.kind.startsWith("edit")?"":this.entriesHtml()}${this.formHtml()}`:c=this.error?o("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?` ${m(this.result.tokensReceived,2)} MARKEE delivered to your wallet.`:""}`} ${L(this.result.explorerUrl,"View receipt")}</div>`:"";this.root.innerHTML=`<style>${H}</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(d?.name||"Markee")}${d?` \xB7 ${d.strategy==="rent"?"For rent":"For sale"}${d.chainId===8453?" \xB7 Base":d.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>${d?.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 I=this.root.querySelector(".winner"),y=d?.entries.find(h=>h.address.toLowerCase()===d.top?.toLowerCase()),M=y?`${y.address}:${y.message}`:"";I&&y?.moderated===!1&&!this.viewed.has(M)&&typeof IntersectionObserver<"u"&&(this.viewObserver=new IntersectionObserver(h=>{h.some(b=>b.isIntersecting)&&(this.viewObserver?.disconnect(),this.viewed.add(M),this.client.recordView(y.address,y.message,window.location.origin).catch(()=>{this.viewed.delete(M)}))},{threshold:.5}),this.viewObserver.observe(I)),s&&((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 B(n={}){let e=new T(n),t,a=n.theme;return{client:e,open(i){return t?.close(),t=new z(e,{...i,theme:i.theme??a}),t},setTheme(i){a=i??{},t?.setTheme(a)},close(){t?.close(),t=void 0}}}function re(n){let e=N(n);e.current=n;let t=N(),a=JSON.stringify(n.placement);return O(()=>{if(!n.open)return;let i=B({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]),O(()=>{t.current?.setTheme(n.theme)},[n.theme]),null}function ne({children:n="Open Markee",onClick:e,...t}){return K("button",{...t,type:"button",onClick:e},n)}export{ne as MarkeeButton,re as MarkeeModal};
|
package/dist/types.d.ts
CHANGED
|
@@ -251,7 +251,8 @@ export interface MarkeeTheme {
|
|
|
251
251
|
radius?: number;
|
|
252
252
|
}
|
|
253
253
|
export interface SDKOptions {
|
|
254
|
-
|
|
254
|
+
/** Optional development override; defaults to the Markee-hosted API. */
|
|
255
|
+
apiUrl?: string;
|
|
255
256
|
wallet?: WalletAdapter;
|
|
256
257
|
fetch?: typeof fetch;
|
|
257
258
|
theme?: MarkeeTheme;
|