user-avatar
e
eatahine
Joined
icon image
Sui Community
144 REP
48 Feedbacks
0 Submission

FEEDBACK

Submitted

SUI Farming Game Project Description The SUI Farming Game is a decentralized farming simulation implemented on the SUI blockchain using the Move programming language. In this game, players can plant crops, harvest rewards, and attempt to steal crops from other players. The game includes various special events and mechanics to enhance gameplay, such as double rewards, double anti-steal rates, and more. Key Features Planting: Players can plant crops by investing SUI tokens. Each crop has a unique maturity period and reward value. Harvesting: Once crops mature, players can harvest them to earn rewards. Stealing: Players can attempt to steal crops from other players. Success depends on various factors, including special events and random chance. Special Events: Special events can influence the game, such as doubling the anti-steal rate or ensuring 100% steal failure. Admin Controls: The game includes administrative controls to pause and resume gameplay.

90Points
5 Feedbacks
144 REP
Feedback

Helo Sofar, I recommended some ways to enhance the code;

  • Line 111: In get_game_by_epoch, the assertion uses != instead of == to check for the existence of the game. It should be assert!(vec_map::contains(&director.epoch_games, &epoch), E_GAME_DOES_NOT_EXIST);

  • Line 130: In get_farmer_by_epoch, the assertion uses != instead of == to check for the existence of the farmer. It should be assert!(vec_map::contains(&epoch_game.farm_users, &sender), E_NOT_INVOLVED_IN_PLANTING);

  • Line 101: In planting, the investment_value is asserted to be greater than or equal to 1000 Sui (1_000). This might be a bug as the intended minimum investment could be lower.

  • Line 147: In steal, the NOT_EXISTED_AVAILABLE_FARMER error is asserted if steal_flag is not true. It should likely be asserted if steal_flag is still false after iterating through all users, indicating no available target for stealing.

  • Line 181: In harvest, the rewards are updated before checking if the crop has already been harvested. This could lead to incorrect reward distribution if a user tries to harvest twice.

  • Access Control: While the code uses an AdminCap for pausing/resuming the game, other critical actions (e.g., transferring ownership, modifying game rules) lack access control checks.

  • Randomness: The steal function relies on a user-supplied random number generator (rnd). This can be manipulated by malicious users to increase their steal success rate. Consider using a Sui-provided verifiable random number generator (VRNG).

  • Reentrancy: The code doesn't explicitly protect against reentrancy vulnerabilities. Malicious contracts could exploit this to manipulate the game state during transactions.

  • Thread Safety: The code uses thread-local variables for internal state management, which might not be ideal for concurrent calls. Consider using proper synchronization mechanisms or re-evaluate your data access patterns if needed.

  • Logging: The current logging implementation uses debug::print, which might not be suitable for production as it doesn't provide a persistent log. Explore using IC's event logging capabilities for a more robust solution.

7.5 SUI
7.5 REP
Submitted

The appointment_booking is designed to facilitate the scheduling and management of appointments between patients and clinics. This includes functionalities for creating and managing clinics, patients, and appointments, as well as handling financial transactions related to appointment bookings

70Points
3 Feedbacks
144 REP
Feedback

Hello Ploperu, here are a few suggestions I made

  • Limited Authorization: While access control checks exist for specific functions, there's no role-based access control. Anyone can potentially create clinics, which might not be desirable. Consider implementing roles (e.g., admin, patient, clinic) and restricting actions based on those roles.

  • Data Validation: The code lacks explicit validation for user-provided data like appointment descriptions, clinic details, etc. Malicious users could inject invalid data that disrupts functionality. Implement server-side validation to ensure data integrity.

  • Missing Payment Confirmation: The make_payment function transfers funds but doesn't update the appointment status. It should ideally update the appointment status to "Confirmed" after successful payment.

  • Limited Payment Options: Currently, only Sui coin payments are supported. Consider integrating with a payment gateway or allowing other payment methods for broader user adoption.

  • Missing Cancellation Functionality: Patients or clinics cannot cancel appointments. Implement functionalities for canceling appointments with appropriate logic (e.g., potential refunds).

  • Appointment Listing Missing: Features to retrieve a list of appointments for a patient or clinic are absent. This would be beneficial for users to manage their bookings.

  • Logic Error (get_appointment_for_clinic): The function retrieves an appointment based on created_at. If multiple appointments have the same creation time (unlikely but possible due to concurrency), it might return an unexpected appointment. Consider using a unique identifier instead of created_at for retrieving appointments.

  • Status Management: The status field in Appointment is a string. Using an enum (e.g., Pending, Confirmed, Cancelled) would provide a more structured and secure way to manage appointment statuses.

  • Logging: Implementing logging for successful appointments, payments, withdrawals, and errors would be helpful for auditing and debugging purposes.

  • Notifications: Sending notifications to patients and clinics about appointment confirmations, cancellations, or status changes could enhance user experience.

5 SUI
5 REP
Submitted

The Co_Invest_Club module is expertly crafted for the management of investment clubs within the Sui blockchain ecosystem. This robust module facilitates the establishment of clubs, enrollment of members, and administration of investments, all while ensuring secure and efficient transaction handling in a decentralized environment. This comprehensive tool is designed to streamline the operations of investment clubs, promoting transparency and accountability in financial dealings.

70Points
3 Feedbacks
144 REP
Feedback

Hello, I made a few suggestions to improve the code;

  • Investment Calculation: In generate_investment_amount, the total_amount_payable directly uses the provided amount_payable without multiplying it by the member's number_of_shares. This could lead to incorrect investment amounts if amount_payable isn't intended to represent the per-share amount.

  • Investment Due Dates: The code doesn't explicitly set due dates for investments. It only checks if the current time is past the provided date added to the payment_date (which is the creation time). Consider allowing admins to define due dates for investments.

  • Gender Restriction: The gender field in Member is restricted to MALE or FEMALE. A more inclusive approach for gender options might be preferable.

  • Event Emission: Implementing events can notify interested parties about club activities (e.g., new member, successful investment).

  • Role-Based Access Control (RBAC): A more granular permission system with different member roles (e.g., admin, member) could be implemented for better access control.

6.25 SUI
6.25 REP
Submitted

The Music Marketplace module facilitates decentralized management of music tracks, collaborations, and events within a blockchain ecosystem. It provides functionalities for musicians to publish tracks, sell music, handle disputes, collaborate with other artists, manage events, and interact with fans securely and transparently.

70Points
4 Feedbacks
144 REP
Feedback

Hello Benaa, check out the changes I proposed:

  • Potential Infinite Loop: In buy_ticket, if there are no tickets left (event.ticketsSold >= event.tickets), the assertion fails but the function doesn't exit, potentially leading to an infinite loop.

  • Missing Logic in resolve_dispute: As mentioned earlier, the function lacks logic to determine who receives funds (musician or client) during dispute resolution.

  • Missing Authentication: The code currently lacks any explicit authentication mechanism. Anyone can call the public entry functions without verification. You'll need to implement an authentication system (e.g., JWT, Sui wallet integration) to restrict access based on roles (musician, client).

  • Authorization Issues: While MusicianCap provides some access control, it might be beneficial to implement more granular authorization checks within functions. For example, update_track_price could verify that the musician has enough funds in escrow to cover the potential refund if a dispute arises.

  • Escrow Shortcomings:

    • The current escrow system doesn't handle disputes involving partial refunds. Consider allowing for more complex dispute resolution where only a portion of the escrow might be transferred.
    • withdraw_from_escrow allows a musician to withdraw funds even if a track is sold. This could be risky if a dispute arises later. You might want to restrict withdrawals until disputes are settled or the track is marked complete.
  • Event Attendance Tracking: As mentioned before, buying a ticket doesn't translate to attending an event. The system lacks mechanisms to verify ticket validity or manage event attendance.

  • Implement proper error handling using the defined custom errors or a centralized error handling function.

  • Address the identified bugs (infinite loop and missing dispute resolution logic).

  • Integrate an authentication system to control access to public entry functions.

  • Implement more granular authorization checks within functions based on roles and capabilities.

  • Enhance the escrow system to handle partial refunds and restrict withdrawals during disputes.

  • Consider solutions for tracking event attendance and verifying ticket validity (e.g., additional Sui objects or integration with external services).

Submitted

This smart contract is designed to manage a parking lot on the Sui blockchain. It includes functionality for administering the parking lot, creating and managing parking slots, recording payments, calculating parking fees, and distributing profits. The contract ensures that only the administrator can perform certain actions, such as creating parking slots and withdrawing profits, while enabling users to reserve and use parking slots. The parking lot’s operations and financial transactions are transparently managed and recorded on the blockchain.

50Points
4 Feedbacks
144 REP
Feedback

Hello zwhqq, check out the suggestions I made concerning tour code;

  1. Missing Clock object in create_payment_record: The function takes a clock argument but doesn't use it to get the timestamp. Update the code to utilize clock.timestamp_ms() for payment_time.

  2. Inconsistent error code for withdraw_profits: The function uses error code 101 which isn't defined. It should likely use the existing EParkingSlotNotAvailable or define a new error code specific to unauthorized withdrawals.

  3. Redundant check in enter_slot: The function checks if the slot is not occupied (!slot.status) which might be redundant after the reserve_slot function is called. Consider removing this check if reserve_slot is intended for pre-reservation before occupying the slot.

  4. Missing Fee Payment: The code calculates parking fees but lacks a mechanism to collect payment before exiting a slot. An attacker could occupy a slot and exit without paying. Implement a function for users to pay before exiting.

  5. Reentrancy Protection: The code is susceptible to reentrancy attacks. Explore mechanisms like ObjectRef to prevent attackers from manipulating function calls during execution.

  • Error Handling: Consider using Sui's error handling functions (assert!, abort!) for more specific error messages.
  • Peak Hour Handling: Implement logic in calculate_parking_fee to account for potential peak hour pricing based on the _is_peak parameter.
  • Test Function Naming: Rename test_generate_slots to better reflect its purpose (e.g., test_init_parking_lot).
  • Additional Considerations:
    • Implement a maximum parking duration.
    • Integrate user authentication for reserving slots (optional).
    • Consider emitting events for actions like entering/exiting slots and creating payment records.
5 SUI
5 REP
Submitted

Decent_learner is a decentralized e-learning platform where users can enroll in courses, and educators can offer their expertise. Payments are handled through a decentralized finance (DeFi) mechanism, allowing seamless transactions and financial incentives for both learners and educators. It involves storing of instances of these objects in a persistent store (such as the blockchain state) and provided functions to manipulate them within your module.

70Points
5 Feedbacks
144 REP
Feedback

Hello Hez_dev, check out a few suggestions I put foward; Missing Return Type: The withdraw function doesn't explicitly return anything. Consider returning a result (e.g., bool for success/failure) or performing an action after successful withdrawal.

Reentrancy Attacks: The code doesn't implement mechanisms to prevent reentrancy attacks during enrollment or withdrawal. An attacker could exploit this to manipulate the system during a transaction (e.g., enrolling twice for the same course).

Concurrency Control: The code doesn't explicitly handle potential concurrency issues when multiple users try to modify the same data concurrently (e.g., two students enrolling in the same course at the same time).

Data Validation: While the code checks for sufficient funds and course existence before enrollment, there might be additional checks to consider: * Valid student reference * Unique course enrollment (preventing duplicate enrollments)

Event Logging: As mentioned before, emitting events for specific actions can be beneficial for auditing and monitoring.

Educator Withdrawals: The withdraw function provides a way for educators to withdraw funds.

Course Completion Tracking: The enroll function now updates the completed_courses field for students (assuming completion upon enrollment).

