Verona 백서

Verona

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 54쪽 중 50쪽

strict ceiling on CPU computations, as users must bear the cost for the utilized cycles. * **Disk Usage**: All disk access in CosmWasm contracts is channeled through reads and writes on the KVStore. The Cosmos SDK already enforces gas payments for KVStore access. Given that all disk interactions within the contracts are implemented through callbacks into the SDK, the associated charges are applied accordingly. In cases where CosmWasm is integrated into an alternate runtime, it becomes essential to ensure appropriate gas charges are imposed for access to disk resources within that runtime as well. ## Insights Gained from Ethereum To develop resilient smart contract functionalities, it's essential to draw insights from both the achievements and limitations of Ethereum. Therefore, we can examine the most prevalent attack vectors in Ethereum, along with their mitigation strategies, to assess their applicability to Cosmwasm. Many of these attack vectors have been inherently addressed in Cosmwasm's design, while some challenges still exist. Plans are in place to address the remaining issues. * **Reentrancy**: As previously discussed, CosmWasm mitigates reentrancy attacks by returning messages to execute other contracts within the same atomic operation, but after the contract's execution has completed. This approach, rooted in the actor model, eliminates the possibility of reentrancy attacks, ensuring there is never a volatile state during contract calls. * **Arithmetic Under/Overflows**: Rust in CosmWasm allows developers to set overflow-checks = true in the Cargo manifest, causing the program to abort if any overflow is detected. There is no option to bypass safe math. * **Delegate Call**: CosmWasm does not incorporate Delegate Call logic. While modules can be imported, they are linked together at compile time, enabling comprehensive testing of the entire contract as a unified entity. There are no concealed entry points within a contract's logic. * **Default Visibilities**: Instead of automatically generating entry points for every function/method in the code or assuming public visibility if not specified, developers must explicitly define a list of messages to be handled and dispatch them to the relevant functions. This approach eliminates the risk of accidentally exposing a function. * **Short Address/Parameter Attack**: This exploit capitalizes on the RLP encoding mechanism and fixed 32-byte stack size, which does not apply to CosmWasm's type-checking JSON parser. * **Unchecked CALL Return Values**: CosmWasm does not allow direct calls to other contracts; instead, sent messages are dispatched by a router. The router verifies the result of all messages, and if any message in the chain returns an error, the entire transaction is aborted, and state changes are rolled back. This ensures safe execution and rollback of states in case of issues when scheduling calls to other contracts. * **Uninitialized Storage Pointers**: CosmWasm requires explicit loading of variables from storage, as it does not automatically initialize them. Rust itself does not permit uninitialized variables, emphasizing the explicitness of storage handling. * **Floating Points and Precision**: Both Solidity and CosmWasm avoid floating-point operations due to potential non-determinism in rounding, which can vary depending on the CPU. In CosmWasm, you can seamlessly import Rust packages and select a suitable one for internal use. For instance, you can utilize "rust\_decimal," a pure Rust Decimal implementation suitable for precise financial calculations, or employ fixed-point decimal math, supporting up to 128-bit numbers, accommodating a wide range of use cases. * **Tx.Origin Authentication**: CosmWasm refrains from exposing tx.origin, relying solely on the contract or the user directly calling the contract through params.message.signer. This design ensures that only one value needs to be compared, eliminating the possibility of relying on incorrect authentication methods. \ \ <br> # Tutorials Our tutorials are here to guide you through essential concepts and practical examples. Whether you're a beginner or an experienced developer, our tutorials are designed to help you master key aspects. Sections include, but are not limited to: ## [Testing Functions](/en/others/archived/cosmwasm-resources/tutorials/testing) Delving into the realm of testing. We'll equip you with the knowledge and tools to execute effective tests, ensuring the robustness and reliability of your code. Key topics within this section include: **Testing Query Functions**: Rigorously test query functions by invoking them with diverse parameters and validating the results. This process guarantees that users can interact with your smart contract as intended. **Testing Error Handling and Edge Cases**: Strategies to encompass error-handling scenarios and edge cases within your tests. This practice ensures that your smart contract behaves correctly even in unexpected situations or when presented with unforeseen inputs. **Testing with Custom Mock Dependencies**: Understanding of creating custom mock dependencies for your tests, allowing you to simulate various scenarios and conditions that may arise during smart contract execution. This approach aids in verifying the contract's behavior under a spectrum of circumstances. ## [Storage and State Modeling](/en/others/archived/cosmwasm-resources/tutorials/key-value-storage) The intricacies of storage and state modeling. Learn how to efficiently store and manipulate data within your applications, and you'll acquire insights into database systems, data structures, and more. Some of the key topics in this section include: * Understanding how storage in Cosmos-SDK is built upon a key-value store. * Exploring the role of indexes as key structures that enable efficient iteration over primary keys while providing valuable information. ## [CosmWasm By Example](/en/others/archived/cosmwasm-resources/tutorials/cosmwasm-by-example) This section provides a deep dive into CosmWasm through practical examples. You'll explore mathematical concepts, the process of instantiating a CosmWasm contract, timelocks, crowdfunding mechanisms, response handling, and more. \ <br> # Testing This section provides insights into coding and contract testing practices. It covers various aspects related to cosmwasm smart contracts and offers valuable best practices and tips for effective testing: #### 1. Testing Query Functions Learn how to write and execute unit tests for cosmwasm smart contract query functions. Best practices in this area involve testing query functions with a range of parameters to validate their responses. This approach ensures that users can seamlessly interact with the smart contract as intended. #### 2. Testing Error Handling and Edge Cases Discover the importance of testing error handling scenarios and edge cases within your contract. This testing ensures that your smart contract behaves correctly when faced with unexpected situations or unusual inputs, thereby enhancing its robustness and reliability. #### 3. Testing with Custom Mock Dependencies Explore the concept of creating custom mock dependencies for your tests. These dependencies simulate various scenarios and conditions that may arise during the execution of your smart contract. By doing so, you can verify your contract's behavior under diverse circumstances, ensuring its adaptability and effectiveness. \ For comprehensive guidance on conducting unit testing for cosmwasm smart contracts, refer to the following tutorial linked [here](https://vimeo.com/457705991). By this stage, your code should be successfully compiled, even though you may not have yet confirmed its functionality. While it's possible to deploy the code to the blockchain after every change, this approach can be time-consuming and inefficient. It's also essential to maintain the contract's integrity and ensure thorough testing for future modifications. ``` #[cfg(test)] mod tests { use super::*; use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{attr, coins, CosmosMsg}; ``` You can choose whether to house your tests and code within the same file or separate files. An example can be found [here](https://github.com/deus-labs/cw-contracts/blob/main/contracts/simple-option/src/contract.rs). ### Test Initialization For each test, it is important to mock specific variables, such as block time and state. Writing a function for easy setup can make this process more manageable ``` #[test] fn proper_initialization() { let mut deps = mock_dependencies(&[]); let msg = InitMsg { counter_offer: coins(40, "ETH"), expires: 100_000, }; let info = mock_info("creator", &coins(1, "BTC")); // we can just call .unwrap() to assert this was a success let res = init(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // it worked, let's query the state let res = query_config(deps.as_ref()).unwrap(); assert_eq!(100_000, res.expires); assert_eq!("creator", res.owner.as_str()); assert_eq!("creator", res.creator.as_str()); assert_eq!(coins(1, "BTC"), res.collateral); assert_eq!(coins(40, "ETH"), res.counter_offer); } ``` Excellent, you've established a foundational test environment initializer. This one is relatively straightforward, allowing you to pass variables to the function and implement diverse adjustments. For additional customization options, consider exploring [cosmwasm-plus](https://github.com/CosmWasm/cw-plus). ### Mocking Dependencies, Environment, and Message Information We should enhance three key mocking tools: ``` /// All external requirements that can be injected for unit tests. /// It sets the given balance for the contract itself, nothing else pub fn mock_dependencies( contract_balance: &[Coin], ) -> OwnedDeps<MockStorage, MockApi, MockQuerier> { let contract_addr = HumanAddr::from(MOCK_CONTRACT_ADDR); OwnedDeps { storage: MockStorage::default(), api: MockApi::default(), querier: MockQuerier::new(&[(&contract_addr, contract_balance)]), } } ``` ### mock\_dependencies is used for mocking storage, api, and querier. ``` /// Returns a default environment with height, time, chain_id, and contract address. /// You can submit as is to most contracts, or modify height/time if you want to /// test for expiration. /// /// This is intended for use in test code only. pub fn mock_env() -> Env { Env { block: BlockInfo { height: 12_345, time: 1_571_797_419, time_nanos: 879305533, chain_id: "xion-testnet-2".to_string(), }, contract: ContractInfo { address: HumanAddr::from(MOCK_CONTRACT_ADDR), }, } } ``` ### mock\_env is used for mocking blocks, and contract environments. ``` /// Just set sender and sent funds for the message. /// This is intended for use in test code only. pub fn mock_info<U: Into<HumanAddr>>(sender: U, sent: &[Coin]) -> MessageInfo { MessageInfo { sender: sender.into(), sent_funds: sent.to_vec(), } } ``` ### mock\_info is used for mocking transaction environments. Test Transfer Handler ``` #[test] fn transfer() { let mut deps = mock_dependencies(&[]); let msg = InitMsg { counter_offer: coins(40, "ETH"), expires: 100_000, }; let info = mock_info("creator", &coins(1, "BTC")); // we can just call .unwrap() to assert this was a success let res = init(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); // random cannot transfer let info = mock_info("anyone", &[]); let err = handle_transfer(deps.as_mut(), mock_env(), info, HumanAddr::from("anyone")) .unwrap_err(); match err { ContractError::Unauthorized {} => {} e => panic!("unexpected error: {}", e), } // owner can transfer let info = mock_info("creator", &[]); let res = handle_transfer(deps.as_mut(), mock_env(), info, HumanAddr::from("someone")).unwrap(); assert_eq!(res.attributes.len(), 2); assert_eq!(res.attributes[0], attr("action", "transfer")); // check updated properly let res = query_config(deps.as_ref()).unwrap(); assert_eq!("someone", res.owner.as_str()); assert_eq!("creator", res.creator.as_str()); } ``` Test Execute ``` #[test] fn execute() { let mut deps = mock_dependencies(&[]); let amount = coins(40, "ETH"); let collateral = coins(1, "BTC"); let expires = 100_000; let msg = InitMsg { counter_offer: amount.clone(), expires: expires, }; let info = mock_info("creator", &collateral); // we can just call .unwrap() to assert this was a success let _ = init(deps.as_mut(), mock_env(), info, msg).unwrap(); // set new owner let info = mock_info("creator", &[]); let _ = handle_transfer(deps.as_mut(), mock_env(), info, HumanAddr::from("owner")).unwrap(); // random cannot execute let info = mock_info("creator", &amount); let err = handle_execute(deps.as_mut(), mock_env(), info).unwrap_err(); match err { ContractError::Unauthorized {} => {} e => panic!("unexpected error: {}", e), } // expired cannot execute let info = mock_info("owner", &amount); let mut env = mock_env(); env.block.height = 200_000; let err = handle_execute(deps.as_mut(), env, info).unwrap_err(); match err { ContractError::OptionExpired { expired } => assert_eq!(expired, expires), e => panic!("unexpected error: {}", e), } // bad counter_offer cannot execute let msg_offer = coins(39, "ETH"); let info = mock_info("owner", &msg_offer); let err = handle_execute(deps.as_mut(), mock_env(), info).unwrap_err(); match err { ContractError::CounterOfferMismatch { offer, counter_offer, } => { assert_eq!(msg_offer, offer); assert_eq!(amount, counter_offer); } e => panic!("unexpected error: {}", e), } // proper execution let info = mock_info("owner", &amount); let res = handle_execute(deps.as_mut(), mock_env(), info).unwrap(); assert_eq!(res.messages.len(), 2); assert_eq!( res.messages[0], CosmosMsg::Bank(BankMsg::Send { from_address: MOCK_CONTRACT_ADDR.into(), to_address: "creator".into(), amount, }) ); assert_eq!( res.messages[1], CosmosMsg::Bank(BankMsg::Send { from_address: MOCK_CONTRACT_ADDR.into(), to_address: "owner".into(), amount: collateral, }) ); // check deleted let _ = query_config(deps.as_ref()).unwrap_err(); } ``` Now you are prepared to run the tests: ``` cargo test ``` # Key Value Storage Understanding the Functionality of CW Key-Value Storage As previously highlighted, the key-value storage mechanism in Cosmos-SDK operates on the premise that each value is stored under a corresponding key. This storage system is organized within a tree structure, specifically following the cosmos/iavl tree model. To understand the workings of this key-value storage approach, let's delve into its mechanics: <br> <figure><img src="https://3630978198-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FB5Z5ijJgMx0GJO3l1Il9%2Fuploads%2F7pj4gTQUoVHWmqPlZUKO%2FAVL-tree-.png?alt=media&amp;token=40d2fd32-1558-46f4-8ced-5292da1649a4" alt=""><figcaption><p><a href="https://github.com/cosmos/iavl">cosmos/iavl </a>tree model</p></figcaption></figure> In order to facilitate your understanding of KV store iterators, let's employ a highly simplified analogy. Imagine letters enclosed within circles, where each letter represents a key, and each key is associated with a corresponding value. Let's continue by considering a set of saved key-value pairs: **J** -> value1 **JF** -> value2 **JPV** -> value3 **JPVA** -> value4 **JPVD** -> value5 **JPVX** -> value6 Fetching a Single Value with a Known Key is an Efficient O(1) Operation. However, When Navigating Through a Set of Keys, It's Achieved Through Prefix-Based Iteration. **J** key, prefixes: **J** **JF** key, prefixes: **J, JF** **JPV** key, prefixes: **J,JP, JPV** **JPVA** key, prefixes: **J,JP, JPV, JPVA** **JPVD** key, prefixes: **J,JP, JPV, JPVD** **JPVX** key, prefixes: **J,JP, JPV, JPVX** range(**J**) returns all keys because all have **J** as prefix range(**JF**) returns only **JF** \ This is where it gets intriguing.: range(**JPV**) returns **JPV**, **JPVA**, **JPVD**, **JPVX** in order As you can see **J** or **JF** is not returned, because values after JPV is requested. But Why Was **JPVA** Returned? The keys stored in the database are in the form of fixed-length strings. For instance, if we assume that keys are uniformly 8 characters in length, the storage representation of "**JPVA**" would be "**JPVA0000**". When a range request is initiated, the underlying process systematically iterates over all keys within a specific range, starting from "**JPV00000**" and concluding at "**JPVFFFFF**." In this case, "**JPVA**" (among other keys) naturally falls within this range. It's important to note that a range query can also be executed in reverse, offering flexibility in key retrieval. We have two fundamental operations at play: Retrieving Individual Values and Iterating There are just two core functionalities in operation: fetching a single value or navigating through a collection of keys. While data structures often require intricate relationships, we work within the confines of this constrained key-value storage, where these two fundamental operations are paramount. This is accomplished through the construction of indexes.<br> # Indexes Indexes play a vital role in facilitating the process of iterating through primary keys while providing valuable information. Let's delve into a model that involves multiple tokens within a system, with each token being uniquely owned. In this context, it is essential to establish an association between an owner and a token, enabling seamless querying of tokens based on their respective owners. ``` struct Token { pub owner: Addr, pub ticker: String } ``` Tokens are distinguishable through an auto-incremented key, serving as the primary identifier, guaranteeing the uniqueness of each token. ``` (TokenPK) -> Token ``` The owner's index would have the following structure: ``` (owner, TokenPK) -> Token ``` TokenPK is a reference to Token data, and the owner:TokenPK key is a reference to a specific Token. By executing two database queries, one can access the Token data. To obtain all the tokens associated with a specific owner, a prefix range query, as depicted above, can be employed. ``` pub const TOKENS: Map<U8Key, Token> = Map::new("tokens"); // (owner Address, Token PK) -> u8 key pub const OWNER_INDEX: Map<(&Addr, U8Key), &[u8]> = Map::new("owner_tokenpk"); ``` Utilizing the owner information as the key streamlines token access. Nonetheless, it's important to note that any alterations to the state of TOKENS necessitate corresponding updates to the owner field. This concept aligns with storage-plus indexing. The previously mentioned solution works, but its efficiency is compromised by the extensive code complexity. This is where storage-plus/IndexedMap comes into the picture. IndexedMap is a storage manager that incorporates built-in indexing capabilities. It encompasses two types of indexes: **Unique Indexes** and **Multi Indexes**. ### Unique Indexes Maintaining the exclusivity of a data field in a database is a typical necessity. UniqueIndex is an indexing utility that aids in accomplishing this functionality. ``` #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Token { pub owner: Addr, pub ticker: String, pub identifier: u8, // <---- unique value } // TokenIndexes structs keeps a list of indexers pub struct TokenIndexes<'a> { // token.identifier pub identifier: UniqueIndex<'a, U8Key, Token>, } // IndexList is just boilerplate code for fetching a struct's indexes impl<'a> IndexList<Token> for TokenIndexes<'a> { fn get_indexes(&'_ self) -> Box<dyn Iterator<Item=&'_ dyn Index<Token>> + '_> { let v: Vec<&dyn Index<Token>> = vec![&self.identifier]; Box::new(v.into_iter()) } } // tokens() is the storage access function. pub fn tokens<'a>() -> IndexedMap<'a,
프로젝트로 돌아가기