-
Notifications
You must be signed in to change notification settings - Fork 5
/
contract.rs
377 lines (340 loc) · 12.2 KB
/
contract.rs
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use cosmwasm_std::{
coin, entry_point, Binary, Coin, CosmosMsg, Deps, DepsMut, Env, MessageInfo, Reply, Response,
StdError, StdResult, SubMsg,
};
use cw2::set_contract_version;
use neutron_sdk::bindings::msg::MsgIbcTransferResponse;
use neutron_sdk::{
bindings::msg::{IbcFee, NeutronMsg},
sudo::msg::{RequestPacket, RequestPacketTimeoutHeight, TransferSudoMsg},
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::state::{
read_reply_payload, read_sudo_payload, save_reply_payload, save_sudo_payload, IBC_FEE,
IBC_SUDO_ID_RANGE_END, IBC_SUDO_ID_RANGE_START, TEST_COUNTER_ITEM,
};
use crate::{
integration_tests_mock_handlers::{set_sudo_failure_mock, unset_sudo_failure_mock},
state::{IntegrationTestsSudoFailureMock, INTEGRATION_TESTS_SUDO_FAILURE_MOCK},
};
// Default timeout for IbcTransfer is 10000000 blocks
const DEFAULT_TIMEOUT_HEIGHT: u64 = 10000000;
const CONTRACT_NAME: &str = concat!("crates.io:neutron-contracts__", env!("CARGO_PKG_NAME"));
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
pub struct InstantiateMsg {}
#[entry_point]
pub fn instantiate(
deps: DepsMut,
_env: Env,
_info: MessageInfo,
_msg: InstantiateMsg,
) -> StdResult<Response> {
deps.api.debug("WASMDEBUG: instantiate");
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
Ok(Response::default())
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
Send {
channel: String,
to: String,
denom: String,
amount: u128,
timeout_height: Option<u64>,
},
SetFees {
recv_fee: u128,
ack_fee: u128,
timeout_fee: u128,
denom: String,
},
ResubmitFailure {
failure_id: u64,
},
/// Used only in integration tests framework to simulate failures.
/// After executing this message, contract will fail, all of this happening
/// in sudo callback handler.
IntegrationTestsSetSudoFailureMock {
state: IntegrationTestsSudoFailureMock,
},
/// Used only in integration tests framework to simulate failures.
/// After executing this message, contract will revert back to normal behaviour.
IntegrationTestsUnsetSudoFailureMock {},
}
#[entry_point]
pub fn execute(
deps: DepsMut,
env: Env,
_: MessageInfo,
msg: ExecuteMsg,
) -> StdResult<Response<NeutronMsg>> {
deps.api
.debug(format!("WASMDEBUG: execute: received msg: {:?}", msg).as_str());
match msg {
// NOTE: this is an example contract that shows how to make IBC transfers!
// Please add necessary authorization or other protection mechanisms
// if you intend to send funds over IBC
ExecuteMsg::Send {
channel,
to,
denom,
amount,
timeout_height,
} => execute_send(deps, env, channel, to, denom, amount, timeout_height),
ExecuteMsg::SetFees {
recv_fee,
ack_fee,
timeout_fee,
denom,
} => execute_set_fees(deps, recv_fee, ack_fee, timeout_fee, denom),
ExecuteMsg::ResubmitFailure { failure_id } => execute_resubmit_failure(deps, failure_id),
// Used only in integration tests framework to simulate failures.
// After executing this message, contract fail, all of this happening
// in sudo callback handler.
ExecuteMsg::IntegrationTestsSetSudoFailureMock { state } => {
set_sudo_failure_mock(deps, state)
}
ExecuteMsg::IntegrationTestsUnsetSudoFailureMock {} => unset_sudo_failure_mock(deps),
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct Type1 {
pub message: String,
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub struct Type2 {
pub data: String,
}
fn sudo_callback1(deps: Deps, payload: Type1) -> StdResult<Response> {
deps.api
.debug(format!("WASMDEBUG: callback1: sudo payload: {:?}", payload).as_str());
Ok(Response::new())
}
fn sudo_callback2(deps: Deps, payload: Type2) -> StdResult<Response> {
deps.api
.debug(format!("WASMDEBUG: callback2: sudo payload: {:?}", payload).as_str());
Ok(Response::new())
}
#[derive(Serialize, Deserialize)]
pub enum SudoPayload {
HandlerPayload1(Type1),
HandlerPayload2(Type2),
}
fn msg_with_sudo_callback<C: Into<CosmosMsg<T>>, T>(
deps: DepsMut,
msg: C,
payload: SudoPayload,
) -> StdResult<SubMsg<T>> {
let id = save_reply_payload(deps.storage, payload)?;
Ok(SubMsg::reply_on_success(msg, id))
}
fn prepare_sudo_payload(mut deps: DepsMut, _env: Env, msg: Reply) -> StdResult<Response> {
let payload = read_reply_payload(deps.storage, msg.id)?;
let resp: MsgIbcTransferResponse = serde_json_wasm::from_slice(
msg.result
.into_result()
.map_err(StdError::generic_err)?
.data
.ok_or_else(|| StdError::generic_err("no result"))?
.as_slice(),
)
.map_err(|e| StdError::generic_err(format!("failed to parse response: {:?}", e)))?;
let seq_id = resp.sequence_id;
let channel_id = resp.channel;
save_sudo_payload(deps.branch().storage, channel_id, seq_id, payload)?;
Ok(Response::new())
}
#[entry_point]
pub fn reply(deps: DepsMut, env: Env, msg: Reply) -> StdResult<Response> {
match msg.id {
IBC_SUDO_ID_RANGE_START..=IBC_SUDO_ID_RANGE_END => prepare_sudo_payload(deps, env, msg),
_ => Err(StdError::generic_err(format!(
"unsupported reply message id {}",
msg.id
))),
}
}
fn get_fee_item(denom: String, amount: u128) -> Vec<Coin> {
if amount == 0 {
vec![]
} else {
vec![coin(amount, denom)]
}
}
fn execute_set_fees(
deps: DepsMut,
recv_fee: u128,
ack_fee: u128,
timeout_fee: u128,
denom: String,
) -> StdResult<Response<NeutronMsg>> {
let fee = IbcFee {
recv_fee: get_fee_item(denom.clone(), recv_fee),
ack_fee: get_fee_item(denom.clone(), ack_fee),
timeout_fee: get_fee_item(denom, timeout_fee),
};
IBC_FEE.save(deps.storage, &fee)?;
Ok(Response::default())
}
fn execute_send(
mut deps: DepsMut,
env: Env,
channel: String,
to: String,
denom: String,
amount: u128,
timeout_height: Option<u64>,
) -> StdResult<Response<NeutronMsg>> {
let fee = IBC_FEE.load(deps.storage)?;
let coin1 = coin(amount, denom.clone());
let msg1 = NeutronMsg::IbcTransfer {
source_port: "transfer".to_string(),
source_channel: channel.clone(),
sender: env.contract.address.to_string(),
receiver: to.clone(),
token: coin1,
timeout_height: RequestPacketTimeoutHeight {
revision_number: Some(2),
revision_height: timeout_height.or(Some(DEFAULT_TIMEOUT_HEIGHT)),
},
timeout_timestamp: 0,
fee: fee.clone(),
memo: "".to_string(),
};
let coin2 = coin(2 * amount, denom);
let msg2 = NeutronMsg::IbcTransfer {
source_port: "transfer".to_string(),
source_channel: channel,
sender: env.contract.address.to_string(),
receiver: to,
token: coin2,
timeout_height: RequestPacketTimeoutHeight {
revision_number: Some(2),
revision_height: timeout_height.or(Some(DEFAULT_TIMEOUT_HEIGHT)),
},
timeout_timestamp: 0,
fee,
memo: "".to_string(),
};
let submsg1 = msg_with_sudo_callback(
deps.branch(),
msg1,
SudoPayload::HandlerPayload1(Type1 {
message: "message".to_string(),
}),
)?;
let submsg2 = msg_with_sudo_callback(
deps.branch(),
msg2,
SudoPayload::HandlerPayload2(Type2 {
data: "data".to_string(),
}),
)?;
deps.as_ref()
.api
.debug(format!("WASMDEBUG: execute_send: sent submsg1: {:?}", submsg1).as_str());
deps.api
.debug(format!("WASMDEBUG: execute_send: sent submsg2: {:?}", submsg2).as_str());
Ok(Response::default().add_submessages(vec![submsg1, submsg2]))
}
fn execute_resubmit_failure(_: DepsMut, failure_id: u64) -> StdResult<Response<NeutronMsg>> {
let msg = NeutronMsg::submit_resubmit_failure(failure_id);
Ok(Response::default().add_message(msg))
}
// Err result returned from the `sudo()` handler will result in the `Failure` object stored in the chain state.
// It can be resubmitted later using `NeutronMsg::ResubmitFailure { failure_id }` message.
#[allow(unreachable_code)]
#[entry_point]
pub fn sudo(deps: DepsMut, _env: Env, msg: TransferSudoMsg) -> StdResult<Response> {
match INTEGRATION_TESTS_SUDO_FAILURE_MOCK.may_load(deps.storage)? {
Some(IntegrationTestsSudoFailureMock::Enabled) => {
// Used only in integration tests framework to simulate failures.
deps.api
.debug("WASMDEBUG: sudo: mocked failure on the handler");
return Err(StdError::generic_err(
"Integrations test mock error".to_string(),
));
}
Some(IntegrationTestsSudoFailureMock::EnabledInfiniteLoop) => {
// Used only in integration tests framework to simulate failures.
deps.api
.debug("WASMDEBUG: sudo: mocked infinite loop failure on the handler");
if let TransferSudoMsg::Response { request, data: _ } = msg {
deps.api.debug(
format!(
"WASMDEBUG: infinite loop failure response; sequence_id = {:?}",
&request.sequence.unwrap_or_default().to_string()
)
.as_str(),
);
}
let mut counter: u64 = 0;
while counter < 18_446_744_073_709_551_615u64 {
counter = counter.checked_add(1).unwrap_or_default();
TEST_COUNTER_ITEM.save(deps.storage, &counter)?;
}
deps.api.debug("WASMDEBUG: after infinite loop");
TEST_COUNTER_ITEM.save(deps.storage, &counter)?;
return Ok(Response::default());
}
_ => {}
}
match msg {
TransferSudoMsg::Response { request, data } => sudo_response(deps, request, data),
TransferSudoMsg::Error { request, details } => sudo_error(deps, request, details),
TransferSudoMsg::Timeout { request } => sudo_timeout(deps, request),
}
}
fn sudo_error(deps: DepsMut, req: RequestPacket, data: String) -> StdResult<Response> {
deps.api.debug(
format!(
"WASMDEBUG: sudo_error: sudo error received: {:?} {}",
req, data
)
.as_str(),
);
Ok(Response::new())
}
fn sudo_timeout(deps: DepsMut, req: RequestPacket) -> StdResult<Response> {
deps.api.debug(
format!(
"WASMDEBUG: sudo_timeout: sudo timeout ack received: {:?}",
req
)
.as_str(),
);
Ok(Response::new())
}
fn sudo_response(deps: DepsMut, req: RequestPacket, data: Binary) -> StdResult<Response> {
deps.api.debug(
format!(
"WASMDEBUG: sudo_response: sudo received: {:?} {}",
req, data
)
.as_str(),
);
let seq_id = req
.sequence
.ok_or_else(|| StdError::generic_err("sequence not found"))?;
let channel_id = req
.source_channel
.ok_or_else(|| StdError::generic_err("channel_id not found"))?;
match read_sudo_payload(deps.storage, channel_id, seq_id)? {
SudoPayload::HandlerPayload1(t1) => sudo_callback1(deps.as_ref(), t1),
SudoPayload::HandlerPayload2(t2) => sudo_callback2(deps.as_ref(), t2),
}
// at this place we can safely remove the data under (channel_id, seq_id) key
// but it costs an extra gas, so its on you how to use the storage
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema)]
pub struct MigrateMsg {}
#[entry_point]
pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> StdResult<Response> {
deps.api.debug("WASMDEBUG: migrate");
Ok(Response::default())
}