Add scenario-driven SDK examples and use-cases with real-world storytelling#108
Add scenario-driven SDK examples and use-cases with real-world storytelling#108mahabubAlahi merged 44 commits intodevelopfrom
Conversation
- 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.
- Replace hardcoded event name "TreasuryFactoryTreasuryDeployed" with the constant TREASURY_FACTORY_EVENTS.TreasuryDeployed in both all-or-nothing and keep-whats-raised treasury deployment scripts. - Enhance code maintainability and clarity by utilizing centralized event constants.
- Update error handling patterns to include matching by error name using type-safe constants. - Introduce a fallback mechanism for unknown contract errors, improving clarity and maintainability of error messages. - Expand documentation to reflect the new error handling patterns.
- Added comprehensive documentation on multi-token support in the README files across various examples. - Updated code comments to clarify the handling of multiple ERC-20 tokens in campaign configurations and treasury operations. - Adjusted example scripts to reflect the use of USDC instead of cUSD for consistency in token representation.
- Introduced comprehensive documentation for various use cases, including Escrow, Marketplace, Prepayment, Flexible Funding, and Crowdfunding. - Each guide outlines the business context, integration flow, and relevant Oak contracts, enhancing clarity for developers.
- Renamed and reorganized example scripts for clarity: `06a-partial-withdrawal.ts` is now `06a-approve-partial-withdrawal.ts`, and `06b-final-withdrawal.ts` is now `06b-execute-partial-withdrawal.ts`. - Added new example script `06c-final-withdrawal.ts` for executing final withdrawals after the campaign deadline. - Updated README files to reflect changes in withdrawal steps and clarify the withdrawal delay configuration for production use.
- Updated the refund example scripts to require trimmed environment variables for pledge token IDs, enhancing error handling by throwing descriptive errors when the required IDs are not provided. - This change ensures that the scripts fail gracefully with clear messages, improving developer experience and reducing potential runtime errors.
… use cases - Changed the refund function for NFT payments from `claimRefund(paymentId)` to `claimRefundSelf(paymentId)` across healthcare, marketplace, and prepayment documentation. - Clarified roles for refund processes, specifying that the buyer (NFT owner) is responsible for initiating refunds for NFT payments. - Enhanced consistency in terminology and improved clarity in the documentation regarding refund procedures.
- Updated jest configuration to exclude files in the `src/examples` and `src/scripts` directories from coverage reports, improving the accuracy of coverage metrics by focusing on relevant source files.
- Updated comments and README to distinguish between two independent payment flows: Flow A (off-chain payment via `createPayment`) and Flow B (on-chain payment via `processCryptoPayment`). - Enhanced descriptions to improve understanding of the payment process, including the roles of the platform admin and buyer in each flow. - Added details on the NFT minting process as proof of payment for on-chain transactions.
- Updated the payment process documentation to distinguish between two independent payment flows: Flow A (off-chain payment via `createPayment`) and Flow B (on-chain payment via `processCryptoPayment`). - Enhanced descriptions to improve understanding of the payment process, including the roles of the platform admin and buyer in each flow. - Added details on the NFT minting process as proof of payment for on-chain transactions.
- Revised the E-Commerce Marketplace documentation to remove references to ItemRegistry, emphasizing the use of PaymentTreasury for product escrow with line items. - Clarified the integration flow and payment processes, including the roles of buyers and sellers, and updated the steps to reflect the removal of ItemRegistry interactions. - Enhanced overall readability and consistency in the documentation regarding payment flows and order processing.
- Enhanced README files to clarify the roles of Backers and Platform Admins in the campaign process, specifically regarding the recording of payment gateway fees. - Updated the community project documentation to better explain the pledge process, including tips and the recording of gateway fees, ensuring clear guidance for both backers and platform administrators. - Improved overall readability and consistency in the documentation, reflecting recent changes in the pledge and fee recording processes.
…ents - Added prerequisites for backers to approve the treasury contract to manage their pledge NFTs before calling `claimRefund` in both all-or-nothing and keep-whats-raised examples. - Clarified that the treasury is an ERC-721, requiring direct approval on the treasury entity. - Enhanced comments to improve understanding of the refund process and NFT handling.
- Added instructions for backers to approve the treasury to manage their pledge NFTs before calling `claimRefund` in both all-or-nothing and flexible funding scenarios. - Clarified that the treasury acts as the ERC-721 contract, requiring direct approval on the treasury entity. - Improved comments to enhance understanding of the refund process and NFT handling.
- Changed the privateKey assignment in the example to use a non-null assertion, ensuring that the environment variable is treated as defined. This improves type safety and prevents potential runtime errors.
- Updated the README files for various use cases, including Escrow, Marketplace, and Crowdfunding, to improve clarity on roles, payment processes, and refund mechanisms. - Clarified the prepayment process in the Automotive Prepayment documentation, emphasizing time-based expiry for vehicle deposits. - Enhanced the description of the KeepWhatsRaised model in the Community Project documentation, detailing the tip collection process and partial withdrawal capabilities. - Improved overall readability and consistency across all documentation, ensuring accurate representation of the functionalities and processes involved.
…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.
…-chain payment flow
- 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.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: be936dde3c
ℹ️ 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".
| const removedSlots = new Set( | ||
| removedLogs | ||
| .filter((log) => log.args?.platformHash === platformHash) | ||
| .map((log) => String(log.args?.implementationId)), | ||
| ); |
There was a problem hiding this comment.
Track latest slot action when deriving active implementations
Building removedSlots from every historical TreasuryImplementationRemoved event causes false negatives when a slot is removed and later re-registered: the later registration is still filtered out, so the script undercounts active implementations and can incorrectly report setup problems. Derive current slot state from the latest event per implementationId (or replay register/remove events in order) instead of treating any past removal as permanent.
Useful? React with 👍 / 👎.
| const allApproved = activeRegistrations.every((reg) => { | ||
| const addr = (reg.args?.implementation as string)?.toLowerCase(); | ||
| return latestApproval.get(addr) === true; | ||
| }); |
There was a problem hiding this comment.
Require a non-empty approved implementation set
every(...) on activeRegistrations is vacuously true for an empty list, so this verification can report "All ... approved" even when no implementation is registered at all. In that state the platform still cannot deploy treasuries, so the script may give a false onboarding success signal unless it also checks activeRegistrations.length > 0.
Useful? React with 👍 / 👎.
Summary
Add 65 scenario-driven TypeScript examples across 7 scenarios, each telling a real-world story that walks developers through the Oak Contracts SDK step by step — from platform onboarding to crowdfunding campaigns, e-commerce payments, event monitoring, error handling, and advanced integration patterns.
Every example follows the same structure: a narrative describes who is involved, what they are doing, and why — then working TypeScript code demonstrates how, using the SDK exactly as it would be used in production. Non-technical readers can follow the story; developers can copy the code.
How to Explore These Examples
Start here:
packages/contracts/src/examples/README.md— the index page that explains the folder structure, the four roles (Protocol Admin, Platform Admin, Creator, Backer), and which scenario to begin with.Each scenario folder has a
README.mdwith the full story, a step-by-step walkthrough, a files table, and a role reference from the smart contract.Scenarios
Scenario 0 — Platform Enlistment (
00-platform-enlistment/)Story: NovaPay, a digital marketplace, wants to join Oak Protocol. The Protocol Admin enlists them on-chain, then NovaPay registers and gets approval for treasury implementations.
Steps: Enlist platform → Verify enlistment → Register treasury implementations (AllOrNothing, KeepWhatsRaised, PaymentTreasury, TimeConstrainedPaymentTreasury) → Protocol Admin approves → Final verification → Optional configuration (line item types, claim delay, platform data keys, adapter, protocol admin functions)
Scenario 1 — All-or-Nothing Campaign (
01-campaign-all-or-nothing/)Story: Maya, a ceramic artist, crowdfunds $5,000 for her "Earth & Fire" collection on ArtFund. Backers pledge with ERC-20 tokens and receive NFT receipts. If the goal is met, Maya withdraws funds; if not, every backer gets a full refund.
Steps: Create campaign → Look up address → Review details → Deploy treasury → Add/remove reward tiers → Backer pledges (with or without reward) → Monitor dashboard → Disburse fees → Success: withdraw / Failure: refund (burns NFT) → Pause/unpause → Cancel treasury
Scenario 2 — Keep-What's-Raised Campaign (
02-campaign-keep-whats-raised/)Story: TechForge, a dev team, raises $10,000 for an open-source tool. Unlike All-or-Nothing, they keep whatever is raised. They can withdraw partial funds mid-campaign (with platform approval) and sweep the rest after the deadline.
Steps: Create campaign → Deploy treasury → Configure fees/delays → Add/remove rewards → Backer pledges (with tips, gateway fees) → Partial withdrawal (6a) + Final withdrawal (6b) → Monitor dashboard → Disburse fees → Claim residual funds → Claim tips → Refund (after deadline + delay) → Update campaign → Pause/unpause → Cancel
Scenario 3 — Payment Treasury (
03-campaign-payment-treasury/)Story: CeloMarket, an artisan marketplace, processes e-commerce payments on-chain. Sam buys a $120 ceramic vase with $15 shipping. The payment flows through line items, gets confirmed, and funds become available for withdrawal.
Steps: Setup treasury → Create payment (single + batch) → Buyer sends crypto payment → Confirm payment (single + batch) → Read payment data + treasury dashboard → Handle refunds (off-chain: admin-directed / on-chain: NFT owner self-service) → Disburse fees → Withdraw → Claim expired funds (TimeConstrained only) → Claim non-goal line items → Pause/unpause → Cancel
Scenario 4 — Event Monitoring (
04-event-monitoring/)Story: ArtFund's product team builds an analytics dashboard with historical event queries, real-time WebSocket watchers, raw log decoding, and pre-built metrics aggregation.
Steps: Fetch historical logs → Query treasury events → Set up real-time watchers → Decode raw transaction logs → Aggregate metrics (platform stats, campaign summary, treasury report)
Scenario 5 — Error Handling (
05-error-handling/)Story: Kai, a frontend developer, builds a campaign management UI that previews transactions before sending, shows clear error messages on reverts, and handles read-only sessions gracefully.
Steps: Simulate before send → Prepare transaction for external signing (multisig, AA) → Catch typed errors with recovery hints → Handle read-only client → Complete simulate-then-send pattern → One-call
simulateWithErrorDecodeconvenience wrapperScenario 6 — Advanced Patterns (
06-advanced-patterns/)Story: ArtFund scales to dozens of campaigns. Their engineering team needs batched reads, flexible signer resolution, physical product tracking, and browser wallet integration.
Steps: Multicall batch reads → Per-entity signer override → Per-call signer override → Item registry (single + batch) → Protocol registry keys (global + platform-scoped) → Non-blocking receipt lookup → Browser wallet (MetaMask) integration → Privy embedded wallet integration
Design Decisions
(Optional)in file tables and JSDoc headers.Use-case-driven integration guides:
Added comprehensive guides covering Escrow, Marketplace, Prepayment, Flexible Funding, and Crowdfunding use cases. Each guide walks developers through the business context, integration flow, and relevant Oak contracts.