Submitted

# Module: virtualbank > NOTE: sui version >= 1.24.1 and the edition = " 2024.beta ". - This module is represents a virtual bank system, and user can swap their SUI coins to virtual bank. - Bank is a global shared object that is managed by the admin, which is designated by the ownership of the bank owner capability. - The bank owner can initialize bank, set the exchange rate, add coins to the bank, and withdraw coins from the bank. - Users can exchange two types of coins through virtual banks ## Structs ### (1) Bank - A Bank is a global shared object that is managed by the admin. - The bank owner can initialize bank, set the exchange rate, add coins to the bank, and withdraw coins from the bank. ### (2) AdminCap: - Ownership of the Bank object is represented by holding the bank owner capability object. - The shop owner has the ability to add items to the shop, unlist items, and withdraw from the shop. ## Functions ### (1) initialize: initialize a bank Function to initialize a bank with initial coins and rate. ### (2) set_rate: Set rate to bank: Function to set the exchange rate of the bank. ### (3) add: add coins to the bank. Entry function to add coins to the bank. ### (4) swap_a_b: Swaps coins of type B for coins of type A Swaps coins of type B for coins of type A based on the bank's exchange rate. ### (5) swap_b_a: Swaps coins of type B for coins of type A Swaps coins of type B for coins of type A based on the bank's exchange rate. ### (6) withdraw: Withdraws all coins of type A and B Withdraws all coins of type A and B from the bank and transfers them to the sender.

80Points
4 Feedbacks
144 REP
Feedback

Hello sony9997, here are a few suggestions I made ro enhance your code;

  • Specific Error Codes: While the code uses a generic EInsufficientBalance error code, consider using more specific error codes for different scenarios (e.g., insufficient balance for coin A, insufficient balance for coin B). This provides more informative messages for debugging.

  • Custom Errors: Instead of relying on assertions, consider defining custom error types (e.g., InsufficientBalanceError) to improve readability and maintainability.

  • Authorization Checks: Currently, only withdraw requires admin capabilities. Consider adding authorization checks for other sensitive operations like swap_a_b and swap_b_a to prevent unauthorized swaps.

  • Reentrancy Protection: The code might be vulnerable to reentrancy attacks. Transactions can potentially call other functions before the current transaction completes, leading to unexpected behavior. Explore mechanisms like Sui's SerializedObject or implement custom checks to prevent reentrancy.

  • Comments: While the code uses comments to explain function purposes, adding comments within functions to explain specific logic steps would enhance readability.

  • Variable Naming: Consider using more descriptive variable names (e.g., initialBalance instead of balance1).

  • Zero-Value Swaps: The code asserts that the coin value for swaps must be greater than zero. However, it might be worth considering how to handle zero-value swaps explicitly (e.g., returning an error or doing nothing).

  • Self-Transfer (withdraw): The #[allow(lint(self_transfer))] attribute suppresses a warning for self-transfer in the withdraw function. While this might be intentional, ensure the logic behind the self-transfer is sound and avoids unintended consequences.

5 SUI
5 REP
2.5 REP
Submitted

The School Management Smart Contract is a decentralized application (DApp) built on the SUI (Move) programming language for the Move blockchain. It provides a comprehensive solution for managing various aspects of a school, including student enrollment, attendance tracking, fee management, and more. Features: Student Enrollment: Allows administrators to register new students, storing their personal information such as name, age, gender, and contact details. Attendance Tracking: Enables teachers to mark attendance for students, keeping track of their attendance records securely on the blockchain. Fee Management: Facilitates the collection of fees from students and tracks their payment status. It generates detailed bills for students and records payment transactions. Academic Records: Stores academic records such as grades, exam results, and class assignments securely on the blockchain. User Permissions: Implements role-based access control, allowing administrators, teachers, and students to access specific functionalities based on their roles.

70Points
4 Feedbacks
144 REP
Feedback

Hello fils, I proposed a few ways to enhance the code;

  • Logic Error in generate_fee: Adding the provided date to the current timestamp might lead to unexpected behavior if the intended date represents an absolute time. Consider allowing absolute timestamps or relative offsets (e.g., days from now).

  • Missing Logic in pay_fee: The function doesn't explicitly join the received Sui coin with the school's balance. The commented line (// join the balance) needs proper implementation.

  • Limited Access Control: The current SchoolCap approach provides basic access control. It's recommended to implement a more granular role-based access control system (e.g., admin vs teacher) for different functionalities like creating schools, enrolling students, generating fees, and withdrawing funds.

  • Unrestricted View Function: The get_fee_amount function requires context for access control, but it's unclear how it restricts access to the fee amount. Ideally, it should only return the fee amount for the student associated with the caller (sender's context).

  • Missing Error Handling: The code lacks informative error messages for functions like enroll_student and pay_fee. Consider using Sui error codes and human-readable messages for better debugging.

  • Incomplete Functionality: Comments indicate incompleteness in functions like // Enroll a student and // Pay fee. It's essential to complete their implementation for intended functionalities.

5 SUI
5 REP
Submitted

The project is a savings plan smart contract built on SUI (Secure Universal Integration), a programming language tailored for blockchain development. The smart contract enables users to participate in a savings plan by joining with a specified amount of coins. Users can increase their shares over time, redeem shares, and create savings proposals within the plan. These proposals include details such as the amount, recipient, and duration. Users can vote on proposals, and if a proposal receives sufficient votes, it is executed, distributing funds according to the community's decision. The contract ensures transparency and security in managing savings within a decentralized environment, providing users with a reliable platform for collaborative financial planning.

70Points
3 Feedbacks
144 REP
Feedback

Hello 25teddy, I proposed a few changes to your code, here they are:

Potential Redundant Check in execute_saving: There might be a redundant check for saving.ended before setting it to true in the execute_saving function.

Sybil Attacks: The current implementation doesn't mitigate Sybil attacks where malicious actors create multiple accounts to influence voting.

Off-chain Coordination: There's no mechanism to prevent off-chain coordination between members to manipulate voting.

Code Optimization: While some checks were potentially addressed, further review for optimization opportunities might exist (e.g., redundant calculations).

6.25 SUI
6.25 REP
Submitted

A Decentralized Peer-to-Peer Lending Platform with Web Application Integration using zkLogin . This project aims leverages blockchain technology to facilitate direct lending between individuals without the need for traditional financial intermediaries with smart contract-based lending protocol on a blockchain network, allowing users to create, fund, and manage loans securely and transparently. and a User-friendly Web Application with easier login of zklogin and intuitive features for borrowing, lending, managing loans, and tracking loan performance. repayment scheduling, and communication with borrowers/lenders and also Rating and Review System

50Points
6 Feedbacks
144 REP
Feedback

Hello Olisehgenesis, take a look at the proposed changes;

  • Missing add_interest logic: The repay_loan function doesn't include logic to add interest to the repayment amount.

  • Potential infinite loop: The find_loan_index_by_id function might get stuck in an infinite loop if no loan with the provided ID exists. Consider adding a check to break the loop after iterating through all loans.

  • Missing access control: The code doesn't enforce access control for modifying loans or reputations. Malicious actors could potentially tamper with these objects.

  • Unprivileged loan creation: Anyone can create a loan for another user (setting borrower to a non-zero address) which could be used for scams.

  • Unverified loan repayment: The repay_loan function doesn't verify if the transferred amount covers the entire loan amount with interest.

  • Loan Due Date Enforcement: The code doesn't handle loan due dates. You could implement logic to check for overdue loans and potentially penalize borrowers (e.g., late fees, impact reputation).

  • Event Handling: The LoanRepaidEvent is emitted but not used. Consider processing the event for actions like updating borrower reputation or triggering notifications.

  • Error Handling: The code uses assert! for error checking. Consider using proper error types and handling for a more robust system (e.g., returning custom error messages).

  • The FLOAT_SCALING constant isn't used in the provided code.

  • Consider adding comments to explain the purpose of functions and variables for better readability.

5 SUI
5 REP
Submitted

Introducing the Freelancer Platform Smart Contract, designed to operate on the Sui blockchain. This advanced smart contract lays the groundwork for a comprehensive freelancer platform, encompassing all necessary functionality to manage freelancers, clients, job postings, proposals, and projects. With this contract, the Sui blockchain becomes a dynamic hub for freelancers and clients to connect, collaborate, and complete projects securely. Experience a new level of trust and efficiency in freelancing with the Freelancer Platform Smart Contract on the Sui blockchain.

50Points
4 Feedbacks
144 REP
Feedback

Hello, i suggested a few ways to improve the code;

  • Access Control: Implement capability-based access control or other mechanisms to restrict actions based on user roles (freelancer, client, admin).
  • Data Integrity: Consider cascading deletes or introducing flags when deleting objects to ensure related objects are handled appropriately.
  • Freelancer Skills: Change skills to a Set<String> to avoid duplicate entries.
  • Client Functionalities: Implement functions for clients to post jobs, view proposals, and manage projects.
  • Proposal and Project Management: Implement functions for selecting/rejecting proposals and marking projects as completed.
  • Payment System: Integrate a secure payment system (e.g., escrow service) to handle project payments.
Submitted

This is a market app that allows users to perform basic operations such as: 0. Minting Widgets: Create new widget objects (play objects) to be listed on the marketplace. 1. Getting Owned Widgets: Retrieve a list of widget IDs currently owned by the connected wallet address. 2. Listing Items: Sell owned widgets by specifying the ask price and listing them on the marketplace. 3. Getting Marketplace Listings: View currently available listings on the marketplace, including ask prices and corresponding widget IDs. 4. Buying Listed Items: Purchase a listed widget by transferring the specified ask price in SUI. 5. Taking Profits: (For sellers) Withdraw SUI earned from selling items on the marketplace. Notes: Widgets are placeholders for different items that can be sold on the marketplace

100Points
4 Feedbacks
144 REP
Feedback

Hello icis_04, I found a few ways to enhance your code's functionality; Limited access control: While delist and take_profits have internal checks, other functions like buy and delist_and_take might benefit from explicit access control mechanisms to prevent unauthorized purchases or item removals. Error handling: The code uses custom error codes, but consider adopting Sui Move's built-in error handling for more structured and informative error management. Event logging: Implementing events for actions like listing, buying, and taking profits could improve transparency and facilitate monitoring. Reentrancy and concurrency: The code doesn't explicitly address reentrancy or concurrent access issues for shared objects like marketplace. Consider adding appropriate locks or guards to prevent unexpected behavior.

Submitted

The decentralized_real_estate on the Sui blockchain platform is designed to facilitate the buying, selling, and renting of real estate properties through a decentralized network. This module allows users to create property listings, initiate and verify transactions, manage rental agreements, and handle payments efficiently.

70Points
4 Feedbacks
144 REP
Feedback

