bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 54쪽 중 48쪽
ry_wasm_smart(mocked_contract_addr.clone(), &config_msg)
.unwrap();
asserteq!(count_response.count, 1)
// Now let's reset the counter with the other ExecuteMsg
let msg = ExecuteMsg::Reset {}
let _ = router.execute_contract(
owner.clone(),
mocked_contract_addr.clone(),
&msg,
&[],
)
.unwrap();
// And again use the available contract query to verify the result
// Query the contract to verify the counter was incremented
let config_msg = QueryMsg::Count{};
let count_response: CountResponse = router
.wrap()
.query_wasm_smart(mocked_contract_addr.clone(), &config_msg)
.unwrap();
asserteq!(count_response.count, 0)
}
```
## **Simulating External Contracts**
#### Understanding the Scope of Mocking
If you've reviewed the previous section, you likely have a grasp of the effort involved in mocking your own contracts. However, as you proceed with mocking and testing, you might encounter a challenge when your contracts interact with external services like Terraswap, Anchor, or other IBC-related services. Rest assured, it's a surmountable issue.
**Addressing External Services**
You might initially attempt to mock one of these services using the same method outlined earlier, only to realize that you lack access to their contract code. Contract code is essential for importing functions like execute, instantiate, and Query. In the case of protocols, their Rust packages typically don't include contract code; they provide what's necessary for interaction, such as messages and certain helper functions.
**The Path Forward**
Despite these challenges, there's still a path forward. You can make progress by crafting a simplified mock of the external service you're engaging with. The process parallels that of mocking your contracts, but you'll need to implement all the required functionality. The task is eased by the ability to create a more compact ExecuteMsg containing only the functions you intend to use or a mock Query handler featuring only the queries required. Below, you'll find an example of a mock for third-party contract:
```
pub fn contract_ping_pong_mock() -> Box<dyn Contract<Empty>> {
let contract = ContractWrapper::new(
|deps, _, info, msg: MockExecuteMsg| -> StdResult<Response> {
match msg {
MockExecuteMsg::Receive(Cw20ReceiveMsg {
sender: _,
amount: _,
msg,
}) => {
let received: PingMsg = from_binary(&msg)?;
Ok(Response::new()
.add_attribute("action", "pong")
.set_data(to_binary(&received.payload)?))
}
}})}
|_, _, msg: MockQueryMsg| -> StdResult<Binary> {
match msg {
MockQueryMsg::Pair {} => Ok(to_binary(&mock_pair_info())?),
```
**Tailoring Your Mocked Contracts to Fit Your Needs**
In the process of defining your custom mocked contracts, you enjoy a considerable degree of flexibility. You can conveniently skip the inclusion of dependencies, environmental variables, and information variables that go unused, simply by using an underscore (\_). Furthermore, you hold the power to furnish any desired responses for specific ExecuteMsg or Query requests. The real challenge lies in effectively mocking these diverse services.
<br>
# Architecture of Multi-Chain Contracts
CosmWasm is purpose-built to serve as a multi-chain solution for smart contracts, distinctively crafted within the Cosmos ecosystem. Unlike isolated chains, it's tailored for networks of interconnected blockchains. But what precisely does "multi-chain" signify?
## Diverse Chains, Uniform Contracts
All CosmWasm code is deliberately crafted to remain agnostic regarding the specific details of the underlying blockchain. When you develop a CosmWasm contract, it becomes compatible with various chains within the expansive Cosmos ecosystem.
## Inter-Blockchain Contracts
CosmWasm contracts leverage the Inter-Blockchain Communication protocol (IBC), enabling seamless authentication and data exchange between different blockchains. IBC offers an open and permissionless method for transmitting data packets across blockchains, empowering you to write code on one chain that can execute transactions on another. To facilitate this capability, CosmWasm fully adopts the actor model, ensuring that code is inherently designed for IBC utilization. Consequently, messages in CosmWasm operate on a "fire-and-forget" principle, eliminating the need to await promises and mitigating concerns related to race conditions and reentrancy attacks. By incorporating IBC primitives into CosmWasm's libraries, you can unleash the extensive potential of inter-chain messaging and execution.
## Seamless Integration
CosmWasm's design leans towards that of a library rather than a comprehensive framework, resulting in minimal API dependencies. This flexibility empowers you to harness the capabilities of CosmWasm without becoming overly reliant on it.
This approach offers two noteworthy advantages:
1. Simplified Support for Multiple Languages: The design simplifies the process of adding support for multiple programming languages when creating smart contracts.
2. Versatility Beyond Cosmos SDK: Because it imposes minimal requirements on the host system, CosmWasm can be seamlessly integrated into various frameworks, not limited solely to the Cosmos SDK. The core runtime logic, cosmwasm-vm, is coded in Rust, with wasmvm providing a versatile Go binding. This adaptability allows CosmWasm to serve as a robust foundation for your smart contracts and decentralized applications, ensuring they can be effortlessly migrated to different blockchains and programming languages.
# Actor Models for Contract Calls
The actor model is a design pattern used to build reliable, distributed systems. The fundamental principles are that each Actor has exclusive access to its own internal state and that Actors cannot call each other directly. Instead, they dispatch messages through a Dispatcher, which maintains the system's state and maps addresses to code and storage. Fundamentally, the Actor pattern can be encapsulated in this interface:
```
pub trait Actor {
fn handle(msgPayload: &[u8]) -> Vec<Msg>;
}
pub struct Msg {
pub destination: Vec<u8>,
pub payload: Vec<u8>,
}
```
This is the basic model that was used to model contracts in CosmWasm.
A user can see the same influence in the function:
`pub fn handle<T: Storage>(store: &mut T, params: Params, msg: Vec<u8>) -> Result<Response>`
The response contains a Rust Vec and some metadata, while store provides access to the contract's internal state and params refer to the global immutable context.
From this basic design, a few other useful aspects can be derived:
* First, there is a loose coupling between Actors, limited to the format of the data packets (the recipient must support a superset of what a user sends). There are no complex APIs or function pointers to pass around. This is much like using REST or RPC calls as a boundary between services, which is a scalable way to compose systems from multiple vendors.
* Secondly, each Actor can effectively run on its own thread, with its own queue. This enables both concurrency and serialized execution within each actor. This means that the Handle method above cannot be executed in the middle of a previously executed Handle call. Handle is a synchronous call and returns before the Actor can process the next message. This implies that CosmWasm prevents reentrancy attacks by design.
> Info:
>
> The contract can directly access other contracts' state through a technique called raw querying. Raw queries are used for achieving better performance in query execution and raw queries are also used if the performance of the API query model is not so good.
Another important aspect related to CosmWasm is locality: For two actors to communicate, a contract creator or user needs to send a message to the actor. Actors can only communicate with other actors after they have received the other actor's address. This is a flexible way to set up topologies in a distributed manner, and only requires you to hard-code the data format to pass to such addresses. Once some standard interfaces are established (such as ERC20, ERC721, ENS, etc.), we can support composability between large classes of contracts and different backing codes.
### Security benefits
By enforcing private internal state, a given contract can guarantee all valid transitions in its internal state. This is in contrast to the capabilities model used in Cosmos SDK, where trusted modules are passed a StoreKey in their constructor, which allows full read and write access to the storage of other modules. In the Cosmos SDK, we can audit the modules before calling them, and safely pass in such a powerful set of rights at compile time. However, in a smart contract system, there are no compile-time checks, and we need to establish stricter boundaries between contracts. This allows us to comprehensively reason over all possible transitions in a contract's state (and use quick-check-like methods to test it).
As mentioned above, serialized execution prevents all concurrent executions of a contract's code. By enforcing serialized execution, the contract will write all changes to storage before exiting and have a proper view when the next message is processed.
REENTRANCY ATTACK
The way that CosmWasm is built, resembles having an automatic mutex over the entire contract code. This prevents reentrancy attacks, which are the most common attack vectors for smart contracts built on Ethereum. An example of a reentrancy attack that is prevented by design in CosmWasm is the following: Contract A calls into Contract B, which calls back into Contract A. There may be local changes in memory in Contract A from the first call (eg. deduct a balance), that are not yet persisted, so the second call can use the outdated state a second time (eg. authorize sending a balance twice).
### Atomic execution
One problem with sending messages is atomically committing a state change over two contracts. There are many cases where we want to ensure that all returned messages were properly processed before committing our state. In order to tackle this issue, before executing a Msg that came from an external transaction, we create a SavePoint of the global data store and pass in a subset to the first contract. We then execute all returned messages inside the same sub-transaction. If all messages succeed, we can commit the sub-transaction. If any message fails (or we run out of gas), we abort execution and roll back the state to before the first contract was executed.
This allows us to optimistically update code, relying on rollback for error handling. For example, if an exchange matches a trade between two "ERC20" tokens, it can fulfill the offer and return two messages to move token A to the buyer and token B to the seller. ERC20 tokens use a concept of allowance, so the owner "allows" the exchange to move up to X tokens from their account. When executing the returned messages, it turns out that the buyer doesn't have sufficient token B (or provided an insufficient allowance). This message will fail, causing the entire sequence to be reverted. If the transaction fails, the offer is not marked as fulfilled, and no tokens change hands.
While many developers may be more comfortable thinking about directly calling the other contract in their execution path and handling the errors, almost all the same cases can be achieved with an optimistic update and return approach. Furthermore, there is no room for making mistakes in the contract's error handling code.
### Dynamically linking host modules
The aspects of locality and loose coupling mean that we don't even need to link to other CosmWasm contracts. We can send messages to anything for which the Dispatcher has an address. For example, we can return a SendMsg, which will be processed by the native x/bank module in Cosmos SDK, moving native tokens. As we define standard interfaces for composability, we can define interfaces to call into core modules and then pass in the address to the native module in the contract constructor.
### Inter blockchain messaging
Since the Actor model doesn't attempt to make synchronous calls to another contract, and instead just returns a message "to be executed", it is a good match for making cross-chain contract calls using IBC. The only caveat here is that the atomic execution guarantee we provided above no longer applies. The other call will not be made by the same dispatcher, so we need to store an intermediate state in the contract itself. That means a state that cannot be changed until the result of the IBC call is known. After the result of the IBC call is known, the intermediate state can then be safely applied or reverted.
For example, if we want to move tokens from chain A to chain B, we would first prepare to execute the following transactions:
* Contract A must reduce the token supply of the sender.
* Contract A must create an "escrow" for those tokens linked to the IBC message ID, sender, and receiving chain.
* Contract A commits state and returns a message to initiate an IBC transaction to chain B
* If the IBC send fails, then the contract is atomically reverted as above.
After some time, a success or error/timeout message will be returned from the IBC module to the token contract:
* Contract A would validate the message came from the IBC handler (authorization) and refers to a known IBC message ID it has in escrow.
* If it was a success, the escrow would be deleted and the escrowed tokens would be placed in an account for "Chain B" (meaning that only a future IBC message from Chain B may release them).
* If it was an error, the escrow would be deleted and the escrowed tokens would be returned to the account of the original sender.
Users can imagine a similar scenario in cases of moving NFT ownership, cross-chain staking, etc.
\\
# Names and Addresses
## Names and addresses <a href="#names-and-addresses" id="names-and-addresses"></a>
Blockchains use addresses to identify external actors through a hash of a public key. On-chain addresses are represented using a concise, immutable binary format, typically 20 or 32 bytes long, often derived from a hashing function.
Binary addresses are typically represented in a human-readable format using two common notations: IPv4 and IPv6 addresses. These addresses are used to identify devices on a network. Here are two examples of each:
#### IPv4 Addresses:
1. **IPv4 Decimal-Dotted Notation**: This is the most common way to represent IPv4 addresses. It consists of four decimal numbers separated by periods (dots), where each number can range from 0 to 255. For example: `192.168.1.1`
2. **IPv4 CIDR Notation**: Classless Inter-Domain Routing (CIDR) notation is used to represent a range of IPv4 addresses using a network address followed by a prefix length. For example, `192.168.1.0/24` represents a range of IP addresses from `192.168.1.0` to `192.168.1.255`, with a subnet mask of `255.255.255.0`.
#### IPv6 Addresses:
1. **IPv6 Colon-Hexadecimal Notation**: IPv6 addresses are much longer than IPv4 addresses and are represented as eight groups of four hexadecimal digits separated by colons. For example: `2001:0db8:85a3:0000:0000:8a2e:0370:7334`
2. **IPv6 Compressed Notation**: To make IPv6 addresses more manageable, leading zeros within each group of hexadecimal digits can be omitted, and consecutive groups of zeros can be represented with a double colon (::). For example, `2001:db8::1` represents the same address as `2001:0db8:0000:0000:0000:0000:0000:0001`.
These representations allow humans to easily work with and understand IP addresses in various contexts, such as configuring network devices or specifying access control rules.
### Addresses <a href="#addr" id="addr"></a>
Addresses in the Cosmos SDK are 20-character long strings and include security checks, such as chain-prefix in Bech32, checksums in Bech32, and checksummed hex (EIP55). Since CosmWasm is an extension of the Cosmos SDK, it adheres to the same address rules; wallets, smart contracts, and modules each have an identifier address with a specific prefix.
When providing an address to smart contracts, you can submit it as a string and subsequently validate the input as an Addr. The Addr serves as a wrapper for a plain string, offering valuable utility functions such as address validation through string validation.
There is also a more uncommon representation of an address, called a **Canonical** Address, which is the binary representation used internally in the blockchain. This representation can be used for all storage lookups, and its format can be converted into multiple types of string addresses.
To better understand Canonical Addresses, we can think about Bitcoin transitioning from Base58 to Bech32 encoding, along with SegWit: once the encoding changes, **message.signer** would lose access to their own account. Canonical Addresses provide us with a stable identifier to work with.
### Naming <a href="#naming" id="naming"></a>
We can consider names as a form of address, albeit one that requires a contract query (with storage access) to resolve. It cannot be resolved merely by calling a pure function.
[<br>](https://docs.archway.io/developers/cosmwasm-documentation/architecture/querying)
# Querying Contract State
You can view the state of a contract either as an external client using the CLI or while executing another contract. In this section, we will explore the two types of queries: raw and custom. We will also look at the semantics of querying via an external client and as an internal client (another contract). We will pay special attention not only to how it works in practice but also to the design and security issues of executing queries from one contract to another.
## Raw queries
The simplest query to implement is just raw read access to the key-value store. If the caller (either an external client or another contract) passes in the raw binary key used in the contract's storage, we can easily return the raw binary value. The benefit of this approach is that it is easy to implement and universal. The downside is that it requires knowledge of the exact contract being executed, as it expects the caller to know the implementation of the contract storage.
As Raw Queries are implemented inside the wasmd runtime, they circumvent the VM. As a consequence, they require no support from the CosmWasm contract, and the whole contract state is visible. The **query\_raw** function is exposed to all callers, both external and internal.
## Custom queries
As it is often not desirable to tightly couple to implementation details, it is preferable to depend on an interface instead. For example, we can define a standard for "CW20" **ExecuteMsg** for calling the contract, and we can define such a standard for a **QueryMsg** as well. For example, querying balance by address, querying allowance via granter + grantee, and querying token info (ticker, decimals, etc). By defining a standard interface, we allow for many implementations, including complex contracts, where the "CW20" interface is only a small subset of their functionality.
To enable custom queries, we allow each contract to expose a query function that can access its data store in read-only mode. This allows loading any data and even performing calculations on it. This method is exposed as **query\_custom** to all callers, both external and internal. As the data format (both for query and response) can be anything the contract desires, it should be documented in the public schema, along with **ExecuteMsg** and **InitMsg**.
Note that executing a contract may consume an unbounded amount of gas, whereas **query\_raw** will read one key and has a small, mostly fixed cost. With **query\_custom**, we need to enforce a gas limit. As the method to enforce a gas limit is done differently for external and internal calls, we will delve into the details below.
## External queries
External queries are the primary way th프로젝트로 돌아가기