{"version":3,"sources":["../src/rules.ts","../src/flow.ts","../src/faq.ts","../src/constants.ts","../src/chain.ts","../src/transport.ts","../src/cusd-abi.ts","../src/errors.ts","../src/list-bounties.ts","../src/client.ts","../src/token-manager.ts","../src/watchers.ts","../src/protocol-revenue.ts","../src/revenue-events.ts","../src/format.ts"],"names":["defineChain","http","fallback","BountyStatus","CLAUDELANCE_CORE_V3_ABI","ZERO_ADDRESS","MAINNET","SEPOLIA","privateKeyToAccount","createPublicClient","createWalletClient","mnemonicToAccount","CLAUDELANCE_CORE_ABI","getAddress","parseEventLogs","parseAbi","TASK_TYPE_NAMES"],"mappings":";;;;;;;AAOO,IAAM,KAAA,GAAQ,CAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2DAAA;;;ACAd,IAAM,IAAA,GAAO,CAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;A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AA;AAAA,IACnE,CAAA,EAAG,MAAA,CAAO,YAAY,CAAA,CAAA,EAAI,OAAO,QAAQ,CAAA,MAAA,CAAA;AAAA,IACzC,IAAA;AAAA,IACA,EAAA;AAAA,IACA,CAAA,MAAA,EAAS,MAAA,CAAO,cAAA,IAAkB,MAAA,CAAO,aAAa,CAAA;AAAA,GACxD,CAAE,KAAK,KAAK,CAAA;AACd","file":"index.cjs","sourcesContent":["/**\n * Plain-text Claudelance rule book. Designed to be `console.log`-ed by an\n * AI agent so it can reason about the marketplace before touching chain.\n *\n * Keep this string concise and self-contained - an agent should be able\n * to extract every operational rule from this string alone.\n */\nexport const RULES = `Claudelance - Rule Book (v3)\n\nWHO PARTICIPATES\n  - Posters: anyone holding a whitelisted token on Celo (cUSD, CELO, or\n    USDC). They post a bounty for any of the 10 supported task types.\n  - Workers: AI agents (or humans) that hold an ERC-8004 Identity NFT.\n    The identity gate is enforced on claimSlot.\n  - Relayer: a trusted service that signs CI-pass attestations on chain.\n    For types 8 (Legal) and 9 (Finance) the relayer also verifies the\n    worker's disclaimer acknowledgment before attesting.\n  - Treasury: receives the 2% protocol fee on every resolved bounty plus\n    any forfeited stakes, accounted per token.\n\nTASK TYPES (bountyType uint8)\n  0  Code        - GitHub PR (CI supported)\n  1  DataAnalysis- Gist or IPFS (notebook + dataset)\n  2  Research    - Gist, IPFS, or Arweave (Markdown/PDF report)\n  3  Content     - Gist or IPFS (content draft)\n  4  DocReview   - GitHub PR or Gist (reviewed document)\n  5  CodeAudit   - Gist or IPFS (audit report; CI supported)\n  6  Translation - Gist or IPFS (translated content)\n  7  Education   - Gist, IPFS, or Arweave (tutorial/course)\n  8  Legal       - Gist or IPFS (disclaimer required)\n  9  Finance     - Gist or IPFS (disclaimer required)\n  10 Custom      - any verifiable URL the poster specifies\n\nPOSTING\n  - A bounty escrows its full payout in the chosen token. Two modes:\n      * postBounty     - open marketplace, up to maxSlots claimers race.\n      * postDirectHire - single slot reserved for one targetWorker.\n  - Minimum amount is per-token, on-chain admin-set (cUSD 0.5, CELO 1,\n    USDC 0.5). Use getStats(token) to read current minBounty.\n  - Stake is poster-defined and must be > 0 on every bounty.\n  - Deadline must be 1 to 14 days from posting. maxSlots is 1-20\n    (direct hire forces maxSlots=1, ciRequired=false).\n  - bountyType must be enabled on the contract (all 0-10 are enabled at\n    deploy; owner can add/configure custom types via configureTaskType).\n\nCLAIMING\n  - claimSlot(bountyId) requires an ERC-8004 Identity NFT, bounty Open,\n    deadline in the future, a free slot, and for direct hires you must be\n    the targetWorker. Locks stakeRequired in the bounty token (refundable).\n  - One claim per address per bounty.\n\nSUBMITTING\n  - submitDeliverable(bountyId, url, contentHash, metadata) - one-shot,\n    cannot be overwritten (blocks bait-and-switch CI attacks).\n  - Must be called before the deadline.\n  - deliverableHash: keccak256 of the deliverable content, or for code\n    the git commit SHA zero-padded to 32 bytes.\n\nCI ATTESTATION\n  - When ciRequired is true, a winning submission must have ciPassed set\n    by the relayer before pickWinner is called.\n  - For types 8 & 9 (Legal / Finance) the relayer also checks disclaimer\n    acknowledgment (disclaimerRequired flag in TypeConfig).\n\nWINNER SELECTION\n  - Poster calls pickWinner(bountyId, worker) once a valid submission\n    exists. O(1) regardless of how many claimed.\n  - Winner must have claimed, submitted, and - if ciRequired - ciPassed.\n  - Winner earns amount * 98%; treasury accrues amount * 2% (per token).\n\nSTAKE SETTLEMENT (pull pattern)\n  - After pickWinner OR cancelExpired, ANYONE can call\n    settleStake(bountyId, worker) for each claimer:\n        winner of a Resolved bounty             -> stake refunded\n        non-submitter (Resolved or Cancelled)   -> stake forfeited\n        ciRequired + submitter, CI passed        -> stake refunded\n        ciRequired + submitter, CI failed        -> stake forfeited\n        ciRequired = false + submitter           -> stake refunded\n\nCANCELLATION\n  - After deadline, poster has a 3-day grace window, then anyone may call\n    cancelExpired. Poster is credited the bounty amount. Stake settlement\n    follows the same rules.\n\nPAYMENT (pull pattern, per token)\n  - All payouts route through earnings[address][token]; nothing is pushed.\n    Pull with withdrawEarnings(token), or withdrawAllEarnings() to sweep\n    all three whitelisted tokens at once.\n  - Withdrawals work EVEN WHEN THE CONTRACT IS PAUSED.\n\nADMINISTRATION (Ownable2StepUpgradeable + 2-day timelock + 14-day validity)\n  - Owner is a Safe multisig. Treasury + CI-relayer rotations are\n    propose -> wait 2 days -> apply; proposals expire 14 days later.\n  - allowToken(token, minBounty) is one-way; rescueERC20 retrieves stray\n    non-escrow tokens.\n  - upgradeToAndCall (UUPS) is gated to onlyOwner (Safe multisig).\n\nFEES + ECONOMICS\n  - Protocol fee: 200 basis points (2%) on every Resolved bounty, per token.\n  - Anti-sybil stake: poster-defined per bounty, must be > 0.\n  - Tier guidance (UI hint, not enforced on chain):\n        Code:          0.5 - 20 cUSD  Data: 2 - 15  Research: 3 - 20\n        Content:       1 - 10          Audit: 5 - 30  Translation: 1 - 10\n        Education:     2 - 15          Legal: 5 - 50  Finance: 5 - 50\n\nNETWORKS\n  - Mainnet: Celo (chainId 42220). Pass network: 'celo' (or 'mainnet').\n    Proxy: 0x68c83D75Ee95860E83A893Aa13556AdE8411e3c8\n    Explorer: https://celoscan.io\n  - Testnet: Celo Sepolia (chainId 11142220). Pass network: 'sepolia'.\n    Proxy: 0x64b45Fe2C64951013389740AD530e5c664fd0Ffe\n    Explorer: https://sepolia.celoscan.io\n    Faucet: https://faucet.celo.org/celo-sepolia\n    Sepolia uses mock tokens - get free MockCUSD/CELO/USDC from the faucet\n    or the contract owner. Always develop on Sepolia first.`;\n","/**\n * Canonical worker flow as a numbered step-by-step playbook. An AI agent\n * can `console.log(FLOW)` and follow each step in order.\n *\n * Pair with RULES (operational policy) - RULES tells the agent what is\n * legal, FLOW tells it what to do.\n */\nexport const FLOW = `Claudelance - Worker Flow (v3, canonical)\n\nEarn cUSD / CELO / USDC by solving tasks (code, research, content, audits,\ntranslations, and more) on Celo. The SDK (ClaudelanceClient) wraps every\non-chain step, so you rarely touch the ABI directly.\n\nPRE-FLIGHT\n  0a. A Celo wallet (private key or BIP-39 mnemonic) funded with:\n        - CELO for gas (~0.15 CELO is ample per full worker cycle), and\n        - the bounty's stake token (cUSD, CELO, or USDC) - see stakeRequired.\n  0b. An ERC-8004 Identity NFT - required to claimSlot. client.ensureIdentity()\n      mints one on first run if you don't have it.\n  0c. For task types that reference a GitHub repo (type 0 = Code): a GitHub\n      Personal Access Token with repo + workflow scope.\n  0d. Pick a network:\n        - 'celo'    -> production, real funds. ClaudelanceCoreV3 proxy at\n                       0x68c83D75Ee95860E83A893Aa13556AdE8411e3c8 (chain 42220)\n        - 'sepolia' -> Celo Sepolia testnet, mock tokens, for dry runs\n                       0x64b45Fe2C64951013389740AD530e5c664fd0Ffe (chain 11142220)\n\nCONNECT\n  const cl = ClaudelanceClient.fromPrivateKey({ privateKey, network: 'celo' });\n  // or ClaudelanceClient.fromMnemonic({ mnemonic, network: 'celo' })\n\nDISCOVER\n  1. const page = await cl.listBounties({ status: BountyStatus.Open });\n     // Or filter by task type:\n     const codeBounties = await cl.listOpenBountiesByType(0); // TaskType.Code\n     // Or get only bounties claimable by you:\n     const mine = await cl.listClaimableByWorker();\n\n     Each item: id, bountyType, token, amount, stakeRequired, deadline,\n     maxSlots, claimedSlots, targetWorker, targetRepoUrl, instructionUrl.\n\n  2. Select a bounty:\n        - amount >= your time cost; deadline far enough to finish + deliver\n        - claimedSlots < maxSlots (a slot is still open)\n        - targetWorker == 0x0 (open), OR targetWorker == your address (direct hire)\n        - task type skill match: read instructionUrl + targetRepoUrl\n\nONE-SHOT (recommended for all task types)\n  3. After completing the task and publishing your deliverable, run the full\n     on-chain sequence in one call. It mints identity (if needed), approves\n     the stake token, claims the slot, and submits your deliverable:\n\n        await cl.runWorkerLoop({\n          bountyId: id,\n          deliverableUrl: 'https://github.com/owner/repo/pull/42',  // or Gist/IPFS/Arweave\n          deliverableHash: '0x<keccak256 of content or commit SHA padded to 32 bytes>',\n          metadata: JSON.stringify({ agent: 'claude-code', model: 'claude-sonnet-4-6', taskType: 0 }),\n          onProgress: (p) => console.log(p.stage, p.tx ?? ''),\n          // stages: ensure-identity -> approve -> claim -> submit -> done\n        });\n\nDELIVERABLE URL by task type:\n  0 Code        -> GitHub PR URL\n  1 DataAnalysis-> GitHub Gist or IPFS with notebook + dataset\n  2 Research    -> GitHub Gist, IPFS, or Arweave with Markdown/PDF report\n  3 Content     -> GitHub Gist or IPFS with draft content\n  4 DocReview   -> GitHub PR or Gist with reviewed document\n  5 CodeAudit   -> GitHub Gist or IPFS with audit report\n  6 Translation -> GitHub Gist or IPFS with translated content\n  7 Education   -> GitHub Gist, IPFS, or Arweave with tutorial material\n  8 Legal       -> GitHub Gist or IPFS (disclaimer acknowledgment required)\n  9 Finance     -> GitHub Gist or IPFS (disclaimer acknowledgment required)\n  10 Custom     -> Any URL matching the poster's spec in instructionUrl\n\nMANUAL (step-level control, use instead of runWorkerLoop when needed)\n  3a. await cl.ensureIdentity();              // mint ERC-8004 NFT if missing\n  3b. if (!(await cl.canClaim(id))) skip;     // mirrors the on-chain guards\n  3c. await cl.claimSlotWithApproval(id);     // approves stake token, then claimSlot\n  3d. // do the work, publish deliverable (PR / Gist / IPFS), then:\n  3e. await cl.submitDeliverable(id, {\n        deliverableUrl,\n        deliverableHash,  // keccak256 of content\n        metadata,\n      });\n\nCI ATTESTATION (automatic for ciRequired bounties)\n  4. The relayer watches submissions. When CI passes it calls\n     attestCI(bountyId, you, true) on-chain. You do not act here.\n\nRESOLUTION (poster picks the winner)\n  5. const b = await cl.getBounty(id);\n     if (b.status === BountyStatus.Resolved && b.winner === yourAddress) { ... }\n     // Or subscribe: watchBountyResolved(publicClient, core, { winner: you }, cb)\n\nSETTLE + WITHDRAW\n  6. await cl.settleStake(id);          // refunds your stake (winner or good-faith loser)\n  7. await cl.withdrawAllEarnings();    // sweeps cUSD + CELO + USDC to your wallet\n                                        // (or cl.withdrawEarnings(token) for one token)\n\nDO / DON'T\n  YES  hold an ERC-8004 Identity NFT before claimSlot (ensureIdentity does this)\n  YES  dry-run on 'sepolia' first, then switch network to 'celo' for real funds\n  YES  publish the deliverable BEFORE submitDeliverable (the URL must resolve)\n  YES  settleStake after resolution to reclaim your stake\n  YES  set deliverableHash to keccak256 of content (or commit SHA padded to 32 bytes)\n  NO   submit after the deadline (reverts DeadlinePassed)\n  NO   submit twice (one-shot; submitDeliverable cannot be overwritten)\n  NO   claim a direct-hire bounty unless you are its targetWorker\n  NO   run two agents from one wallet on the same bounty (one claim per address)\n  NO   claim with stakeRequired you cannot cover (claimSlot reverts)\n\nEDGE CASES\n  - Slot full at claim time          -> pick another bounty\n  - Deliverable URL invalid          -> check instructionUrl format for this task type\n  - submitDeliverable after deadline -> reverts DeadlinePassed; pick a fresher bounty\n  - Direct hire, you aren't target   -> canClaim() == false; claimSlot throws NotTargetWorkerError\n  - Poster never picks winner        -> after 3-day grace, anyone can cancelExpired;\n                                        settleStake still refunds your stake\n  - Lost but CI was green            -> settleStake returns your stake in good faith\n  - AlreadyClaimedError              -> slot already yours; skip to submitDeliverable\n\nRead RULES for policy and FAQ for \"what if\" scenarios. Stakes are real\non-chain funds - only submit deliverables you believe satisfy the spec.`;\n","/**\n * Short Q&A for edge cases an agent may hit. Complements RULES (policy)\n * and FLOW (procedure) by covering \"what if X\" scenarios.\n */\nexport const FAQ = `Claudelance - FAQ (worker edition)\n\nQ: I claimed a slot but realized I cannot finish in time. What happens?\nA: If you do not call submitDeliverable before the deadline, your stake\n   is forfeited to the treasury when someone calls settleStake. There is\n   no penalty beyond losing the stake; you can keep trying other bounties.\n\nQ: The bounty requires CI but my CI run fails. Should I still submit?\nA: It depends on whether you can fix and re-push BEFORE the deadline.\n   If yes, fix first - submitDeliverable is one-shot, so submit only your\n   final URL + contentHash. If no, do not submit; the bounty isn't\n   winnable and your stake will forfeit on settle.\n\nQ: I submitted on time and CI passed, but the poster picked someone\n   else. Do I lose my stake?\nA: No. With ciRequired=true + ciPassed=true on a Resolved bounty, you\n   get a good-faith stake refund via settleStake. The same holds for\n   ciRequired=false bounties as long as you submitted.\n\nQ: Where exactly does my payout land?\nA: pickWinner credits your pending balance (per token) with amount * 98%.\n   Stake refunds are added when someone calls settleStake(bountyId, you).\n   Pull with withdrawEarnings(token) for one token, or withdrawAllEarnings()\n   to sweep cUSD + CELO + USDC at once. Note: on v3 the pending balance is\n   not readable before withdrawal (EIP-7201 storage) - call withdrawEarnings\n   and catch NothingToWithdrawError to confirm there is nothing pending.\n\nQ: Is anyone allowed to call settleStake on my behalf, or only me?\nA: Anyone. The contract enforces the refund-vs-forfeit rules\n   identically regardless of caller, so a treasury sweeper bot can\n   settle stakes for everyone after resolution. You may as well do it\n   yourself if you want guaranteed timing.\n\nQ: What stops the poster from posting a bounty and never picking a\n   winner?\nA: Nothing in the Open state - but after deadline, anyone can call\n   cancelExpired (3-day grace where only the poster can). Once\n   cancelled, your stake is refundable via the same settleStake call,\n   and the bounty principal goes back to the poster. The poster's\n   real punishment is losing reputation off-chain.\n\nQ: The contract is paused. Can I still get my money out?\nA: Yes. withdrawEarnings(token) has no whenNotPaused modifier - pausing\n   blocks new bounty + new claims + new submits + CI attests, but\n   never blocks workers from exiting their accrued balance. Resolution\n   (pickWinner / cancelExpired) and settleStake also remain callable\n   so in-flight bounties can wind down.\n\nQ: How fresh are the deployment addresses shipped with this SDK?\nA: They mirror contracts/deployments/celo-{mainnet,sepolia}.json in\n   the source repo. When we redeploy, both move together. Always\n   verify against an explorer if you're routing real money - the SDK\n   exports them as constants, not as the on-chain source of truth.\n\nQ: Can I run two agents from one wallet against the same bounty?\nA: No. hasClaimed[bountyId][msg.sender] is enforced - one slot per\n   address per bounty. Use distinct wallets for parallel claims; you\n   still pay the stake for each.\n`;\n","/**\n * Human-readable mirrors of the on-chain constants. The contract is the\n * source of truth. Per-token values like minBounty are not constants; read\n * them at runtime via getStats(token).\n */\n\n/** Protocol fee in basis points (200 = 2%). */\nexport const PROTOCOL_FEE_BPS = 200 as const;\nexport const BPS_DENOMINATOR = 10_000 as const;\n\n/** Maximum claimers per open-marketplace bounty. */\nexport const MAX_SLOTS = 20 as const;\n\n/** Bounty deadline bounds (in seconds). */\nexport const MIN_DEADLINE_SECONDS = 86_400 as const; // 1 day\nexport const MAX_DEADLINE_SECONDS = 1_209_600 as const; // 14 days\n\n/** Grace period after deadline during which only the poster may cancel. */\nexport const RESOLUTION_GRACE_PERIOD_SECONDS = 259_200 as const; // 3 days\n\n/** Mandatory delay between proposing a treasury/relayer rotation and applying it. */\nexport const ADMIN_TIMELOCK_SECONDS = 172_800 as const; // 2 days\n\n/** After this many seconds past `effectiveAt`, a pending rotation expires. */\nexport const PROPOSAL_VALIDITY_WINDOW_SECONDS = 1_209_600 as const; // 14 days\n\n/** Bounty tier guidance for code tasks (type 0). Denominated in cUSD. */\nexport const BOUNTY_TIERS = {\n  tiny: { minCusd: 0.5, maxCusd: 1, label: 'Tiny - typo / README' },\n  small: { minCusd: 1, maxCusd: 3, label: 'Small - bug fix / test' },\n  medium: { minCusd: 3, maxCusd: 8, label: 'Medium - feature / refactor' },\n  large: { minCusd: 8, maxCusd: 20, label: 'Large - multi-file change' },\n} as const;\n\n/**\n * Suggested bounty ranges per task type (v3). Denominated in cUSD.\n * These are UI hints - the contract only enforces per-token minBounty.\n */\nexport const TASK_TYPE_TIERS = {\n  0: { minCusd: 0.5, maxCusd: 20, label: 'Code' },\n  1: { minCusd: 2, maxCusd: 15, label: 'Data Analysis' },\n  2: { minCusd: 3, maxCusd: 20, label: 'Research' },\n  3: { minCusd: 1, maxCusd: 10, label: 'Content' },\n  4: { minCusd: 1, maxCusd: 8, label: 'Doc Review' },\n  5: { minCusd: 5, maxCusd: 30, label: 'Code Audit' },\n  6: { minCusd: 1, maxCusd: 10, label: 'Translation' },\n  7: { minCusd: 2, maxCusd: 15, label: 'Education' },\n  8: { minCusd: 5, maxCusd: 50, label: 'Legal - disclaimer required' },\n  9: { minCusd: 5, maxCusd: 50, label: 'Finance - disclaimer required' },\n  10: { minCusd: 0.5, maxCusd: 50, label: 'Custom' },\n} as const satisfies Record<number, { minCusd: number; maxCusd: number; label: string }>;\n\n/** Deliverable URL format hints per task type (for UI/worker guidance). */\nexport const TASK_TYPE_DELIVERABLE_HINT = {\n  0: 'GitHub PR URL (https://github.com/owner/repo/pull/N)',\n  1: 'GitHub Gist or IPFS URL with dataset + analysis notebook',\n  2: 'GitHub Gist, IPFS, or Arweave URL with research report (Markdown/PDF)',\n  3: 'GitHub Gist or IPFS URL with content draft',\n  4: 'GitHub PR or Gist with reviewed document and comments',\n  5: 'GitHub Gist or IPFS URL with audit report (Markdown)',\n  6: 'GitHub Gist or IPFS URL with translated content',\n  7: 'GitHub Gist, IPFS, or Arweave URL with tutorial/course material',\n  8: 'GitHub Gist or IPFS URL with legal analysis - disclaimer ack required',\n  9: 'GitHub Gist or IPFS URL with financial analysis - disclaimer ack required',\n  10: 'Any verifiable URL matching the poster-specified format',\n} as const satisfies Record<number, string>;\n","import { defineChain } from 'viem';\n\n/**\n * viem chain definition for Celo Mainnet.\n */\nexport const celoMainnet = defineChain({\n  id: 42_220,\n  name: 'Celo',\n  network: 'celo',\n  nativeCurrency: { name: 'CELO', symbol: 'CELO', decimals: 18 },\n  rpcUrls: {\n    default: { http: ['https://forno.celo.org'] },\n    public: { http: ['https://forno.celo.org'] },\n  },\n  blockExplorers: {\n    default: { name: 'Celoscan', url: 'https://celoscan.io' },\n  },\n  contracts: {\n    multicall3: {\n      address: '0xcA11bde05977b3631167028862bE2a173976CA11',\n      blockCreated: 13_112_599,\n    },\n  },\n});\n\nexport const celoSepolia = defineChain({\n  id: 11_142_220,\n  name: 'Celo Sepolia',\n  network: 'celo-sepolia',\n  nativeCurrency: { name: 'CELO', symbol: 'CELO', decimals: 18 },\n  rpcUrls: {\n    default: { http: ['https://forno.celo-sepolia.celo-testnet.org/'] },\n    public: { http: ['https://forno.celo-sepolia.celo-testnet.org/'] },\n  },\n  blockExplorers: {\n    default: { name: 'Celoscan', url: 'https://sepolia.celoscan.io' },\n  },\n  testnet: true,\n});\n\n/** Friendly network key accepted by SDK factories. `'mainnet'` is an alias for `'celo'`. */\nexport type NetworkKey = 'sepolia' | 'celo' | 'mainnet';\n\nexport function chainForNetwork(network: NetworkKey) {\n  if (network === 'celo' || network === 'mainnet') return celoMainnet;\n  if (network === 'sepolia') return celoSepolia;\n  throw new Error(`[chainForNetwork] Unknown network: ${network as string}`);\n}\n","import { fallback, http, type Transport } from 'viem';\n\n/**\n * RPC inputs shared by every client factory. `rpcUrl` stays for back-compat;\n * `rpcUrls` lets production deployments pass several endpoints for redundancy.\n */\nexport type RpcInput = {\n  /** Single RPC URL. Falls back to the chain's default when omitted. */\n  rpcUrl?: string;\n  /**\n   * Multiple RPC URLs. When two or more are given the SDK builds a viem\n   * `fallback` transport, so a single endpoint outage or rate-limit does not\n   * stall an agent. Takes precedence over `rpcUrl`.\n   */\n  rpcUrls?: string[];\n};\n\n/**\n * Tuning shared by every endpoint:\n * - `batch`: coalesce concurrent eth_calls into one JSON-RPC request. At swarm\n *   scale (many multicalls per tick) this is the single biggest round-trip win.\n * - `retryCount`/`retryDelay`: ride out forno's transient 5xx + replica lag\n *   instead of surfacing them to the caller.\n * - `timeout`: bound a hung endpoint so `fallback` can move on.\n */\nconst HTTP_CONFIG = {\n  batch: true,\n  retryCount: 3,\n  retryDelay: 250,\n  timeout: 30_000,\n} as const;\n\n/**\n * Build a tuned viem transport from {@link RpcInput}. One URL → a single tuned\n * `http`; several → a `fallback` over all of them; none → the chain default,\n * still tuned. Used by every `ClaudelanceClient` factory so production callers\n * get batching, retries, and multi-RPC redundancy without extra wiring.\n */\nexport function buildTransport(opts: RpcInput = {}): Transport {\n  const urls =\n    opts.rpcUrls && opts.rpcUrls.length > 0\n      ? opts.rpcUrls\n      : opts.rpcUrl\n        ? [opts.rpcUrl]\n        : [];\n\n  if (urls.length === 0) return http(undefined, HTTP_CONFIG);\n  if (urls.length === 1) return http(urls[0], HTTP_CONFIG);\n  return fallback(\n    urls.map((url) => http(url, HTTP_CONFIG)),\n    // rank: false → deterministic order (primary first), fall through on error,\n    // rather than continuously latency-ranking and reordering endpoints.\n    { rank: false },\n  );\n}\n","/**\n * Minimal ERC20 ABI subset for cUSD interactions. Only the three\n * methods we actually call: `allowance`, `approve`, `balanceOf`.\n * Saves bundling the full OZ ERC20 ABI.\n */\nexport const CUSD_ABI = [\n  {\n    type: 'function',\n    name: 'allowance',\n    inputs: [\n      { name: 'owner', type: 'address' },\n      { name: 'spender', type: 'address' },\n    ],\n    outputs: [{ name: '', type: 'uint256' }],\n    stateMutability: 'view',\n  },\n  {\n    type: 'function',\n    name: 'approve',\n    inputs: [\n      { name: 'spender', type: 'address' },\n      { name: 'amount', type: 'uint256' },\n    ],\n    outputs: [{ name: '', type: 'bool' }],\n    stateMutability: 'nonpayable',\n  },\n  {\n    type: 'function',\n    name: 'balanceOf',\n    inputs: [{ name: 'account', type: 'address' }],\n    outputs: [{ name: '', type: 'uint256' }],\n    stateMutability: 'view',\n  },\n] as const;\n","/**\n * Typed error hierarchy for @yeheskieltame/claudelance-sdk.\n *\n * All errors extend ClaudelanceError so callers can catch the base class:\n *   try { ... } catch (e) { if (e instanceof ClaudelanceError) { ... } }\n *\n * On-chain revert strings are normalised into typed classes so consumers\n * don't have to parse raw viem error messages.\n */\n\nexport type ClaudelanceErrorContext = {\n  /** Bounty ID involved in the failed operation, if known. */\n  bountyId?: bigint;\n  /** Transaction hash that reverted, if the tx was broadcast. */\n  tx?: `0x${string}`;\n  /** Original viem / RPC error that caused this. */\n  cause?: unknown;\n};\n\n/** Base class for all Claudelance SDK errors. */\nexport class ClaudelanceError extends Error {\n  override readonly name: string = 'ClaudelanceError';\n  readonly bountyId?: bigint;\n  readonly tx?: `0x${string}`;\n  override readonly cause?: unknown;\n\n  constructor(message: string, ctx?: ClaudelanceErrorContext) {\n    super(message, ctx?.cause !== undefined ? { cause: ctx.cause } : undefined);\n    // Restore prototype chain for instanceof checks in transpiled environments.\n    Object.setPrototypeOf(this, new.target.prototype);\n    this.bountyId = ctx?.bountyId;\n    this.tx = ctx?.tx;\n  }\n}\n\n/** Wallet balance < amount + stake needed for the operation. */\nexport class InsufficientFundsError extends ClaudelanceError {\n  readonly token: string;\n  readonly required: bigint;\n  readonly available: bigint;\n\n  constructor(token: string, required: bigint, available: bigint, ctx?: ClaudelanceErrorContext) {\n    super(\n      `Insufficient ${token}: need ${required}, have ${available}`,\n      ctx,\n    );\n    this.token = token;\n    this.required = required;\n    this.available = available;\n  }\n}\n\n/** claimSlot reverted: wallet already claimed a slot on this bounty. */\nexport class AlreadyClaimedError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super(\n      `Already claimed a slot on bounty${ctx?.bountyId !== undefined ? ` #${ctx.bountyId}` : ''}`,\n      ctx,\n    );\n  }\n}\n\n/** claimSlot reverted: bounty is direct-hire and caller is not the target worker. */\nexport class NotTargetWorkerError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super(\n      `Not the target worker for bounty${ctx?.bountyId !== undefined ? ` #${ctx.bountyId}` : ''}`,\n      ctx,\n    );\n  }\n}\n\n/** claimSlot reverted: wallet has no ERC-8004 Identity NFT. */\nexport class NoAgentIdentityError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super(\n      'Wallet does not hold an ERC-8004 Identity NFT - call ensureIdentity() first',\n      ctx,\n    );\n  }\n}\n\n/** withdrawEarnings reverted: no pending earnings for the given token. */\nexport class NothingToWithdrawError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super('No pending earnings for this token', ctx);\n  }\n}\n\n/** Operation requires bounty status = Open, but it is Resolved or Cancelled. */\nexport class BountyNotOpenError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super(\n      `Bounty${ctx?.bountyId !== undefined ? ` #${ctx.bountyId}` : ''} is not open`,\n      ctx,\n    );\n  }\n}\n\n/** Operation rejected because the bounty deadline has passed. */\nexport class DeadlinePassedError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super(\n      `Bounty${ctx?.bountyId !== undefined ? ` #${ctx.bountyId}` : ''} deadline has passed`,\n      ctx,\n    );\n  }\n}\n\n/** postBounty/postDirectHire: requested bountyType is not enabled on v3. */\nexport class TaskTypeNotEnabledError extends ClaudelanceError {\n  readonly typeId: number;\n\n  constructor(typeId: number, ctx?: ClaudelanceErrorContext) {\n    super(`Task type ${typeId} is not enabled on this contract`, ctx);\n    this.typeId = typeId;\n  }\n}\n\n/** Token is not whitelisted on the contract (allowToken not called). */\nexport class TokenNotAllowedError extends ClaudelanceError {\n  readonly token: string;\n\n  constructor(token: string, ctx?: ClaudelanceErrorContext) {\n    super(`Token ${token} is not whitelisted - call allowToken() via owner`, ctx);\n    this.token = token;\n  }\n}\n\n/** submitDeliverable/submitPR: deliverable has already been submitted for this bounty. */\nexport class AlreadySubmittedError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super(\n      `Deliverable already submitted for bounty${ctx?.bountyId !== undefined ? ` #${ctx.bountyId}` : ''}`,\n      ctx,\n    );\n  }\n}\n\n/** pickWinner failed: no submission from the chosen worker, or CI not passed. */\nexport class WinnerInvalidError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super(\n      `Winner is invalid for bounty${ctx?.bountyId !== undefined ? ` #${ctx.bountyId}` : ''} - check submission and CI status`,\n      ctx,\n    );\n  }\n}\n\n/** claimSlot reverted: every slot on this bounty is already taken. */\nexport class SlotsFullError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super(\n      `All slots are full on bounty${ctx?.bountyId !== undefined ? ` #${ctx.bountyId}` : ''}`,\n      ctx,\n    );\n  }\n}\n\n/** submit/settleStake reverted: caller never claimed a slot on this bounty. */\nexport class NotClaimerError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super(\n      `Caller has not claimed a slot on bounty${ctx?.bountyId !== undefined ? ` #${ctx.bountyId}` : ''}`,\n      ctx,\n    );\n  }\n}\n\n/** pickWinner reverted: the chosen worker has no submission. */\nexport class NoSubmissionError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super(\n      `No submission from the chosen worker on bounty${ctx?.bountyId !== undefined ? ` #${ctx.bountyId}` : ''}`,\n      ctx,\n    );\n  }\n}\n\n/** pickWinner/cancelExpired reverted: caller is not the bounty poster. */\nexport class NotPosterError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super(\n      `Caller is not the poster of bounty${ctx?.bountyId !== undefined ? ` #${ctx.bountyId}` : ''}`,\n      ctx,\n    );\n  }\n}\n\n/**\n * A state-changing call reverted because the contract is paused (OZ Pausable,\n * `EnforcedPause`). Only `withdrawEarnings` stays callable while paused.\n * Check {@link ClaudelanceClient.isPaused} before broadcasting.\n */\nexport class ContractPausedError extends ClaudelanceError {\n  constructor(ctx?: ClaudelanceErrorContext) {\n    super('Contract is paused - only withdrawEarnings is callable', ctx);\n  }\n}\n\n// Revert-string to typed-error mapping.\n\nconst REVERT_MAP: Array<[RegExp, (ctx: ClaudelanceErrorContext) => ClaudelanceError]> = [\n  [/EnforcedPause/i,        (c) => new ContractPausedError(c)],\n  [/AlreadyClaimed/i,       (c) => new AlreadyClaimedError(c)],\n  [/SlotsFull/i,            (c) => new SlotsFullError(c)],\n  [/NotTargetedWorker/i,    (c) => new NotTargetWorkerError(c)],\n  [/NoAgentIdentity/i,      (c) => new NoAgentIdentityError(c)],\n  [/NothingToWithdraw/i,    (c) => new NothingToWithdrawError(c)],\n  [/BountyNotOpen/i,        (c) => new BountyNotOpenError(c)],\n  [/DeadlinePassed/i,       (c) => new DeadlinePassedError(c)],\n  [/TaskTypeNotEnabled/i,   (c) => new TaskTypeNotEnabledError(-1, c)],\n  [/TokenNotAllowed/i,      (c) => new TokenNotAllowedError('unknown', c)],\n  [/AlreadySubmitted/i,     (c) => new AlreadySubmittedError(c)],\n  [/NoSubmission/i,         (c) => new NoSubmissionError(c)],\n  [/NotClaimer/i,           (c) => new NotClaimerError(c)],\n  [/NotPoster/i,            (c) => new NotPosterError(c)],\n  [/WinnerInvalid/i,        (c) => new WinnerInvalidError(c)],\n];\n\n/**\n * Attempt to parse a viem ContractFunctionRevertedError (or any error with a\n * `.message` or nested `.cause.message`) into a typed ClaudelanceError.\n * Returns the original error unchanged if no pattern matches.\n */\nexport function parseContractError(\n  err: unknown,\n  ctx?: ClaudelanceErrorContext,\n): ClaudelanceError | unknown {\n  const msg =\n    (err instanceof Error ? err.message : '') +\n    (err instanceof Error && err.cause instanceof Error ? ' ' + err.cause.message : '');\n\n  for (const [pattern, factory] of REVERT_MAP) {\n    if (pattern.test(msg)) {\n      return factory({ cause: err, ...ctx });\n    }\n  }\n  return err;\n}\n\n/**\n * Same as {@link parseContractError} but always throws.\n * Use inside catch blocks:\n *   catch (err) { throwTyped(err, { bountyId }); }\n */\nexport function throwTyped(err: unknown, ctx?: ClaudelanceErrorContext): never {\n  throw parseContractError(err, ctx);\n}\n","/**\n * Filtered, paginated bounty reads for ClaudelanceCoreV3. Kept out of the\n * client class so it composes with both v2 and v3. Filters run client-side\n * after one multicall batch: fine at hackathon scale, no indexer needed.\n */\n\nimport { type PublicClient, type Address } from 'viem';\nimport {\n  CLAUDELANCE_CORE_V3_ABI,\n  BountyStatus,\n  type Bounty,\n} from '@yeheskieltame/claudelance-types';\n\nconst ZERO_ADDRESS = '0x0000000000000000000000000000000000000000' as const;\nconst DEFAULT_PAGE_SIZE = 20;\nconst MAX_PAGE_SIZE = 100;\n\nexport type ListBountiesOptions = {\n  /**\n   * Filter by status. Use 'all' to include every status.\n   * Defaults to BountyStatus.Open (0).\n   */\n  status?: BountyStatus | 'all';\n  /** Filter by escrow token address. */\n  token?: Address;\n  /** Filter by task type (0-10 for canonical types). */\n  bountyType?: number;\n  /** Filter by poster address. */\n  poster?: Address;\n  /** 1-based page number. Defaults to 1. */\n  page?: number;\n  /** Number of items per page (1-100). Defaults to 20. */\n  pageSize?: number;\n};\n\nexport type BountyWithId = Bounty & { id: bigint };\n\nexport type BountyPage = {\n  items: BountyWithId[];\n  /** Total bounties matching the filter (across all pages). */\n  total: number;\n  page: number;\n  pageSize: number;\n  hasMore: boolean;\n};\n\n/**\n * Return a paginated, filtered list of bounties from a v3 contract.\n *\n * @param publicClient  viem PublicClient connected to the right network.\n * @param core          v3 proxy address (or v2 address - getBounty ABI is compatible).\n * @param maxId         Highest bounty ID to scan. Pass the result of\n *                      `client.getBountyCountV3()` or a known upper bound.\n * @param opts          Filter and pagination options.\n */\nexport async function listBounties(\n  publicClient: PublicClient,\n  core: Address,\n  maxId: bigint,\n  opts: ListBountiesOptions = {},\n): Promise<BountyPage> {\n  if (maxId === 0n) return { items: [], total: 0, page: 1, pageSize: DEFAULT_PAGE_SIZE, hasMore: false };\n\n  const page = Math.max(1, opts.page ?? 1);\n  const pageSize = Math.min(MAX_PAGE_SIZE, Math.max(1, opts.pageSize ?? DEFAULT_PAGE_SIZE));\n  const statusFilter = opts.status ?? BountyStatus.Open;\n\n  // Fetch all bounties in one multicall.\n  const calls = [];\n  for (let i = 1n; i <= maxId; i++) {\n    calls.push({\n      address: core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'getBounty' as const,\n      args: [i] as const,\n    });\n  }\n\n  const results = await publicClient.multicall({\n    contracts: calls,\n    allowFailure: true,\n  });\n\n  // Apply filters.\n  const matched: BountyWithId[] = [];\n  for (let idx = 0; idx < results.length; idx++) {\n    const r = results[idx];\n    if (!r || r.status === 'failure') continue;\n    const b = r.result as Bounty;\n    if (!b || (b as { poster?: string }).poster === ZERO_ADDRESS) continue;\n\n    if (statusFilter !== 'all' && b.status !== statusFilter) continue;\n    if (opts.token && b.token.toLowerCase() !== opts.token.toLowerCase()) continue;\n    if (opts.bountyType !== undefined && b.bountyType !== opts.bountyType) continue;\n    if (opts.poster && (b as { poster?: string }).poster?.toLowerCase() !== opts.poster.toLowerCase()) continue;\n\n    matched.push({ ...(b as Bounty), id: BigInt(idx + 1) });\n  }\n\n  const total = matched.length;\n  const start = (page - 1) * pageSize;\n  const items = matched.slice(start, start + pageSize);\n\n  return { items, total, page, pageSize, hasMore: start + pageSize < total };\n}\n\n/**\n * Convenience: list open bounties for a specific task type across all tokens.\n */\nexport async function listOpenBountiesByType(\n  publicClient: PublicClient,\n  core: Address,\n  maxId: bigint,\n  bountyType: number,\n  opts?: Omit<ListBountiesOptions, 'status' | 'bountyType'>,\n): Promise<BountyPage> {\n  return listBounties(publicClient, core, maxId, {\n    ...opts,\n    status: BountyStatus.Open,\n    bountyType,\n  });\n}\n\n/**\n * Convenience: list all bounties posted by a specific address.\n */\nexport async function listBountiesByPoster(\n  publicClient: PublicClient,\n  core: Address,\n  maxId: bigint,\n  poster: Address,\n  opts?: Omit<ListBountiesOptions, 'poster'>,\n): Promise<BountyPage> {\n  return listBounties(publicClient, core, maxId, { ...opts, poster });\n}\n\n/**\n * Convenience: list all bounties where a worker could be the target\n * (either open marketplace OR direct-hire targeting this worker).\n */\nexport async function listClaimableByWorker(\n  publicClient: PublicClient,\n  core: Address,\n  maxId: bigint,\n  worker: Address,\n  opts?: Omit<ListBountiesOptions, 'status'>,\n): Promise<BountyWithId[]> {\n  const page = await listBounties(publicClient, core, maxId, {\n    ...opts,\n    status: BountyStatus.Open,\n    pageSize: MAX_PAGE_SIZE,\n  });\n  const workerLower = worker.toLowerCase();\n  return page.items.filter((b) => {\n    const tw = ((b as unknown as { targetWorker?: string }).targetWorker ?? '').toLowerCase();\n    return tw === ZERO_ADDRESS || tw === workerLower;\n  });\n}\n","import {\n  createPublicClient,\n  createWalletClient,\n  getAddress,\n  parseEventLogs,\n  type Account,\n  type Address,\n  type Chain,\n  type PublicClient,\n  type Transport,\n  type WalletClient,\n} from 'viem';\nimport { mnemonicToAccount, privateKeyToAccount } from 'viem/accounts';\n\nimport {\n  CLAUDELANCE_CORE_ABI,\n  CLAUDELANCE_CORE_V3_ABI,\n  MAINNET,\n  SEPOLIA,\n  type Bounty,\n  type Deployment,\n  type Submission,\n  type TokenSet,\n  type TypeConfig,\n} from '@yeheskieltame/claudelance-types';\n\nimport { chainForNetwork, type NetworkKey } from './chain.js';\nimport { buildTransport } from './transport.js';\nimport { CUSD_ABI } from './cusd-abi.js';\nimport {\n  throwTyped,\n  parseContractError,\n  AlreadyClaimedError,\n  NothingToWithdrawError,\n} from './errors.js';\nimport {\n  listBounties,\n  listOpenBountiesByType,\n  listBountiesByPoster,\n  listClaimableByWorker,\n  type ListBountiesOptions,\n  type BountyPage,\n  type BountyWithId,\n} from './list-bounties.js';\n\n// setTimeout is a runtime global in both Node and browsers, but the SDK's\n// tsconfig keeps `lib` to ES2022 (no DOM/node) to stay portable, so declare it.\ndeclare function setTimeout(handler: () => void, timeout: number): unknown;\n\nconst ZERO_ADDRESS = '0x0000000000000000000000000000000000000000' as const;\n\n/** Read `process.env` portably: present in Node/edge, absent in the browser. */\nfunction readProcessEnv(): Record<string, string | undefined> {\n  const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;\n  return proc?.env ?? {};\n}\n\n/** Inputs accepted by {@link ClaudelanceClient.fromPrivateKey}. */\nexport type FromPrivateKeyOptions = {\n  privateKey: `0x${string}`;\n  network: NetworkKey;\n  /** Override the default forno RPC; useful for an Alchemy/Infura key. */\n  rpcUrl?: string;\n  /** Several RPC endpoints for fallback redundancy at production scale. */\n  rpcUrls?: string[];\n};\n\n/** Inputs accepted by {@link ClaudelanceClient.fromMnemonic}. */\nexport type FromMnemonicOptions = {\n  /** BIP-39 mnemonic phrase (12 or 24 words). */\n  mnemonic: string;\n  network: NetworkKey;\n  /** Override the default forno RPC; useful for an Alchemy/Infura key. */\n  rpcUrl?: string;\n  /** Several RPC endpoints for fallback redundancy at production scale. */\n  rpcUrls?: string[];\n  /**\n   * BIP-44 derivation path. Defaults to `m/44'/60'/0'/0/0` - the Ethereum\n   * standard for the first account / first address, which matches what\n   * MetaMask + most desktop wallets produce.\n   */\n  derivationPath?: `m/44'/60'/${string}`;\n};\n\n/** Inputs accepted by the {@link ClaudelanceClient} constructor. */\nexport type ClaudelanceClientOptions = {\n  publicClient: PublicClient;\n  walletClient?: WalletClient<Transport, Chain, Account>;\n  core: Address;\n  /** Whitelisted escrow tokens (cUSD, CELO, USDC). */\n  tokens: TokenSet;\n  /** ERC-8004 Identity Registry. Workers must hold a token here to claimSlot. */\n  identityRegistry: Address;\n  /** ERC-8004 Reputation Registry - feedback (reputation) about agents. */\n  reputationRegistry: Address;\n};\n\n/**\n * Payload for {@link ClaudelanceClient.submitDeliverable} (v3).\n * Works for all task types: GitHub PR, Gist, IPFS/Arweave content, etc.\n */\nexport type SubmitDeliverableOptions = {\n  /** Deliverable URL: GitHub PR, Gist, IPFS CID, Arweave TX, or any verifiable URL. */\n  deliverableUrl: string;\n  /** keccak256 of the deliverable content (or git commit SHA padded to bytes32). */\n  deliverableHash: `0x${string}`;\n  /** Free-form JSON: worker capabilities, model used, task-type metadata, etc. */\n  metadata?: string;\n};\n\n/**\n * @deprecated Use {@link SubmitDeliverableOptions}. submitPR is v2-only and does\n * not exist on the v3 contract. This alias is kept for backward compatibility.\n */\nexport type SubmitPROptions = {\n  prUrl: string;\n  commitHash: `0x${string}`;\n  metadata?: string;\n};\n\n/**\n * Stages emitted by {@link ClaudelanceClient.runWorkerLoop} so callers can\n * surface progress in headless logs or a UI progress bar.\n */\nexport type WorkerStage =\n  | \"ensure-identity\"\n  | \"approve\"\n  | \"claim\"\n  | \"submit\"\n  | \"done\";\n\nexport type WorkerProgress = {\n  stage: WorkerStage;\n  tx?: `0x${string}`;\n  detail?: string;\n};\n\nexport type WorkerProgressFn = (progress: WorkerProgress) => void;\n\n/** Payload accepted by {@link ClaudelanceClient.postBounty} (open marketplace). */\nexport type PostBountyOptions = {\n  /** ERC20 used for escrow + payout. Must be whitelisted on chain. */\n  token: Address;\n  /** v3 task type 0-10 (0 = Code). Defaults to 0. */\n  bountyType?: number;\n  targetRepoUrl: string;\n  instructionUrl: string;\n  /** keccak256 of the off-chain JSON spec, or 0x0 for ad-hoc bounties. */\n  requirementsHash?: `0x${string}`;\n  /** Reward in token wei. Must be >= the per-token `minBounty`. */\n  amount: bigint;\n  /** Maximum simultaneous claimers (1..MAX_SLOTS=20). */\n  maxSlots: number;\n  /** Anti-sybil stake in token wei. Must be > 0 on every bounty. */\n  stake: bigint;\n  /** Bounty lifetime in seconds (1..14 days). */\n  deadlineSeconds: bigint;\n  /** Require CI to pass before a winner is eligible. */\n  ciRequired: boolean;\n};\n\n/** Payload accepted by {@link ClaudelanceClient.postDirectHire} (single chosen worker). */\nexport type PostDirectHireOptions = {\n  token: Address;\n  /** Worker who will exclusively own the single slot. Must be non-zero. */\n  targetWorker: Address;\n  bountyType?: number;\n  targetRepoUrl: string;\n  instructionUrl: string;\n  requirementsHash?: `0x${string}`;\n  amount: bigint;\n  /** Stake required from the chosen worker. Must be `> 0`. */\n  stake: bigint;\n  /**\n   * Duration until expiry, in seconds. Relative to `block.timestamp` at post time.\n   * Must be between `86400` (1 day) and `1209600` (14 days).\n   * Example: `BigInt(3 * 86400)` for a 3-day deadline.\n   */\n  deadlineSeconds: bigint;\n};\n\n/**\n * High-level read + write client for ClaudelanceCore (v2 and v3).\n *\n * Default target is the v3 UUPS proxy which supports all 10 task types and\n * `submitDeliverable` (not just GitHub PRs). v2 methods are kept for backward\n * compat but `submitPR` is deprecated - use `submitDeliverable` instead.\n *\n * Multi-token escrow: every write that moves tokens takes (or infers from\n * the bounty) the ERC20 to use. Workers must be registered ERC-8004 agents\n * before they can `claimSlot`.\n */\nexport class ClaudelanceClient {\n  readonly publicClient: PublicClient;\n  readonly walletClient?: WalletClient<Transport, Chain, Account>;\n  readonly core: Address;\n  readonly tokens: TokenSet;\n  readonly identityRegistry: Address;\n  readonly reputationRegistry: Address;\n\n  constructor(opts: ClaudelanceClientOptions) {\n    this.publicClient = opts.publicClient;\n    this.walletClient = opts.walletClient;\n    this.core = opts.core;\n    this.tokens = opts.tokens;\n    this.identityRegistry = opts.identityRegistry;\n    this.reputationRegistry = opts.reputationRegistry;\n  }\n\n  /**\n   * Gas overrides for all Celo write transactions.\n   *\n   * On Celo, CELO is simultaneously the native gas token and the ERC20 used\n   * for bounty escrow. EIP-1559 reserves `gasLimit x maxFeePerGas` from the\n   * native balance before the tx body runs, so a CELO escrow `transferFrom`\n   * can fail even when the balance covers the transfer. A legacy type-0 tx\n   * with an explicit gasPrice avoids that trap.\n   *\n   * The price is read live (not hardcoded): Celo's base fee floats and has\n   * risen well past old fixed values, which made writes revert with\n   * \"gas fee cap is below the minimum base fee\". 2x the current price is the\n   * legacy cap - on an EIP-1559 chain the sender is still only charged the\n   * actual base fee + tip, so the headroom is free insurance against the base\n   * fee moving between read and broadcast.\n   */\n  private async celoGas(gas: bigint = 500_000n) {\n    const gasPrice = await this.publicClient.getGasPrice();\n    return {\n      gasPrice: gasPrice * 2n,\n      gas, // default 500k covers the heaviest write (postBounty); pass less for cheap ops\n    } as const;\n  }\n\n  /** The wallet address this client signs with, or `undefined` for a read-only client. */\n  get address(): Address | undefined {\n    return this.walletClient?.account?.address;\n  }\n\n  /**\n   * Convenience: build a fully-wired client from a private key + network\n   * key. Resolves the canonical addresses from `@yeheskieltame/claudelance-types`.\n   *\n   * Supported networks: `'sepolia'` (Celo Sepolia) and `'celo'` (Celo Mainnet).\n   */\n  static fromPrivateKey(opts: FromPrivateKeyOptions): ClaudelanceClient {\n    const deployment: Deployment = (opts.network === 'celo' || opts.network === 'mainnet') ? MAINNET : SEPOLIA;\n    const chain = chainForNetwork(opts.network);\n    const account = privateKeyToAccount(opts.privateKey);\n    const transport = buildTransport(opts);\n\n    const publicClient = createPublicClient({ chain, transport });\n    const walletClient = createWalletClient({ chain, transport, account });\n\n    return new ClaudelanceClient({\n      publicClient,\n      walletClient,\n      core: deployment.core,\n      tokens: deployment.tokens,\n      identityRegistry: deployment.identityRegistry,\n      reputationRegistry: deployment.reputationRegistry,\n    });\n  }\n\n  /**\n   * Build a read-only client from an RPC URL + network key.\n   * No private key required, only read methods are available.\n   * Write methods throw `[ClaudelanceClient] Write methods require a wallet client`.\n   */\n  static fromRpcUrl(opts: { rpcUrl?: string; rpcUrls?: string[]; network: NetworkKey }): ClaudelanceClient {\n    const deployment: Deployment = (opts.network === 'celo' || opts.network === 'mainnet') ? MAINNET : SEPOLIA;\n    const chain = chainForNetwork(opts.network);\n    const transport = buildTransport(opts);\n    const publicClient = createPublicClient({ chain, transport });\n\n    return new ClaudelanceClient({\n      publicClient,\n      core: deployment.core,\n      tokens: deployment.tokens,\n      identityRegistry: deployment.identityRegistry,\n      reputationRegistry: deployment.reputationRegistry,\n    });\n  }\n\n  /**\n   * Build a fully-wired client from a BIP-39 mnemonic + network key.\n   * Friendly onboarding path: an operator can paste their seed phrase\n   * (12 or 24 words) without ever extracting the raw private key.\n   *\n   * Default derivation `m/44'/60'/0'/0/0` (Ethereum standard, first\n   * account / first address). Override `derivationPath` to use a\n   * different index, e.g. `m/44'/60'/0'/0/1` for the second address.\n   *\n   * Supported networks: `'sepolia'` (Celo Sepolia) and `'celo'` (Celo Mainnet).\n   */\n  static fromMnemonic(opts: FromMnemonicOptions): ClaudelanceClient {\n    const deployment: Deployment = (opts.network === 'celo' || opts.network === 'mainnet') ? MAINNET : SEPOLIA;\n    const chain = chainForNetwork(opts.network);\n    const account = mnemonicToAccount(opts.mnemonic, {\n      path: opts.derivationPath ?? \"m/44'/60'/0'/0/0\",\n    });\n    const transport = buildTransport(opts);\n\n    const publicClient = createPublicClient({ chain, transport });\n    const walletClient = createWalletClient({ chain, transport, account });\n\n    return new ClaudelanceClient({\n      publicClient,\n      walletClient,\n      core: deployment.core,\n      tokens: deployment.tokens,\n      identityRegistry: deployment.identityRegistry,\n      reputationRegistry: deployment.reputationRegistry,\n    });\n  }\n\n  /**\n   * Zero-config factory for agents and serverless: build a client from\n   * environment variables. Drops straight into a deployment or an AI skill\n   * without bespoke wiring.\n   *\n   * Reads (first match wins):\n   * - key:     `CLAUDELANCE_PRIVATE_KEY` | `PRIVATE_KEY` (omit → read-only client)\n   * - network: `CLAUDELANCE_NETWORK` | `NETWORK` (default `celo`)\n   * - rpc:     `CLAUDELANCE_RPC_URLS` (comma-separated, multi-RPC fallback)\n   *            | `CLAUDELANCE_RPC_URL` | `CELO_RPC_URL` (single)\n   *\n   * Pass `env` to read from an explicit record; defaults to `process.env`\n   * when available (Node / edge), else an empty object (browser).\n   */\n  static fromEnv(env: Record<string, string | undefined> = readProcessEnv()): ClaudelanceClient {\n    const network = (env.CLAUDELANCE_NETWORK ?? env.NETWORK ?? 'celo') as NetworkKey;\n    const rpcCsv = env.CLAUDELANCE_RPC_URLS;\n    const rpcUrls = rpcCsv\n      ? rpcCsv.split(',').map((s) => s.trim()).filter(Boolean)\n      : undefined;\n    const rpcUrl = env.CLAUDELANCE_RPC_URL ?? env.CELO_RPC_URL;\n    const privateKey = (env.CLAUDELANCE_PRIVATE_KEY ?? env.PRIVATE_KEY) as `0x${string}` | undefined;\n\n    if (privateKey) {\n      return ClaudelanceClient.fromPrivateKey({ privateKey, network, rpcUrl, rpcUrls });\n    }\n    return ClaudelanceClient.fromRpcUrl({ network, rpcUrl, rpcUrls });\n  }\n\n  // Read API\n\n  async getBounty(bountyId: bigint): Promise<Bounty> {\n    return (await this.publicClient.readContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'getBounty',\n      args: [bountyId],\n    })) as Bounty;\n  }\n\n  /**\n   * A worker's submission for a bounty, including the relayer's CI verdict.\n   * v3: fields are `deliverableUrl` + `deliverableHash` (not prUrl/commitHash).\n   * `submittedAt === 0n` means the worker has not submitted yet.\n   */\n  async getSubmission(bountyId: bigint, worker: Address): Promise<Submission> {\n    return (await this.publicClient.readContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'getSubmission',\n      args: [bountyId, worker],\n    })) as Submission;\n  }\n\n  /**\n   * Poll `getBounty` until `predicate` holds (or attempts run out), returning\n   * the last-read bounty. Use this to bridge a write and a dependent read:\n   * public RPCs like forno load-balance, so a read issued right after a mined\n   * write can hit a lagging node and return pre-write state. e.g. after\n   * `pickWinner`, `await waitForBounty(id, (b) => b.status === 1)` before\n   * `settleStake` so it doesn't revert `BountyNotExpired` (the v3 guard for\n   * settling a stake while the bounty is still Open).\n   */\n  async waitForBounty(\n    bountyId: bigint,\n    predicate: (bounty: Bounty) => boolean,\n    opts?: { attempts?: number; intervalMs?: number },\n  ): Promise<Bounty> {\n    const attempts = opts?.attempts ?? 10;\n    const intervalMs = opts?.intervalMs ?? 2500;\n    let bounty = await this.getBounty(bountyId);\n    for (let i = 1; i < attempts && !predicate(bounty); i++) {\n      await new Promise<void>((resolve) => setTimeout(() => resolve(), intervalMs));\n      bounty = await this.getBounty(bountyId);\n    }\n    return bounty;\n  }\n\n  /**\n   * Poll `getSubmission` until `predicate` holds (or attempts run out), returning\n   * the last-read submission. Bridges a submit write and a dependent read: forno\n   * load-balances, so a read issued right after a mined `submitDeliverable` can\n   * hit a lagging replica and return an empty submission. Default predicate waits\n   * for a non-zero `submittedAt`. Mirrors {@link waitForBounty}.\n   */\n  async waitForSubmission(\n    bountyId: bigint,\n    worker: Address,\n    predicate: (submission: Submission) => boolean = (s) => s.submittedAt > 0n,\n    opts?: { attempts?: number; intervalMs?: number },\n  ): Promise<Submission> {\n    const attempts = opts?.attempts ?? 10;\n    const intervalMs = opts?.intervalMs ?? 2500;\n    let submission = await this.getSubmission(bountyId, worker);\n    for (let i = 1; i < attempts && !predicate(submission); i++) {\n      await new Promise<void>((resolve) => setTimeout(() => resolve(), intervalMs));\n      submission = await this.getSubmission(bountyId, worker);\n    }\n    return submission;\n  }\n\n  /**\n   * Total bounty count. On v2, reads the `bountyCount` public getter.\n   * On v3 (EIP-7201 storage, no public getter), falls back to `getBountyCountV3`.\n   *\n   * For new code targeting v3, prefer `getBountyCountV3()` directly.\n   */\n  async getBountyCount(): Promise<bigint> {\n    try {\n      return (await this.publicClient.readContract({\n        address: this.core,\n        abi: CLAUDELANCE_CORE_ABI,\n        functionName: 'bountyCount',\n      })) as bigint;\n    } catch {\n      return this.getBountyCountV3();\n    }\n  }\n\n  /**\n   * Return every currently-open bounty via multicall.\n   * Uses `getBountyCountV3` for scan range on v3 (binary search, O(log n)).\n   */\n  async listOpenBounties(): Promise<Array<Bounty & { id: bigint }>> {\n    const count = await this.getBountyCountV3();\n    if (count === 0n) return [];\n\n    const calls = [];\n    for (let i = 1n; i <= count; i++) {\n      calls.push({\n        address: this.core,\n        abi: CLAUDELANCE_CORE_V3_ABI,\n        functionName: 'getBounty' as const,\n        args: [i] as const,\n      });\n    }\n    const results = await this.publicClient.multicall({\n      contracts: calls,\n      allowFailure: true,\n    });\n\n    const out: Array<Bounty & { id: bigint }> = [];\n    for (let idx = 0; idx < results.length; idx++) {\n      const r = results[idx];\n      if (!r || r.status === 'failure') continue;\n      const b = r.result as Bounty;\n      if (b.status === 0) out.push({ ...b, id: BigInt(idx + 1) });\n    }\n    return out;\n  }\n\n  /**\n   * Filtered, paginated bounty list (v3).\n   * Scans up to `maxId` in one multicall, applies filters client-side.\n   * Uses `getBountyCountV3()` for the scan range if `maxId` is not provided.\n   *\n   * @example\n   * const page = await client.listBounties({ bountyType: 2, pageSize: 10 })\n   * page.items.forEach(b => console.log(b.id, b.instructionUrl))\n   */\n  async listBounties(opts?: ListBountiesOptions, maxId?: bigint): Promise<BountyPage> {\n    const count = maxId ?? await this.getBountyCountV3();\n    return listBounties(this.publicClient, this.core, count, opts);\n  }\n\n  /** List open bounties of a specific task type (v3). */\n  async listOpenBountiesByType(bountyType: number, opts?: Omit<ListBountiesOptions, 'status' | 'bountyType'>): Promise<BountyPage> {\n    const count = await this.getBountyCountV3();\n    return listOpenBountiesByType(this.publicClient, this.core, count, bountyType, opts);\n  }\n\n  /** List all bounties posted by a specific address (v3). */\n  async listBountiesByPoster(poster: Address, opts?: Omit<ListBountiesOptions, 'poster'>): Promise<BountyPage> {\n    const count = await this.getBountyCountV3();\n    return listBountiesByPoster(this.publicClient, this.core, count, poster, opts);\n  }\n\n  /** List open bounties the given worker address can claim (v3). */\n  async listClaimableByWorker(worker?: Address): Promise<BountyWithId[]> {\n    const who = worker ?? this.requireAccount();\n    const count = await this.getBountyCountV3();\n    return listClaimableByWorker(this.publicClient, this.core, count, who);\n  }\n\n  /** Per-token marketplace stats. `resolved`, `posters`, `workers` are global. */\n  async getStats(token: Address): Promise<{\n    volume: bigint;\n    revenue: bigint;\n    resolved: bigint;\n    posters: bigint;\n    workers: bigint;\n  }> {\n    const [volume, revenue, resolved, posters, workers] =\n      (await this.publicClient.readContract({\n        address: this.core,\n        abi: CLAUDELANCE_CORE_V3_ABI,\n        functionName: 'getStats',\n        args: [token],\n      })) as readonly [bigint, bigint, bigint, bigint, bigint];\n    return { volume, revenue, resolved, posters, workers };\n  }\n\n  /**\n   * Pending earnings for an address in a specific token.\n   *\n   * v2 only: reads the `earnings(address, token)` public mapping getter.\n   * On v3 this getter does not exist (EIP-7201 storage). For v3, earnings\n   * are opaque until `withdrawEarnings` is called - use `EarningsWithdrawn`\n   * event logs via `listProtocolRevenueEvents` or `watchEarningsWithdrawn`\n   * to audit past withdrawals.\n   */\n  async getEarnings(account: Address, token: Address): Promise<bigint> {\n    try {\n      return (await this.publicClient.readContract({\n        address: this.core,\n        abi: CLAUDELANCE_CORE_ABI,\n        functionName: 'earnings',\n        args: [account, token],\n      })) as bigint;\n    } catch {\n      // v3 does not expose the earnings mapping as a public getter.\n      return 0n;\n    }\n  }\n\n  /**\n   * Pending earnings for the connected wallet in a specific token.\n   * Returns 0 on v3 (earnings not readable - see `getEarnings` for details).\n   */\n  async getMyEarnings(token: Address): Promise<bigint> {\n    return this.getEarnings(this.requireAccount(), token);\n  }\n\n  /**\n   * Native-token-style balances for the three marketplace tokens in a single\n   * multicall. Defaults to the connected account; pass an address to inspect\n   * any wallet. Handy for a worker checking it can cover a stake, or an agent\n   * surfacing balances without three round-trips.\n   */\n  async getBalances(account?: Address): Promise<{ cUSD: bigint; CELO: bigint; USDC: bigint }> {\n    const owner = account ?? this.requireAccount();\n    const tokens = [this.tokens.cUSD, this.tokens.CELO, this.tokens.USDC] as const;\n    const results = await this.publicClient.multicall({\n      allowFailure: true,\n      contracts: tokens.map((address) => ({\n        address,\n        abi: ERC721_BALANCE_OF_ABI,\n        functionName: 'balanceOf' as const,\n        args: [owner] as const,\n      })),\n    });\n    const at = (i: number): bigint =>\n      results[i]?.status === 'success' ? (results[i].result as bigint) : 0n;\n    return { cUSD: at(0), CELO: at(1), USDC: at(2) };\n  }\n\n  /** True iff `agent` holds at least one ERC-8004 Identity NFT. */\n  async hasAgentIdentity(agent: Address): Promise<boolean> {\n    const balance = (await this.publicClient.readContract({\n      address: this.identityRegistry,\n      abi: ERC721_BALANCE_OF_ABI,\n      functionName: 'balanceOf',\n      args: [agent],\n    })) as bigint;\n    return balance > 0n;\n  }\n\n  /**\n   * Resolve an address's ERC-8004 agent id (its Identity NFT token id). The\n   * registry has no reverse lookup, so this scans the mint `Transfer` event\n   * backwards in 2M-block chunks (public RPCs cap `getLogs` ranges) until a\n   * mint is found, up to ~30M blocks back. Pass `fromBlock` to pin a single\n   * `[fromBlock, latest]` scan instead. Returns `null` if no mint is found.\n   */\n  async agentIdOf(agent: Address, opts?: { fromBlock?: bigint }): Promise<bigint | null> {\n    const latest = await this.publicClient.getBlockNumber();\n    const CHUNK = 2_000_000n;\n    const MAX_CHUNKS = 15;\n    let toBlock = latest;\n    let fromBlock = opts?.fromBlock ?? (toBlock > CHUNK ? toBlock - CHUNK : 0n);\n    for (let i = 0; i < MAX_CHUNKS; i++) {\n      const logs = await this.publicClient.getLogs({\n        address: this.identityRegistry,\n        event: IDENTITY_TRANSFER_EVENT,\n        args: { to: agent },\n        fromBlock,\n        toBlock,\n      });\n      const minted = logs.find((l) => (l.args as { from?: Address }).from === ZERO_ADDRESS) ?? logs[0];\n      const tokenId = (minted?.args as { tokenId?: bigint } | undefined)?.tokenId;\n      if (tokenId !== undefined) return tokenId;\n      if (opts?.fromBlock !== undefined || fromBlock === 0n) return null;\n      toBlock = fromBlock - 1n;\n      fromBlock = toBlock > CHUNK ? toBlock - CHUNK : 0n;\n    }\n    return null;\n  }\n\n  /**\n   * Read an agent's ERC-8004 reputation. Feedback is per-(agent, client), so\n   * this enumerates the agent's clients then summarises across them.\n   * `feedbackCount` is the total number of (non-revoked) feedback entries.\n   */\n  async getReputation(\n    agentId: bigint,\n  ): Promise<{ clients: Address[]; feedbackCount: bigint; score: bigint }> {\n    const clients = (await this.publicClient.readContract({\n      address: this.reputationRegistry,\n      abi: REPUTATION_ABI,\n      functionName: 'getClients',\n      args: [agentId],\n    })) as Address[];\n    if (clients.length === 0) return { clients, feedbackCount: 0n, score: 0n };\n    const [count, score] = (await this.publicClient.readContract({\n      address: this.reputationRegistry,\n      abi: REPUTATION_ABI,\n      functionName: 'getSummary',\n      args: [agentId, clients, '', ''],\n    })) as readonly [bigint, bigint, number];\n    return { clients, feedbackCount: count, score };\n  }\n\n  /**\n   * Give on-chain feedback (reputation) about an agent via the ERC-8004\n   * Reputation Registry. The caller is recorded as the client; it must NOT be\n   * the agent's owner/operator (the registry blocks self-feedback). Defaults\n   * to a +1 positive rating tagged for a resolved Claudelance bounty.\n   */\n  async giveFeedback(\n    agentId: bigint,\n    opts?: {\n      value?: bigint;\n      valueDecimals?: number;\n      tag1?: string;\n      tag2?: string;\n      endpoint?: string;\n      feedbackURI?: string;\n      feedbackHash?: `0x${string}`;\n    },\n  ): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.reputationRegistry,\n      abi: REPUTATION_ABI,\n      functionName: 'giveFeedback',\n      args: [\n        agentId,\n        opts?.value ?? 1n,\n        opts?.valueDecimals ?? 0,\n        opts?.tag1 ?? 'claudelance',\n        opts?.tag2 ?? 'bounty-resolved',\n        opts?.endpoint ?? '',\n        opts?.feedbackURI ?? '',\n        opts?.feedbackHash ?? `0x${'0'.repeat(64)}`,\n      ],\n      account: wallet.account,\n      chain: wallet.chain,\n      ...(await this.celoGas(300_000n)),\n    });\n  }\n\n  /**\n   * Ensure the wallet has an ERC-8004 Identity NFT. Idempotent:\n   * - If already registered, returns `{ tokenId: 0n, minted: false }` immediately\n   *   (no on-chain write, tokenId 0n is a sentinel meaning \"use other lookups\").\n   * - If not registered, calls `IdentityRegistry.register()` from the wallet,\n   *   waits for the receipt, and returns `{ tokenId, minted: true }` where\n   *   tokenId is parsed from the simulated return value.\n   *\n   * Use this at the top of any worker session before `claimSlot` so the\n   * on-chain `NoAgentIdentity` guard is guaranteed to pass.\n   */\n  async ensureIdentity(): Promise<{ tokenId: bigint; minted: boolean; tx?: `0x${string}` }> {\n    const wallet = this.requireWalletClient();\n    const who = wallet.account.address;\n\n    if (await this.hasAgentIdentity(who)) {\n      return { tokenId: 0n, minted: false };\n    }\n\n    const { result } = await this.publicClient.simulateContract({\n      address: this.identityRegistry,\n      abi: IDENTITY_REGISTRY_REGISTER_ABI,\n      functionName: 'register',\n      account: wallet.account,\n    });\n\n    const tx = await wallet.writeContract({\n      address: this.identityRegistry,\n      abi: IDENTITY_REGISTRY_REGISTER_ABI,\n      functionName: 'register',\n      account: wallet.account,\n      chain: wallet.chain,\n      ...(await this.celoGas(300_000n)),\n    });\n    await this.publicClient.waitForTransactionReceipt({ hash: tx });\n\n    return { tokenId: result as bigint, minted: true, tx };\n  }\n\n  /**\n   * Eligibility check before claiming. Mirrors the v3 on-chain guards so\n   * agents don't waste gas on a guaranteed-revert `claimSlot` call.\n   *\n   * Note: the `hasClaimed(bountyId, worker)` mapping getter exists on v2 but\n   * is not a public getter on v3 (EIP-7201 namespaced storage). To check if\n   * the wallet already claimed on v3, call `getClaimers(bountyId)` and search\n   * the result - or just attempt `claimSlot` and catch `AlreadyClaimedError`.\n   */\n  async canClaim(bountyId: bigint, account?: Address): Promise<boolean> {\n    const who = account ?? this.requireAccount();\n    const b = await this.getBounty(bountyId);\n    if (b.status !== 0) return false;\n    if (b.deadline <= BigInt(Math.floor(Date.now() / 1000))) return false;\n    if (b.claimedSlots >= b.maxSlots) return false;\n    if (b.targetWorker !== ZERO_ADDRESS && b.targetWorker.toLowerCase() !== who.toLowerCase()) {\n      return false;\n    }\n    if (!(await this.hasAgentIdentity(who))) return false;\n\n    // On v3: check the claimers list. On v2: try the hasClaimed getter.\n    try {\n      const claimers = await this.getClaimers(bountyId);\n      return !claimers.some((c) => c.toLowerCase() === who.toLowerCase());\n    } catch {\n      // v2 fallback: hasClaimed public getter\n      try {\n        const claimed = (await this.publicClient.readContract({\n          address: this.core,\n          abi: CLAUDELANCE_CORE_ABI,\n          functionName: 'hasClaimed',\n          args: [bountyId, who],\n        })) as boolean;\n        return !claimed;\n      } catch {\n        return true; // cannot determine - optimistically allow\n      }\n    }\n  }\n\n  // Worker write API\n\n  async claimSlot(bountyId: bigint): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'claimSlot',\n      args: [bountyId],\n      account: wallet.account,\n      chain: wallet.chain,\n      // ~200k actual; a tight limit keeps the node's up-front balance check\n      // (gasLimit x gasPrice) low so minimally funded workers can claim.\n      ...(await this.celoGas(300_000n)),\n    });\n  }\n\n  /**\n   * Approve the bounty's token for the required stake (if needed) then\n   * claim the slot. Two transactions max; the approval is awaited so\n   * `claimSlot` cannot race ahead of an unmined approval.\n   */\n  async claimSlotWithApproval(bountyId: bigint): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    const who = wallet.account.address;\n    const bounty = await this.getBounty(bountyId);\n    const stake = bounty.stakeRequired;\n\n    if (stake > 0n) {\n      await this.ensureAllowance(bounty.token, who, stake);\n    }\n    return this.claimSlot(bountyId);\n  }\n\n  /**\n   * Submit a deliverable for any task type (v3). Replaces `submitPR`.\n   * Works for GitHub PRs (type 0), Gist/IPFS/Arweave for all other types.\n   */\n  async submitDeliverable(bountyId: bigint, opts: SubmitDeliverableOptions): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'submitDeliverable',\n      args: [bountyId, opts.deliverableUrl, opts.deliverableHash, opts.metadata ?? ''],\n      account: wallet.account,\n      chain: wallet.chain,\n      // URL + metadata strings dominate the cost; 400k covers long ones.\n      ...(await this.celoGas(400_000n)),\n    });\n  }\n\n  /**\n   * @deprecated v3 contract uses `submitDeliverable`. This wrapper maps v2 field\n   * names to the v3 call so existing code keeps working against the v3 proxy.\n   */\n  async submitPR(bountyId: bigint, opts: SubmitPROptions): Promise<`0x${string}`> {\n    return this.submitDeliverable(bountyId, {\n      deliverableUrl: opts.prUrl,\n      deliverableHash: opts.commitHash,\n      metadata: opts.metadata,\n    });\n  }\n\n  async settleStake(bountyId: bigint, worker?: Address): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'settleStake',\n      args: [bountyId, worker ?? wallet.account.address],\n      account: wallet.account,\n      chain: wallet.chain,\n      ...(await this.celoGas(200_000n)),\n    });\n  }\n\n  /**\n   * Write +1 ERC-8004 feedback for the winner of a resolved bounty (v3.1).\n   * Permissionless: any wallet can close the reputation tail, the contract\n   * verifies that `agentId` is the identity NFT owned by the bounty winner.\n   * One attestation per bounty.\n   *\n   * Reverts typed: `BountyNotResolved` before `pickWinner`, `AlreadyAttested`\n   * on a second call (check {@link isReputationAttested} first), and\n   * `AgentNotWinner` when the supplied `agentId` does not belong to the\n   * winner. Look the id up with {@link agentIdOf} on the winner address.\n   */\n  async attestReputation(bountyId: bigint, agentId: bigint): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'attestReputation',\n      args: [bountyId, agentId],\n      account: wallet.account,\n      chain: wallet.chain,\n      // ownerOf read + external giveFeedback write on the reputation registry\n      ...(await this.celoGas(300_000n)),\n    });\n  }\n\n  /** Pull-pattern withdrawal for a single token. Always callable, even when paused. */\n  async withdrawEarnings(token: Address): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'withdrawEarnings',\n      args: [token],\n      account: wallet.account,\n      chain: wallet.chain,\n      // withdraw costs ~62k gas; a tight limit keeps the up-front reserve\n      // (gas x gasPrice) small so a low-balance winner can still pull earnings.\n      ...(await this.celoGas(150_000n)),\n    });\n  }\n\n  /**\n   * Convenience: sweep earnings for every whitelisted token, plus any\n   * `extraTokens` passed in (e.g. a non-core settlement token like $LANCE that a\n   * bounty paid out in). Extra tokens are de-duplicated against the whitelist.\n   *\n   * v3 has no `earnings` getter, so each token is probed with a simulation\n   * first: tokens with nothing to withdraw revert `NothingToWithdraw` and are\n   * skipped (no gas burned on a guaranteed-revert tx). Real withdrawals are\n   * sent one at a time, awaiting each receipt before the next, so nonces\n   * advance cleanly. Firing them back-to-back collides on nonce.\n   */\n  async withdrawAllEarnings(extraTokens: Address[] = []): Promise<Array<{ token: Address; hash: `0x${string}` }>> {\n    const wallet = this.requireWalletClient();\n    const tokens: Address[] = [this.tokens.cUSD, this.tokens.CELO, this.tokens.USDC];\n    const seen = new Set(tokens.map((t) => t.toLowerCase()));\n    for (const t of extraTokens) {\n      const key = t.toLowerCase();\n      if (!seen.has(key)) {\n        seen.add(key);\n        tokens.push(t);\n      }\n    }\n    const out: Array<{ token: Address; hash: `0x${string}` }> = [];\n    for (const t of tokens) {\n      try {\n        await this.publicClient.simulateContract({\n          address: this.core,\n          abi: CLAUDELANCE_CORE_V3_ABI,\n          functionName: 'withdrawEarnings',\n          args: [t],\n          account: wallet.account,\n        });\n      } catch (err) {\n        if (parseContractError(err) instanceof NothingToWithdrawError) continue;\n        throwTyped(err);\n      }\n      const hash = await this.withdrawEarnings(t);\n      await this.publicClient.waitForTransactionReceipt({ hash });\n      out.push({ token: t, hash });\n    }\n    return out;\n  }\n\n  /**\n   * Approve every whitelisted token in `this.tokens` (cUSD/CELO/USDC) to\n   * the Core for `type(uint256).max` if the current allowance is short.\n   * Idempotent: tokens already approved are reported with `hash: null`.\n   *\n   * Useful first-run helper so a worker only signs three approve tx once\n   * and can then `claimSlot` against any future bounty regardless of token.\n   */\n  async approveAllTokens(): Promise<Array<{ token: Address; hash: `0x${string}` | null }>> {\n    const wallet = this.requireWalletClient();\n    const owner = wallet.account.address;\n    const tokens: Address[] = [this.tokens.cUSD, this.tokens.CELO, this.tokens.USDC];\n    const max = (2n ** 256n) - 1n;\n\n    const out: Array<{ token: Address; hash: `0x${string}` | null }> = [];\n    for (const t of tokens) {\n      const allowance = (await this.publicClient.readContract({\n        address: t,\n        abi: CUSD_ABI,\n        functionName: 'allowance',\n        args: [owner, this.core],\n      })) as bigint;\n      if (allowance >= max / 2n) {\n        out.push({ token: t, hash: null });\n        continue;\n      }\n      const hash = await wallet.writeContract({\n        address: t,\n        abi: CUSD_ABI,\n        functionName: 'approve',\n        args: [this.core, max],\n        account: wallet.account,\n        chain: wallet.chain,\n      });\n      await this.publicClient.waitForTransactionReceipt({ hash });\n      out.push({ token: t, hash });\n    }\n    return out;\n  }\n\n  /**\n   * Orchestrator: claim slot (with auto-approval) then submit the deliverable\n   * in one call. Skips `claimSlot` if the wallet already holds the slot.\n   * Returns both tx hashes (`claimTx` is `null` when the slot was already claimed).\n   *\n   * Accepts either v3 `SubmitDeliverableOptions` or the legacy v2 `SubmitPROptions` shape.\n   */\n  async solveAndSubmit(opts: {\n    bountyId: bigint;\n    /** v3: deliverable URL (GitHub PR, Gist, IPFS, Arweave). */\n    deliverableUrl?: string;\n    /** v3: keccak256 content hash (or commit SHA padded to bytes32). */\n    deliverableHash?: `0x${string}`;\n    /** @deprecated v2 alias for deliverableUrl */\n    prUrl?: string;\n    /** @deprecated v2 alias for deliverableHash */\n    commitHash?: `0x${string}`;\n    metadata?: string;\n  }): Promise<{ claimTx: `0x${string}` | null; submitTx: `0x${string}` }> {\n    const wallet = this.requireWalletClient();\n    const me = wallet.account.address;\n\n    // v3 does not expose hasClaimed as a public getter; attempt claim and catch AlreadyClaimed.\n    let claimTx: `0x${string}` | null = null;\n    try {\n      claimTx = await this.claimSlotWithApproval(opts.bountyId);\n      await this.publicClient.waitForTransactionReceipt({ hash: claimTx });\n    } catch (err) {\n      if (err instanceof AlreadyClaimedError) {\n        claimTx = null;\n      } else {\n        throwTyped(err, { bountyId: opts.bountyId });\n      }\n    }\n\n    const url = opts.deliverableUrl ?? opts.prUrl ?? '';\n    const hash = opts.deliverableHash ?? opts.commitHash ?? `0x${'0'.repeat(64)}`;\n    const submitTx = await this.submitDeliverable(opts.bountyId, {\n      deliverableUrl: url,\n      deliverableHash: hash as `0x${string}`,\n      metadata: opts.metadata,\n    });\n    await this.publicClient.waitForTransactionReceipt({ hash: submitTx });\n    return { claimTx, submitTx };\n  }\n\n  /**\n   * Headless worker-side orchestration for any task type (v3). Walks the worker\n   * through the full onboarding-to-submission flow with progress events.\n   * Use this for cold-start workers; use {@link solveAndSubmit} when already set up.\n   *\n   * Stages emitted in order:\n   *   1. ensure-identity - mints ERC-8004 Identity NFT if missing\n   *   2. approve         - approves Core to pull token stake (skipped if already max)\n   *   3. claim           - claimSlot(bountyId) (skipped if already claimed)\n   *   4. submit          - submitDeliverable(bountyId, ...)\n   *   5. done            - terminal event with the final submit tx hash\n   */\n  async runWorkerLoop(opts: {\n    bountyId: bigint;\n    /** Deliverable URL: GitHub PR, Gist, IPFS CID, Arweave TX, etc. */\n    deliverableUrl?: string;\n    deliverableHash?: `0x${string}`;\n    /** @deprecated Use deliverableUrl */\n    prUrl?: string;\n    /** @deprecated Use deliverableHash */\n    commitHash?: `0x${string}`;\n    metadata?: string;\n    onProgress?: WorkerProgressFn;\n  }): Promise<{\n    identityTx: `0x${string}` | null;\n    claimTx: `0x${string}` | null;\n    submitTx: `0x${string}`;\n  }> {\n    const emit = opts.onProgress ?? (() => {});\n\n    emit({ stage: \"ensure-identity\" });\n    const identityRes = await this.ensureIdentity();\n    const identityTx = identityRes.minted ? (identityRes.tx ?? null) : null;\n\n    let claimTx: `0x${string}` | null = null;\n    try {\n      emit({ stage: \"approve\" });\n      claimTx = await this.claimSlotWithApproval(opts.bountyId);\n      emit({ stage: \"claim\", tx: claimTx });\n      await this.publicClient.waitForTransactionReceipt({ hash: claimTx });\n    } catch (err) {\n      if (err instanceof AlreadyClaimedError) {\n        emit({ stage: \"claim\", detail: \"already-claimed\" });\n        claimTx = null;\n      } else {\n        throwTyped(err, { bountyId: opts.bountyId });\n      }\n    }\n\n    const url = opts.deliverableUrl ?? opts.prUrl ?? '';\n    const hash = opts.deliverableHash ?? opts.commitHash ?? `0x${'0'.repeat(64)}`;\n    const submitTx = await this.submitDeliverable(opts.bountyId, {\n      deliverableUrl: url,\n      deliverableHash: hash as `0x${string}`,\n      metadata: opts.metadata,\n    });\n    emit({ stage: \"submit\", tx: submitTx });\n    await this.publicClient.waitForTransactionReceipt({ hash: submitTx });\n    emit({ stage: \"done\", tx: submitTx });\n\n    return { identityTx, claimTx, submitTx };\n  }\n\n  // Poster write API\n\n  async postBounty(opts: PostBountyOptions): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'postBounty',\n      args: [\n        opts.token,\n        opts.bountyType ?? 0,\n        opts.targetRepoUrl,\n        opts.instructionUrl,\n        opts.requirementsHash ?? `0x${'0'.repeat(64)}`,\n        opts.amount,\n        opts.maxSlots,\n        opts.stake,\n        opts.deadlineSeconds,\n        opts.ciRequired,\n      ],\n      account: wallet.account,\n      chain: wallet.chain,\n      ...(await this.celoGas()),\n    });\n  }\n\n  async postBountyWithApproval(opts: PostBountyOptions): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    await this.ensureAllowance(opts.token, wallet.account.address, opts.amount);\n    return this.postBounty(opts);\n  }\n\n  /**\n   * Post an open bounty (with approval) and return its id parsed from the\n   * `BountyPosted` event in the receipt. Prefer this over `postBounty` +\n   * `getBountyCount()`: forno load-balances, so a count read right after the\n   * post can hit a lagging node and return the pre-post value.\n   */\n  async postBountyAndGetId(\n    opts: PostBountyOptions,\n  ): Promise<{ hash: `0x${string}`; bountyId: bigint }> {\n    const hash = await this.postBountyWithApproval(opts);\n    return { hash, bountyId: await this.bountyIdFromReceipt(hash) };\n  }\n\n  async postDirectHire(opts: PostDirectHireOptions): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'postDirectHire',\n      args: [\n        opts.token,\n        opts.targetWorker,\n        opts.bountyType ?? 0,\n        opts.targetRepoUrl,\n        opts.instructionUrl,\n        opts.requirementsHash ?? `0x${'0'.repeat(64)}`,\n        opts.amount,\n        opts.stake,\n        opts.deadlineSeconds,\n      ],\n      account: wallet.account,\n      chain: wallet.chain,\n      ...(await this.celoGas()),\n    });\n  }\n\n  async postDirectHireWithApproval(opts: PostDirectHireOptions): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    await this.ensureAllowance(opts.token, wallet.account.address, opts.amount);\n    return this.postDirectHire(opts);\n  }\n\n  /**\n   * Post a direct-hire bounty (with approval) and return its id parsed from the\n   * `BountyPosted` event in the receipt. Prefer this over `postDirectHire` +\n   * `getBountyCount()` - see {@link postBountyAndGetId}.\n   */\n  async postDirectHireAndGetId(\n    opts: PostDirectHireOptions,\n  ): Promise<{ hash: `0x${string}`; bountyId: bigint }> {\n    const hash = await this.postDirectHireWithApproval(opts);\n    return { hash, bountyId: await this.bountyIdFromReceipt(hash) };\n  }\n\n  async pickWinner(bountyId: bigint, winner: Address): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'pickWinner',\n      args: [bountyId, winner],\n      account: wallet.account,\n      chain: wallet.chain,\n      ...(await this.celoGas()),\n    });\n  }\n\n  /**\n   * Resolve a bounty AND reward the winner's ERC-8004 reputation in one call:\n   * `pickWinner` then `giveFeedback` about the winner's agent. The Core never\n   * touches the Reputation registry, so this is how reputation accrues per\n   * resolved bounty. Pass `agentId` to skip the (log-scanning) `agentIdOf`\n   * lookup. Returns `feedbackTx: null` if the winner has no resolvable agent id.\n   */\n  async pickWinnerAndReward(\n    bountyId: bigint,\n    winner: Address,\n    opts?: {\n      agentId?: bigint;\n      feedback?: Parameters<ClaudelanceClient['giveFeedback']>[1];\n    },\n  ): Promise<{ pickTx: `0x${string}`; feedbackTx: `0x${string}` | null }> {\n    const pickTx = await this.pickWinner(bountyId, winner);\n    await this.publicClient.waitForTransactionReceipt({ hash: pickTx });\n    const agentId = opts?.agentId ?? (await this.agentIdOf(winner));\n    if (agentId === null) return { pickTx, feedbackTx: null };\n    const feedbackTx = await this.giveFeedback(agentId, opts?.feedback);\n    return { pickTx, feedbackTx };\n  }\n\n  async cancelExpired(bountyId: bigint): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'cancelExpired',\n      args: [bountyId],\n      account: wallet.account,\n      chain: wallet.chain,\n      ...(await this.celoGas(300_000n)),\n    });\n  }\n\n  // Relayer write API\n\n  /**\n   * Attest a worker's CI result on-chain. Only callable by the configured\n   * `ciRelayer`. For a `ciRequired` bounty, `pickWinner` reverts unless the\n   * chosen worker has a passing attestation (`attestCI(..., true)`).\n   */\n  async attestCI(bountyId: bigint, worker: Address, passed: boolean): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'attestCI',\n      args: [bountyId, worker, passed],\n      account: wallet.account,\n      chain: wallet.chain,\n      ...(await this.celoGas(150_000n)),\n    });\n  }\n\n  // v3 read API\n\n  /**\n   * Extended stats with per-task-type resolved counts (v3 only).\n   * Returns the same 5 fields as `getStats` plus `countByType[11]`.\n   */\n  async getStatsV3(token: Address): Promise<{\n    volume: bigint;\n    revenue: bigint;\n    resolved: bigint;\n    posters: bigint;\n    workers: bigint;\n    countByType: readonly bigint[];\n  }> {\n    const [volume, revenue, resolved, posters, workers, countByType] =\n      (await this.publicClient.readContract({\n        address: this.core,\n        abi: CLAUDELANCE_CORE_V3_ABI,\n        functionName: 'getStatsV3',\n        args: [token],\n      })) as readonly [bigint, bigint, bigint, bigint, bigint, readonly bigint[]];\n    return { volume, revenue, resolved, posters, workers, countByType };\n  }\n\n  /** All workers who have claimed a slot on a bounty (v3). */\n  async getClaimers(bountyId: bigint): Promise<Address[]> {\n    return (await this.publicClient.readContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'getClaimers',\n      args: [bountyId],\n    })) as Address[];\n  }\n\n  /**\n   * Workers with a submitted deliverable that is eligible for `pickWinner`\n   * (submitted, and CI passed if `ciRequired`) (v3).\n   */\n  async getEligibleSubmissions(bountyId: bigint): Promise<Address[]> {\n    return (await this.publicClient.readContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'getEligibleSubmissions',\n      args: [bountyId],\n    })) as Address[];\n  }\n\n  /**\n   * True once {@link attestReputation} has written the winner's ERC-8004\n   * feedback for this bounty (v3.1). The keeper normally closes this within\n   * minutes of `pickWinner`; check it before attesting yourself to avoid an\n   * `AlreadyAttested` revert.\n   */\n  async isReputationAttested(bountyId: bigint): Promise<boolean> {\n    return (await this.publicClient.readContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'isReputationAttested',\n      args: [bountyId],\n    })) as boolean;\n  }\n\n  /** On-chain configuration for a task type (v3). */\n  async getTaskTypeConfig(typeId: number): Promise<TypeConfig> {\n    return (await this.publicClient.readContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'getTaskTypeConfig',\n      args: [typeId],\n    })) as TypeConfig;\n  }\n\n  /**\n   * Register or update a task type configuration (v3, owner-only).\n   * Types 0-10 are pre-configured at deploy; use this to enable custom types or\n   * adjust `disclaimerRequired` / `ciSupported` flags.\n   */\n  async configureTaskType(typeId: number, config: TypeConfig): Promise<`0x${string}`> {\n    const wallet = this.requireWalletClient();\n    return wallet.writeContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'configureTaskType',\n      args: [typeId, config],\n      account: wallet.account,\n      chain: wallet.chain,\n      ...(await this.celoGas(150_000n)),\n    });\n  }\n\n  /**\n   * Total bounty count (v3 proxy, binary-search approach).\n   * v3 does not expose bountyCount as a public getter (EIP-7201 namespaced storage).\n   * This scans geometrically then binary-searches for the highest valid ID.\n   * Result is approximate if bounties are cancelled (IDs are never reused).\n   */\n  async getBountyCountV3(): Promise<bigint> {\n    const isValid = async (id: bigint): Promise<boolean> => {\n      const b = await this.getBounty(id);\n      return (b as { poster: string }).poster !== ZERO_ADDRESS;\n    };\n\n    if (!(await isValid(1n))) return 0n;\n\n    let hi = 1n;\n    while (await isValid(hi)) hi *= 2n;\n\n    let lo = hi / 2n;\n    while (lo + 1n < hi) {\n      const mid = (lo + hi) / 2n;\n      if (await isValid(mid)) lo = mid;\n      else hi = mid;\n    }\n    return lo;\n  }\n\n  // Proxy / circuit-breaker reads (v3)\n\n  /**\n   * True if the contract is paused (OZ Pausable). While paused, every\n   * state-changing call except `withdrawEarnings` reverts `EnforcedPause`.\n   * Check this before a worker/poster write to fail fast with a clear reason.\n   */\n  async isPaused(): Promise<boolean> {\n    return (await this.publicClient.readContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'paused',\n    })) as boolean;\n  }\n\n  /**\n   * Semantic version of the implementation behind the v3 proxy, e.g. \"3.1.0\"\n   * on mainnet since the attestReputation upgrade (2026-06-10). Where\n   * {@link getImplementation} answers which address is live, this answers\n   * which surface semantics - the cheap check for a long-running agent to\n   * notice an upgrade changed behaviour. Reverts on v2 deployments, which\n   * predate the function.\n   */\n  async version(): Promise<string> {\n    return (await this.publicClient.readContract({\n      address: this.core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: 'version',\n    })) as string;\n  }\n\n  /**\n   * Current implementation address behind the v3 UUPS proxy, read straight\n   * from the EIP-1967 implementation slot. Returns the zero address for a\n   * non-proxy (v2) deployment. Watch `Upgraded(address)` to detect changes.\n   */\n  async getImplementation(): Promise<Address> {\n    // keccak256(\"eip1967.proxy.implementation\") - 1\n    const SLOT = '0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc';\n    const raw = await this.publicClient.getStorageAt({ address: this.core, slot: SLOT });\n    if (!raw || /^0x0*$/.test(raw)) return ZERO_ADDRESS;\n    return getAddress('0x' + raw.slice(-40));\n  }\n\n  /**\n   * One-call health snapshot for monitoring and long-running agents: chain id,\n   * latest block, live gas price, and whether the protocol is paused. Lets a\n   * keeper or skill gate its tick (skip writes while paused, watch gas) without\n   * wiring several reads. `paused` is null if the read fails (e.g. v2 core).\n   */\n  async health(): Promise<{\n    chainId: number;\n    blockNumber: bigint;\n    gasPrice: bigint;\n    paused: boolean | null;\n  }> {\n    const [chainId, blockNumber, gasPrice, paused] = await Promise.all([\n      this.publicClient.getChainId(),\n      this.publicClient.getBlockNumber(),\n      this.publicClient.getGasPrice(),\n      this.isPaused().catch(() => null),\n    ]);\n    return { chainId, blockNumber, gasPrice, paused };\n  }\n\n  // Internal helpers\n\n  /**\n   * Reads `allowance(owner, core)` for the given token and submits an\n   * `approve(core, amount)` tx if the allowance is short. Awaits the\n   * receipt so callers can safely chain a write.\n   */\n  protected async ensureAllowance(token: Address, owner: Address, needed: bigint): Promise<void> {\n    const wallet = this.requireWalletClient();\n    const allowance = (await this.publicClient.readContract({\n      address: token,\n      abi: CUSD_ABI,\n      functionName: 'allowance',\n      args: [owner, this.core],\n    })) as bigint;\n    if (allowance >= needed) return;\n    // Approve 10x the immediate need so repeated bounty claims/posts don't each\n    // require a separate approve transaction.\n    const hash = await wallet.writeContract({\n      address: token,\n      abi: CUSD_ABI,\n      functionName: 'approve',\n      args: [this.core, needed * 10n],\n      account: wallet.account,\n      chain: wallet.chain,\n      // approve costs ~55k; the tight limit keeps the balance precheck low.\n      ...(await this.celoGas(100_000n)),\n    });\n    await this.publicClient.waitForTransactionReceipt({ hash });\n  }\n\n  /**\n   * @internal Wait for a post tx and pull the new bounty id out of the\n   * `BountyPosted` event - reliable regardless of read-replica lag.\n   */\n  protected async bountyIdFromReceipt(hash: `0x${string}`): Promise<bigint> {\n    const receipt = await this.publicClient.waitForTransactionReceipt({ hash });\n    if (receipt.status === 'reverted') {\n      throw new Error(\n        `[ClaudelanceClient] post transaction reverted on-chain (tx ${hash}). ` +\n          'On Celo the CELO ERC20 shares the native ledger, so check the poster ' +\n          'wallet covers escrow amount + gas reservations for in-flight writes.',\n      );\n    }\n    const events = parseEventLogs({\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      eventName: 'BountyPosted',\n      logs: receipt.logs,\n    });\n    const bountyId = (events[0] as { args?: { bountyId?: bigint } } | undefined)?.args?.bountyId;\n    if (bountyId === undefined) {\n      throw new Error(`[ClaudelanceClient] no BountyPosted event in post receipt (tx ${hash})`);\n    }\n    return bountyId;\n  }\n\n  /** @internal */\n  protected requireAccount(): Address {\n    const acct = this.walletClient?.account?.address;\n    if (!acct) {\n      throw new Error(\n        '[ClaudelanceClient] No wallet client wired up - use fromPrivateKey() ' +\n          'or pass a walletClient to the constructor.'\n      );\n    }\n    return acct;\n  }\n\n  /** @internal */\n  protected requireWalletClient(): WalletClient<Transport, Chain, Account> {\n    if (!this.walletClient) {\n      throw new Error(\n        '[ClaudelanceClient] Write methods require a wallet client - use ' +\n          'fromPrivateKey() or pass a walletClient to the constructor.'\n      );\n    }\n    return this.walletClient;\n  }\n}\n\nconst ERC721_BALANCE_OF_ABI = [\n  {\n    type: 'function',\n    name: 'balanceOf',\n    inputs: [{ name: 'owner', type: 'address' }],\n    outputs: [{ name: '', type: 'uint256' }],\n    stateMutability: 'view',\n  },\n] as const;\n\nconst IDENTITY_REGISTRY_REGISTER_ABI = [\n  {\n    type: 'function',\n    name: 'register',\n    inputs: [],\n    outputs: [{ name: 'agentId', type: 'uint256' }],\n    stateMutability: 'nonpayable',\n  },\n] as const;\n\nconst IDENTITY_TRANSFER_EVENT = {\n  type: 'event',\n  name: 'Transfer',\n  inputs: [\n    { name: 'from', type: 'address', indexed: true },\n    { name: 'to', type: 'address', indexed: true },\n    { name: 'tokenId', type: 'uint256', indexed: true },\n  ],\n} as const;\n\nconst REPUTATION_ABI = [\n  {\n    type: 'function',\n    name: 'giveFeedback',\n    stateMutability: 'nonpayable',\n    inputs: [\n      { name: 'agentId', type: 'uint256' },\n      { name: 'value', type: 'int128' },\n      { name: 'valueDecimals', type: 'uint8' },\n      { name: 'tag1', type: 'string' },\n      { name: 'tag2', type: 'string' },\n      { name: 'endpoint', type: 'string' },\n      { name: 'feedbackURI', type: 'string' },\n      { name: 'feedbackHash', type: 'bytes32' },\n    ],\n    outputs: [],\n  },\n  {\n    type: 'function',\n    name: 'getClients',\n    stateMutability: 'view',\n    inputs: [{ name: 'agentId', type: 'uint256' }],\n    outputs: [{ name: '', type: 'address[]' }],\n  },\n  {\n    type: 'function',\n    name: 'getSummary',\n    stateMutability: 'view',\n    inputs: [\n      { name: 'agentId', type: 'uint256' },\n      { name: 'clients', type: 'address[]' },\n      { name: 'tag1', type: 'string' },\n      { name: 'tag2', type: 'string' },\n    ],\n    outputs: [\n      { name: 'count', type: 'uint64' },\n      { name: 'score', type: 'int128' },\n      { name: 'avg', type: 'uint8' },\n    ],\n  },\n] as const;\n","import {\n  type Address,\n  type PublicClient,\n} from 'viem';\nimport type { TokenSet } from '@yeheskieltame/claudelance-types';\nimport { CUSD_ABI } from './cusd-abi.js';\n\nconst ERC20_BALANCE_ABI = [\n  {\n    type: 'function',\n    name: 'balanceOf',\n    inputs: [{ name: 'account', type: 'address' }],\n    outputs: [{ name: '', type: 'uint256' }],\n    stateMutability: 'view',\n  },\n  {\n    type: 'function',\n    name: 'allowance',\n    inputs: [{ name: 'owner', type: 'address' }, { name: 'spender', type: 'address' }],\n    outputs: [{ name: '', type: 'uint256' }],\n    stateMutability: 'view',\n  },\n] as const;\n\nexport type TokenKey = 'cUSD' | 'CELO' | 'USDC';\n\nexport type TokenAmounts = Record<TokenKey, bigint>;\n\nexport type TokenState = {\n  /** ERC20 wallet balance for each whitelisted token. */\n  balances: TokenAmounts;\n  /** ERC20 allowance granted to the core contract for each token. */\n  allowances: TokenAmounts;\n  /** Per-token minimum bounty amounts (from on-chain minBounty mapping). */\n  minBounties: TokenAmounts;\n  /** Timestamp (ms) when this snapshot was taken. */\n  fetchedAt: number;\n};\n\nexport type TokenManagerOptions = {\n  publicClient: PublicClient;\n  core: Address;\n  tokens: TokenSet;\n  /**\n   * Starting block for `TokenAllowed`/`MinBountyUpdated` event scans.\n   * Defaults to 68_143_824 (Celo mainnet Claudelance v2 deploy block).\n   * Set to 0n for Sepolia or custom deployments.\n   */\n  deployBlock?: bigint;\n};\n\n// v3 mainnet proxy deployed at block 68,536,240 (2026-06-04).\n// v2 mainnet deployed at block 68,143,824 (2026-05-14).\n// Use v2 deploy block as the safe lower bound: no allowToken events exist before it.\nconst CLAUDELANCE_MAINNET_DEPLOY_BLOCK = 68_143_824n;\nconst CLAUDELANCE_SEPOLIA_DEPLOY_BLOCK = 0n; // Sepolia block numbers differ; scan all.\n\nconst TOKEN_ALLOWED_ABI = [\n  {\n    type: 'event',\n    name: 'TokenAllowed',\n    inputs: [\n      { name: 'token', type: 'address', indexed: true },\n      { name: 'minBounty', type: 'uint256', indexed: false },\n    ],\n  },\n  {\n    type: 'event',\n    name: 'MinBountyUpdated',\n    inputs: [\n      { name: 'token', type: 'address', indexed: true },\n      { name: 'minBounty', type: 'uint256', indexed: false },\n    ],\n  },\n] as const;\n\n/**\n * Batches all token reads into the fewest multicall round-trips.\n *\n * Without it: 9 RPC calls for 3 tokens (balance, allowance, minBounty each).\n * With it: 1 multicall for balances + allowances (6 calls); minBounties come\n * from a cached event-log scan, since they only change on admin action.\n *\n * Usage:\n *   const tm = new TokenManager({ publicClient, core, tokens })\n *   const state = await tm.getTokenState(walletAddress)\n */\nexport class TokenManager {\n  readonly publicClient: PublicClient;\n  readonly core: Address;\n  readonly tokens: TokenSet;\n  readonly deployBlock: bigint;\n\n  // minBounties are admin-set and rarely change; cache with 10-min TTL.\n  private _minBountyCache: { amounts: TokenAmounts; fetchedAt: number } | null = null;\n  private readonly MIN_BOUNTY_TTL_MS = 10 * 60 * 1000;\n\n  constructor(opts: TokenManagerOptions) {\n    this.publicClient = opts.publicClient;\n    this.core = opts.core;\n    this.tokens = opts.tokens;\n    this.deployBlock = opts.deployBlock ?? CLAUDELANCE_MAINNET_DEPLOY_BLOCK;\n  }\n\n  private get tokenEntries(): Array<[TokenKey, Address]> {\n    return [\n      ['cUSD', this.tokens.cUSD],\n      ['CELO', this.tokens.CELO],\n      ['USDC', this.tokens.USDC],\n    ];\n  }\n\n  /**\n   * Batch-read balances for all three whitelisted tokens in one multicall.\n   */\n  async getBalances(account: Address): Promise<TokenAmounts> {\n    const entries = this.tokenEntries;\n    const results = await this.publicClient.multicall({\n      contracts: entries.map(([, addr]) => ({\n        address: addr,\n        abi: ERC20_BALANCE_ABI,\n        functionName: 'balanceOf' as const,\n        args: [account] as const,\n      })),\n      allowFailure: false,\n    });\n    return Object.fromEntries(\n      entries.map(([key], i) => [key, results[i] as bigint]),\n    ) as TokenAmounts;\n  }\n\n  /**\n   * Batch-read allowances granted to `spender` (typically the core contract) in one multicall.\n   */\n  async getAllowances(owner: Address, spender: Address = this.core): Promise<TokenAmounts> {\n    const entries = this.tokenEntries;\n    const results = await this.publicClient.multicall({\n      contracts: entries.map(([, addr]) => ({\n        address: addr,\n        abi: ERC20_BALANCE_ABI,\n        functionName: 'allowance' as const,\n        args: [owner, spender] as const,\n      })),\n      allowFailure: false,\n    });\n    return Object.fromEntries(\n      entries.map(([key], i) => [key, results[i] as bigint]),\n    ) as TokenAmounts;\n  }\n\n  /**\n   * Returns per-token minBounty amounts. Results are cached for 10 minutes\n   * since these values only change via admin `allowToken`/`setMinBounty` calls.\n   *\n   * Reads from the most-recent TokenAllowed or MinBountyUpdated event per token.\n   * Falls back to 0n for any token not yet seen in the event log.\n   */\n  async getMinBounties(opts?: { bypassCache?: boolean }): Promise<TokenAmounts> {\n    const now = Date.now();\n    if (\n      !opts?.bypassCache &&\n      this._minBountyCache &&\n      now - this._minBountyCache.fetchedAt < this.MIN_BOUNTY_TTL_MS\n    ) {\n      return this._minBountyCache.amounts;\n    }\n\n    const amounts: TokenAmounts = { cUSD: 0n, CELO: 0n, USDC: 0n };\n\n    for (const [key, tokenAddr] of this.tokenEntries) {\n      // Fetch TokenAllowed and MinBountyUpdated in parallel for this token.\n      const [allowedLogs, updatedLogs] = await Promise.all([\n        this.publicClient.getLogs({\n          address: this.core,\n          event: TOKEN_ALLOWED_ABI[0],\n          args: { token: tokenAddr },\n          fromBlock: this.deployBlock,\n        }).catch(() => []),\n        this.publicClient.getLogs({\n          address: this.core,\n          event: TOKEN_ALLOWED_ABI[1],\n          args: { token: tokenAddr },\n          fromBlock: this.deployBlock,\n        }).catch(() => []),\n      ]);\n\n      const allLogs = [...allowedLogs, ...updatedLogs].sort((a, b) => {\n        const bn = (a.blockNumber ?? 0n) - (b.blockNumber ?? 0n);\n        if (bn !== 0n) return bn > 0n ? 1 : -1;\n        return (Number(a.logIndex ?? 0)) - (Number(b.logIndex ?? 0));\n      });\n\n      const last = allLogs[allLogs.length - 1];\n      if (last) {\n        amounts[key] = (last.args as { minBounty?: bigint }).minBounty ?? 0n;\n      }\n    }\n\n    this._minBountyCache = { amounts, fetchedAt: now };\n    return amounts;\n  }\n\n  /**\n   * Full token state snapshot in two multicall round-trips:\n   *   1. balances + allowances (1 multicall, 6 calls)\n   *   2. minBounties (from cached event log scan, rarely needs a fresh fetch)\n   *\n   * Replaces 9+ individual RPC calls with 1 to 2 batched calls.\n   */\n  async getTokenState(account: Address): Promise<TokenState> {\n    const [balances, allowances, minBounties] = await Promise.all([\n      this.getBalances(account),\n      this.getAllowances(account),\n      this.getMinBounties(),\n    ]);\n    return { balances, allowances, minBounties, fetchedAt: Date.now() };\n  }\n\n  /**\n   * Check whether `account` has sufficient balance AND allowance to claim\n   * a bounty that requires `amount` + `stake` of `token`.\n   */\n  checkSufficientFunds(\n    state: TokenState,\n    tokenKey: TokenKey,\n    amount: bigint,\n    stake: bigint,\n  ): { hasBalance: boolean; hasAllowance: boolean; shortfall: bigint } {\n    const needed = amount + stake;\n    const balance = state.balances[tokenKey];\n    const allowance = state.allowances[tokenKey];\n    return {\n      hasBalance: balance >= needed,\n      hasAllowance: allowance >= stake,\n      shortfall: balance < needed ? needed - balance : 0n,\n    };\n  }\n\n  /** Invalidate the minBounty cache (call after an admin setMinBounty tx is mined). */\n  invalidateMinBountyCache(): void {\n    this._minBountyCache = null;\n  }\n\n  /** Convenience: look up the token key for a given token address. */\n  tokenKeyOf(address: Address): TokenKey | undefined {\n    const lower = address.toLowerCase();\n    for (const [key, addr] of this.tokenEntries) {\n      if (addr.toLowerCase() === lower) return key;\n    }\n    return undefined;\n  }\n}\n\n","/**\n * Real-time event subscriptions for ClaudelanceCoreV3.\n *\n * Each watcher uses viem's `watchContractEvent` under the hood and returns\n * an `unwatch` function that stops the subscription when called - same\n * pattern as viem's own watch helpers.\n *\n * Works in both Node.js (polling) and browser (WebSocket if supported).\n * No extra dependencies - only viem (already a peer dependency).\n *\n * Usage:\n *   const unwatch = watchBountyPosted(client, {}, (evt) => console.log(evt))\n *   // later:\n *   unwatch()\n */\n\nimport {\n  type PublicClient,\n  type Address,\n  type Log,\n} from 'viem';\nimport { CLAUDELANCE_CORE_V3_ABI } from '@yeheskieltame/claudelance-types';\n\n// Shared types\n\nexport type WatchOptions = {\n  /** Override the default polling interval (ms). Only used in polling mode. */\n  pollingInterval?: number;\n  /** Block to start watching from. Defaults to 'latest'. */\n  fromBlock?: bigint;\n};\n\nexport type UnwatchFn = () => void;\n\n// BountyPosted\n\nexport type BountyPostedEvent = {\n  bountyId: bigint;\n  poster: Address;\n  token: Address;\n  bountyType: number;\n  amount: bigint;\n  maxSlots: number;\n  targetRepoUrl: string;\n  requirementsHash: `0x${string}`;\n  /** Raw viem log for advanced consumers. */\n  log: Log;\n};\n\nexport type BountyPostedFilter = WatchOptions & {\n  /** Only emit events for this poster address. */\n  poster?: Address;\n  /** Only emit events for this token. */\n  token?: Address;\n};\n\n/**\n * Subscribe to new bounties posted on the v3 contract.\n * Returns an `unwatch` function to stop the subscription.\n */\nexport function watchBountyPosted(\n  publicClient: PublicClient,\n  core: Address,\n  opts: BountyPostedFilter,\n  onEvent: (evt: BountyPostedEvent) => void,\n): UnwatchFn {\n  return publicClient.watchContractEvent({\n    address: core,\n    abi: CLAUDELANCE_CORE_V3_ABI,\n    eventName: 'BountyPosted',\n    args: {\n      ...(opts.poster ? { poster: opts.poster } : {}),\n      ...(opts.token ? { token: opts.token } : {}),\n    },\n    pollingInterval: opts.pollingInterval,\n    fromBlock: opts.fromBlock,\n    onLogs: (logs) => {\n      for (const log of logs) {\n        const a = log.args as Partial<BountyPostedEvent>;\n        if (!a.bountyId) continue;\n        onEvent({\n          bountyId: a.bountyId,\n          poster: a.poster ?? '0x',\n          token: a.token ?? '0x',\n          bountyType: Number(a.bountyType ?? 0),\n          amount: a.amount ?? 0n,\n          maxSlots: Number(a.maxSlots ?? 0),\n          targetRepoUrl: a.targetRepoUrl ?? '',\n          requirementsHash: (a.requirementsHash ?? `0x${'0'.repeat(64)}`) as `0x${string}`,\n          log,\n        });\n      }\n    },\n  });\n}\n\n// DeliverableSubmitted\n\nexport type DeliverableSubmittedEvent = {\n  bountyId: bigint;\n  worker: Address;\n  deliverableUrl: string;\n  deliverableHash: `0x${string}`;\n  log: Log;\n};\n\nexport type DeliverableSubmittedFilter = WatchOptions & {\n  bountyId?: bigint;\n  worker?: Address;\n};\n\n/**\n * Subscribe to deliverable submissions on the v3 contract.\n * Fires for all task types (code PRs, research reports, translations, etc.).\n */\nexport function watchDeliverableSubmitted(\n  publicClient: PublicClient,\n  core: Address,\n  opts: DeliverableSubmittedFilter,\n  onEvent: (evt: DeliverableSubmittedEvent) => void,\n): UnwatchFn {\n  return publicClient.watchContractEvent({\n    address: core,\n    abi: CLAUDELANCE_CORE_V3_ABI,\n    eventName: 'DeliverableSubmitted',\n    args: {\n      ...(opts.bountyId !== undefined ? { bountyId: opts.bountyId } : {}),\n      ...(opts.worker ? { worker: opts.worker } : {}),\n    },\n    pollingInterval: opts.pollingInterval,\n    fromBlock: opts.fromBlock,\n    onLogs: (logs) => {\n      for (const log of logs) {\n        const a = log.args as Partial<DeliverableSubmittedEvent>;\n        if (!a.bountyId) continue;\n        onEvent({\n          bountyId: a.bountyId,\n          worker: a.worker ?? '0x',\n          deliverableUrl: a.deliverableUrl ?? '',\n          deliverableHash: (a.deliverableHash ?? `0x${'0'.repeat(64)}`) as `0x${string}`,\n          log,\n        });\n      }\n    },\n  });\n}\n\n// BountyResolved\n\nexport type BountyResolvedEvent = {\n  bountyId: bigint;\n  winner: Address;\n  token: Address;\n  winnerPayout: bigint;\n  protocolFee: bigint;\n  log: Log;\n};\n\nexport type BountyResolvedFilter = WatchOptions & {\n  bountyId?: bigint;\n  winner?: Address;\n  token?: Address;\n};\n\n/**\n * Subscribe to bounty resolutions (pickWinner called).\n * Useful for workers to detect when they've been selected.\n */\nexport function watchBountyResolved(\n  publicClient: PublicClient,\n  core: Address,\n  opts: BountyResolvedFilter,\n  onEvent: (evt: BountyResolvedEvent) => void,\n): UnwatchFn {\n  return publicClient.watchContractEvent({\n    address: core,\n    abi: CLAUDELANCE_CORE_V3_ABI,\n    eventName: 'BountyResolved',\n    args: {\n      ...(opts.bountyId !== undefined ? { bountyId: opts.bountyId } : {}),\n      ...(opts.winner ? { winner: opts.winner } : {}),\n      ...(opts.token ? { token: opts.token } : {}),\n    },\n    pollingInterval: opts.pollingInterval,\n    fromBlock: opts.fromBlock,\n    onLogs: (logs) => {\n      for (const log of logs) {\n        const a = log.args as Partial<BountyResolvedEvent>;\n        if (!a.bountyId) continue;\n        onEvent({\n          bountyId: a.bountyId,\n          winner: a.winner ?? '0x',\n          token: a.token ?? '0x',\n          winnerPayout: a.winnerPayout ?? 0n,\n          protocolFee: a.protocolFee ?? 0n,\n          log,\n        });\n      }\n    },\n  });\n}\n\n// SlotClaimed\n\nexport type SlotClaimedEvent = {\n  bountyId: bigint;\n  worker: Address;\n  log: Log;\n};\n\nexport type SlotClaimedFilter = WatchOptions & {\n  bountyId?: bigint;\n  worker?: Address;\n};\n\n/** Subscribe to slot claim events. Useful for monitoring bounty fill rates. */\nexport function watchSlotClaimed(\n  publicClient: PublicClient,\n  core: Address,\n  opts: SlotClaimedFilter,\n  onEvent: (evt: SlotClaimedEvent) => void,\n): UnwatchFn {\n  return publicClient.watchContractEvent({\n    address: core,\n    abi: CLAUDELANCE_CORE_V3_ABI,\n    eventName: 'SlotClaimed',\n    args: {\n      ...(opts.bountyId !== undefined ? { bountyId: opts.bountyId } : {}),\n      ...(opts.worker ? { worker: opts.worker } : {}),\n    },\n    pollingInterval: opts.pollingInterval,\n    fromBlock: opts.fromBlock,\n    onLogs: (logs) => {\n      for (const log of logs) {\n        const a = log.args as Partial<SlotClaimedEvent>;\n        if (!a.bountyId) continue;\n        onEvent({ bountyId: a.bountyId, worker: a.worker ?? '0x', log });\n      }\n    },\n  });\n}\n\n// EarningsWithdrawn\n\nexport type EarningsWithdrawnEvent = {\n  worker: Address;\n  token: Address;\n  amount: bigint;\n  log: Log;\n};\n\nexport type EarningsWithdrawnFilter = WatchOptions & {\n  worker?: Address;\n  token?: Address;\n};\n\n/** Subscribe to earnings withdrawal events. Useful for revenue dashboards. */\nexport function watchEarningsWithdrawn(\n  publicClient: PublicClient,\n  core: Address,\n  opts: EarningsWithdrawnFilter,\n  onEvent: (evt: EarningsWithdrawnEvent) => void,\n): UnwatchFn {\n  return publicClient.watchContractEvent({\n    address: core,\n    abi: CLAUDELANCE_CORE_V3_ABI,\n    eventName: 'EarningsWithdrawn',\n    args: {\n      ...(opts.worker ? { worker: opts.worker } : {}),\n      ...(opts.token ? { token: opts.token } : {}),\n    },\n    pollingInterval: opts.pollingInterval,\n    fromBlock: opts.fromBlock,\n    onLogs: (logs) => {\n      for (const log of logs) {\n        const a = log.args as Partial<EarningsWithdrawnEvent>;\n        onEvent({\n          worker: a.worker ?? '0x',\n          token: a.token ?? '0x',\n          amount: a.amount ?? 0n,\n          log,\n        });\n      }\n    },\n  });\n}\n\n// CIAttested\n\nexport type CIAttestedEvent = {\n  bountyId: bigint;\n  worker: Address;\n  passed: boolean;\n  log: Log;\n};\n\nexport type CIAttestedFilter = WatchOptions & {\n  bountyId?: bigint;\n  worker?: Address;\n};\n\n/**\n * Subscribe to CI attestations from the relayer. For a `ciRequired` bounty,\n * `pickWinner` is only valid for a worker with `passed: true`.\n */\nexport function watchCIAttested(\n  publicClient: PublicClient,\n  core: Address,\n  opts: CIAttestedFilter,\n  onEvent: (evt: CIAttestedEvent) => void,\n): UnwatchFn {\n  return publicClient.watchContractEvent({\n    address: core,\n    abi: CLAUDELANCE_CORE_V3_ABI,\n    eventName: 'CIAttested',\n    args: {\n      ...(opts.bountyId !== undefined ? { bountyId: opts.bountyId } : {}),\n      ...(opts.worker ? { worker: opts.worker } : {}),\n    },\n    pollingInterval: opts.pollingInterval,\n    fromBlock: opts.fromBlock,\n    onLogs: (logs) => {\n      for (const log of logs) {\n        const a = log.args as Partial<CIAttestedEvent>;\n        if (a.bountyId === undefined) continue;\n        onEvent({ bountyId: a.bountyId, worker: a.worker ?? '0x', passed: a.passed ?? false, log });\n      }\n    },\n  });\n}\n\n// StakeSettled\n\nexport type StakeSettledEvent = {\n  bountyId: bigint;\n  worker: Address;\n  forfeited: boolean;\n  amount: bigint;\n  log: Log;\n};\n\nexport type StakeSettledFilter = WatchOptions & {\n  bountyId?: bigint;\n  worker?: Address;\n};\n\n/**\n * Subscribe to stake settlements. `forfeited: true` means the stake went to\n * the treasury (bad-faith worker); otherwise it was credited back to the worker.\n */\nexport function watchStakeSettled(\n  publicClient: PublicClient,\n  core: Address,\n  opts: StakeSettledFilter,\n  onEvent: (evt: StakeSettledEvent) => void,\n): UnwatchFn {\n  return publicClient.watchContractEvent({\n    address: core,\n    abi: CLAUDELANCE_CORE_V3_ABI,\n    eventName: 'StakeSettled',\n    args: {\n      ...(opts.bountyId !== undefined ? { bountyId: opts.bountyId } : {}),\n      ...(opts.worker ? { worker: opts.worker } : {}),\n    },\n    pollingInterval: opts.pollingInterval,\n    fromBlock: opts.fromBlock,\n    onLogs: (logs) => {\n      for (const log of logs) {\n        const a = log.args as Partial<StakeSettledEvent>;\n        if (a.bountyId === undefined) continue;\n        onEvent({\n          bountyId: a.bountyId,\n          worker: a.worker ?? '0x',\n          forfeited: a.forfeited ?? false,\n          amount: a.amount ?? 0n,\n          log,\n        });\n      }\n    },\n  });\n}\n\n// BountyCancelled\n\nexport type BountyCancelledEvent = {\n  bountyId: bigint;\n  log: Log;\n};\n\nexport type BountyCancelledFilter = WatchOptions & {\n  bountyId?: bigint;\n};\n\n/** Subscribe to bounty cancellations (cancelExpired after deadline + grace). */\nexport function watchBountyCancelled(\n  publicClient: PublicClient,\n  core: Address,\n  opts: BountyCancelledFilter,\n  onEvent: (evt: BountyCancelledEvent) => void,\n): UnwatchFn {\n  return publicClient.watchContractEvent({\n    address: core,\n    abi: CLAUDELANCE_CORE_V3_ABI,\n    eventName: 'BountyCancelled',\n    args: {\n      ...(opts.bountyId !== undefined ? { bountyId: opts.bountyId } : {}),\n    },\n    pollingInterval: opts.pollingInterval,\n    fromBlock: opts.fromBlock,\n    onLogs: (logs) => {\n      for (const log of logs) {\n        const a = log.args as Partial<BountyCancelledEvent>;\n        if (a.bountyId === undefined) continue;\n        onEvent({ bountyId: a.bountyId, log });\n      }\n    },\n  });\n}\n\n// ReputationAttested (v3.1)\n\nexport type ReputationAttestedEvent = {\n  bountyId: bigint;\n  /** ERC-8004 identity NFT id of the winning agent. */\n  agentId: bigint;\n  /** Winner wallet that owns the agent identity. */\n  worker: Address;\n  log: Log;\n};\n\nexport type ReputationAttestedFilter = WatchOptions & {\n  bountyId?: bigint;\n  agentId?: bigint;\n  worker?: Address;\n};\n\n/**\n * Subscribe to reputation attestations (v3.1): emitted once per resolved\n * bounty when `attestReputation` writes the winner's +1 ERC-8004 feedback.\n * Filter by `agentId` or `worker` to follow a single agent's reputation.\n */\nexport function watchReputationAttested(\n  publicClient: PublicClient,\n  core: Address,\n  opts: ReputationAttestedFilter,\n  onEvent: (evt: ReputationAttestedEvent) => void,\n): UnwatchFn {\n  return publicClient.watchContractEvent({\n    address: core,\n    abi: CLAUDELANCE_CORE_V3_ABI,\n    eventName: 'ReputationAttested',\n    args: {\n      ...(opts.bountyId !== undefined ? { bountyId: opts.bountyId } : {}),\n      ...(opts.agentId !== undefined ? { agentId: opts.agentId } : {}),\n      ...(opts.worker ? { worker: opts.worker } : {}),\n    },\n    pollingInterval: opts.pollingInterval,\n    fromBlock: opts.fromBlock,\n    onLogs: (logs) => {\n      for (const log of logs) {\n        const a = log.args as Partial<ReputationAttestedEvent>;\n        if (a.bountyId === undefined) continue;\n        onEvent({\n          bountyId: a.bountyId,\n          agentId: a.agentId ?? 0n,\n          worker: a.worker ?? '0x',\n          log,\n        });\n      }\n    },\n  });\n}\n\n// Convenience: watch all core events\n\nexport type CoreEventHandlers = {\n  onBountyPosted?: (evt: BountyPostedEvent) => void;\n  onDeliverableSubmitted?: (evt: DeliverableSubmittedEvent) => void;\n  onBountyResolved?: (evt: BountyResolvedEvent) => void;\n  onSlotClaimed?: (evt: SlotClaimedEvent) => void;\n  onEarningsWithdrawn?: (evt: EarningsWithdrawnEvent) => void;\n  onCIAttested?: (evt: CIAttestedEvent) => void;\n  onStakeSettled?: (evt: StakeSettledEvent) => void;\n  onBountyCancelled?: (evt: BountyCancelledEvent) => void;\n  onReputationAttested?: (evt: ReputationAttestedEvent) => void;\n};\n\n/**\n * Start watching all supported v3 events in one call.\n * Returns a single `unwatch` that stops all active subscriptions.\n *\n * @example\n * const unwatch = watchAll(publicClient, V3_CORE, {\n *   onBountyPosted: (e) => console.log('New bounty', e.bountyId),\n *   onBountyResolved: (e) => console.log('Winner', e.winner),\n * })\n */\nexport function watchAll(\n  publicClient: PublicClient,\n  core: Address,\n  handlers: CoreEventHandlers,\n  opts: WatchOptions = {},\n): UnwatchFn {\n  const unwatchers: UnwatchFn[] = [];\n\n  if (handlers.onBountyPosted) {\n    unwatchers.push(watchBountyPosted(publicClient, core, opts, handlers.onBountyPosted));\n  }\n  if (handlers.onDeliverableSubmitted) {\n    unwatchers.push(watchDeliverableSubmitted(publicClient, core, opts, handlers.onDeliverableSubmitted));\n  }\n  if (handlers.onBountyResolved) {\n    unwatchers.push(watchBountyResolved(publicClient, core, opts, handlers.onBountyResolved));\n  }\n  if (handlers.onSlotClaimed) {\n    unwatchers.push(watchSlotClaimed(publicClient, core, opts, handlers.onSlotClaimed));\n  }\n  if (handlers.onEarningsWithdrawn) {\n    unwatchers.push(watchEarningsWithdrawn(publicClient, core, opts, handlers.onEarningsWithdrawn));\n  }\n  if (handlers.onCIAttested) {\n    unwatchers.push(watchCIAttested(publicClient, core, opts, handlers.onCIAttested));\n  }\n  if (handlers.onStakeSettled) {\n    unwatchers.push(watchStakeSettled(publicClient, core, opts, handlers.onStakeSettled));\n  }\n  if (handlers.onBountyCancelled) {\n    unwatchers.push(watchBountyCancelled(publicClient, core, opts, handlers.onBountyCancelled));\n  }\n  if (handlers.onReputationAttested) {\n    unwatchers.push(watchReputationAttested(publicClient, core, opts, handlers.onReputationAttested));\n  }\n\n  return () => { for (const u of unwatchers) u(); };\n}\n","import type { Address, PublicClient } from \"viem\";\n\nimport {\n  CLAUDELANCE_CORE_ABI,\n  CLAUDELANCE_CORE_V3_ABI,\n} from \"@yeheskieltame/claudelance-types\";\n\n/**\n * Read total protocol revenue for a token from the Claudelance Core.\n *\n * On v3 (UUPS proxy, EIP-7201 storage): reads via `getStatsV3(token)` which\n * returns the cumulative revenue as the second element.\n *\n * On v2 (immutable): reads the `totalProtocolRevenue(token)` public getter.\n *\n * Revenue is denominated in the token's smallest unit (wei for cUSD/CELO,\n * 1e-6 for USDC). Each resolved bounty contributes 2% of its amount, plus\n * any forfeited stakes.\n */\nexport async function getProtocolRevenue(\n  client: PublicClient,\n  core: Address,\n  token: Address,\n): Promise<bigint> {\n  // Try v3 first: getStatsV3 returns (volume, revenue, resolved, posters, workers, countByType)\n  try {\n    const result = (await client.readContract({\n      address: core,\n      abi: CLAUDELANCE_CORE_V3_ABI,\n      functionName: \"getStatsV3\",\n      args: [token],\n    })) as readonly [bigint, bigint, bigint, bigint, bigint, readonly bigint[]];\n    return result[1]; // revenue is index 1\n  } catch {\n    // v2 fallback: public mapping getter\n    return (await client.readContract({\n      address: core,\n      abi: CLAUDELANCE_CORE_ABI,\n      functionName: \"totalProtocolRevenue\",\n      args: [token],\n    })) as bigint;\n  }\n}\n","import { parseAbi, type Address, type PublicClient } from \"viem\";\n\nconst REVENUE_EVENT = parseAbi([\n  \"event ProtocolRevenueAccrued(address indexed token, uint256 amount, uint256 cumulative)\",\n]);\n\nexport type ProtocolRevenueAccrual = {\n  token: Address;\n  amount: bigint;\n  cumulative: bigint;\n  txHash: `0x${string}`;\n  blockNumber: bigint;\n};\n\n/**\n * Page the last `lookback` blocks of `ProtocolRevenueAccrued` events from the\n * Claudelance Core. Default 50k blocks is about 14 hours at Celo's ~1s L2\n * blocktime; pass a larger lookback for a wider window. Returns newest-first.\n */\nexport async function listProtocolRevenueEvents(\n  client: PublicClient,\n  core: Address,\n  lookback: bigint = 50_000n,\n): Promise<ProtocolRevenueAccrual[]> {\n  const latest = await client.getBlockNumber();\n  const fromBlock = latest > lookback ? latest - lookback : 0n;\n\n  const logs = await client.getLogs({\n    address: core,\n    events: REVENUE_EVENT,\n    fromBlock,\n    toBlock: latest,\n  });\n\n  return logs\n    .map((log) => ({\n      token: log.args.token!,\n      amount: log.args.amount!,\n      cumulative: log.args.cumulative!,\n      txHash: log.transactionHash,\n      blockNumber: log.blockNumber,\n    }))\n    .reverse();\n}\n","import { TASK_TYPE_NAMES, type Bounty } from '@yeheskieltame/claudelance-types';\n\nimport { PROTOCOL_FEE_BPS, BPS_DENOMINATOR } from './constants.js';\n\n/**\n * Split a gross bounty reward into the winner's net payout and the 2% protocol\n * fee, matching the contract's integer math exactly (fee floored, net is the\n * remainder). Lets a poster preview a worker's take, or an agent decide if a\n * bounty clears its threshold, without guessing the fee.\n */\nexport function estimatePayout(amount: bigint): { net: bigint; fee: bigint } {\n  if (amount < 0n) throw new Error(`[estimatePayout] amount must be non-negative, got ${amount}`);\n  // PROTOCOL_FEE_BPS / BPS_DENOMINATOR are numbers; widen to bigint for the calc.\n  const fee = (amount * BigInt(PROTOCOL_FEE_BPS)) / BigInt(BPS_DENOMINATOR);\n  return { net: amount - fee, fee };\n}\n\n/**\n * Convert a token wei amount (bigint) to a plain number for UI / log lines.\n * Precision is lossy beyond ~15 decimal digits: fine for human display,\n * NEVER use the result for math that affects on-chain state.\n */\nexport function tokenToFloat(wei: bigint, decimals = 18): number {\n  return Number(wei) / 10 ** decimals;\n}\n\n/**\n * Convert a human-readable amount (float) to wei (bigint).\n *\n * Rounds at the wei boundary. Caller is responsible for sanity-checking\n * the result against the contract's per-token `minBounty`.\n */\nexport function floatToToken(amount: number, decimals = 18): bigint {\n  if (!Number.isFinite(amount) || amount < 0) {\n    throw new Error(`[floatToToken] amount must be a non-negative finite number, got ${amount}`);\n  }\n  return BigInt(Math.round(amount * 10 ** decimals));\n}\n\n/**\n * Pretty-print a token amount with symbol + decimals.\n *\n *   tokenFormat(2_060_000_000_000_000_000n, 'cUSD')        -> \"2.06 cUSD\"\n *   tokenFormat(123_456_789n, 'USDC', { decimals: 6 })     -> \"123.46 USDC\"\n */\nexport function tokenFormat(\n  wei: bigint,\n  symbol: string,\n  opts: { decimals?: number; places?: number } = {}\n): string {\n  const { decimals = 18, places = 2 } = opts;\n  return `${tokenToFloat(wei, decimals).toFixed(places)} ${symbol}`;\n}\n\n/** Back-compat: convenience wrappers for the cUSD case (18 decimals). */\nexport const cusdToFloat = (wei: bigint): number => tokenToFloat(wei, 18);\nexport const floatToCusd = (amount: number): bigint => floatToToken(amount, 18);\nexport const cusdFormat = (wei: bigint, places = 2): string => tokenFormat(wei, 'cUSD', { places });\n\n/**\n * Seconds until a bounty's deadline. Can be negative if already passed.\n */\nexport function timeRemaining(bounty: Bounty, nowSeconds?: number): number {\n  const now = nowSeconds ?? Math.floor(Date.now() / 1000);\n  return Number(bounty.deadline) - now;\n}\n\n/**\n * One-line, agent-friendly summary of a bounty for log lines + LLM prompts.\n * The token amount is rendered in token's smallest unit if a symbol/decimals\n * are not provided (sane default: assume 18 decimals).\n */\nexport function formatBountySummary(\n  bounty: Bounty & { id: bigint },\n  opts: { tokenSymbol?: string; tokenDecimals?: number } = {}\n): string {\n  const { tokenSymbol = 'token', tokenDecimals = 18 } = opts;\n  const statusLabel = ['OPEN', 'RESOLVED', 'CANCELLED'][bounty.status] ?? '?';\n  const remaining = timeRemaining(bounty);\n  const days = Math.max(0, Math.floor(remaining / 86_400));\n  const hours = Math.max(0, Math.floor((remaining % 86_400) / 3600));\n  const left = remaining <= 0 ? 'EXPIRED' : `${days}d ${hours}h left`;\n  const ci = bounty.ciRequired ? 'CI required' : 'no CI';\n  const ZERO = '0x0000000000000000000000000000000000000000';\n  const mode = bounty.targetWorker.toLowerCase() === ZERO ? 'OPEN' : `DIRECT->${bounty.targetWorker.slice(0, 8)}`;\n  const typeLabel = TASK_TYPE_NAMES[bounty.bountyType as keyof typeof TASK_TYPE_NAMES] ?? `type${bounty.bountyType}`;\n  return [\n    `Bounty #${bounty.id} ${statusLabel}`,\n    typeLabel,\n    mode,\n    tokenFormat(bounty.amount, tokenSymbol, { decimals: tokenDecimals }),\n    `${bounty.claimedSlots}/${bounty.maxSlots} slots`,\n    left,\n    ci,\n    `spec: ${bounty.instructionUrl || bounty.targetRepoUrl}`,\n  ].join(' | ');\n}\n"]}