Hello chrispus, I proposed a few ways to enhance the code;

  • Missing Dependency: The calculate_property_tax function depends on an unspecified oracle to retrieve real-world tax rates. Without this integration, the function provides an unrealistic tax calculation.

  • Event Persistence: Events are emitted using event::emit but their persistence mechanism isn't defined. Consider storing them in a separate object or using an existing Sui Move framework for event handling.

  • Reentrancy Attacks: The code might be vulnerable to reentrancy attacks in some functions (e.g., pay_rent). If an attacker can call pay_rent multiple times within the same transaction before the state update is reflected, they could potentially exploit inconsistencies. Consider using Sui's Mutate capability or similar mechanisms to mitigate this risk.

  • Insufficient Verification Logic: While the verify_transaction function requires two verifications, it doesn't implement any reputation system or criteria for verifiers. Malicious verifiers could potentially collude to approve fraudulent transactions. You might want to explore adding a verification reputation system or requiring specific roles for verifiers.

  • Missing Access Control for Rental Agreements: The end_rental_agreement function only checks if the sender is the owner, but it doesn't verify if they are indeed the owner of the specific property referenced in the agreement. This could lead to unauthorized users ending agreements for properties they don't own. Consider adding a check to ensure the sender is the owner of the property associated with the rental agreement.

  • Formal Verification: Consider using formal verification techniques to ensure the code's correctness and identify potential vulnerabilities before deployment.

  • Regular Audits: Conduct regular security audits of the codebase to identify and address new threats or emerging vulnerabilities.

  • Transaction Fee Implementation: The concept of a transaction fee for verification is mentioned but not implemented. You could explore adding a mechanism to collect and distribute these fees.

  • Error Handling Granularity: While error codes are used, consider improving the granularity of error messages to provide more specific information to users in case of failures.

Submitted

FOX Swap is a platform on the Sui blockchain. FOX Swap allows users to engage in transactions and add liquidity, among other activities. A distinctive feature of this project is that users can acquire Liquidity Provider Tokens (LPs) by adding liquidity. Upon acquiring LPs, users are entitled to claim one free lottery ticket each epoch. FOX Swap features multiple lottery pools, with each offering a unique drawing method. Users can choose to receive lottery tickets from any of these pools. Should a user win in a lottery draw, they are rewarded with Fox tokens as their prize.

100Points
4 Feedbacks
144 REP
Feedback

Hello vv1133 check out the suggestions I proposed:

  • Rounding Errors: The swap functions (swap_coin_a_to_coin_b and swap_coin_b_to_coin_a) use integer calculations for the swap amount. Depending on the pool's liquidity and coin precision, rounding errors might occur, potentially leading to slight discrepancies in the swapped amount compared to the expected value based on the constant product formula. Consider using higher precision calculations (e.g., fixed-point math) or rounding strategies to minimize these errors.

  • Integer Overflow: Some calculations involve multiplying large values. Depending on the underlying integer size in Sui Move, there's a risk of integer overflow. It's essential to check for potential overflows during calculations, especially when dealing with large coin amounts.

  • Coupon Functionality: The get_daily_coupon function doesn't specify what the lottery_type parameter is used for within the context of the code. It's unclear if this parameter has any implemented functionality related to different types of coupons or rewards.

  • Front-running Attacks: While the code itself doesn't show vulnerabilities, it's important to consider potential front-running attacks in the overall system design. An attacker might monitor transactions and exploit a small time window to get a better exchange rate before the user's swap transaction is processed. Implementing mechanisms like transaction batching or delaying exchange rate updates can help mitigate such attacks.

  • Reentrancy Attacks: The code doesn't explicitly show reentrancy protection techniques. If other smart contracts can interact with the fox_swap module, reentrancy attacks might be possible. Consider using Sui Move's features like borrow_mut with caution and potentially implementing reentrancy guards to prevent attackers from exploiting these vulnerabilities.

  • Error Handling: While the code asserts preconditions, consider adding more informative error messages or returning specific error codes to provide better feedback to users in case of failures.

  • Documentation: Adding comments and documentation to explain the purpose of functions, variables, and calculations would improve code readability and maintainability.

Submitted

Decentralized Insurance Platform on Sui Blockchain This smart contract module implements a decentralized insurance platform on the Sui blockchain using the Move programming language. It allows users to create, buy, and manage insurance policies for various assets. The platform also supports the creation and verification of claims, and manages community liquidity pools to back insurance policies.

70Points
4 Feedbacks
144 REP
Feedback

Hello aaroncharo, I made a few suggestionsas to how your code can be enhanced:

  • Logic Error in pay_premium (commented out): The commented-out section in pay_premium assigns the payer's address to policy.owner even though the original owner might be different. This could lead to unintended ownership changes.

  • Missing Check in pay_premium: The pay_premium function doesn't explicitly check if the payment amount is equal to the required premium. An attacker could potentially exploit this to pay less than the required amount.

  • Potential Pool Manipulation: The current implementation in stake allows anyone to call the function with any amount (even 0). This could be exploited for pool manipulation (adding invalid stakes).

  • Missing Access Control: The code doesn't implement access control for sensitive operations like creating policies or manipulating the pool balance.

  • Unnecessary Verification Logic: The verify_claim function currently checks all_conditions_met which is always set to true. This logic can be removed if the actual claim verification logic is implemented elsewhere.

Submitted

This project implements a cafeteria transaction system using the Sui blockchain. It features user registration, menu and order management, and enhanced payment processing functionalities. The smart contract is written in Sui Move, a language designed for secure and efficient blockchain applications.

90Points
4 Feedbacks
144 REP
Feedback

Hello Daisya, check out the suggestions I proposed:

  • Partial Payment Inconsistency: The get_order_details function doesn't reflect the current paid amount for partially paid orders. There's a discrepancy between the tracked total_price and the actual payment captured in process_partial_payment.

  • Limited Error Handling: While basic checks exist for insufficient balance and order payment status, consider adding more robust error handling to prevent unexpected behavior. This could include catching specific Sui Move errors and providing informative error messages for users.

  • Missing Access Control: Currently, the code doesn't implement access control mechanisms. Anyone with access to the code could potentially manipulate user data, orders, or system functions.

  • Track Paid Amount: In the Order struct, add a field paid_amount: u64 to keep track of the total amount paid for the order so far. Update this field in process_partial_payment to reflect the partial payment.

  • Enhanced Error Handling: Use Sui Move error handling mechanisms like ensure or if statements with specific error checks. Provide informative error messages to users or log errors for debugging.

  • Access Control: Implement role-based access control (RBAC). Define different user roles (e.g., user, admin) and restrict access to functions based on those roles. Consider using Sui's capabilities framework for authorization.

  • Input Validation: Validate user input for functions like register_user, create_menu_item, and place_order to prevent potential manipulation of data.

  • Security Audits: Regularly conduct security audits of the code to identify and address potential vulnerabilities.

5 SUI
5 REP
Submitted

The Budget Tracking Smart Contract is a decentralized blockchain solution designed to streamline budget management and expense tracking on the SUI blockchain platform. By leveraging Move-based technology, users can record expenses, manage budgets, and track refunds securely and transparently. This contract provides a reliable and immutable ledger for financial transactions, ensuring accountability and efficiency in budget management processes for individuals and organizations alike.

70Points
3 Feedbacks
144 REP
Feedback

Hello Jackline0, I have a few observations and changes concerning your code.

  1. Redundant Ownership Check in amount: The amount function performs an ownership check that might be unnecessary. Since record_expense already ensures the user creating the expense is the owner, this check may not be necessary.

  2. Missing Retailer Interaction: The module currently doesn't handle retailer interaction directly. While a user can claim a refund from a retailer by transferring the refunded balance, there's no way for the retailer to acknowledge the claim or potentially offer a partial refund.

  3. Potential for Abuse in claim_from_retailer: The claim_from_retailer function allows the user to claim from a retailer without any verification from the retailer's side. This could be abused if a user makes a false claim and transfers the funds.

  4. Custom Error Codes: While custom error codes are used, consider replacing them with Sui Move's built-in SuiError for more structured error handling and informative messages.

6.25 SUI
6.25 REP
Submitted

A decentralized event planning platform developed on the SUI blockchain

70Points
5 Feedbacks
144 REP
Feedback

Hello Bodman, I have propose a few changes that could improve the overall functionality of the code:

  • Unused addr field: The Participant struct has an addr field of type address but it's not used anywhere in the current code. Consider removing it if unnecessary.

  • Potential Out-of-Bounds Access: Functions like complete_task and update_participant_balance rely on mutable borrows (vector::borrow_mut) of elements based on indices (event_index and participant_index). If these indices are invalid (out of bounds), the code might panic or lead to unexpected behavior.

  • Missing Event Deletion: There's no functionality for deleting events. This could lead to the EventPlanner object accumulating data indefinitely.

  • Event Completion Logic Missing: The finished flag in Event doesn't have associated logic for handling event completion (e.g., notifying participants, finalizing budgets).

  • Access Control: While data ownership is established through the EventPlanner object, there's no explicit access control on functions. Anyone calling the functions could potentially modify events or participants if not addressed.

  • Reentrancy Attacks: The code doesn't explicitly protect against reentrancy attacks. If a function modifies multiple objects within a transaction, a malicious contract could exploit this for unintended consequences. Consider using Sui's Mutex or other techniques to prevent reentrancy.

  • Error Handling: The code doesn't handle potential errors like out-of-bounds indexing or invalid data. Incorporating Sui's error handling mechanisms (SuiMoveError) would improve robustness.

  • Event Lifecycle Management: Adding functionalities for deleting events or tasks would enhance the system's completeness.

  • Performance Optimization: For a large number of events, pagination or filtering techniques could be implemented to improve search and retrieval performance.

  • get_events Function: Consider using iterators or functions accepting event indices for improved data security and avoiding unnecessary exposure of the entire event vector.

Submitted

SUI Bet is a betting platform built on the SUI blockchain, offering users the ability to create and participate in betting pools for various token pairs. Leveraging smart contracts and blockchain technology, SUI Bet ensures transparent and secure betting transactions without the need for intermediaries. Users can create pools by specifying the tokens involved and setting the fee percentage, while participants can place bets on different events by swapping tokens within these pools. With SUI Bet, users can enjoy a trustless and censorship-resistant betting experience, facilitated by the decentralized nature of the SUI blockchain.

70Points
6 Feedbacks
144 REP
Feedback

Hello Elsang, I have a few suggestions to make concerning your code;

  • Missing drop implementation: The BetShare struct definition has a drop annotation but lacks the actual implementation. While not critical for functionality, it's good practice to have a proper drop implementation.

  • Inconsistent naming: The function get_amounts uses snake_case (value) while other getters use camelCase (supplyValue). Consider unifying the naming convention.

  • Integer Overflow: Calculations involving large values might overflow. It's advisable to use math libraries with overflow checks or consider using 128-bit integers for some calculations.

  • Rounding Errors: Price calculations might introduce rounding errors due to integer division. Using fixed-point math libraries or more precise calculations could mitigate this.

  • Uninitialized Variables: The code doesn't explicitly initialize some variables. Ensure proper initialization before using them to prevent undefined behavior.

  • Access Control: Currently, there's no access control on functionalities like creating pools or adding/removing liquidity. Implementing mechanisms like permissions or ownership checks would be essential.

  • Reentrancy Attacks: The swap functions might be susceptible to reentrancy attacks if not carefully designed. Consider using Sui's Mutex or other mechanisms to prevent this.

  • Price Manipulation: The price calculation functions (price_x_to_y and price_y_to_x) are publicly accessible. Malicious actors could potentially exploit these to manipulate prices (flash loan attacks). Consider adding checks or restrictions on who can access these functions.

  • Error Handling: While the code uses assert!, consider using proper error handling mechanisms like returning custom error types to provide more informative feedback during transaction failures.

  • Event Logging: Emitting events for significant actions (pool creation, swaps, liquidity addition/removal) would be valuable for monitoring and debugging purposes.

6.25 SUI
6.25 REP
Submitted

Example of marketplace for trading tales using the Kiosk framework on Sui where you can : - mint a tale - create a kiosk and list your tales for sell - establish rules for transfer policies

50Points
7 Feedbacks
144 REP
Feedback

