Skip to content

Contracts SDK v1.2#109

Merged
mahabubAlahi merged 94 commits intomainfrom
develop
Apr 17, 2026
Merged

Contracts SDK v1.2#109
mahabubAlahi merged 94 commits intomainfrom
develop

Conversation

@adnanhq
Copy link
Copy Markdown
Contributor

@adnanhq adnanhq commented Apr 17, 2026

Release: Contracts SDK v1.2

What's New

Simulation & Transaction Preparation

  • Simulation returns SimulationResult — every simulate.* method now returns { result, request } instead of void, unlocking gas estimation, calldata inspection, and account-abstraction flows.
  • prepareContractWrite / toPreparedTransaction — build raw transaction params (to, data, value, gas) without sending, for AA UserOps, Safe multisig, or custom signing flows. prepareContractWrite is now generic over TAbi to preserve ABI-driven type safety for functionName.
  • simulateWithErrorDecode — one-call simulate-then-decode wrapper that returns a typed SimulationResult or throws a decoded contract error.
  • Structured simulation request format — simulation responses now use ViemSimulateRequest with structured fields (address, abi, functionName, args) instead of raw to/data.

Client Enhancements

  • getReceipt() on the client — non-blocking transaction receipt lookup. Returns null for unmined transactions; re-throws non-receipt errors (e.g. network failures) instead of swallowing them.
  • multicall utility — batch multiple read calls into a single RPC round-trip.

Type-Safe Constants

  • Event name constantsGLOBAL_PARAMS_EVENTS, CAMPAIGN_INFO_EVENTS, ALL_OR_NOTHING_EVENTS, KEEP_WHATS_RAISED_EVENTS, PAYMENT_TREASURY_EVENTS, ITEM_REGISTRY_EVENTS, TREASURY_FACTORY_EVENTS, CAMPAIGN_INFO_FACTORY_EVENTS.
  • Error name constants — matching *ErrorNames objects for every contract.

Expanded Exports

  • All contract ABIs (GLOBAL_PARAMS_ABI, CAMPAIGN_INFO_ABI, etc.) from @oaknetwork/contracts-sdk/contracts.
  • Additional viem re-exports: encodeFunctionData, decodeFunctionResult, decodeEventLog.

ABI & SDK Gap Fixes

  • paused() reads added to GlobalParams and PaymentTreasury.
  • New events wired up across contracts:
    • GlobalParams: PlatformLineItemTypeSet, PlatformLineItemTypeRemoved, DataAddedToRegistry
    • PaymentTreasury: Paused, Unpaused
    • CampaignInfo, AllOrNothing, KeepWhatsRaised: Cancelled, Paused, Unpaused (from PausableCancellable)
    • Each with get*Logs + watch* helpers.
  • PledgeNFT surface on CampaignInfo — 10 new reads (getPledgeCount, getPledgeData, getImageURI, contractURI, name, symbol, tokenURI, ownerOf, balanceOf, supportsInterface), PledgeNFTMinted / ImageURIUpdated / ContractURIUpdated events, and a new PledgeData struct.
  • 7 new shared typed errors with recovery hints: PausedError, NotPausedError, CancelledError, NotCancelledError, CannotCancel, PledgeNFTUnAuthorized, PledgeNFTInvalidJsonString.
  • ERC-721 methods removed from AllOrNothing & KeepWhatsRaisedapprove, setApprovalForAll, safeTransferFrom, transferFrom, balanceOf, ownerOf, tokenURI and related events (Approval, ApprovalForAll, Transfer) removed from treasury contracts. These operations belong on the CampaignInfo contract, which manages all pledge NFTs.

Metrics & Reporting

New @oaknetwork/contracts-sdk/metrics subpath with platform, campaign, and treasury aggregation helpers for dashboards and analytics.

Scenario-Driven Examples (70+ examples across 7 scenarios)

