bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 54쪽 중 52쪽
functions and aligns them with the user's requested function, specifically 'GetResponse' in our case. Subsequently, it invokes the get\_response function:
```
pub fn get_response(deps: Deps) -> Result<QueryResponse, StdError> {
let result = RESULT.load(deps.storage)?;
to_binary(&result)
}
```
The get\_response function mentioned above returns the result of the mathematical operation.
## Example
To employ mathematical operations within CosmWasm, you should generate the following files: lib.rs, contract.rs, msg.rs, error.rs, and state.rs.
## lib.rs
```
pub mod contract;
mod error;
pub mod msg;
pub mod state;
pub use crate::error::ContractError;
```
## contract.rs
```
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{
to_binary, Deps, DepsMut, Env, MessageInfo, QueryResponse, Response, StdError,
};
use cw2::set_contract_version;
use crate::error::ContractError;
use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg};
use crate::state::{OperationsResponse, RESULT};
// version info for migration info
const CONTRACT_NAME: &str = "crates.io:cosmwasm-math";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
/* Deps allows to access:
1. Read/Write Storage Access
2. General Blockchain APIs
3. The Querier to the blockchain (raw data queries) */
deps: DepsMut,
/* env gives access to global variables which represent environment information.
For example:
- Block Time/Height
- contract address
- Transaction Info */
_env: Env,
/* Message Info gives access to information used for authorization.
1. Funds sent with the message.
2. The message sender (signer). */
_info: MessageInfo,
_msg: InstantiateMsg,
) -> Result<Response, ContractError> {
/* Instantiating the state that will be stored to the blockchain */
let operation_response = OperationsResponse {
addition_result: 0,
subtraction_result: 0,
multiplication_result: 0,
division_result: 0,
modulo_result: 0,
exponentiation_result: 0,
};
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION).unwrap();
// Save the state in deps.storage which creates a storage for contract data on the blockchain.
RESULT.save(deps.storage, &operation_response).unwrap();
Ok(Response::new().add_attribute("method", "instantiate"))
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
_env: Env,
_info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::Operations { a, b } => execute::execute_operations(deps, a, b),
}
}
pub mod execute {
use super::*;
pub fn execute_operations(deps: DepsMut, a: u128, b: u128) -> Result<Response, ContractError> {
// Checking if numbers are not zero
if a == 0 && b == 0 {
return Err(ContractError::CanNotBeZero());
}
// Addition
let addition_result = a + b;
// Subtraction
let subtraction_result = a - b;
// Multiplication
let multiplication_result = a * b;
// Division
let division_result = a / b;
// Modulo
let modulo_result = a % b;
// Exponentiation
let exponent: u32 = 3;
let exponentiation_result: u128 = a.pow(exponent);
// Create the response
let response = OperationsResponse {
addition_result,
subtraction_result,
multiplication_result,
division_result,
modulo_result,
exponentiation_result,
};
// Fetching the state
RESULT.load(deps.storage).unwrap();
// Update the state
RESULT.save(deps.storage, &response).unwrap();
let res = Response::new().add_attributes(vec![
("action", "operations"),
("a", &a.to_string()),
("b", &b.to_string()),
("addition_res", &addition_result.to_string()),
("substraction_res", &subtraction_result.to_string()),
("multiplicationn_res", &multiplication_result.to_string()),
("division_res", &division_result.to_string()),
("modulo_res", &modulo_result.to_string()),
("exponential_res", &exponentiation_result.to_string()),
]);
Ok(res)
}
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> Result<QueryResponse, StdError> {
match msg {
QueryMsg::GetResponse {} => query::get_response(deps),
}
}
pub mod query {
use super::*;
pub fn get_response(deps: Deps) -> Result<QueryResponse, StdError> {
let result = RESULT.load(deps.storage)?;
to_binary(&result)
}
}
#[cfg(test)]
mod tests {
use super::*;
use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};
use cosmwasm_std::{coins, from_binary};
#[test]
fn proper_initialization() {
let mut deps = mock_dependencies();
let msg = InstantiateMsg {};
let info = mock_info("creator", &coins(1000, "earth"));
// we can just call .unwrap() to assert this was a success
let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
assert_eq!(0, res.messages.len());
// it worked, let's query the state
let res = query(deps.as_ref(), mock_env(), QueryMsg::GetResponse {}).unwrap();
let value: OperationsResponse = from_binary(&res).unwrap();
assert_eq!(0, value.addition_result);
assert_eq!(0, value.subtraction_result);
assert_eq!(0, value.multiplication_result);
assert_eq!(0, value.division_result);
assert_eq!(0, value.modulo_result);
assert_eq!(0, value.exponentiation_result);
}
#[test]
fn increment() {
let mut deps = mock_dependencies();
let msg = InstantiateMsg {};
let info = mock_info("creator", &coins(2, "token"));
let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
// testing operation function
let info = mock_info("anyone", &coins(2, "token"));
let msg = ExecuteMsg::Operations { a: 5, b: 5 };
let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap();
// should get basic math operation for 5 and 5
let res = query(deps.as_ref(), mock_env(), QueryMsg::GetResponse { }).unwrap();
let value: OperationsResponse = from_binary(&res).unwrap();
assert_eq!(10, value.addition_result);
assert_eq!(0, value.subtraction_result);
assert_eq!(25, value.multiplication_result);
assert_eq!(1, value.division_result);
assert_eq!(0, value.modulo_result);
assert_eq!(125, value.exponentiation_result);
}
}
```
## msg.rs
```
use cosmwasm_schema::{cw_serde, QueryResponses};
#[cw_serde]
pub struct InstantiateMsg {}
#[cw_serde]
pub enum ExecuteMsg {
Operations { a: u128, b: u128 },
}
#[cw_serde]
#[derive(QueryResponses)]
pub enum QueryMsg {
#[returns(u128)]
GetResponse {},
}
```
## error.rs
```
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ContractError {
#[error("Numbers can not be zero")]
CanNotBeZero(),
}
```
## state.rs
```
use cosmwasm_schema::cw_serde;
use cw_storage_plus::Item;
#[cw_serde]
pub struct OperationsResponse {
pub addition_result: u128,
pub subtraction_result: u128,
pub multiplication_result: u128,
pub division_result: u128,
pub modulo_result: u128,
pub exponentiation_result: u128,
}
// Mapping of result of two numbers
pub const RESULT: Item<OperationsResponse> = Item::new("result");
```
{% hint style="info" %}
Attribution: The code and examples are sourced from "[CosmWasm by Example](https://www.cosmwasmbyexample.com/examples)." You can review the code on [GitHub](https://github.com/athena-consulting/cosmwasm-by-example/tree/main/cosmwasm-math).
{% endhint %}
# Instantiating CosmWasm Contract
In this section, we elucidate the process of initializing a smart contract. This is achieved by presenting the structure of the "InstantiateMsg" passed during contract creation and the "Instantiate" function that is executed when the contract is initiated.
### Explanation
The InstantiateMsg serves as the initialization message, responsible for handling the variables provided when the contract is instantiated.
This function can be located within the msg.rs file.
```
/// Variables for contract instantiation.
/// Exclude variables susceptible to replay attacks or secret data.
pub struct InstantiateMsg {
pub sent_message: String,
}
```
{% hint style="info" %}
Ensure that sensitive data vulnerable to replay attacks is not included.
{% endhint %}
### Instantiate
Upon the creation of the contract, the instantiate function configures the initial state of the smart contract, performs essential validations, and can act in a manner similar to an execute message.
You can find this function in the contract.rs file:
```
pub fn instantiate(
deps: DepsMut,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
// Initialize contract's state.
let state = State {
global_var: msg.sent_message,
};
// Save state to the blockchain.
STATE.save(deps.storage, &state)?;
Ok(Response::new().add_attribute("instantiated", "true"))
}
```
## Example
To instantiate contracts using CosmWasm, you should generate the following files: lib.rs, contract.rs, msg.rs, error.rs, state.rs, and helpers.rs.
### lib.rs
```
pub mod contract;
mod error;
pub mod helpers;
pub mod msg;
pub mod state;
pub use crate::error::ContractError;
```
### contract.rs
```
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, to_binary};
// use cw2::set_contract_version;
use crate::error::ContractError;
use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg};
use crate::state::{State, STATE};
/*
// version info for migration info
const CONTRACT_NAME: &str = "crates.io:instantiation";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
*/
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
deps: DepsMut,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
/* Code is executed at contract creation and accepts an `InstantiateMsg`
Used to set initial (default) state variables of the smart contract
Can perform checks and acts like an execute message.
*/
let state = State {
global_var: msg.sent_message,
};
// Pushes the data to blockchain storage
STATE.save(deps.storage, &state)?;
Ok(Response::new()
.add_attribute("instantiated", "true"))
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
_deps: DepsMut,
_env: Env,
_info: MessageInfo,
_msg: ExecuteMsg,
) -> Result<Response, ContractError> {
unimplemented!()
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
QueryMsg::GetMessage {} => to_binary(&query::message(deps)?),
}
}
pub mod query {
use crate::msg::GetMessageResponse;
use super::*;
pub fn message(deps: Deps) -> StdResult<GetMessageResponse> {
let state = STATE.load(deps.storage)?;
Ok(GetMessageResponse { message: state.global_var })
}
}
#[cfg(test)]
mod tests {
use cosmwasm_std::{testing::{mock_dependencies, mock_env, mock_info}, Addr, from_binary};
use crate::msg::GetMessageResponse;
use super::*;
#[test]
fn instantiate_test() {
let mut deps = mock_dependencies();
let env = mock_env();
let msg = InstantiateMsg { sent_message: "Hey!".to_string()};
let info = mock_info("creator", &[]);
instantiate(deps.as_mut(), env.clone(), info, msg).unwrap();
// Query data from blockchain
let res = query(deps.as_ref(), env, QueryMsg::GetMessage { }).unwrap();
let message: GetMessageResponse = from_binary(&res).unwrap();
assert_eq!("Hey!".to_string(), message.message);
}
}
```
### msg.rs
```
use cosmwasm_schema::{cw_serde, QueryResponses};
#[cw_serde]
/* variables to be passed to contract at instantiation.
secret variables or any variable that is open to a replay attack should not be
part of the InstantiateMsg
*/
pub struct InstantiateMsg {
pub sent_message: String
}
#[cw_serde]
pub enum ExecuteMsg {}
#[cw_serde]
#[derive(QueryResponses)]
pub enum QueryMsg {
#[returns(GetMessageResponse)]
GetMessage {}
}
#[cw_serde]
pub struct GetMessageResponse {
pub message: String
}
```
### error.rs
```
use cosmwasm_std::StdError;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum ContractError {
#[error("{0}")]
Std(#[from] StdError),
#[error("Unauthorized")]
Unauthorized {},
// Add any other custom errors you like here.
// Look at https://docs.rs/thiserror/1.0.21/thiserror/ for details.
}
```
### state.rs
```
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use cw_storage_plus::Item;
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
pub struct State {
pub global_var: String,
}
pub const STATE: Item<State> = Item::new("state");
```
### helpers.rs
```
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use cosmwasm_std::{to_binary, Addr, CosmosMsg, StdResult, WasmMsg};
use crate::msg::ExecuteMsg;
/// CwTemplateContract is a wrapper around Addr that provides a lot of helpers
/// for working with this.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
pub struct CwTemplateContract(pub Addr);
impl CwTemplateContract {
pub fn addr(&self) -> Addr {
self.0.clone()
}
pub fn call<T: Into<ExecuteMsg>>(&self, msg: T) -> StdResult<CosmosMsg> {
let msg = to_binary(&msg.into())?;
Ok(WasmMsg::Execute {
contract_addr: self.addr().into(),
msg,
funds: vec![],
}
.into())
}
}
```
{% hint style="info" %}
Attribution: The code and examples are sourced from "[CosmWasm by Example](https://www.cosmwasmbyexample.com/examples)." You can review the code on [GitHub](https://github.com/athena-consulting/cosmwasm-by-example/tree/main/instantiation),
{% endhint %}
# Timelocks
## Explanation: What is a Timelock Contract, How Does It Work, What does it do?
### Timelock Smart Contract Mechanism:
A timelock smart contract serves as an effective mechanism to introduce a delay system for executing function calls on other smart contracts. This unique contract structure establishes a predefined minimum time delay requirement before a scheduled operation can proceed.
### Functionality of a Timelock Contract:
While the Timelock contract does not fall strictly under the category of MultiSig/Voting Contracts, it closely adheres to the fundamental principles outlined in CW3-spec compliant contracts. Rather than facilitating immediate execution, this contract allows addresses to propose or schedule operations, which subsequently undergo a specified delay period before final execution can take place.
### Timelock Contract Instantiation:
#### Initial Configuration
Upon the deployment of the Timelock contract, the following parameters can be configured:
**Minimum Time Delay**: Set a predefined time delay before operations can be executed.
**Administrators and Proposers**: Assign addresses to fulfill these roles. Operations can only be scheduled by proposers if their execution time exceeds the set delay.
#### **Administrators**
Administrators are responsible for the initial setup and ensuring compatibility with potential target contracts. In the absence of specified addresses, the contract initiator automatically assumes the role of administrator. Once the configuration is complete, administrators have the authority to freeze the Timelock, rendering it immutable. This action is irreversible and can render the contract non-modifiable.
#### Proposers
Proposers are tasked with scheduling operations to be executed after the specified delay. It's crucial to ensure that the Timelock contract possesses the necessary permissions on the target contracts. Additionally, propellers should specify executor addresses responsible for the final execution of operations on the target contract. In cases where no executor is specified, any address can carry out the operation once the scheduled time arrives.
{% hint style="info" %}
*It's important to note that scheduling operations with the Timelock does not guarantee their execution. Proposers retain the option to cancel scheduled operations before they are executed. Therefore, the selection of responsible proposers holds significant importance in this context.*
{% endhint %}
### InstantiateMsg
```
pub struct InstantiateMsg {
pub admins: Option<Vec<String>>,
pub proposers: Vec<String>,
pub min_delay: Duration,
}
Query
pub enum QueryMsg {
GetOperationStatus {
operation_id: Uint64,
},
GetExecutionTime {
operation_id: Uint64,
},
GetAdmins {},
GetOperations {
start_after: Option<u64>,
limit: Option<u32>,
},
GetMinDelay {},
GetProposers {},
GetExecutors {
operation_id: Uint64,
},
}
```
### ExecuteMsg
```
pub enum ExecuteMsg {
Schedule {
target_address: String,
data: Binary,
title: String,
description: String,
execution_time: Scheduled,
executors: Option<Vec<String>>,
},
Cancel {
operation_id: Uint64,
},
Execute {
operation_id: Uint64,
},
RevokeAdmin {
admin_address: String,
},
AddProposer {
proposer_address: String,
},
RemoveProposer {
proposer_address: String,
},
UpdateMinDelay {
new_delay: Duration,
},
Freeze {},
}
```
## Example
To generate a CosmWasm timelocks contract, you can prepare the following files: lib.rs, contract.rs, msg.rs, error.rs, and state.rs.
### lib.rs
```
pub mod contract;
mod error;
pub mod helpers;
pub mod msg;
pub mod state;
pub use crate::error::ContractError;
```
### contract.rs
```
#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::WasmMsg::Execute;
use cosmwasm_std::{
to_binary, Addr, Binary, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Order, Response, StdError,
StdResult, Uint64,
};
use cw2::set_contract_version;
use cw_storage_plus::Bound;
use cw_utils::{Duration, Scheduled};
use std::ops::Add;
use crate::error::ContractError;
use crate::msg::{ExecuteMsg, InstantiateMsg, OperationListResponse, QueryMsg};
use crate::state::{Operation, OperationStatus, Timelock, CONFIG, OPERATION_LIST, OPERATION_SEQ};
// version info for migration info
const CONTRACT_NAME: &str = "crates.io:timelock";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
let mut admins = vec![];
match msg.admins {
None => {
admins.push(info.sender.clone());
}
Some(admin_list) => {
for admin in admin_list {
admins.push(deps.api.addr_validate(&admin)?);
}
}
}
admins.push(env.contract.address);
let mut proposers = vec![];
for proposer in msg.proposers {
proposers.push(deps.api.addr_validate(&proposer)?);
}
let timelock = Timelock {
min_time_delay: msg.min_delay,
proposers,
admins,
frozen: false,
};
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
OPERATION_SEQ.save(deps.storage, &Uint64::zero())?;
CONFIG.save(deps.storage, &timelock)?;
Ok(Response::new()
.add_attribute("Method: ", "instantiate")
.add_attribute("Admin: ", info.sender)
.add_attribute(
"Proposers: ",
timelock
.proposers
.into_iter()
.map(|item| item.to_string())
.collect::<String>(),
)
.add_attribute("minTimeDelay: ", timelock.min_time_delay.to_string()))
}
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
_env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::Schedule {
target_address,
data,
title,
description,
execution_time,
executors,
} => execute_schedule(
deps,
_env,
info,
target_address,
data,
title,
description,
execution_time,
executors,
),
ExecuteMsg::Execute { operation_id } => execute_execute(deps, _env, info, operation_id),
ExecuteMsg::Cancel { operation_id } => execute_cancel(deps, _env, info, operation_id),
ExecuteMsg::RevokeAdmin { admin_address } => {
execute_revoke_admin(deps, _env, info, admin_address)
}
ExecuteMsg::AddProposer { proposer_address } => {
execute_add_proposer(deps, _env, info, proposer_address)
}
ExecuteMsg::RemoveProposer { proposer_address } => {
execute_remove_proposer(deps, _env, info, proposer_address)
}
ExecuteMsg::UpdateMinDelay { new_delay } => {
execute_update_min_delay(deps, _env, info, new_delay)
}프로젝트로 돌아가기