Hello 0xriazaka, here is an improvement to tour code;

  • Authorization Checks: While the code uses KioskOwnerCap for seller functions, there might be a need for additional authorization checks within the kiosk functions themselves. For example, unplace_tale and delist_tale could verify that the seller is attempting to remove their own tale.

  • Fungibility: The code assumes tales are unique (identified by ID). If some tales are meant to be fungible (identical copies), additional logic might be needed to handle them appropriately.

  • Transfer Policy Review: The details of the TransferPolicy implementation are not available. It's crucial to ensure these policies enforce intended restrictions and prevent unauthorized access or manipulation of tales after purchase.

  • Error Handling: The code doesn't explicitly handle potential errors from Kiosk operations like place_tale or purchase_tale. Consider implementing proper error handling (e.g., returning error codes or Sui exceptions) to provide informative feedback to users and developers.

  • Insufficient Information: Without knowing the structure of T (tale object), it's difficult to identify potential issues related to data validation or manipulation.

  • Event Handling: While not a security concern, implementing events for actions like purchase or withdrawal could be beneficial for monitoring marketplace activity and building additional features (e.g., notifications).

Submitted

A simple Sui Move version AMM Dex based on the logic of UniswapV2. ## Introduction + This module implements the factory and pool logic of UniswapV2 where anyone can freely create pair of two coin types, add or remove liquidity, and swap. + After a `Pool` of two coin types is created, a `PoolItem` will be added to `Factory`'s `table` field, which guarantees there is at most one pool for a pair. + The two coin types of a pair are first sorted according to their `type_name`, and then assigned to `PoolItem`'s `a` and `b` fields respectively. + Users can add liquidity to the pool according to the current ratio of coin balances. The remaining coin will be returned to the users as well as the LP coin. + Each pool are set with a `0.3%` swap fee by default which is actually distributed to all LP holders. + Core functions like `create_pool`, `add_liquidity`, `remove_liquidity`, `swap_a_for_b`, `swap_b_for_a` are all provided with three kind of interfaces (call with `Balance`, call with `Coin` and return `Coin`, call with `Coin` and transfer the output `Coin` to the sender in that entry function) considering both composability and convenience. ## Structs 1. LP witness + LP witness `LP<A, B>` is used as unique identifier of `Coin<LP<A, B>>` type. 2. Pool + A `Pool<A, B>` is a global shared object that is created by the one who calls the `create_pool` function. + It records its `Balance<A>`, `Balance<B>`, `Supply<LP<A, B>>`, and default fee. 3. Factory + A `Factory` is a global shared object that is created only once during the package publishment. + It has a `table` field recording each `PoolItem`. 4. PoolItem + A `PoolItem` is used to record the pool info in the `Factory`. + It guarantees each pair is unique and the coin types it records are sorted. ## Core functions 1. create_pool<A, B> + Create a new `Pool<A, B>` with initial liquidity. + Input with `Factory`, `Balance<A>` and `Balance<B>`, return `Balance<LP<A, B>>`. 2. create_pool_with_coins<A, B> + Input with `Factory`, `Coin<A>` and `Coin<B>`, return `Coin<LP<A, B>>`. 3. create_pool_with_coins_and_transfer_lp_to_sender<A, B> + Input with `Factory`, `Coin<A>` and `Coin<B>`, and transfer `Coin<LP<A, B>>` to sender in the function. 4. add_liquidity<A, B> + Add liquidity to `Pool<A, B>` to get LP coin. + Input with `Pool<A, B>`, `Balance<A>`, `Balance<B>` and minimal LP output amount, return remaining `Balance<A>`, `Balance<B>`, and `Balance<LP<A, B>>`. 5. add_liquidity_with_coins<A, B> + Input with `Pool<A, B>`, `Coin<A>`, `Coin<B>` and minimal LP output amount, return remaining `Coin<A>`, `Coin<B>`, and `Coin<LP<A, B>>`. 6. add_liquidity_with_coins_and_transfer_to_sender<A, B> + Input with `Pool<A, B>`, `Coin<A>`, `Coin<B>` and minimal LP output amount, and transfer remaining `Coin<A>`, `Coin<B>`, and `Coin<LP<A, B>>` to sender in the function. 7. remove_liquidity<A, B> + Remove liquidity from `Pool<A, B>` and burn LP coin. + Input with `Pool<A, B>`, `Balance<LP<A, B>>` and minimal A output amount, minimal B output amount, return `Balance<A>` and `Balance<B>`. 8. remove_liquidity_with_coins<A, B> + Input with `Pool<A, B>`, `Coin<LP<A, B>>` and minimal A output amount, minimal B output amount, return `Coin<A>` and `Coin<B>`. 9. remove_liquidity_with_coins_and_transfer_to_sender<A, B> + Input with `Pool<A, B>`, `Coin<LP<A, B>>` and minimal A output amount, minimal B output amount, and transfer `Coin<A>` and `Coin<B>` to sender in the function. 10. swap_a_for_b<A, B> + Swap exact `Balance<A>` for `Balance<B>`. + Input with `Pool<A, B>`, `Balance<A>` and minimal B output amount, return `Balance<B>`. 11. swap_a_for_b_with_coin<A, B> + Input with `Pool<A, B>`, `Coin<A>` and minimal B output amount, return `Coin<B>`. 12. swap_a_for_b_with_coin_and_transfer_to_sender<A, B> + Input with `Pool<A, B>`, `Coin<A>` and minimal B output amount, and transfer `Coin<B>` to sender in the function. 13. swap_b_for_a<A, B> + Swap exact `Balance<B>` for `Balance<A>`. + Input with `Pool<A, B>`, `Balance<B>` and minimal A output amount, return `Balance<A>`. 14. swap_b_for_a_with_coin<A, B> + Input with `Pool<A, B>`, `Coin<B>` and minimal A output amount, return `Coin<A>`. 15. swap_b_for_a_with_coin_and_transfer_to_sender<A, B> + Input with `Pool<A, B>`, `Coin<B>` and minimal A output amount, and transfer `Coin<A>` to sender in the function. ## Unit test ![](<https://github.com/KyrinCode/sui-move-amm-uniswapV2/blob/main/unit%20test.png>)

100Points
4 Feedbacks
144 REP
Feedback

Hello KyrinCode, I went through your code and suggested a few ways to improve on it;

  • Lack of Access Control: The code doesn't seem to have any access control mechanisms. Anyone could potentially create pools or manipulate existing ones. Ideally, there should be checks to restrict these actions to authorized users.

  • Reentrancy Attacks: The code might be vulnerable to reentrancy attacks, where a malicious contract can call another function (e.g., transferring funds out) before the current function completes. This could lead to unexpected behavior and loss of funds. Consider using reentrancy guards like checks for external calls before modifying pool balances.

  • Price Manipulation: The Uniswap v2 AMM is susceptible to flash loan attacks where a large amount of a token is borrowed momentarily to manipulate the price within a pool and then pay back the loan. This can be mitigated by setting time delays or minimum swap amounts.

  • Math Overflow/Underflow: The code relies on unchecked mathematical operations like multiplication and division. It's essential to implement checks to prevent potential overflows or underflows that could lead to unexpected behavior.

  • Rounding Errors: Repeated calculations involving decimals can accumulate rounding errors. Consider using fixed-point math libraries or careful rounding techniques to minimize their impact.

  • There are a few typos in the code: * ceil_div_u128 function name might be a typo. It could be ceil_div with a u128 argument. * destroy_zero_or_transfer_balance function seems to have an extra space before the opening parenthesis.

  • Price Oracle: This code doesn't implement a price oracle for determining the exchange rate between tokens during swaps. An external oracle would be necessary for accurate pricing.

  • Liquidity Incentives: The current implementation doesn't have mechanisms for incentivizing liquidity providers beyond fees.

5 SUI
5 REP
Submitted

The SUI Hospital Management module facilitates the comprehensive management of hospital operations within a decentralized system. It offers functionalities for managing hospital information, staff, patients, appointments, inventory, financial transactions, and more. This module ensures efficient and secure management of hospital resources while maintaining transparency and accountability.

80Points
3 Feedbacks
144 REP
Feedback

Hello, I proposed a few changes to your code;

  • Potential rounding errors: The code doesn't explicitly address potential rounding errors during monetary calculations. When dealing with Coin<SUI> amounts, especially for small transactions, rounding errors might occur. Consider using fixed-point math libraries or implementing rounding strategies to minimize these errors.

  • Inventory item total cost: The InventoryItem struct doesn't store the total cost, which is quantity * unit_price. This can lead to redundant calculations when managing the total inventory value. It's recommended to add a calculated field for the total cost within the struct.

  • Limited authorization checks: While some methods perform authorization checks, others don't. For example, functionalities like adding new staff or modifying appointments lack proper authorization. Implementing access control mechanisms is crucial to prevent unauthorized modifications to hospital data.

  • Address-based authorization: The current authorization relies on comparing addresses. This might not be ideal for future scalability or managing different user roles within the hospital. Consider implementing a more robust Role-Based Access Control (RBAC) system to define and manage user permissions effectively.

  • On-chain medical history: Storing patient medical history directly on-chain raises privacy concerns. Depending on regulations, it might be better to store this information off-chain with a secure reference on-chain or implement encryption mechanisms for sensitive data.

  • Error handling: The code uses assertions for error handling (e.g., insufficient balance). Consider returning specific error codes or throwing exceptions to provide more informative feedback to users in case of failures during transactions.

  • Event logging: Implementing event logging functionalities can be beneficial for auditing purposes and future integrations. Log important actions within the hospital system (e.g., adding a patient, discharging a patient) to track activity.

  • Documentation: Adding comments and documentation to explain the purpose of functions, variables, and data structures would improve code readability and maintainability for future developers.

Submitted

This smart contract implements the basic process of patient medical treatment. The doctor prescribes the appropriate medication based on the patient's information and condition, creating a Treatment object. This object is shared so that the pharmacist can set the medication price based on the drug. The patient then pays for the medication through the balance in the patient's object. Once the patient completes the payment, the Treatment is automatically added to the patient's treatments list. The patient object is created by the patient, who can also deposit or withdraw SUI from it. The pharmacist sets the medication prices and the payment by the patient must be completed within 24 hours of the visit to prevent the misuse of drugs. Additionally, each doctor and pharmacist only has access to their own hospital's system.

70Points
3 Feedbacks
144 REP
Feedback

Hello jjk, here a few suggestions to enhance the code;

  • Limited Authorization: While Caps provide basic access control, consider implementing RBAC for finer control. For example, specific doctors could access only their patients' treatments.

  • Data Validation: The code lacks user-input validation for treatment details or pharmacist-set prices. Malicious users could inject invalid data. Implement server-side validation to ensure data integrity.

  • Logic Error (addtreatment): The addtreatment function checks if the treatment is complete before adding it to the patient's table. This might prevent adding completed treatments for future reference. Revise the logic if allowing completed treatments in the patient's history is desired.

  • Missing Treatment Listing: Patients cannot view their treatment history (completed treatments). Implement functionality to retrieve a list of treatments for a patient.

  • Limited Treatment Status Updates: Doctors and pharmacists cannot update treatment status beyond "complete" (e.g., "in progress"). Consider adding additional status options or allowing for more granular updates.

  • Timeout in set_price: The timeout in set_price is based on treatment.data + ONE_DAY. This might not be suitable for all scenarios. Explore a more configurable timeout mechanism.

  • Logging: Logging successful transactions, payments, and withdrawals would be beneficial for auditing and debugging.

  • The init function seems to transfer the AdminCap to the transaction sender

  • The hospital_withdraw function allows the admin to withdraw all hospital funds to any address. This could be a security risk if not carefully controlled.

Submitted