A complete, narrative-first example library under packages/contracts/src/examples/. Each scenario tells a real-world story with clear role markers (Protocol Admin, Platform Admin, Creator, Backer):

  • Scenario 0 — Platform Enlistment (NovaPay onboarding, with filtered verification against shared deployments)
  • Scenario 1 — All-or-Nothing Crowdfunding (Maya's ceramics — campaign creation with receipt-based address discovery, treasury deployment, rewards, pledges, success/failure paths)
  • Scenario 2 — Keep-What's-Raised Crowdfunding (TechForge open-source tool — partial withdrawals, tips, gateway fees, configurable refund delays)
  • Scenario 3 — Payment Treasury / E-commerce (CeloMarket marketplace — campaign creation, treasury deployment, off-chain and on-chain payment flows, line items, refunds)
  • Scenario 4 — Event Monitoring (historical queries, real-time watchers, raw log decoding, metrics aggregation)
  • Scenario 5 — Error Handling (simulate-before-send, typed errors, read-only clients, multisig/AA prep, simulateWithErrorDecode)
  • Scenario 6 — Advanced Patterns (multicall, signer overrides, item registry, getReceipt, MetaMask & Privy wallets)

Use-Case Integration Guides

Business-oriented guides under packages/contracts/src/use-cases/ covering:

  • Crowdfunding — Creative campaign (ArtFund, AllOrNothing)
  • Flexible Funding — Community project (TechForge, KeepWhatsRaised)
  • Marketplace — E-commerce (CeloMarket, CampaignInfoFactory + PaymentTreasury)
  • Escrow — Healthcare (MedConnect, CampaignInfoFactory + PaymentTreasury)
  • Prepayment — Automotive (Karma, CampaignInfoFactory + TimeConstrainedPaymentTreasury)

All use cases now include the full lifecycle: campaign creation → treasury deployment → operations.

Documentation

  • README updated with Examples and Use Cases sections, five client configuration patterns, transaction receipt methods, and simulation utilities.
  • Examples README with folder structure tree and scenario overview table.
  • Use-cases README with contract-to-use-case mapping and common patterns (simulate-before-send, multicall, fee lifecycle, signer flexibility).

Internal / Quality

  • packages/contracts holds 100 % statement / branch / function / line coverage (enforced in CI).
  • Example and script files excluded from coverage collection.
  • Stricter typings: Bytes4 for supportsInterface, TAbi generic for prepareContractWrite, ViemSimulateRequest for structured simulation responses.
  • Shared error handler for GlobalParams, ItemRegistry, and PaymentTreasury error parsing.
  • getReceipt catches TransactionReceiptNotFoundError specifically, re-throws other errors.
  • Platform verification script derives active registrations from Registered vs Removed event replay, and evaluates approvals using the latest event per implementation address.

Migration Notes

  • simulate.* methods now return SimulationResult ({ result, request }) instead of void. Callers that previously discarded the return value are unaffected; callers that want structured data can now destructure it.
  • AllOrNothing and KeepWhatsRaised entities no longer expose ERC-721 methods (approve, setApprovalForAll, balanceOf, ownerOf, tokenURI, safeTransferFrom, transferFrom) or events (Approval, ApprovalForAll, Transfer). Use the CampaignInfo entity for all NFT operations instead.
  • Prefer the new typed event / error name constants (e.g. ALL_OR_NOTHING_EVENTS.Receipt) over string literals for safer refactors.

Test Plan

  • CI green on pnpm build, pnpm lint, pnpm test (100 % coverage thresholds enforced for packages/contracts)
  • Changesets bot produces the expected minor version bump for @oaknetwork/contracts-sdk
  • Spot-check README + examples render correctly on GitHub / npm
  • Verify @oaknetwork/contracts-sdk/metrics and /contracts subpath exports resolve in a downstream consumer

…tion utilities for enhanced transaction handling
- Reduce README from ~1,100 lines to ~430 lines by replacing exhaustive
API listings with a summary table and doc links.
- Add documentation for
new client features: getReceipt(), SimulationResult return type,
prepareContractWrite/toPreparedTransaction utilities, and ABI exports.
…d improve error handling

- Refactor simulateContract response handling to utilize structured request fields (address, abi, functionName, args) instead of raw to/data fields.
- Enhance toSimulationResult function to encode calldata from the new request structure.
- Update unit tests to reflect changes in request structure and expected results.
- Modify the toPreparedTransaction function to preserve undefined gas values instead of defaulting to 0n.
- Update unit tests to reflect the new behavior of gas handling in prepared transactions.
- Add step-by-step examples covering the complete platform onboarding flow: enlistment, verification, treasury implementation registration, and approval.
- Include optional configuration steps for line item types, claim delays, platform data keys, and protocol admin functions.
- Document the process in a README with roles, responsibilities, and a role reference table from the smart contract.
- Add a comprehensive set of examples demonstrating the all-or-nothing crowdfunding process, including campaign creation, treasury deployment, reward management, backer pledges, and monitoring campaign progress.
- Include functionality for fee disbursement, fund withdrawal upon success, and refund claims upon failure.
- Document the entire flow in a README, outlining roles, responsibilities, and a reference table for smart contract functions.
- Add a complete set of examples demonstrating the Keep-What's-Raised crowdfunding process, including campaign creation, treasury deployment, reward management, backer pledges, and monitoring campaign progress.
- Include functionality for partial and final withdrawals, fee disbursement, and refund claims.
- Document the entire flow in a README, outlining roles, responsibilities, and a reference table for smart contract functions.
- Add a complete set of examples demonstrating the e-commerce payment process, including treasury setup, payment creation, crypto payment processing, payment confirmation, and refund handling.
- Include functionality for reading payment and treasury data, disbursing fees, withdrawing funds, and claiming expired or non-goal line items.
- Document the entire flow in a README, outlining roles, responsibilities, and a reference table for smart contract functions.
- Introduce a series of examples demonstrating event monitoring for an analytics dashboard, including fetching historical campaign events, treasury-specific events, real-time event watchers, decoding raw logs, and aggregating metrics.
- Each step is documented in a README, outlining the process and providing a reference table for the implemented functionalities.
- Introduce a series of examples demonstrating error handling and transaction safety in smart contract interactions.
- Include steps for simulating transactions, preparing for external signing, catching typed errors, handling read-only clients, and implementing a safe transaction pattern.
- Provide a convenience wrapper for simulation and error decoding in a single call.
- Document the entire flow in a README, outlining the process and providing a reference table for the implemented functionalities.
- Introduce a series of examples demonstrating advanced patterns in smart contract interactions, including multicall for batch reads, per-entity and per-call signer overrides, item registration in the ItemRegistry, and protocol registry value lookups.
- Implement non-blocking receipt lookups and browser wallet integrations for enhanced user experience.
- Document the entire flow in a README, outlining the scenarios and providing a reference table for the implemented functionalities.
- Introduce a new setup module for shared client configuration across examples, including environment variable requirements for RPC URL and contract addresses.
- Implement functions to create a client instance and validate environment variables, enhancing the usability of example contracts.
- Introduce a new README.md file containing real-world examples that demonstrate the capabilities of the Oak Contracts SDK, including platform onboarding, crowdfunding campaigns, e-commerce checkout, and more.
- Each scenario is structured with a detailed explanation, folder organization, and step-by-step TypeScript files to facilitate understanding and implementation.
- Provide a clear overview of roles involved in each scenario, enhancing the usability for developers and stakeholders.
- Add comments for additional treasury implementations in the TypeScript example, including PaymentTreasury and TimeConstrainedPaymentTreasury, clarifying their use cases and registration process.
- Update README.md to reflect the new treasury implementations, detailing their functionalities and differences, ensuring clarity for developers on the SDK interface and registration requirements.
- Correct the property name from 'treasury' to 'treasuryAddress' in the treasury deployment logs for both all-or-nothing and keep-whats-raised examples, ensuring consistency and accuracy in the code.
… example

- Update error message check to use startsWith for better matching of "No signer configured" error, providing clearer guidance for users to connect their wallet before performing actions.
… treasury example

- Update the treasury example to wait for transaction mining before allowing withdrawals, preventing potential reverts if fees have not been disbursed yet. This enhances the reliability of the contract interactions.
- Comment out the platformHash definition in the optional configuration example to clarify its usage in subsequent examples.
- Remove unused import of keccak256 in the error handling example to streamline the code and improve readability.
- Update the treasury deployment examples to decode the TreasuryDeployed event directly from the transaction receipt, ensuring accurate retrieval of the treasury address and avoiding ambiguity with multiple deploys in the same block.
…xample

- Change the refund process to allow NFT owners to claim refunds directly by burning their NFT, enhancing user experience and clarity in the refund flow.
- Update comments and variable names for better understanding of the refund mechanism, distinguishing between crypto and off-chain payment scenarios.
- Introduce a new events.ts file containing type-safe constants for event names emitted by various contracts, including GlobalParams, CampaignInfoFactory, CampaignInfo, TreasuryFactory, AllOrNothing, KeepWhatsRaised, PaymentTreasury, and ItemRegistry.
- Update index.ts to re-export these event constants for improved accessibility.
mahabubAlahi and others added 21 commits April 17, 2026 20:26
…nt functions

- Remove tests for token management functions (balanceOf, ownerOf, tokenURI, approve, setApprovalForAll, safeTransferFrom, transferFrom) from AllOrNothing, CampaignInfo, and KeepWhatsRaised contracts to enhance test clarity and maintainability.
- Update related test cases to ensure they accurately reflect the current contract functionalities, improving overall test coverage and reliability.
…ised contracts

- Eliminate redundant event names (Approval, ApprovalForAll, Transfer) from the AllOrNothing and KeepWhatsRaised contracts to streamline the event definitions.
- Update the event constants accordingly to enhance code clarity and maintainability while ensuring the remaining functionalities of the contracts remain intact.
…nInfo contract

- Modified the pledge and refund processes in the AllOrNothing, KeepWhatsRaised, and PaymentTreasury examples to reflect that pledge NFTs are managed through the CampaignInfo contract instead of the treasury contracts.
- Updated relevant comments and documentation to clarify the approval process for NFTs, ensuring that users understand the need to approve the CampaignInfo contract before calling refund functions.
- Enhanced overall clarity and maintainability of the code by consolidating NFT management logic.
…ampaignInfo contract

- Revised documentation across crowdfunding, escrow, and marketplace use cases to reflect that pledge NFTs are managed via the CampaignInfo contract instead of the treasury contracts.
- Enhanced comments to specify the approval process for NFTs, ensuring users understand the need to approve the CampaignInfo contract before invoking refund functions.
- Improved clarity and consistency in refund flow descriptions, detailing the distinct paths for cancellation and refunds based on payment types.
…ionality

- Updated the README and code examples for the Payment Treasury to enhance clarity on the payment processes, including both off-chain and on-chain flows.
- Introduced new files for creating campaigns, deploying treasuries, processing payments, and handling refunds, ensuring a comprehensive guide for users.
- Clarified the roles of platform admins and creators in managing campaigns and treasuries, and detailed the steps for fee disbursement and fund withdrawal.
- Improved documentation to reflect the distinct paths for payment processing and refund handling, emphasizing the NFT management through the CampaignInfo contract.
…ontract

- Revised the README files for Escrow, Marketplace, and Prepayment use cases to reflect the integration of the CampaignInfo contract in the payment processes.
- Clarified the roles of CampaignInfoFactory and TreasuryFactory in creating and deploying contracts, enhancing the understanding of the overall flow.
- Improved the integration flow steps to detail the creation of CampaignInfo contracts before deploying PaymentTreasury and TimeConstrainedPaymentTreasury.
- Enhanced clarity on the NFT management process and the distinct roles of platform admins and campaign creators in managing funds and payments.
- Updated the verification process for treasury registrations to filter and confirm implementations specific to the NovaPay platform, avoiding false positives from shared deployments.
- Added detailed logging for registered implementations and their approval status, ensuring clarity on which implementations are approved.
- Improved comments to clarify the purpose of each verification step, specifically for NovaPay, enhancing overall code readability and maintainability.
Update event log fetching documentation and improve code consistency
- Updated the verification process to derive active treasury registrations by filtering out removed implementations, ensuring accurate tracking of current registrations for the NovaPay platform.
- Improved logging to reflect the count of active implementations and their approval status, providing clearer insights into the treasury's state.
- Enhanced comments for better understanding of the verification steps and the significance of approval events in the context of treasury management.
- Introduced a new "Examples" section detailing scenario-driven TypeScript examples that cover various SDK functionalities, providing users with practical implementation stories.
- Added a "Use Cases" section that outlines business-oriented integration guides, illustrating how real companies can utilize the SDK for specific applications.
- Enhanced the README to improve navigation and understanding of the SDK's capabilities, directing users to relevant resources for both executable examples and documentation guides.
…ements

Add missing events, reads, errors, type-safe constants, simulation results, transaction preparation, and getReceipt
Add scenario-driven SDK examples and use-cases with real-world storytelling
@adnanhq adnanhq requested a review from mahabubAlahi April 17, 2026 18:28
@mahabubAlahi mahabubAlahi requested a review from devmahmud April 17, 2026 18:29
@adnanhq adnanhq changed the title Contracts SDK v2 Contracts SDK v1.2 Apr 17, 2026
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e404554e84

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread packages/contracts/src/errors/parse-contract-error.ts
Comment thread packages/contracts/src/utils/prepare.ts
@mahabubAlahi mahabubAlahi merged commit 8e45823 into main Apr 17, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants