Home
Welcome to Sui Community Forum
New Articles
- Journey as a SUI Move smart contract developerArticleBahador59Mar 15, 2025
In today's article, I wanna dive into a roadmap suggestion for those who like to enter into the SUI move development way. 1. Understand Blockchain Fundamentals Core Concepts:* Familiarize yourself with key blockchain concepts such as decentralization, consensus mechanisms, cryptographic primitives, and smart contracts. SUI Blockchain Overview:* Learn about what makes SUI unique—its object-centric data model, performance goals, and how it handles state management. 2. Learn the Move Language Language Basics:* Start with the fundamentals of the Move programming language. Focus on: Resource Types:* How resources work to ensure safety and ownership. Modules and Structs:* How to define modules and data structures. Entry Functions:* How transactions are executed through designated entry points. Recommended Resources: Utilize official Move language tutorials, documentation, and sample code repositories. 3. Set Up Your Development Environment Tools and CLI:* Install the SUI CLI and set up the Move toolchain on your local machine. Local Test Environment:* Configure a local SUI development network or use available testnets. This helps you experiment with smart contract deployment and testing before going live. IDE & Debugging:* Choose an Integrated Development Environment (IDE) that supports Move (for example, VSCode with Move extensions) and get familiar with debugging and testing your contracts. 4. Build Your First Simple Contract Hands-on Tutorials:* Start with a simple project such as a token contract. This will allow you to apply the basic Move constructs. Explore SUI-Specific Patterns:* Work with SUI’s object model and learn how transactions are processed within the SUI ecosystem. Documentation & Examples:* Leverage SUI’s developer documentation and sample projects to understand best practices. 5. Deep Dive into SUI-Specific Features Object-Centric Model:* Understand how SUI treats objects differently from account-based blockchains like Ethereum. Gas & Transaction Model:* Study how gas fees are calculated and how transaction execution is managed in SUI. State Management:* Learn about SUI’s approach to state storage, modular updates, and object lifecycle management. 6. Testing, Debugging, and Deployment Unit and Integration Testing:* Write tests to verify the logic and safety of your smart contracts. Make sure you cover edge cases and potential vulnerabilities. Local and Testnet Deployment:* Deploy your contracts in a controlled environment to see how they perform in real conditions. Tooling:* Utilize SUI’s debugging tools and logging features to iterate and improve your code. 7. Security Best Practices and Code Audits Understand Common Pitfalls:* Study common security vulnerabilities in smart contracts (e.g., reentrancy, improper access controls) and how Move’s design mitigates them. Code Reviews:* Get involved in community code reviews or collaborate with peers to audit and improve your code. Formal Verification:* Explore any available formal verification tools for Move to mathematically prove the correctness of your contracts. 8. Join the SUI Developer Community Community Channels:* Engage with other developers via forums, Discord channels, or community calls. Sharing experiences and challenges is invaluable. Open Source Contributions:* Contribute to open source projects or developer repositories related to SUI and Move. Stay Updated:* Follow SUI and Move blogs, GitHub repositories, and social media channels to keep track of new developments, updates, and best practices. 9. Explore Advanced Topics Complex Applications:* As you become more comfortable, experiment with more advanced smart contract designs such as decentralized finance (DeFi) protocols, NFTs, or multi-signature wallets. Interoperability and Integration:* Learn how to interact with other smart contracts and integrate SUI Move modules with off-chain systems. Performance and Scalability:* Explore techniques to optimize your contracts for speed and cost-efficiency on the SUI blockchain. 10. Build a Portfolio and Keep Practicing Showcase Projects:* Develop and document a series of projects that demonstrate your understanding and expertise. Continuous Learning:* Blockchain and Move are evolving rapidly—make continuous learning a habit by revisiting documentation, attending workshops, and participating in hackathons. Feedback Loop:* Use community feedback to refine your skills and stay ahead of the curve in smart contract development. Although the above Items are suggestions and are not the only way to turn into an SUI developer, I hope it is helpful for you guys. Happy coding. Happy SUIng!
0 - Setting Up a Project to Test the SUI Name Service (SuiNS)Article0xduckmove115Mar 12, 2025
The SUI Name Service (SuiNS) is a decentralized naming system on the SUI blockchain that allows users to map human-readable names (e.g., "0xduck.sui") to blockchain addresses or other data, enhancing usability and accessibility. For developers, testing the SuiNS SDK is an essential step to ensure applications can resolve these names correctly. In this article, we’ll walk you through the process of setting up a project to test the SuiNS SDK, from preparing your development environment to querying a name record like "0xduck.sui" and understanding the results. Introduction to SUI Name Service The SUI Name Service (SuiNS) simplifies blockchain interactions by allowing users to register memorable names instead of using complex cryptographic addresses. For example, instead of sending tokens to "0x1234...abcd", you could send them to "0xduck.sui". Testing the SuiNS SDK ensures that your application can correctly interact with this system, retrieving and interpreting name records as needed. In this project, we’ll set up a Node.js environment, connect to the SUI mainnet, and write a script to query the name record for "0xduck.sui". By the end, you’ll have a working setup to explore SuiNS further. Prerequisites Before starting, ensure you have the following: Node.js (version 14 or higher) and npm (version 6 or higher) installed. Download them from nodejs.org if needed. Basic understanding of JavaScript, particularly asynchronous programming (e.g., async/await). A code editor like Visual Studio Code (VS Code) for writing and running scripts. An internet connection to install packages and connect to the SUI. Setting Up the Development Environment Let’s create a new project directory and initialize it as a Node.js project. This will provide a clean workspace for our test. Step-by-Step Instructions: Open your terminal (e.g., Command Prompt, PowerShell, or a Unix shell). Create a new directory: mkdir suins-test-project cd suins-test-project Initialize a Node.js project: Run this command to create a package.json file with default settings: npm init -y Your project is now set up with a basic structure. Installing Dependencies Run the following in your terminal: npm install @mysten/suins @mysten/sui Verify the Installation: Check that the packages are added to package.json under dependencies. You can also confirm the installed versions by running: npm list @mysten/suins @mysten/sui This should output something like: suins-test-project@1.0.0 ├── @mysten/sui@x.x.x └── @mysten/suins@y.y.y Configuring the SUI Client The SUI client connects your project to the SUI blockchain. For testing, we’ll use the mainnet. Create a Script File: In your project directory, create a file named test-suins.js: touch test-suins.js # On Unix/macOS echo. > test-suins.js # On Windows Open test-suins.js in your editor and add the following: import { getFullnodeUrl, SuiClient } from '@mysten/sui/client'; // Create a SUI client connected to the testnet const suiClient = new SuiClient({ url: getFullnodeUrl('testnet') }); Note: If you encounter an error about ES modules (e.g., "Cannot use import statement outside a module"), add "type": "module" to your package.json: { "name": "suins-test-project", "version": "1.0.0", "type": "module", ... } Testing the Name Service Now, let’s write a script to query the name record for "0xduck.sui" and log the result. import { getFullnodeUrl, SuiClient } from '@mysten/sui/client'; import { SuinsClient } from '@mysten/suins'; // Create a SUI client connected to the testnet // const suiClient = new SuiClient({ url: getFullnodeUrl('mainnet') }); const client = new SuiClient({ url: getFullnodeUrl('mainnet') }); // Create a SuiNS client using the SUI client const suinsClient = new SuinsClient({ client, network: 'mainnet', }); // Function to test the name service async function testNameService() { try { // Query the name record for 'demo.sui' const nameRecord = await suinsClient.getNameRecord('0xduck.sui'); // Log the result console.log('Name Record for "0xduck.sui":', nameRecord); } catch (error) { console.error('Error fetching name record:', error.message); } } testNameService(); In your terminal, execute: node test-suins.js
2 - Suibase, a great tool to experience the SUIArticleBahador59Mar 11, 2025
As I was checking some resources for the SUI development, I faced a tool named, suibase. In my exploration on that, I found it very helpful, especially when using localnet which a local explorer will be set up on our local system. I loved it so much. as there is stated in the official website of Suibase: Suibase makes it easy to create "workdirs", each defining a distinct development environment targeting a network. It seems like virtual env in python programming. As far as I found this tool, there are many usefull functionalities which we can take benefit of: Key functionalities of Suibase include: Workdir Management: Suibase enables the creation of isolated workdirs for each network, ensuring that configurations and dependencies are maintained separately. This isolation facilitates organized and efficient development workflows. Suibase Simplified Command-Line Interface:* The tool provides scripts such as lsui, dsui, tsui, and msui, which serve as frontends to the Mysten Labs sui binaries for localnet, devnet, testnet, and mainnet, respectively. These scripts eliminate the need to manually switch environments, as they automatically execute the appropriate sui client and keystore for the targeted network. Localnet Operations:* Suibase offers commands like localnet start, localnet stop, and localnet status to manage the local network. Additionally, the localnet regen command allows developers to reset the network to its initial state, complete with predefined addresses and aliases, which is particularly useful for testing purposes. Faucet Functionality:* The localnet faucet command enables the distribution of Sui coins to specified addresses or all addresses within the localnet, facilitating testing and development activities. Independent Installation:* Suibase operates independently of other Mysten Labs installations and keystores, ensuring that it does not interfere with existing setups. This design allows Suibase to coexist safely with standard installations on the same system. By providing these features, Suibase enhances the development experience on the Sui network, offering a structured and efficient environment for building and testing applications. I recommend testing it!
2 - How to fix the SUI installation error?ArticleBahador59Mar 11, 2025
When I try to install and build the SUI binary on my local system with this command: cargo install --git https://github.com/MystenLabs/sui.git --bin sui --branch devnet I face this error: Please specify a package, e.g. cargo install --git https://github.com/MystenLabs/sui.git anemo-benchmark. After some digging, I found the solution and was able to install and build it error-free and completely using some modification in the above command: For Devnet: cargo install --locked --git https://github.com/MystenLabs/sui.git sui --branch devnet For Testnet: cargo install --locked --git https://github.com/MystenLabs/sui.git sui --branch devnet This way, you can install and build SUI on your local machine and start on your way! Best of luck.
2 - How Transactions Work in SuiArticleBahador59Mar 10, 2025
One of the cool things that attracted me to the SUI chain is the working manner of transactions, so in this article, we are going to get some knowledge about how transactions work in the SUI blockchain. Every transaction in Sui explicitly lists which objects it will read or modify. Because each object is independent, the Sui validators can easily check the list of objects for each incoming transaction. This helps the system decide which transactions can run simultaneously: Independent transactions (no overlapping objects): If two transactions involve completely different objects, they do not conflict with each other. Sui knows these won’t interfere, so it can execute them at the same time in parallel. For example, one transaction might update Alice’s coin object while another might transfer Bob’s NFT object – since these are separate objects, there’s no need to wait for one before doing the other. Conflicting transactions (shared objects): If two transactions try to use the same object, they conflict and cannot be executed at the exact same moment. Sui will handle this by ordering and executing those particular transactions one after the other to avoid any confusion or double-spending. In this case, the network’s consensus mechanism comes into play to decide a fair order for the transactions that touch the same data. Only the transactions that conflict are ordered; all other independent transactions can proceed in parallel without waiting. In essence, Sui’s transaction model separates “simple” transactions from “dependent” ones. Simple transactions that affect only a single owner’s objects can often be processed very quickly without involving the whole network in heavy coordination. More complex transactions (for example, ones interacting with a shared smart contract object that many users might use) go through a traditional ordering process (consensus) to ensure they don’t conflict with each other. This way, Sui only uses global consensus when it’s truly needed, and it can let most transactions fly through concurrently when there are no overlaps in the data they touch. Parallel Execution in Sui vs. Traditional Blockchains On traditional blockchains like Bitcoin or Ethereum, transactions are processed sequentially (one after the other). Even if two transactions have nothing to do with each other, a sequential system will still put one in line behind the other, creating unnecessary waiting. This is like having a single checkout register at a store – even customers buying different items must stand in the same queue. It causes congestion and slows things down during busy periods. Sui takes a different approach by allowing the parallel execution of transactions. This is analogous to having many checkout counters open: multiple transactions can be handled at the same time as long as they are independent, which vastly improves throughput and efficiency. Because of Sui’s object-centric design, operations on one object do not impact or delay operations on another object . Validators in the Sui network can leverage multiple CPU cores and threads to execute several transactions simultaneously, much like processing multiple tasks in parallel on a computer. The result is a significant boost in scalability – Sui can handle a large number of transactions per second without breaking a sweat. Tests have demonstrated that Sui’s approach can support massive throughput (on the order of hundreds of thousands of transactions per second) thanks to this parallelism. Equally important, parallel execution reduces latency for individual transactions, meaning users see their transactions confirmed faster because they aren’t stuck waiting behind unrelated transactions. Overall, Sui’s parallel execution model eliminates the bottlenecks that plague single-threaded (sequential) blockchains, enabling the network to scale up and handle workloads that would overwhelm traditional designs. Finality and Confirmation Speed Finality refers to how quickly a transaction is irreversibly confirmed (i.e. once confirmed, it won’t be reverted). Sui is designed for quick finality, often reaching confirmation in a fraction of a second. In practice, a typical Sui transaction can be confirmed in around 300–500 milliseconds (well under one second) once it’s processed – essentially near-instant for the user. This is much faster than many older blockchains. For comparison, Ethereum’s network usually needs on the order of several seconds to minutes to truly finalize a transaction (Ethereum blocks are around ~12 seconds apart, and it may take a couple of blocks or more for high confidence), while Bitcoin might require dozens of minutes (due to 10-minute block times and multiple confirmations) for a transaction to be considered final. Sui’s modern consensus and parallel execution give it a major speed advantage: transactions on Sui are confirmed almost immediately after you send them. There’s no long wait for a new block to include the transaction or for multiple confirmations. In short, Sui provides sub-second finality, which means users can send a transaction and see it permanently settled right away. This fast confirmation is especially beneficial for applications like gaming, real-time finance, or retail payments, where waiting even tens of seconds could be too slow. Sui delivers confidence to the user quickly, making the blockchain feel much more responsive compared to traditional chains.
2 - Comparing Sui vs EthereumArticleBahador59Mar 10, 2025
In this article, we are going to find out some of the differences between Sui and Ethereum and be able to choose from them based on our project requirements. Sui utilizes novel design choices, including a unique object-centric data model and the Move programming language (originating from Facebook’s Diem project), to enable high throughput and secure smart contract execution. Both platforms enable developers to create smart contracts and decentralized applications, but they differ fundamentally in architecture and approach. This article provides a detailed comparison of Ethereum and Sui, highlighting key differences in their programming paradigms, features, architecture, consensus mechanisms, scalability, developer experience, and ecosystem maturity. Let's compare these two chains: Consensus Mechanism: Sui Delegated Proof-of-Stake with Byzantine consensus (Narwhal & Bullshark). Validators (chosen each epoch) use a DAG-based mempool (Narwhal) and BFT consensus (Bullshark) for fast ordering. Near-instant finality (sub-second in ideal conditions) is achieved with this optimized consensus. Ethereum Proof-of-Stake .Validators stake ETH to propose and validate blocks; finality achieved via epochs and attestations(approx~ 13 minutes or 2 epochs) Smart Contract Language Sui Move. Uses an adapted Move language that treats assets as objects with strict ownership rules. Move’s design prevents asset duplication or loss by default and enforces safety at the language level. This leads to more secure contracts out-of-the-box, with a slightly stricter programming model. Ethereum Solidity (also Vyper for pythonists, Yul, and Huff). Contracts compiled to EVM bytecode. Solidity is flexible but prone to developer errors if not carefully written; extensive audits and best practices are needed for security. Execution Model Sui Parallel execution via object-centric design. Transactions in Sui specify the objects they read/write. If transactions affect independent objects (especially “owned” objects with separate owners), they can be executed concurrently by validators. Only conflicts (e.g. two txns touching the same “shared” object) require ordering through consensus. This enables multiple transactions to be processed simultaneously, dramatically improving throughput., Ethereum Sequential execution on the EVM. Transactions are ordered in each block and executed one by one on every node, which means each transaction must run to completion (updating global state) before the next begins. This simplifies state management but creates a bottleneck – even independent transactions cannot be processed in parallel. Transaction Processing Sui Sub-second block finality in optimal conditions; theoretical throughput in the tens of thousands TPS. Sui’s design (parallel execution and efficient consensus) has demonstrated >120,000 TPS in test settings. In practice, Sui’s mainnet is expected to handle high loads without sharding. Transaction fees are designed to remain stable, with gas price governance per epoch, keeping costs low even as demand grows. Ethereum 12 second block time; throughput historically 15–30 TPS on mainnet (scaling achieved via Layer-2 solutions). Finality is probabilistic per block, with economic finality after 2 epochs (6-13 minutes) in PoS. Gas fees can spike under load, and users often rely on rollups or sidechains for higher performance. Scalability Sui Horizontal scalability by design. Sui can utilize more validator resources to increase throughput – analogous to adding more “lanes” for transactions. The network does not have a fixed TPS limit; if more hardware is added and transactions are independent, throughput scales up. This makes Sui capable of scaling on the base layer for high-demand use cases (e.g., gaming, social networks) without immediately needing layer-2s or sharding. Ethereum Relies on Layer-2 scaling (Rollups like Optimistic or ZK-Rollups) and future sharding upgrades. Ethereum’s roadmap (Danksharding, etc.) aims to increase base layer throughput, but currently, the strategy is to offload activity to L2 networks and use Ethereum for settlement. This approach maintains decentralization but pushes true scale to auxiliary networks. Developer Experience Sui Growing and security-focused. Sui provides a new toolkit (Sui CLI, SDKs, Move compiler, etc.) and detailed documentation. Developers may need to learn the Move language and adapt to thinking in terms of objects and resources. This learning curve can be offset by Sui’s emphasis on correctness – by following Sui’s model, developers naturally avoid many pitfalls. The ecosystem is actively building tools (for example, Move package managers and testing frameworks), and Mysten Labs has invested in developer outreach (hackathons, tutorials). While not as extensive as Ethereum’s, Sui’s developer community is enthusiastic, and early adopters benefit from direct support channels as the ecosystem matures. Ethereum Ethereum has numerous developer tools: IDEs (Remix online IDE), frameworks (Foundry, Hardhat, Brownie), libraries (Web3.js, Ethers.js, Viem.js, etc.), and test networks. The community support is unparalleled – countless tutorials, forums, and established patterns exist. However, mastering Ethereum development requires understanding gas mechanics, security patterns, and the EVM’s constraints, which can be challenging for newcomers. My above explanations can be summarized into this line: In summary, Ethereum stands as the established general-purpose blockchain with broad adoption and a rich ecosystem, whereas Sui is an emerging high-performance blockchain incorporating new paradigms for scalability and safety. As blockchain technology evolves, both platforms could coexist, each inspiring improvements in the other. Ethereum might adopt some parallelization techniques (research is ongoing into parallel EVM execution, and Sui will certainly learn from Ethereum’s experiences in governance and community building. For developers and businesses, the choice will come down to the demands of their project: the comfort of the tried-and-true versus the allure of the new and fast. By understanding the key differences outlined above – from programming models to consensus – one can make an informed decision or strategy that harnesses the best of both worlds, potentially leveraging Ethereum’s solidity and Sui’s agility to build the next generation of decentralized applications
3 - This article aims to learn and understand the #UTXO model from $BTC to $SUIArticle0xduckmove115Mar 08, 2025
This article aims to learn and understand the UTXO model. It uses an easy-to-understand way to simply sort out the UTXO models and implementation methods from $BTC to $SUI. I will provides a comprehensive overview, which we expand here for clarity and depth, ensuring a professional and thorough analysis. As one of the core design principles of Bitcoin, the UTXO model has become an important technical paradigm in the blockchain field since its birth. It plays an important role in ensuring transaction security and traceability, and provides another path besides the traditional account balance model. As blockchain technology has been continuously updated and iterated in recent years, the UTXO model itself has also been constantly evolving and expanding. Introduction to UTXO and Its Origins The UTXO model, or Unspent Transaction Output, is a fundamental concept in Bitcoin, where each transaction output that hasn’t been spent is tracked as a UTXO. This model treats transactions like cash, where spending involves selecting specific UTXOs to cover the amount, as opposed to modifying a single balance. The example: Alice and Bob each start with 5 dollars. In the account model, if Bob robs Alice of 2 dollars, Alice’s balance becomes 3, and Bob’s becomes 7. In the UTXO model, Alice’s 5-dollar UTXO is spent to create two new UTXOs: 2 dollars to Bob and 3 dollars back to Alice, with Bob now holding his original 5-dollar UTXO and the new 2-dollar one, totaling 7 dollars. This approach, as detailed in Understanding UTXO: A Comprehensive Guide, ensures transparency and prevents double-spending, with each UTXO publicly tracked on-chain while preserving privacy through anonymous addresses. It is not difficult to see that Alice is left with 3 dollars and Bob is left with 7 dollars. This accounting method, which is similar to elementary school addition and subtraction, frequently appears in the banking system and is called the account/balance model. In it, the balance of an account exists as a single value. If a different approach from the account model is used, such as UTXO to represent the wealth transfer between Alice and Bob, the diagram will look different: Comparison with Account/Balance Model The account/balance model, common in banking, maintains a single balance per account, updated with each transaction Its simplicity but notes state contention issues when multiple transactions modify the same account, often requiring locks and causing performance bottlenecks, especially under high transaction volumes. In contrast, the UTXO model, as explained in Exploring the UTXO Model: What Sets It Apart in the Blockchain World?, avoids this by processing transactions on independent UTXOs, enabling parallel execution without locks, thus improving throughput and concurrency. Privacy is another advantage, with crypto wallets generating new addresses per transaction, making it harder to link to individuals, unlike the account model’s fixed addresses, which are more susceptible to correlation analysis. However, the UTXO’s limitations in handling complex business logic, such as multi-stage contracts, which led to Ethereum’s account-based model, as mentioned in What is a UTXO? Unspent Transaction Output Explained . SUI’s Object Model: Bridging UTXO and Account Models SUI, as detailed in the X post and supported by Object Model | Sui Documentation, centers storage around objects, not accounts, with two key types: OwnedObject (address-owned) and SharedObject. The OwnedObject enhanced UTXO, where only the owner can operate, and each version is spent once, aligning with UTXO’s principles. For instance, an address-owned object can only be modified by its owner, similar to spending a UTXO. SharedObject, conversely, is accessible to everyone, akin to the account model, but requires consensus to order reads and writes, addressing state contention, as noted in Sui Components | Sui Documentation. This is managed through special processing like local sorting. The Sui's Object-Oriented Approach highlights how SUI’s model impacts scalability, security, and user experience. Ownership Types in SUI | Ownership type | Description | Accessibility |--------|--------|-------- | Address-owned | Owned by a specific 32-byte address (account address or object ID) | Only accessible to its owner | Immutable | Can't be mutated, transferred, or deleted; no owner | Accessible to anyone | Shared | Shared using 0x2::transfer::share_object function | Accessible to everyone | Wrapped | Organizes data structures by putting a field of struct type in another | Not specified Owned objects include address-owned, aligning with UTXO, while shared objects are explicitly accessible to all, fitting the account model’s broader access. My conclusion and Future Considerations The transition from Bitcoin’s UTXO to SUI’s object model represents a significant evolution, offering flexibility and addressing UTXO’s limitations in complex logic through SharedObject, while retaining UTXO’s concurrency benefits via OwnedObject. This dual approach, as explored in Exploring Sui’s Object-Centric Model and the Move Programming Language, positions SUI as a versatile platform, potentially setting a new standard for blockchain data models.
4 - Developing a Dice Game Contract in Sui MoveArticle0xduckmove115Mar 07, 2025
In this tutorial, I’ll guide you through the process of creating a dice game smart contract using Sui Move. This contract enables players to bet on the outcome of a dice roll, with an admin managing the prize pool. By the end, you'll have a fully functional contract and a solid understanding of several key Sui Move concepts. Introduction The dice game contract we'll build allows for the following functionalities: Initialization: The contract creator sets up the game. Admin Management: An admin can deposit tokens into the prize pool and withdraw them as needed. Player Interaction: Players participate by guessing the dice roll outcome and placing bets. This tutorial assumes you have a basic understanding of Sui Move and focuses on introducing new concepts through practical implementation. Before dive into the code, let’s explore the key concepts you’ll encounter: 1.1 Adding Dependencies: To use tokens from another contract (e.g., a faucet token contract), you need to add it as a dependency in your project. This is done by updating the Move.toml file of your contract: [dependencies] coin_duck = { local = "../coin_duck"”} Here, coin_duck is the faucet token contract located at the specified path. The depended contract must also specify its published-at field in its own Move.toml with the package ID obtained upon publication, like so: rust published-at = "packageId_from_publication" 1.2 Using Assertions Assertions ensure that certain conditions are met during contract execution. The assert! macro checks a condition and, if it fails, throws an error and halts execution. This is useful for preventing invalid states, such as betting more than a player’s balance. 1.3 Generating Random Numbers Fairness in the dice game relies on random number generation. Sui Move provides the random module for this purpose. You’ll create a RandomGenerator object and use it to generate a random number between 1 and 6, simulating a dice roll. 1.4 Working with Coin and Balance In Sui Move, tokens are managed using the coin and balance modules: Coin: A wrapper around Balance, used for transferring tokens. Balance: Represents the actual token amount, allowing operations like splitting and merging. Key methods include: coin::value(in_coin): Returns the total value of a Coin object. coin::take(&mut balance, amount, ctx): Extracts a specified amount from a Balance to create a Coin. in_coin.balance_mut().split(amount): Splits a specified amount from a Coin’s Balance. balance.join(balance): Merges one Balance into another. These operations will be used to manage the game’s prize pool and player bets. The Dice Game Contract Here’s the complete code for the dice game contract, followed by detailed explanations: /// Game: Dice rolling. Players bet and guess the number. If correct, they win an amount equal to their bet; if incorrect, the bet goes to the game pool. module game_duck:game_duck; use sui::balance::{Self, Balance}; use sui::coin::{Self, Coin}; use sui::random::{Random, new_generator, generate_u8_in_range}; use coin_duck::duckfaucet::DUCKFAUCET; const ErrorUserInsufficient: u64 = 0x101; const ErrorGameInsufficient: u64 = 0x102; public struct Game has key { id: UID, pool_amount: Balance, } public struct Admin has key { id: UID, } fun init(ctx: &mut TxContext) { let game = Game { id: object::new(ctx), pool_amount: balance::zero() }; transfer::share_object(game); let admin = Admin { id: object::new(ctx) }; transfer::transfer(admin, ctx.sender()); } public entry fun addCoinToGamePool(game: &mut Game, in_coin: &mut Coin, amount: u64, _: &mut TxContext) { let value = coin::value(in_coin); assert!(amount = amount, ErrorGameInsufficient); let coin = coin::take(&mut game.pool_amount, amount, ctx); transfer::public_transfer(coin, ctx.sender()); } entry fun play(game: &mut Game, random: &Random, guess_num: u8, in_coin: &mut Coin, amount: u64, ctx: &mut TxContext) { assert!(game.pool_amount.value() >= (amount * 3), ErrorGameInsufficient); assert!(in_coin.balance().value() >= amount, ErrorUserInsufficient); let mut g = new_generator(random, ctx); let win_num = generate_u8_in_range(&mut g, 1, 6); if (win_num == guess_num) { let reward_coin = coin::take(&mut game.pool_amount, amount, ctx); in_coin.join(reward_coin); } else { addCoinToGamePool(game, in_coin, amount, ctx); } } Code Breakdown structure Game: A shared object with a unique id and a pool_amount (Balance) to store the prize pool. Admin: A key object owned by the admin for Initialization (init)managing the pool. Initialization (init): Creates a Game object with an empty prize pool and shares it publicly. Creates an Admin object and transfers it to the contract creator. Adding to the Pool (addCoinToGamePool) Takes a specified amount from the admin’s in_coin. Uses assert! to ensure the coin has sufficient value. Splits the amount from in_coin’s Balance and merges it into the game’s pool_amount. Outcome: Win: If the guess matches the roll, a reward equal to the bet is taken from the pool and merged into the player’s in_coin. Lose: If incorrect, the bet is deducted from in_coin and added to the pool via addCoinToGamePool.
3
Posts
147- Discussionyhant3284Mar 16, 2025
How can I access my wallet made with Google on a new browser?
So, I initially signed up and created my wallet using Google, and now I'm having trouble accessing my secret phrase. I want to open my wallet on another browser but can't seem to find a way to do it without a passphrase. How should I proceed?
- Sui
01 - DiscussionLokie10Mar 16, 2025
Step by step guide to create a Suiet wallet
Step by step guide to create a Suiet wallet: Download suiet extension: https://suiet.app/ After successful installation, click on the Suiet icon in your browser and select "Create New". Set a strong password to protect your wallet. Write down and save your recovery phrase in a safe place. This phrase is needed to recover your wallet if needed Done
- Sui
00 - DiscussionLokie10Mar 16, 2025
menjelang walrus TGE
apakah walrus akan jp guys ? coba tulis prediksi kalian dikolom komentar 😁
- Sui
00 - ArticleBahador59Mar 15, 2025
Journey as a SUI Move smart contract developer
In today's article, I wanna dive into a roadmap suggestion for those who like to enter into the SUI move development way. 1. Understand Blockchain Fundamentals Core Concepts:* Familiarize yourself with key blockchain concepts such as decentralization, consensus mechanisms, cryptographic primitives, and smart contracts. SUI Blockchain Overview:* Learn about what makes SUI unique—its object-centric data model, performance goals, and how it handles state management. 2. Learn the Move Language Language Basics:* Start with the fundamentals of the Move programming language. Focus on: Resource Types:* How resources work to ensure safety and ownership. Modules and Structs:* How to define modules and data structures. Entry Functions:* How transactions are executed through designated entry points. Recommended Resources: Utilize official Move language tutorials, documentation, and sample code repositories. 3. Set Up Your Development Environment Tools and CLI:* Install the SUI CLI and set up the Move toolchain on your local machine. Local Test Environment:* Configure a local SUI development network or use available testnets. This helps you experiment with smart contract deployment and testing before going live. IDE & Debugging:* Choose an Integrated Development Environment (IDE) that supports Move (for example, VSCode with Move extensions) and get familiar with debugging and testing your contracts. 4. Build Your First Simple Contract Hands-on Tutorials:* Start with a simple project such as a token contract. This will allow you to apply the basic Move constructs. Explore SUI-Specific Patterns:* Work with SUI’s object model and learn how transactions are processed within the SUI ecosystem. Documentation & Examples:* Leverage SUI’s developer documentation and sample projects to understand best practices. 5. Deep Dive into SUI-Specific Features Object-Centric Model:* Understand how SUI treats objects differently from account-based blockchains like Ethereum. Gas & Transaction Model:* Study how gas fees are calculated and how transaction execution is managed in SUI. State Management:* Learn about SUI’s approach to state storage, modular updates, and object lifecycle management. 6. Testing, Debugging, and Deployment Unit and Integration Testing:* Write tests to verify the logic and safety of your smart contracts. Make sure you cover edge cases and potential vulnerabilities. Local and Testnet Deployment:* Deploy your contracts in a controlled environment to see how they perform in real conditions. Tooling:* Utilize SUI’s debugging tools and logging features to iterate and improve your code. 7. Security Best Practices and Code Audits Understand Common Pitfalls:* Study common security vulnerabilities in smart contracts (e.g., reentrancy, improper access controls) and how Move’s design mitigates them. Code Reviews:* Get involved in community code reviews or collaborate with peers to audit and improve your code. Formal Verification:* Explore any available formal verification tools for Move to mathematically prove the correctness of your contracts. 8. Join the SUI Developer Community Community Channels:* Engage with other developers via forums, Discord channels, or community calls. Sharing experiences and challenges is invaluable. Open Source Contributions:* Contribute to open source projects or developer repositories related to SUI and Move. Stay Updated:* Follow SUI and Move blogs, GitHub repositories, and social media channels to keep track of new developments, updates, and best practices. 9. Explore Advanced Topics Complex Applications:* As you become more comfortable, experiment with more advanced smart contract designs such as decentralized finance (DeFi) protocols, NFTs, or multi-signature wallets. Interoperability and Integration:* Learn how to interact with other smart contracts and integrate SUI Move modules with off-chain systems. Performance and Scalability:* Explore techniques to optimize your contracts for speed and cost-efficiency on the SUI blockchain. 10. Build a Portfolio and Keep Practicing Showcase Projects:* Develop and document a series of projects that demonstrate your understanding and expertise. Continuous Learning:* Blockchain and Move are evolving rapidly—make continuous learning a habit by revisiting documentation, attending workshops, and participating in hackathons. Feedback Loop:* Use community feedback to refine your skills and stay ahead of the curve in smart contract development. Although the above Items are suggestions and are not the only way to turn into an SUI developer, I hope it is helpful for you guys. Happy coding. Happy SUIng!
- Sui
- SDKs and Developer Tools
- Move
0 - DiscussionCarlkawIy183Mar 15, 2025
Why was my SuiPlay0x1 NFT sent to a different address?
Hello everyone, I purchased SuiPlay0x1 through crypto payment using $SUI, but my NFT was delivered to an address that isn't my wallet. I was worried that I might have been scammed by a fake website. Does anyone know what could have gone wrong and how can I fix this?
- NFT Ecosystem
01 - DiscussionMar 14, 2025
Can I access my SUI wallet recovery key via Apple ID?
I recently signed up or logged in to the SUI wallet using my Apple ID, but I've hit a snag. I noticed I can't add my account to the SUI desktop extension because it doesn't support Apple ID integration yet. This got me worried about my private or recovery key. Is there any possible way to retrieve my recovery key? Or is it somehow tied to my Apple ID account?
- Security Protocols
01 - DiscussionMar 14, 2025
How to access Sui Wallet on a new device without a passphrase?
I recently signed up for Sui Wallet using my Google account, but I don't have a passphrase. Now I want to access my wallet from a different device. Can someone guide me on how to log into my wallet on a new device?
- Sui
02 - Expert Q&ATheoremus113Mar 13, 2025
Troubleshooting Enoki API request failures
I've been facing a problem with the Enoki API failing requests for about a week now. I tried turning off my VPN, but it didn't help. Could anyone suggest what steps I should take to resolve this issue?
- Sui
02 - DiscussionMar 13, 2025
Can't click unstake button for SUI on OKX Earn
I'm facing a problem with unstaking my SUI tokens on OKX Earn. The unstake button is not clickable. What should I do to unstake my SUI tokens?
- Sui
01 - Discussionskywinder204Mar 13, 2025
Where to learn about staking risks with Sui?
I'm thinking about staking my Sui holdings but want to know what risks are involved. I found a link but need more info.
- Security Protocols
01
- Sui
- SDKs and Developer Tools
- Architecture
- Move
- NFT Ecosystem
- Transaction Processing
- Security Protocols