INTRODUCTION This module implements a loan system that allows users to borrow and repay loans with interest. It supports creating loan platforms, issuing loans, and managing loan repayments. The module uses Sui Move and includes structures and functions to handle loans, interest calculations, and interactions with the loan platform. KEY STRUCTURES LoanAccount Stores individual loan details for users: - id: Unique identifier of the loan. - inner: Address of the loan account. - loan_date: Timestamp of when the loan was issued. - last_payment_date: Timestamp of the last repayment. - loan_due_date: Due date for the loan repayment. - loan_amount: The principal amount of the loan. - user_address: Address of the user who took the loan. LoanPlatform Represents the platform's loan system: - id: Unique identifier of the loan platform. - inner: Internal ID for the platform. - balance: A Bag containing the platform's balance. - interest_rate: Interest rate applied to loans. LoanPlatformCap Ensures that only authorized entities can manage the loan platform: - id: Unique identifier of the cap. - platform: Internal ID of the associated loan platform. Protocol Manages the protocol's balance: - id: Unique identifier. - balance: A Bag containing the protocol's balance. AdminCap Ensures only admins can withdraw fees: - id: Unique identifier. CORE FUNCTIONS new_loan_platform Creates a new loan platform with a specified interest rate. - Parameters: `interest_rate`, `ctx` - Returns: Transfers LoanPlatformCap to the caller. issue_loan Issues a loan to a user. - Parameters: `protocol`, `loan_platform`, `clock`, `coin_metadata`, `coin`, `ctx` - Returns: `LoanAccount` repay_loan Repays a user's loan. - Parameters: `protocol`, `loan_platform`, `loan_acc`, `clock`, `coin_metadata`, `coin`, `ctx` withdraw_fee Withdraws protocol fees. - Parameters: `admin_cap`, `protocol`, `coin`, `ctx` - Returns: `Coin` withdraw_loan Withdraws loan balance from the platform. - Parameters: `loan_platform`, `cap`, `coin`, `ctx` - Returns: `Coin` Error Constants - EInsufficientFunds (1): Insufficient funds to process the loan. - EInvalidCap (4): Invalid loan cap. Interest Rate - INTEREST_RATE: 5% HELPER FUNCTIONS helper_bag Helper function to manage balances within a Bag. - Parameters: `bag`, `coin`, `balance` ACCESOR FUNCTIONS get_loan_date Fetches the loan issuance date. - Parameters: `loan_account` - Returns: `u64` get_loan_id Fetches the loan account ID. - Parameters: `loan_account` - Returns: `address` get_last_payment_date Fetches the last repayment date. - Parameters: `loan_account` - Returns: `u64` get_loan_due_date Fetches the loan due date. - Parameters: `loan_account` - Returns: `u64` get_loan_owner Fetches the loan owner address. - Parameters: `loan_account` - Returns: `address` SUMMARY This module allows the creation and management of loan platforms, issuance and repayment of loans, and administration of platform balances. It includes detailed error handling, interest rate application, and accessor functions to retrieve loan details. The provided functions ensure secure and efficient loan management within the Sui Move ecosystem.

80Points
4 Feedbacks
144 REP
Feedback

Hello Tarzcop254, I recommended a few ways to enhance the code;

  • Reentrancy Attacks: The code is still vulnerable to reentrancy attacks. Malicious contracts could exploit this during loan issuance or repayment by making multiple calls within a single transaction, potentially manipulating the loan state or stealing funds.

    • Mitigation: Utilize Sui's Mutex or similar mechanisms to ensure exclusive access during critical sections like issuing or repaying loans. This prevents concurrent modifications from other transactions until the critical section is complete.
  • Insufficient Funds Check: The issue_loan function only checks if the provided coin value is greater than or equal to the loan platform's interest rate. It's crucial to also consider the user's balance:

    • Enhancement: Before issuing a loan, verify that the user's balance can cover the loan amount plus the calculated interest. This ensures they have sufficient funds for the entire loan obligation.
  • Default Handling: The code lacks explicit handling for specific scenarios:

    • Loan Repayment When Loan Amount is 0: If a user attempts to repay a loan that has already been paid off (loan amount is 0), the code doesn't explicitly handle this case.
    • Loan/Fee Withdrawal Exceeding Balance: If a user tries to withdraw funds exceeding the available balance in the protocol or loan platform, there's no specific error handling.
    • Recommendation: Implement checks for these situations and provide appropriate error messages (e.g., "Loan already repaid," "Insufficient funds for withdrawal"). Consider returning an error or throwing an exception to prevent unexpected behavior.
  • Event Logging: While Sui's logging capabilities are not explicitly used, consider emitting events for important actions:

    • Loan Issuance
    • Loan Repayment
    • Fee or Loan Withdrawal
    • Benefits: This provides a more comprehensive and auditable record of loan activity, aiding in monitoring, debugging, and potential compliance requirements.
  • Error Handling: Enhance error handling throughout the code to provide more informative messages for potential issues. This can improve debugging and user experience:

    • Use descriptive error messages that clearly indicate the problem encountered.
    • Consider returning appropriate error codes or throwing Sui-specific exceptions for easier identification and handling.
2.5 SUI
2.5 REP
Submitted

# Secure Crowdfunding on Sui Blockchain with Real-Time Price Feeds This project demonstrates a secure and transparent crowdfunding platform built on the Sui blockchain. It leverages Supra's reliable price feed Oracle to ensure accurate and tamper-proof price data throughout the crowdfunding lifecycle. ## Key Functionalities: - **Smart Contract Management:** The platform utilizes smart contracts on Sui to automate and manage the crowdfunding process, eliminating intermediaries and fostering trust. - **Supra Oracle Integration:** Integration with Supra's price feed Oracle guarantees access to reliable and secure price data for setting campaign goals, calculating contributions, and triggering payouts. - **Transparency and Security:** By employing smart contracts and a secure price feed solution, the platform ensures a transparent and secure environment for both campaign creators and contributors. All transactions are immutable and verifiable on the blockchain. ## Benefits Enhanced Trust and Security: Supra's reliable price feed Oracle minimizes the risk of price manipulation and fosters trust within the crowdfunding ecosystem. Increased Efficiency: Smart contracts automate key processes, streamlining the crowdfunding experience for all participants. Greater Accessibility: The project paves the way for a more accessible crowdfunding landscape, enabling broader participation.

100Points
3 Feedbacks
144 REP
Feedback

Hello, I proposed a few way to enhance the code;

  • Missing Error Codes: While there's one error code (ENotFundOwner), consider adding more specific error codes for different failure scenarios (e.g., insufficient funds to withdraw, unauthorized donation attempt).

  • Potential Discrepancy in Target Reaching: The target is reached based on the raised amount in SUI multiplied by the adjusted oracle price. This might introduce rounding errors or discrepancies due to price fluctuations. Consider additional logic or tolerance levels for handling these cases.

  • Unrestricted Donations: Currently, anyone can call donate. This could be a security concern if you intend to restrict donations to specific users or campaigns. Implementing access control mechanisms like allowing only whitelisted addresses to donate would be beneficial.

  • Missing Capability Check in Donate: While withdraw_funds requires a matching capability, there's no check within donate to ensure only authorized users can contribute. This could be addressed by adding a check for a specific role or capability before allowing donations.

  • Limited Fund Information Retrieval: There's no function to retrieve the current raised amount or target details publicly. Consider adding getter functions to access these details without compromising security (e.g., not revealing the total raised amount in USD if the target isn't reached).

  • MIST Conversion Complexity: The code mentions MIST (10^-9 SUI). It might be simpler and more readable to handle donations entirely in SUI and avoid conversion within the contract.

6.25 SUI
6.25 REP
Submitted

The ride-sharing module facilitates the process of organizing rides between riders and drivers on a decentralized platform. It allows users to request rides, accept ride requests, complete rides, handle disputes, rate participants, and manage payments.

70Points
2 Feedbacks
144 REP
Feedback

Hello Lily, here are a few suggestions to improve on your code; In cancel_ride, there's an extra semicolon after ride.dispute = false;.

The update_ride_price function doesn't have any error handling if the provided new_price is negative.

