1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use crate::client::wasm_types::{
    WasmCodeResult, WasmContractInfoResult, WasmParameterResult, WasmQueryRawResult,
};
use crate::{Message, PrivateKey, Terra};
use secp256k1::{Secp256k1, Signing};
use std::path::Path;

use crate::client::tx_types::TXResultSync;
use crate::core_types::Coin;
use crate::errors::TerraRustAPIError;
use crate::messages::wasm::{MsgInstantiateContract, MsgMigrateContract, MsgStoreCode};
use serde::Deserialize;

pub struct Wasm<'a> {
    terra: &'a Terra,
}

impl Wasm<'_> {
    pub fn create(terra: &'_ Terra) -> Wasm<'_> {
        Wasm { terra }
    }
    pub async fn codes(&self, code_id: u64) -> Result<WasmCodeResult, TerraRustAPIError> {
        let code = self
            .terra
            .send_cmd::<WasmCodeResult>(&format!("/wasm/codes/{}", code_id), None)
            .await?;
        Ok(code)
    }
    pub async fn info(
        &self,
        contract_address: &str,
    ) -> Result<WasmContractInfoResult, TerraRustAPIError> {
        let code = self
            .terra
            .send_cmd::<WasmContractInfoResult>(
                &format!("/wasm/contracts/{}", contract_address),
                None,
            )
            .await?;
        Ok(code)
    }
    pub async fn parameters(&self) -> Result<WasmParameterResult, TerraRustAPIError> {
        let code = self
            .terra
            .send_cmd::<WasmParameterResult>("/wasm/parameters", None)
            .await?;
        Ok(code)
    }
    pub async fn query<T: for<'de> Deserialize<'de>>(
        &self,
        contract_address: &str,
        json_query: &str,
    ) -> Result<T, TerraRustAPIError> {
        let code = self
            .terra
            .send_cmd::<T>(
                &format!("/wasm/contracts/{}/store?", contract_address),
                Some(&format!("query_msg={}", json_query)),
            )
            .await?;
        Ok(code)
    }
    pub async fn query_raw(
        &self,
        contract_address: &str,
        key: &str,
        sub_key: &Option<String>,
    ) -> Result<(String, String), TerraRustAPIError> {
        let json_query = match sub_key {
            Some(sub_key_str) => format!("key={}&subkey={}", key, &sub_key_str),
            None => format!("key={}", key),
        };

        let code = self
            .terra
            .send_cmd::<WasmQueryRawResult>(
                &format!("/wasm/contracts/{}/store/raw?", contract_address),
                Some(&json_query),
            )
            .await?;
        let key_vec = subtle_encoding::base64::decode(code.result.key.as_bytes())?;
        let key = String::from_utf8(key_vec)?;
        eprintln!("{}", code.result.key);
        let value_vec = subtle_encoding::base64::decode(code.result.value)?;
        let value = String::from_utf8(value_vec)?;

        Ok((key, value))
    }
    /// store a wasm file onto the chain.
    pub async fn store<C: Signing + Signing>(
        &self,
        secp: &Secp256k1<C>,
        from: &PrivateKey,
        wasm: &str,
        memo: Option<String>,
    ) -> Result<TXResultSync, TerraRustAPIError> {
        let from_public_key = from.public_key(secp);

        let wasm_path = Path::new(wasm);

        let store_message = MsgStoreCode::create_from_file(&from_public_key.account()?, wasm_path)?;
        let messages: Vec<Message> = vec![store_message];

        let resp = self
            .terra
            .submit_transaction_sync(secp, from, messages, memo)
            .await;
        resp
    }
    /// create a contract using code_id, json init args, and optionally admin on the chain
    #[allow(clippy::too_many_arguments)]
    pub async fn instantiate<C: Signing + Signing>(
        &self,
        secp: &Secp256k1<C>,
        from: &PrivateKey,
        code_id: u64,
        json: String,
        coins: Vec<Coin>,
        admin: Option<String>,
        memo: Option<String>,
    ) -> Result<TXResultSync, TerraRustAPIError> {
        let from_public_key = from.public_key(secp);
        let init_message = MsgInstantiateContract::create_from_json(
            &from_public_key.account()?,
            admin,
            code_id,
            &json,
            coins,
        )?;
        let messages: Vec<Message> = vec![init_message];

        let resp = self
            .terra
            .submit_transaction_sync(secp, from, messages, memo)
            .await;

        resp
    }

    /// migrate an existing contract to new_code_id, optionally with a migrate args
    pub async fn migrate<C: Signing + Signing>(
        &self,
        secp: &Secp256k1<C>,
        from: &PrivateKey,
        contract: &str,
        new_code_id: u64,
        migrate: Option<String>,
        memo: Option<String>,
    ) -> Result<TXResultSync, TerraRustAPIError> {
        let from_public_key = from.public_key(secp);

        let migrate_message = if let Some(migrate_string) = migrate {
            MsgMigrateContract::create_from_json(
                &from_public_key.account()?,
                contract,
                new_code_id,
                &migrate_string,
            )?
        } else {
            MsgMigrateContract::create_from_json(
                &from_public_key.account()?,
                contract,
                new_code_id,
                "{}",
            )?
        };

        let messages: Vec<Message> = vec![migrate_message];

        let resp = self
            .terra
            .submit_transaction_sync(secp, from, messages, memo)
            .await;
        resp
    }
}