Potential Infinite Loop: In resolve_dispute if resolved is set to false (meaning no payout to driver), the code attempts to transfer funds to the rider who already has the funds in escrow (since the ride wasn't completed). This could lead to an infinite loop if the transaction keeps failing.

Missing Access Control in some functions: * add_funds_to_ride: Anyone can add funds to a ride, potentially manipulating the escrow pool. It should only be allowed for the rider. * mark_ride_complete (Driver): Any driver can mark a ride complete, even if they weren't assigned to it. It should only be allowed for the assigned driver. * rateDriver and rateRider: Anyone can rate a driver or rider, even if they weren't involved in the ride. It should only be allowed for the respective parties (driver for rider rating, rider for driver rating).

Escrow Manipulation: The code doesn't explicitly prevent adding more funds to the escrow than the initial ride price. This could be a vulnerability if a rider could exploit it to add excessive funds and dispute the ride later.

6.25 SUI
6.25 REP
Submitted

d-MALL is a decentralized store management system built on the Sui blockchain. It facilitates secure and transparent transactions between customers and stores using points as currency. The system employs an escrow mechanism to hold points until a transaction is completed or resolved, ensuring protection for both parties. Customers can buy items, raise disputes if needed, rate stores, and leave reviews, while stores can accept, fulfill, and manage transactions efficiently. d-MALL aims to create a trustworthy and efficient marketplace by leveraging blockchain technology to handle store management and transactions seamlessly.

70Points
3 Feedbacks
144 REP
Feedback

Hello Zei, I have proposed a few changes to the code, check them out;

  • Limited Access Control: While some functions check if the caller is the customer or store involved in the transaction, a more comprehensive RBAC system is recommended. This could define roles like customer, store owner, and potentially an admin (for dispute resolution) with specific permissions for each.

  • Escrow Management: The code doesn't explicitly check if there are enough points in the escrow before releasing payment to the store (in release_payment). An attacker could potentially manipulate the transaction to have a very high price, leading to the store receiving more points than intended.

  • Item and Transaction Updates: Customers can update various aspects of the transaction (item, price, quantity) after creation. This could be exploited for malicious purposes. Consider restricting updates or implementing additional authorization checks.

  • Dispute Resolution: The current implementation allows disputes to be resolved by the customer themself. In a real-world scenario, an impartial third-party or designated authority would likely be responsible for dispute resolution.

  • Item Reviews: While the code allows customers to leave reviews, it doesn't implement any access control for who can see these reviews. Consider implementing privacy controls or allowing stores to moderate reviews.

  • Custom Error Codes: While the code defines custom error codes, it doesn't leverage Sui's built-in error handling mechanisms. Using Sui's errors would provide a more structured approach.

  • Event Logging: The current event logging is limited. Consider expanding it to capture more actions within the store system (e.g., transaction updates, disputes, refunds) for better auditability and future integrations.

  • Insufficient Funds Check: The add_funds function doesn't explicitly check if the customer has enough points (SUI balance) to cover the added amount.

  • Implement a proper RBAC system using Sui's capabilities.

  • In release_payment, ensure escrow_amount is less than or equal to the current balance in the escrow before transferring points.

  • Restrict updates to certain transaction fields (e.g., only allow price updates before store acceptance).

  • Implement a dispute resolution system with a designated authority.

  • Define access control mechanisms for item reviews.

  • Leverage Sui's error handling mechanisms for a more robust approach.

  • Expand event logging for a wider range of actions.

  • Add a check for sufficient funds in add_funds.

5 SUI
5 REP
Submitted

The Travel Planner Platform smart contract enables users to create, manage, and interact with travel plans, including destinations, itineraries, accommodations, activities, transportation, budgets, and user information.

50Points
5 Feedbacks
144 REP
Feedback

Hello riskiraj, I suggested a few ways to enhance the code:

  • The list_all_plans function is currently a placeholder and doesn't provide actual implementation. It's likely there should be logic to iterate through all Plan objects and collect their IDs into a vector. Without this functionality, retrieving all plans is impossible.

  • The code currently doesn't perform any validation on user input for functions like new_plan. Malicious users could potentially provide invalid data (e.g., negative price for accommodation) that might lead to unexpected behavior.

  • The update_plan function allows modifying any aspect of a plan, including the user reference. This could be a security concern if someone gains unauthorized access to a plan ID and attempts to associate it with a different user. Consider adding access control mechanisms to restrict who can modify specific plans.

  • The code doesn't show any checks to verify if the user modifying or deleting a plan is the actual owner. This could be a security vulnerability if someone obtains a plan ID and can manipulate it without authorization. Implementing ownership checks before modifications or deletions is crucial.

  • The purpose and usage of the AdminCap struct are unclear. It's created during initialization but there's no code demonstrating how it's used. If it grants administrative privileges, ensure proper access control mechanisms are in place for its usage.

  • While the code uses object capabilities for data storage, it's worth considering potential scalability issues. If a large number of plans are created, iterating through them all (e.g., for list_all_plans) might become inefficient. Explore alternative data structures or indexing mechanisms for better performance with a growing number of plans.

Submitted

Introducing the Hospital Management System, a comprehensive solution designed to streamline various hospital operations. This project encompasses hospital information management, patient admission and discharge, billing, and patient history tracking. The system features an intuitive user interface for hospital staff to interact with, allowing for efficient management of critical hospital functions. By implementing the Hospital Management System, hospitals can improve workflow, enhance patient care, and simplify administrative tasks, ensuring a more efficient healthcare environment.

70Points
3 Feedbacks
144 REP
Feedback

Hey there, I have a few suggestions for you to consider updating your code:

  • Missing Access Control: Currently, all public functions are accessible to anyone. Implement access control mechanisms to restrict actions based on roles (doctor, admin, etc.).

  • Data Sensitivity: Patient and potentially hospital contact information might be sensitive. Consider encrypting these fields using Sui's capabilities.

  • Data Validation: While data types are defined, add validation logic to ensure valid information is stored. Examples include:

    • Checking patient age is positive.
    • Verifying admission reason and contact information formats.
  • Authorization: The AdminCap is a basic approach. Implement roles with granular permissions for enhanced security (e.g., doctors admit patients, admins create hospitals).

  • Error Handling: Functions like delete_hospital don't handle cases where the object doesn't exist. Implement proper error handling to return informative messages.

  • Transactions: Utilize Sui's transactions to ensure data consistency across modifications. For instance, a transaction can encompass admitting a patient and creating a bill.

  • Events: Consider implementing Sui Move events to notify interested parties about actions (e.g., patient discharge event for nurses).

  • Filtering/Searching: Explore ways for users to filter or search for patients based on criteria (e.g., name, admission date).

  • Audit Logs: Maintain an audit log for critical actions to track activity and ensure accountability.

5940 REP
Submitted

This is a banking application that allows users to perform basic operations such as: 1. Create an account 2. Deposit funds 3. Withdraw funds 4. Transfer funds 5. View transaction history

100Points
3 Feedbacks
144 REP
Feedback

Hello Farzeen, I've gone through the code and noticed some things that could be improved upon:

  1. Unused Function Review the init function's purpose: Determine if it's necessary for initialization or can be removed. If needed, call it appropriately: Ensure it's executed at the correct point in the contract's lifecycle.
  2. Commented-Out Functions Evaluate mint and burn functionality: Decide whether they're required and implement them securely if needed. Remove unused code: If they're not necessary, delete them to reduce code complexity and potential attack surface.
  3. Input Validation Add validation to locked_mint: - Check for valid amount (non-zero, within reasonable bounds). - Validate recipient address format. - Implement other necessary checks based on expected input ranges and types.
  4. Authorization and Access Control Implement role-based access control: Define roles (e.g., admin, minter) with specific permissions. Restrict function calls: Allow only authorized users to execute sensitive functions like locked_mint.
  5. Vesting Schedule Implementation Define vesting logic: Determine the schedule for releasing locked coins (e.g., linear, cliff-based). Implement release mechanisms: Write functions to handle coin release based on the schedule and authorized actions. Test thoroughly: Ensure the release logic works as intended and cannot be manipulated.
  6. Error Handling Use assert statements: Verify preconditions and return errors for invalid inputs or conditions. Handle transaction failures gracefully: Revert state changes and provide informative error messages.
  7. Sui Move-Specific Concerns Follow Sui Move security guidelines: Adhere to best practices for coin and transaction handling. Stay updated on advisories: Keep up with the latest security recommendations for Sui Move.
  8. Security Best Practices Minimize attack surface: Expose only necessary functions and data. Use secure coding practices: Follow secure coding principles and avoid common vulnerabilities. Conduct thorough testing: Test all code paths and edge cases to uncover potential issues. Engage security experts: Consider professional security audits to identify and mitigate risks.
18.75 SUI
18.75 REP
Submitted

The Insurance module facilitates the management of insurance policies and claims within a decentralized system. It allows users to create insurance policies, submit claims, validate claims, and process payouts. Additionally, it supports the creation of administrative capabilities for insurers and authorities.

70Points
3 Feedbacks
144 REP
Feedback

Hello kendev, I went through the code and proposed a few changes to enhance it;

  • Potential Incomplete Payout Logic: The payout function checks if insurance_claim.authority_claim_id is zero before processing the payout. This might not be sufficient. It's safer to ensure all required validations (insurer_validation and authority_validation) are complete before payout.

  • Missing Access Control in Claim Editing: While some access control checks are present, the edit_claim_id function allows editing only if insurance_claim.is_pending is true. It might be better to restrict this action to the policyholder only.

  • Capability Management: The code doesn't explicitly revoke capabilities. Consider adding functionality to revoke capabilities if needed to prevent unauthorized access.

  • Incomplete Claim Validation Check in Payout: As mentioned earlier, the payout function relies on insurance_claim.authority_claim_id being zero. A more secure approach would be to check both insurer_validation and authority_validation before payout.

  • State Management: The is_pending flag could be replaced with a dedicated ClaimState enum to represent the claim lifecycle stages (e.g., Pending, ValidatedByInsurer, ValidatedByAuthority, Paid). This improves clarity and maintainability.

  • Event System: Implementing events for claim creation, validation, and payout can be beneficial for tracking and monitoring purposes.

6.25 SUI
6.25 REP
Submitted

Size Game contract This smart contract primarily implements a game of comparing sizes, wherein upon one party winning, they will receive a prize, while the other party will have their staked SUI in the pool deducted. The create_game function is the main entry point of the smart contract. It takes an input number and a transaction context as parameters. It first validates the input number to ensure it's either 0 or 1. If it's not, it emits an error message. Then, it simulates rolling three dice (with faces numbered 1 to 6 each) and calculates their sum. Based on the rules of the game, it determines whether the player wins or loses based on the sum of the dice rolls and the chosen input number. It emits a result message indicating whether the player won or lost. And the smart contract will issue a reward based on the final result.

30Points
2 Feedbacks
144 REP
Feedback

Hello Dokwon, I found a few errors and made some changes to improve the code: In the seed function, the line sui move build; seems out of place and may cause a syntax error. It should be removed if it's not intended to be a part of the function.

In the bytes_to_u64 function, the return type should be specified as -> u64 after the function signature.

In the bytes_to_u64 function, the variables value and i should be declared as mutable using the mut keyword.

In the rand_u64_with_seed function, the return value is not explicitly specified using the return keyword. It should be return bytes_to_u64(_seed);.

In the rand_u64_range_with_seed function, the expression (value % (high - low)) + low should be enclosed in curly braces to make it explicit that the addition is being applied to the result of the modulo operation.

The rand_u64 and rand_u64_range functions are marked as public which is not a valid Rust keyword. Instead, the intended access level should be pub.

There are several missing semicolons at the end of some statements, such as in the rand_u64_range_with_seed function.

6.25 SUI
6.25 REP
Submitted

This SUI smart contract implements a power bill management system on the Sui blockchain. It allows customers to register, request power units, pay bills, and view their usage and billing information. The contract also facilitates late fee application for overdue bills.

80Points
4 Feedbacks
144 REP
Feedback

Hello, check out the proposed changes;

  • Potential Infinite Loop (view_unpaid_bills): The loop condition i < len might not change if vector::push_back doesn't modify len. To address this:

    • Use an iterator-based approach to loop through the vector (more idiomatic Sui style).
    • Alternatively, keep track of the loop counter and the number of unpaid bills encountered. Exit when the counter reaches the original length or the number of unpaid bills found.
  • Missing Logic in reduce_power_used: Subtracting units without checks could lead to negative usage. Consider:

    • Adding an assertion to ensure customer.units >= units before subtracting.
    • Throwing an error if the customer attempts to reduce units beyond their usage.
  • Missing Authentication: Anyone can call public entry functions. Implement authentication (e.g., JWT, Sui wallet integration) based on roles (customer, contract).

  • Authorization Issues:

    • register_customer: Restrict access to the contract itself or a designated role.
    • withdraw:
      • Check if the customer has any outstanding bills before allowing withdrawal.
      • Consider implementing a minimum balance requirement or allowing only partial withdrawals if there are outstanding bills.
    • General Authorization: Implement role-based authorization checks throughout the code to control access to sensitive functions.
  • Overdue Fee Calculation (apply_late_fees): The current method could lead to very high bills. Consider:

    • A percentage-based late fee on the original bill amount.
    • A capped maximum late fee to prevent excessive charges.
    • A tiered system with increasing late fees based on overdue duration.
8 REP
Submitted

Hotel_booking Sui Move module provides a secure and efficient system for managing hostel bookings within an educational institution. It allows institutions, students, and administrators to interact through a set of well-defined functions, ensuring data integrity and transparent transactions on the Sui blockchain.

70Points
3 Feedbacks
144 REP
Feedback

Hello Jerryj, I went through your code and suggested a few ways to improve on it;

  • top_up_institution_balance: This function is currently commented out and seems redundant as it calls book_room and then adds the payment to the institution's balance again. It's unclear if this is intentional or a leftover function.

  • transfer_room_ownership: This entry function is not implemented and might lead to compilation errors.

  • Potential Double Payment: Calling book_room within top_up_institution_balance might lead to a double payment being deducted from the student and added to the institution if not implemented carefully.

  • Missing Access Control: Some functions like create_institution and withdraw_funds don't explicitly restrict access. Ideally, only authorized personnel within the institution should be able to perform these actions. Consider adding checks on the sender's address or implementing roles within the Institution object.

  • Unimplemented Transfer of Ownership: The transfer_room_ownership function is not implemented. If implemented in the future, ensure proper checks and authorization are in place before transferring ownership of a room to a student.

  • Error Handling: While error codes are defined, the code doesn't explicitly handle them.

  • Logging: The code doesn't seem to have any logging functionality.

Submitted

The Secure_wheels module on the Sui blockchain offers a comprehensive system for managing secure car loans. It establishes distinct roles for borrowers and lenders through dedicated structs: Borrower and Lender. These structs encapsulate relevant information like addresses, credit scores, and loan history.

80Points
4 Feedbacks
144 REP
Feedback

Hello, I made a few suggestions, check them out;

  • Inconsistent Naming: The function get_term_end uses Option<u64> for the return type, while the getter function for other time fields (e.g., get_term_start) uses u64. Consider using a consistent approach.

  • Missing Update in calculate_monthly_payment: The function calculates the monthly payment but doesn't update the monthly_payment field in the Loan object. It should assign the calculated value to loan.monthly_payment.

  • Incomplete update_credit_score: The function lacks the logic to update the borrower's credit score in Sui storage. It currently only assigns the value to a local variable.

  • Potential Reentrancy: The code doesn't explicitly protect against reentrancy vulnerabilities. In functions like make_payment and claim_overdue_pay, if an attacker can call another function in the middle of the payment process, it could manipulate the state and lead to unintended consequences. Consider using Sui's Mutexes or other mechanisms to prevent reentrancy during critical sections.

  • Insufficient Access Control: While access control checks are included in many functions, there might be ways to bypass them. A thorough review is needed to ensure all actions are performed by authorized users.

  • Redundant Getters: Separate functions exist for getting individual loan details. Consider a single function to retrieve all details at once or provide a struct representing a loan summary for easier access to frequently used data.

  • Unclear Coin Transfer: The logic for transferring SUI coins between lender and borrower in add_loan_amount_to_loan and make_payment is not entirely clear. It's recommended to use Sui's transfer function explicitly to ensure secure and traceable coin movements.

Submitted

The `food_share` module on the Sui blockchain platform is designed to facilitate the sharing and distribution of surplus food through a decentralized network. This module allows donors to post surplus food, receivers to claim and assign deliveries, drivers to accept and deliver, and manage payments and disputes efficiently.

70Points
3 Feedbacks
144 REP
Feedback

Hello alvindev, here are afew suggestions I put forward:

  • Missing return statement: The report_issues function doesn't explicitly return anything. Consider returning a result or performing an action after setting the dispute flag.

  • In the rate_driver function comment, "Ensure the function is called by the receiver" is misspelled.

  • Potential Null Dereference: In the mark_as_delivered function, it attempts to dereference the borrowed receiver using *borrow(&post.receiver). This could lead to a null pointer exception if the receiver hasn't been set yet (e.g., a race condition with claiming a post).

  • Missing Check in update_quantity: The update_quantity function doesn't check if the new quantity is valid (e.g., non-negative).

  • Reentrancy Attacks: The code doesn't implement mechanisms to prevent reentrancy attacks. An attacker might exploit this to manipulate the system during a transaction (e.g., claiming a post twice).

  • Missing Access Control for Dispute Resolution: The resolve_issues function allows any user calling the transaction to potentially resolve disputes, which could be a security concern. Ideally, only authorized personnel or a mediator should handle dispute resolution.

  • Data Validation: While not a critical error, consider validating user inputs like best before dates to ensure they are in the future and quantities are positive.

  • Concurrency Control: The code doesn't explicitly handle potential concurrency issues when multiple users try to modify the same data concurrently (e.g., claiming a post). Consider using Sui's SerializedObject or optimistic concurrency control mechanisms.

  • Event Logging: Depending on the application's needs, emitting events for specific actions (e.g., post creation, delivery completion) can be beneficial for auditing and monitoring purposes.

Submitted

The Learning Management System (LMS) module facilitates decentralized management of educational institutes, courses, student enrollments, and grant approvals within a blockchain ecosystem. It provides functionalities for creating and managing institutes, adding courses, enrolling students, handling grant requests, managing balances, and ensuring secure transactions between stakeholders.

70Points
4 Feedbacks
144 REP
Feedback

Hello miri, checkout the changes I proposed:

  • In student_check_balance and institute_check_balance, the return type is &Balance<SUI> while the function body uses just balance. It might be a typo and should likely return the reference (&).

  • In add_enrollment, there's a redundant line course_id = &course.id;. The original reference to course.id should be sufficient.

  • In new_enrollment_request, there's no check to ensure the student exists before creating a request. A malicious user could create requests on behalf of non-existent students.

  • In add_enrollment, the capacity check only considers the current number of enrolled students (vector::length(&course.enrolledStudents)) but doesn't account for potential pending requests that might be approved later, exceeding the actual capacity.

  • Authorization for Grant Approval: Currently, approve_grant_request only checks if the caller's address matches approved_by, but it doesn't implement a specific permission system to restrict who can approve grants. Consider defining roles within the institute (e.g., admin, financial advisor) and associating them with specific addresses to control grant approval access.

  • Potential Reentrancy Issues: The code doesn't explicitly handle reentrancy vulnerabilities. If a function call triggers another transaction that modifies the same data before the current transaction completes, it could lead to unexpected behavior. Consider using Sui's Mutexes or other mechanisms to protect critical sections during balance transfers or updates.

  • Event Logging: As mentioned before, implementing event logging for important actions would enhance auditability and monitoring.

  • Error Handling: The code could benefit from more comprehensive error handling to provide informative messages in case of assertion failures or unexpected conditions.

Submitted

The `energy_marketplace` module facilitates the trading of energy units between providers and buyers in a decentralized marketplace. It allows energy providers to create offers for selling energy units, buyers to bid for energy units, and provides functionalities for handling disputes and resolving them.

70Points
3 Feedbacks
144 REP
Feedback

Hello Magdaline, I made a few suggestions to the code: Missing Error Handling: While the code defines error codes, it doesn't explicitly handle them in all functions. For example, choose_buyer doesn't return an error if the chosen buyer doesn't exist.

Incorrect borrow usage: In choose_buyer and confirm_energy, using *borrow(&self.buyer) might lead to a panic if the buyer is None. Consider using self.buyer.as_ref().unwrap() or checking for None before dereferencing.

  1. In resolve_dispute, there's an extra underscore before the self parameter.

Missing Access Control: Several functions lack access control: * choose_buyer and confirm_energy can be exploited by anyone with the EnergyOfferCap object, allowing unauthorized users to modify offers. * resolve_dispute can be exploited by anyone with the AdminCap object, allowing unauthorized users to manipulate disputes.

Potential Reentrancy: The code doesn't explicitly protect against reentrancy attacks. If a function call triggers another transaction that modifies the same offer concurrently, it could lead to unexpected behavior.

Energy Delivery Verification: The current implementation relies on the seller confirming energy delivery. Consider integrating with oracles or other mechanisms for more secure verification.

Dispute Resolution Bias: The admin has complete control over dispute resolution. Implementing a more transparent and potentially decentralized dispute resolution process could be beneficial.

Submitted

The mobile_market on the Sui blockchain platform is designed to facilitate direct transactions between farmers and consumers, bypassing traditional market intermediaries. This module enables farmers to list products, manage bids, and handle payments securely within a decentralized framework, thus enhancing transparency and efficiency.

80Points
3 Feedbacks
144 REP
Feedback

Hello, here are some suggestions to improve the code;

  1. Capability Verification: In withdraw_from_escrow and product update functions, add checks to ensure the caller owns the valid FarmerCap for the specific product using object::owner or a similar function.
  2. Capability Management: Define a function to grant FarmerCap capabilities to authorized farmers based on specific criteria (e.g., identity verification).
  3. Event Emission: Implement events for actions like purchase, dispute, rating, etc., using the Sui Move event mechanism.
  4. Transaction Handling: Explore using Sui transactions for critical actions that modify multiple objects (e.g., accepting a bid, updating product state, transferring funds).
  5. Consumer Protection: Consider adding functionalities like product reviews or ratings to allow consumers to evaluate farmers and products.
  6. Fungible Token Support: Investigate the feasibility and benefits of using a Sui fungible token for currency within the marketplace.
Submitted

# Linea Vesting - Linear Vesting Module / Contract Linea Vesting is a linear vesting module for Sui. It allows for the creation of linear vesting schedules for a set of coins. The module is designed to be used by the Sui governance to distribute tokens to team members, investors, and other stakeholders over a period of time.

70Points
2 Feedbacks
144 REP
Feedback

Hello Alpkrky, I went through you code and suggested a few ways to improve on it:

  1. The 'new' function asserts but doesn't handle the EInvalidStartDate error gracefully. Consider returning an error value or throwing an exception for further handling. Other functions could also benefit from error handling, especially those interacting with the Sui ecosystem.
  2. Currently, the code doesn't explicitly validate user inputs like start, duration, or amount. Consider adding checks to ensure valid values are used.
  3. While the code doesn't show access control mechanisms, restricting access to sensitive functions like claim could enhance security. Thorough security audits are crucial for financial applications to identify and address potential vulnerabilities.
  4. The linear_vested_amount function is called twice, performing the same calculation. Consider refactoring to call it once and store the result.
Submitted

# sui move simple payment streaming module The simple payment streaming module allows a sender to create a stream to a receiver. A stream is a payment that is sent to the receiver that the receiver can claim over time. Instead of receiving the full payment at once or being restricted to fixed installments, the receiver can claim the pending payments at any time. The sender can close the stream at any time, which will send the claimed amount to the receiver and the unclaimed amount to the sender. ## Creating a stream Anyone can create a stream to anyone else with any coin. The sender specifies the receiver, the payment, and the duration of the stream. The duration is specified in seconds. The receiver can start claiming the stream immediately after it is created. ## Claiming a stream The receiver can claim the stream at any time. The amount claimed is calculated based on the time since the last claim. If the stream duration has passed, the receiver will receive the full amount and the stream will be closed (deleted). ## Closing a stream The receiver can close the stream at any time. The amount to send to the receiver and the amount of to send back to the sender is calculated based on the time since the last claim. If the stream duration has passed, the receiver will receive the full amount and the sender will receive nothing. When a stream is closed, it should be deleted.

90Points
4 Feedbacks
144 REP
Feedback

Hello bitmove, I think you should consider the following areas and see how they can be integrated to improve the overall functionality.

  1. Inconsistent Error Handling: The code uses custom error codes but lacks proper error handling mechanisms. Consider using Sui Move's built-in SuiError for a more structured approach.

  2. Potential Zero-value Object Deletion: In claim_stream and close_stream, if claim_amount is the entire stream amount, the code attempts to delete the stream object even if the remaining balance might be zero. This could lead to unnecessary object deletion and potential Sui Move runtime errors.

  3. Missing Access Control for Claiming: The current implementation relies on the receiver's address for claiming streams. Consider implementing access control mechanisms to allow claiming only for authorized receivers or specific

  4. Reentrancy and Concurrency: The code doesn't address reentrancy or concurrent access to streams. Explore adding locking mechanisms or using Sui Move's STM capabilities to ensure safe concurrent access.

  5. Zero-value Handling Optimization: While destroy_zero ensures cleanup, consider optimizing the code to avoid unnecessary checks and deletions for zero

6.25 SUI
6.25 REP
Submitted

The Construction_Contract_Chain module on the Sui blockchain platform is designed to optimize the management of construction projects through a decentralized approach. This module enables contractors to efficiently create project contracts, manage bids, handle disputes, and ensure secure payment transactions.

0Points
3 Feedbacks
144 REP
Feedback

Hello, these are a few suggestions I made;

  • Redundant Skill Check in add_skills: Both new_worker and add_skills perform the same check for duplicate skills. This can be optimized by having a central function to manage worker skills.

  • Missing Rating Functionality: While a rating field exists in ConstructionJob, there aren't functions to set or use it. Consider implementing a rating system for workers or projects.

  • Security Review: A thorough security review by an expert is still recommended.

  • Access Control for resolve_dispute: Currently, any AdminCap holder can resolve disputes. You might want to implement a more granular permission system for dispute resolution.

  • Event Emission: Consider events to notify interested parties about project updates (e.g., worker chosen, work submitted).

Submitted

# SUI Move Lucky Cafe ## 1 Entity Definition - Coffee Shop (`Cafe`) - Coffee Card (`Card`) - Coffee (`Coffee`) - Owner (`Owner`, `Admin`) - Customer ## 2 Entity Relationship - Any user can create a coffee shop (`Cafe`) and become the owner (`Owner`, `Admin`) - Customers can buy coffee cards (`Card`) - Coffee cards (`Card`) can be exchanged for coffee (`Coffee`) on a `1:1` basis ## 3 Economic Design - Every 5 GAS can buy a coffee card, buy two and get one free, that is, 10 GAS can buy 3 coffee cards, and so on - A coffee Card can be exchanged for a cup of coffee, and after the coffee is exchanged, this coffee card becomes invalid - Each coffee card has a unique lucky number (`Lucky Number`). Anyone can trigger the contract interface to randomly select a lucky number. If the selected lucky number corresponds to a used coffee card, a new lucky number can be drawn again - The holder of the coffee card corresponding to the lucky number can use this lucky number coffee card to get a reward. The reward is to double the number of coffee cards in hand, with a single reward limit of 10 coffee cards. For example: Alice holds 4 coffee cards, one of which has a lucky number of 7. When the randomly selected lucky number is also 7, then good luck happens, `Alice` can destroy this lucky coffee card and double the number of coffee cards she holds. - After the lucky number is drawn randomly, it cannot be drawn again until the corresponding coffee card is redeemed. However, the owner has admin rights and can delete the randomly generated lucky number so that a new lucky number can be selected, to avoid customers not claiming their rewards in time. ## 4 API Definition - **create_cafe**: create a new cafe object with the provided base_drand_round and initializes its fields. - **buy_cafe_card**: buy a card for the cafe object with the provided sui amount. - **buy_coffee**: buy a coffee for the cafe object with the provided card object. - **get_lucky_number**: get the lucky number for the cafe object with the provided drand signature. - **get_reward_with_lucky_card**: get the reward for the more cafe object with the provided lucky card object. - **remove_lucky_number**: remove the winner lucky number of the cafe object. - **get_sender_card_count**: get the sender's card count of the cafe object.

100Points
2 Feedbacks
144 REP
Feedback

Hello rzexin, I made a few adjustment to the code that would improve it's functionality and enhance security:

  1. Corrected cafe.participants update in buy_coffee:

    • The code now decrements cafe.participants after buying coffee with a card, ensuring an accurate participant count.
  2. Added check for empty winner lucky number in get_lucky_number:

    • The code now explicitly checks if the retrieved lucky_number from option::borrow is None before accessing it, preventing potential errors.
  3. Prevented infinite loop in get_reward_with_lucky_card:

    • The loop condition is modified to i < reward_card_count && *card_count > 0. This ensures the loop terminates if reward_card_count is 0 or card_count becomes 0 during the loop, avoiding an infinite loop.
  4. Added access control:

    • The create_cafe function is now marked as private, restricting cafe creation to authorized users. Additional access control checks can be implemented for other sensitive functions.
  5. Verified randomness source:

    • A comment is added to remind developers to verify the security of the underlying randomness generation mechanism used in drand_lib.
  6. Combined redundant cafe_id checks:

    • The duplicated checks for cafe_id in buy_coffee and get_reward_with_lucky_card are removed, improving code clarity.
  7. Used Sui Move error handling:

    • The code now utilizes Sui Move's SuiError type for error handling, providing a more structured and informative approach compared to custom error codes.
18.75 SUI
18.75 REP
Submitted

The Charity Donation Tracking module facilitates the transparent and accountable management of charitable donations, enabling donors, recipients, and authorities to interact in a decentralized manner. It offers functionalities for making donations, tracking their purposes and amounts, validating donations by authorities, transferring donations to recipients, and managing donation cancellations.

90Points
4 Feedbacks
144 REP
Feedback

Hello, I went through your code and suggested a few ways to improve on it;

  • Authority Validation: While claim_by_authority requires the authority to not have validated yet, it might be stricter to also require the donation to not be already validated by another authority.
  • Cancel Donation: The cancel_donation function seems secure, but consider if there's a timeframe or additional checks for when a donation can be canceled (e.g., before a certain time or before validation).
  • Purpose ID Usage: The current implementation doesn't fully utilize purpose_id. You might consider allowing authorities to define purposes and linking donations to specific ones for better categorization and tracking.
  • Transparency: Consider functions for authority figures to add descriptions or details to purposes for increased transparency.
  • Event Emission: Implementing events to notify interested parties about donation activities (e.g., new donation, validation) could enhance transparency.
  • Logging: Maintaining a transaction log for donations could be useful for auditing purposes.
Submitted

# sui-trading-platform INTRODUCTION This module facilitates trading operations within the Sui Move ecosystem, enabling the creation of trading platforms, execution and replication of trades, and management of trader accounts and protocol balances. STRUCTURES TraderAccount Stores details of individual trader accounts: - id: Unique identifier of the trader. - trader_address: Address of the trader. - join_date: Timestamp when the trader joined the platform. - last_trade_date: Timestamp of the trader's last trade. - total_followers: Total number of followers the trader has. - total_trades: Total number of trades executed by the trader. - total_profit: Total profit earned by the trader. TradingPlatform Represents a trading platform: - id: Unique identifier of the trading platform. - inner: Internal ID for the platform. - balance: A Bag containing the platform's balance. - performance_fee_rate: Fee rate applied to trader profits. TradingPlatformCap Ensures authorized management of a trading platform: - id: Unique identifier of the cap. - platform: Internal ID of the associated trading platform. Protocol Manages the protocol's balance: - id: Unique identifier. - balance: A Bag containing the protocol's balance. AdminCap Allows only admins to withdraw fees: - id: Unique identifier. CORE FUNCTIONS new_trading_platform Creates a new trading platform with a specified performance fee rate. - Parameters: `performance_fee_rate`, `ctx` - Returns: Transfers TradingPlatformCap to the caller. execute_trade Executes a trade on behalf of a trader. - Parameters: `protocol`, `trading_platform`, `clock`, `coin_metadata`, `coin`, `ctx` - Returns: `TraderAccount` replicate_trade Replicates a trader's trade. - Parameters: `protocol`, `trading_platform`, `trader_account`, `coin_metadata`, `coin`, `ctx` distribute_profits Distributes profits to followers of a trader. - Parameters: `trader_account`, `_ctx` Error Constants - EInsufficientFunds (1): Insufficient funds to process the trade. - EInvalidCap (4): Invalid cap for trading operations. HELPER FUNCTIONS helper_bag Manages balances within a Bag. - Parameters: `bag_`, `coin`, `balance` Accessor Functions Accessor functions are available for fetching trader account details such as join date, trader ID, last trade date, and total profit. SUMMARY This module enables the creation and management of trading platforms, execution and replication of trades, and distribution of profits to followers. It ensures secure handling of balances and error-free transaction processing within the Sui Move environment.

0Points
2 Feedbacks
144 REP
Feedback

Hello JohnMwaba, I recommended a few ways to enhance your code;

  • Incomplete Follower Replication (replicate_trade): As highlighted before, the replicate_trade function doesn't fully replicate the trade for followers. It needs to update the trader's total profit based on the replicated trade's performance:

  • Missing Logic in distribute_profits: The distribute_profits function is still a placeholder. Implement the logic to distribute profits among followers based on their contributions and the trader's total profit. This might involve iterating through a list of followers or using a suitable data structure to track follower information.

  • Unused Argument (_protocol): The _protocol argument in distribute_profits is unused. Consider removing it or using a descriptive name if it's intended to be used.

  • Commented-Out Line: The commented-out line trader_account.last_trade_date = clock::timestamp_ms(clock); in execute_trade should be uncommented to update the trader's last trade date.

  • Descriptive Variable Names: While not strictly an error, using more descriptive variable names can improve code readability. For example, consider follower_balance instead of _balance in replicate_trade if it specifically refers to the follower's balance.

  • Detailed Error Messages: Explore providing more informative error messages for potential issues (e.g., "Insufficient funds for trade") to aid debugging and user experience.

Submitted

This is a contract for reverse auction. A reverse auction is a type of auction in which the roles of buyer and seller are reversed. Buyers announce a need for goods or services, and sellers compete to offer the lowest price. - In this contract, one calls `create` to initiate a reverse auction and calls `set_price` to offer a lower price. - All users can perform as legitimate bidders. When the price is acceptable, the bidder calls `bid` to bid price, pay and get what is auctioned. - After the sale, the seller could call `claim` to obtain the auction proceeds. - The seller retains the ability to stop the auction at any time, by call `stop`.

90Points
4 Feedbacks
144 REP
Feedback

Hello check out these suggestions I put forward;

  • Implement Authorization Checks: Add checks within auction functions to ensure only the auctioneer with the matching capability can modify the auction state (e.g., using tx_context::is_attached(&auction_cap)).
  • Handle Unsuccessful Bids: Consider modifying bid to return the remaining balance to unsuccessful bidders after the auction ends. This can be achieved using Sui's balance::split and balance::join functions.
  • Explore Reentrancy Protection (Optional): Reentrancy protection mechanisms (e.g., using Sui's ObjectRef) can be explored to mitigate potential reentrancy attacks.
  • Minimum Bid (Optional): If desired, add a function for the auctioneer to set a minimum acceptable bid price.
91 REP
Submitted

Introducing the Shoe Store Smart Contract, built on the innovative Sui blockchain framework. This smart contract encapsulates the functionality required to operate a shoe store, offering seamless transactions and management of shoe inventory. Leveraging the capabilities of the Sui blockchain, this contract ensures secure and efficient operations, providing a reliable foundation for shoe retailing in the digital age. Embrace the future of retail with the Shoe Store Smart Contract on the Sui blockchain framework.

70Points
2 Feedbacks
144 REP
Feedback

Hello Mahesh, I went through your code and suggested a few ways to improve thr code:

  • Missing validation in add_shoe: As mentioned previously, the code lacks validation for user input like price and stock during add_shoe. Malicious actors could exploit this to inject negative values or overflow the stock field.

  • Missing Access Control: Currently, all functions are public. Anyone can call them and potentially manipulate the store or purchase shoes without authorization. Implement access control mechanisms to restrict unauthorized actions. Here are some options:

    • Require authentication for modifying the store (adding, deleting, updating shoes).
    • Use roles to differentiate between store owners and buyers.
  • Concurrency Issues: The code doesn't handle concurrent transactions. If multiple users try to purchase the same shoe simultaneously, it could lead to race conditions where one user reduces the stock while another reads an outdated value, potentially resulting in overselling. Consider using locking mechanisms like Sui's Mutex to ensure data consistency during concurrent access.

294 REP
Submitted

This is a Simple defi lottery contract that depends on randomness from drand. It has the following features: - It allows any player to be able to start the lottery, buy tickets and even end the lottery.- - Players can then check to see if they're the lucky winners of that lottery. - Winner gets all of the prizepool.

70Points
2 Feedbacks
144 REP
Feedback

Hello JoeEdoh,I went through your code and found a few ways to improve on it: Logic Error in checkIfWinner: The code checks if the winner has claimed before setting the winner, which might lead to inconsistencies. Set the winner and then check if they have already claimed to ensure correct state management.

Unnecessary Player Record Deletion: Deleting the player record in checkIfWinner after checking if they won seems unnecessary and might have unintended consequences. Consider keeping the player record for potential future use cases or auditing purposes.

Missing Error Handling: The code doesn't explicitly handle potential errors that might occur during various operations. Implement proper error handling mechanisms to provide informative messages and gracefully handle unexpected situations.

Insecure Randomness Handling: The code directly accepts user-provided randomness signatures without proper validation.