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 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
// This file is part of Gear.
// Copyright (C) 2022-2024 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use super::{GearApi, Result};
use crate::{api::storage::account_id::IntoAccountId32, utils, Error};
use anyhow::anyhow;
use gear_core::{gas::LockId, ids::*, memory::PageBuf, pages::GearPage};
use gear_utils::{MemoryPageDump, ProgramMemoryDump};
use gsdk::{
config::GearConfig,
ext::{
sp_core::H256,
sp_runtime::{AccountId32, MultiAddress},
},
metadata::{
balances::Event as BalancesEvent,
gear::Event as GearEvent,
runtime_types::{
frame_system::pallet::Call as SystemCall,
gear_common::event::{CodeChangeKind, MessageEntry},
gear_core::program::ActiveProgram,
pallet_balances::{pallet::Call as BalancesCall, types::AccountData},
pallet_gear::pallet::Call as GearCall,
pallet_gear_bank::pallet::BankAccount,
pallet_gear_voucher::internal::VoucherId,
sp_weights::weight_v2::Weight,
},
system::Event as SystemEvent,
utility::Event as UtilityEvent,
vara_runtime::RuntimeCall,
Convert, Event,
},
Error as GsdkError, GearGasNode, GearGasNodeId,
};
use hex::ToHex;
use parity_scale_codec::{Decode, Encode};
use std::{
collections::{BTreeMap, HashMap, HashSet},
path::Path,
};
use subxt::blocks::ExtrinsicEvents;
impl GearApi {
/// Returns original wasm code for the given `code_id` at specified
/// `at_block_hash`.
pub async fn original_code_at(
&self,
code_id: CodeId,
at_block_hash: Option<H256>,
) -> Result<Vec<u8>> {
self.0
.api()
.original_code_storage_at(code_id, at_block_hash)
.await
.map_err(Into::into)
}
/// Returns `ActiveProgram` for the given `program_id` at specified
/// `at_block_hash`.
pub async fn program_at(
&self,
program_id: ProgramId,
at_block_hash: Option<H256>,
) -> Result<ActiveProgram<u32>> {
self.0
.api()
.gprog_at(program_id, at_block_hash)
.await
.map_err(Into::into)
}
/// Transfer `value` to `destination`'s account.
///
/// Sends the
/// [`pallet_balances::transfer`](https://crates.parity.io/pallet_balances/pallet/struct.Pallet.html#method.transfer)
/// extrinsic.
///
/// This function returns a hash of the block with the transfer transaction.
pub async fn transfer_keep_alive(&self, destination: ProgramId, value: u128) -> Result<H256> {
let destination: [u8; 32] = destination.into();
let tx = self.0.calls.transfer_keep_alive(destination, value).await?;
for event in tx.wait_for_success().await?.iter() {
if let Event::Balances(BalancesEvent::Transfer { .. }) =
event?.as_root_event::<Event>()?
{
return Ok(tx.block_hash());
}
}
// Sending zero value is a no-op, so now event occurs.
if value == 0 {
return Ok(tx.block_hash());
}
Err(Error::EventNotFound)
}
/// Transfer `value` to `destination`'s account.
///
/// Sends the
/// [`pallet_balances::transfer`](https://crates.parity.io/pallet_balances/pallet/struct.Pallet.html#method.transfer)
/// extrinsic.
///
/// This function returns a hash of the block with the transfer transaction.
pub async fn transfer_allow_death(&self, destination: ProgramId, value: u128) -> Result<H256> {
let destination: [u8; 32] = destination.into();
let tx = self
.0
.calls
.transfer_allow_death(destination, value)
.await?;
for event in tx.wait_for_success().await?.iter() {
if let Event::Balances(BalancesEvent::Transfer { .. }) =
event?.as_root_event::<Event>()?
{
return Ok(tx.block_hash());
}
}
// Sending zero value is a no-op, so now event occurs.
if value == 0 {
return Ok(tx.block_hash());
}
Err(Error::EventNotFound)
}
/// Transfer `value` to `destination`'s account.
///
/// Sends the
/// [`pallet_balances::transfer`](https://crates.parity.io/pallet_balances/pallet/struct.Pallet.html#method.transfer)
/// extrinsic.
///
/// This function returns a hash of the block with the transfer transaction.
pub async fn transfer_all(&self, destination: ProgramId, keep_alive: bool) -> Result<H256> {
let destination: [u8; 32] = destination.into();
let tx = self.0.calls.transfer_all(destination, keep_alive).await?;
for event in tx.wait_for_success().await?.iter() {
if let Event::Balances(BalancesEvent::Transfer { .. }) =
event?.as_root_event::<Event>()?
{
return Ok(tx.block_hash());
}
}
Err(Error::EventNotFound)
}
/// Create a new program from a previously uploaded code identified by
/// [`CodeId`](https://docs.gear.rs/gear_core/ids/struct.CodeId.html) and
/// initialize it with a byte slice `payload`.
///
/// Sends the
/// [`pallet_gear::create_program`](https://docs.gear.rs/pallet_gear/pallet/struct.Pallet.html#method.create_program)
/// extrinsic.
///
/// Parameters:
///
/// - `code_id` is the code identifier that can be obtained by calling the
/// [`upload_code`](Self::upload_code) function;
/// - `salt` is the arbitrary data needed to generate an address for a new
/// program (control of salt uniqueness is entirely on the function
/// caller’s side);
/// - `payload` vector contains data to be processed in the `init` function
/// of the newly deployed "child" program;
/// - `gas_limit` is the maximum gas amount allowed to spend for the program
/// creation and initialization;
/// - `value` to be transferred to the program's account during
/// initialization.
///
/// This function returns a tuple with an init message identifier, newly
/// created program identifier, and a hash of the block with the message
/// enqueuing transaction.
///
/// # See also
///
/// - [`create_program`](Self::create_program) function initializes a newly
/// created program with an encoded payload.
/// - [`create_program_bytes_batch`](Self::create_program_bytes_batch)
/// function creates a batch of programs and initializes them.
/// - [`upload_code`](Self::upload_code) function uploads a code and returns
/// its identifier.
/// - [`upload_program_bytes`](Self::upload_program_bytes) function uploads
/// a new program and initialize it.
pub async fn create_program_bytes(
&self,
code_id: CodeId,
salt: impl AsRef<[u8]>,
payload: impl AsRef<[u8]>,
gas_limit: u64,
value: u128,
) -> Result<(MessageId, ProgramId, H256)> {
let salt = salt.as_ref().to_vec();
let payload = payload.as_ref().to_vec();
let tx = self
.0
.calls
.create_program(code_id, salt, payload, gas_limit, value)
.await?;
for event in tx.wait_for_success().await?.iter() {
if let Event::Gear(GearEvent::MessageQueued {
id,
destination,
entry: MessageEntry::Init,
..
}) = event?.as_root_event::<Event>()?
{
return Ok((id.into(), destination.into(), tx.block_hash()));
}
}
Err(Error::EventNotFound)
}
/// Create a batch of programs.
///
/// A batch is a set of programs to be created within one function call.
/// Every entry of the `args` iterator is a tuple of parameters used in the
/// [`create_program_bytes`](Self::create_program_bytes) function. It is
/// useful when deploying a multi-program dApp.
pub async fn create_program_bytes_batch(
&self,
args: impl IntoIterator<Item = (CodeId, impl AsRef<[u8]>, impl AsRef<[u8]>, u64, u128)>,
) -> Result<(Vec<Result<(MessageId, ProgramId)>>, H256)> {
let calls: Vec<_> = args
.into_iter()
.map(|(code_id, salt, payload, gas_limit, value)| {
RuntimeCall::Gear(GearCall::create_program {
code_id: code_id.into(),
salt: salt.as_ref().to_vec(),
init_payload: payload.as_ref().to_vec(),
gas_limit,
value,
keep_alive: false,
})
})
.collect();
let amount = calls.len();
let tx = self.0.calls.force_batch(calls).await?;
let mut res = Vec::with_capacity(amount);
for event in tx.wait_for_success().await?.iter() {
match event?.as_root_event::<Event>()? {
Event::Gear(GearEvent::MessageQueued {
id,
destination,
entry: MessageEntry::Init,
..
}) => res.push(Ok((id.into(), destination.into()))),
Event::Utility(UtilityEvent::ItemFailed { error }) => {
res.push(Err(self.0.api().decode_error(error).into()))
}
_ => (),
}
}
if res.len() == amount {
Ok((res, tx.block_hash()))
} else {
Err(Error::IncompleteBatchResult(res.len(), amount))
}
}
/// Same as [`create_program_bytes`](Self::create_program_bytes), but
/// initializes a newly created program with an encoded `payload`.
///
/// # See also
///
/// - [`upload_code`](Self::upload_code) function uploads a code and returns
/// its identifier.
/// - [`upload_program`](Self::upload_program) function uploads a new
/// program and initialize it.
pub async fn create_program(
&self,
code_id: CodeId,
salt: impl AsRef<[u8]>,
payload: impl Encode,
gas_limit: u64,
value: u128,
) -> Result<(MessageId, ProgramId, H256)> {
self.create_program_bytes(code_id, salt, payload.encode(), gas_limit, value)
.await
}
/// Migrates an active program identified by `src_program_id` onto another
/// node identified by `dest_node_api` and returns the migrated program
/// identifier. All source program data is taken at the time of
/// `src_block_hash` if it is specified or the most recent one.
pub async fn migrate_program(
&self,
src_program_id: ProgramId,
src_block_hash: Option<H256>,
dest_node_api: &GearApi,
) -> Result<ProgramId> {
if dest_node_api.0.api().gprog(src_program_id).await.is_ok() {
return Err(Error::ProgramAlreadyExists(
src_program_id.as_ref().encode_hex(),
));
}
let mut src_block_hash = src_block_hash;
if src_block_hash.is_none() {
src_block_hash = Some(self.last_block_hash().await?);
}
let dest_program_id = src_program_id;
// Collect data from the source program
let src_program_account_data = self
.account_data_at(src_program_id, src_block_hash)
.await
.or_else(|e| {
if let Error::GearSDK(GsdkError::StorageNotFound) = e {
Ok(AccountData {
free: 0u128,
reserved: 0,
frozen: 0,
flags: gsdk::metadata::runtime_types::pallet_balances::types::ExtraFlags(
170141183460469231731687303715884105728,
),
})
} else {
Err(e)
}
})?;
let src_program_account_bank_data = self
.bank_data_at(src_program_id, src_block_hash)
.await
.or_else(|e| {
if let Error::GearSDK(GsdkError::StorageNotFound) = e {
Ok(BankAccount { gas: 0, value: 0 })
} else {
Err(e)
}
})?;
let src_bank_account_data = self
.account_data_at(crate::bank_address(), src_block_hash)
.await
.or_else(|e| {
if let Error::GearSDK(GsdkError::StorageNotFound) = e {
Ok(AccountData {
free: 0u128,
reserved: 0,
frozen: 0,
flags: gsdk::metadata::runtime_types::pallet_balances::types::ExtraFlags(
170141183460469231731687303715884105728,
),
})
} else {
Err(e)
}
})?;
let mut src_program = self
.0
.api()
.gprog_at(src_program_id, src_block_hash)
.await?;
let src_program_pages = self
.0
.api()
.gpages_at(
src_program_id,
Some(src_program.memory_infix.0),
src_block_hash,
)
.await?;
let src_program_reserved_gas_node_ids: Vec<GearGasNodeId> = src_program
.gas_reservation_map
.iter()
.map(|gr| gr.0.into())
.collect();
let src_program_reserved_gas_nodes = self
.0
.api()
.gas_nodes_at(&src_program_reserved_gas_node_ids, src_block_hash)
.await?;
let mut src_program_reserved_gas_total = 0u64;
let mut accounts_with_reserved_funds = HashSet::new();
for gas_node in &src_program_reserved_gas_nodes {
if let GearGasNode::Reserved {
id, value, lock, ..
} = &gas_node.1
{
accounts_with_reserved_funds.insert(id);
src_program_reserved_gas_total += value + lock.0[LockId::Reservation as usize];
} else {
unreachable!("Unexpected gas node type");
}
}
let src_code_id = src_program.code_hash.0.into();
let src_code_len = self
.0
.api()
.code_len_storage_at(src_code_id, src_block_hash)
.await?;
let src_code = self
.0
.api()
.code_storage_at(src_code_id, src_block_hash)
.await?;
// Apply data to the target program
dest_node_api
.force_set_balance(
dest_program_id.into_account_id(),
src_program_account_data.free,
)
.await?;
dest_node_api
.force_set_balance(crate::bank_address(), src_bank_account_data.free)
.await?;
dest_node_api
.0
.storage
.set_bank_account_storage(
src_program_id.into_account_id(),
src_program_account_bank_data,
)
.await?;
dest_node_api
.0
.storage
.set_code_storage(src_code_id, &src_code)
.await?;
dest_node_api
.0
.storage
.set_code_len_storage(src_code_id, src_code_len)
.await?;
dest_node_api
.0
.storage
.set_gas_nodes(&src_program_reserved_gas_nodes)
.await?;
for account_with_reserved_funds in accounts_with_reserved_funds {
let src_account_bank_data = self
.bank_data_at(account_with_reserved_funds, src_block_hash)
.await
.or_else(|e| {
if let Error::GearSDK(GsdkError::StorageNotFound) = e {
Ok(BankAccount { gas: 0, value: 0 })
} else {
Err(e)
}
})?;
let dest_account_data = dest_node_api
.account_data(account_with_reserved_funds)
.await
.or_else(|e| {
if let Error::GearSDK(GsdkError::StorageNotFound) = e {
Ok(AccountData {
free: 0u128,
reserved: 0,
frozen: 0,
flags:
gsdk::metadata::runtime_types::pallet_balances::types::ExtraFlags(
170141183460469231731687303715884105728,
),
})
} else {
Err(e)
}
})?;
let dest_account_bank_data = self
.bank_data_at(account_with_reserved_funds, None)
.await
.or_else(|e| {
if let Error::GearSDK(GsdkError::StorageNotFound) = e {
Ok(BankAccount { gas: 0, value: 0 })
} else {
Err(e)
}
})?;
dest_node_api
.force_set_balance(
account_with_reserved_funds.into_account_id(),
dest_account_data.free,
)
.await?;
dest_node_api
.0
.storage
.set_bank_account_storage(
account_with_reserved_funds.into_account_id(),
BankAccount {
gas: src_account_bank_data
.gas
.saturating_add(dest_account_bank_data.gas),
value: src_account_bank_data
.value
.saturating_add(dest_account_bank_data.value),
},
)
.await?;
}
let dest_gas_total_issuance =
dest_node_api.0.api().total_issuance().await.or_else(|e| {
if let GsdkError::StorageNotFound = e {
Ok(0)
} else {
Err(e)
}
})?;
dest_node_api
.0
.storage
.set_total_issuance(
dest_gas_total_issuance.saturating_add(src_program_reserved_gas_total),
)
.await?;
dest_node_api
.0
.storage
.set_gpages(
dest_program_id,
src_program.memory_infix.0,
&src_program_pages,
)
.await?;
src_program.expiration_block = dest_node_api.last_block_number().await?;
dest_node_api
.0
.storage
.set_gprog(dest_program_id, src_program)
.await?;
Ok(dest_program_id)
}
/// Get all pages with their data for program at specified block.
pub async fn get_program_pages_data_at(
&self,
program_id: ProgramId,
block_hash: Option<H256>,
) -> Result<BTreeMap<GearPage, PageBuf>> {
let pages_data = self.0.api().gpages_at(program_id, None, block_hash).await?;
let mut res = BTreeMap::new();
for (page, data) in pages_data.into_iter() {
res.insert(
GearPage::try_from(page).map_err(|err| anyhow!("{err}"))?,
PageBuf::from_inner(data.try_into().map_err(|err| anyhow!("{err}"))?),
);
}
Ok(res)
}
/// Get specified pages with their data for program at specified block.
pub async fn get_program_specified_pages_data_at(
&self,
program_id: ProgramId,
pages: impl Iterator<Item = GearPage>,
block_hash: Option<H256>,
) -> Result<BTreeMap<GearPage, PageBuf>> {
let pages_data = self
.0
.api()
.specified_gpages_at(program_id, None, pages.map(Into::into), block_hash)
.await?;
let mut res = BTreeMap::new();
for (page, data) in pages_data.into_iter() {
res.insert(
GearPage::try_from(page).map_err(|err| anyhow::Error::msg(err.to_string()))?,
PageBuf::from_inner(
data.try_into()
.map_err(|_| anyhow::Error::msg("incorrect page data size"))?,
),
);
}
Ok(res)
}
/// Save program (identified by `program_id`) memory dump to the file for
/// further restoring in gclient/gtest. Program memory dumped at the
/// time of `block_hash` if presented or the most recent block.
pub async fn save_program_memory_dump_at<P: AsRef<Path>>(
&self,
program_id: ProgramId,
block_hash: Option<H256>,
file_path: P,
) -> Result {
let program = self.0.api().gprog_at(program_id, block_hash).await?;
let program_pages = self
.0
.api()
.gpages_at(program_id, Some(program.memory_infix.0), block_hash)
.await?
.into_iter()
.map(|(page, data)| {
MemoryPageDump::new(
GearPage::try_from(page)
.unwrap_or_else(|_| panic!("Couldn't decode GearPage from u32: {}", page)),
PageBuf::decode(&mut &*data).expect("Couldn't decode PageBuf"),
)
})
.collect();
let program_account_data =
self.account_data_at(program_id, block_hash)
.await
.or_else(|e| {
if let Error::GearSDK(GsdkError::StorageNotFound) = e {
Ok(AccountData {
free: 0u128,
reserved: 0,
frozen: 0,
flags:
gsdk::metadata::runtime_types::pallet_balances::types::ExtraFlags(
170141183460469231731687303715884105728,
),
})
} else {
Err(e)
}
})?;
ProgramMemoryDump {
pages: program_pages,
balance: program_account_data.free,
reserved_balance: program_account_data.reserved,
}
.save_to_file(file_path);
Ok(())
}
/// Replace entire program memory with one saved earlier in gclient/gtest
pub async fn replace_program_memory<P: AsRef<Path>>(
&self,
program_id: ProgramId,
file_path: P,
) -> Result {
let memory_dump = ProgramMemoryDump::load_from_file(file_path);
let pages = memory_dump
.pages
.into_iter()
.map(|page| page.into_gear_page())
.map(|(page, page_data)| (page.into(), page_data.encode()))
.collect::<HashMap<u32, _>>();
self.force_set_balance(
MultiAddress::Id(program_id.into_account_id()),
memory_dump.balance,
)
.await?;
let program = self.0.api().gprog_at(program_id, None).await?;
self.0
.storage
.set_gpages(program_id, program.memory_infix.0, &pages)
.await?;
Ok(())
}
/// Claim value from the mailbox message identified by `message_id`.
///
/// Sends the
/// [`pallet_gear::claim_value`](https://docs.gear.rs/pallet_gear/pallet/struct.Pallet.html#method.claim_value)
/// extrinsic.
///
/// This function returns a tuple with value and block hash containing the
/// corresponding transaction.
///
/// # See also
///
/// - [`claim_value_batch`](Self::claim_value_batch) function claims a batch
/// of values from the mailbox.
pub async fn claim_value(&self, message_id: MessageId) -> Result<(u128, H256)> {
let value = self
.get_mailbox_message(message_id)
.await?
.map(|(message, _interval)| message.value());
let tx = self.0.calls.claim_value(message_id).await?;
for event in tx.wait_for_success().await?.iter() {
if let Event::Gear(GearEvent::UserMessageRead { .. }) =
event?.as_root_event::<Event>()?
{
return Ok((
value.expect("Data appearance guaranteed above"),
tx.block_hash(),
));
}
}
Err(Error::EventNotFound)
}
/// Claim a batch of values from the mailbox.
///
/// A batch is a set of requests to be executed within one function call.
/// Every entry of the `args` iterator is a message identifier used in the
/// [`claim_value`](Self::claim_value) function. It is useful when
/// processing multiple replies in the mailbox at once.
pub async fn claim_value_batch(
&self,
args: impl IntoIterator<Item = MessageId> + Clone,
) -> Result<(Vec<Result<u128>>, H256)> {
let message_ids: Vec<_> = args.clone().into_iter().collect();
let messages = futures::future::try_join_all(
message_ids.iter().map(|mid| self.get_mailbox_message(*mid)),
)
.await?;
let mut values: BTreeMap<_, _> = messages
.into_iter()
.flatten()
.map(|(msg, _interval)| (msg.id(), msg.value()))
.collect();
let calls: Vec<_> = args
.into_iter()
.map(|message_id| {
RuntimeCall::Gear(GearCall::claim_value {
message_id: message_id.into(),
})
})
.collect();
let amount = calls.len();
let tx = self.0.calls.force_batch(calls).await?;
let mut res = Vec::with_capacity(amount);
for event in tx.wait_for_success().await?.iter() {
match event?.as_root_event::<Event>()? {
Event::Gear(GearEvent::UserMessageRead { id, .. }) => res.push(Ok(values
.remove(&id.into())
.expect("Data appearance guaranteed above"))),
Event::Utility(UtilityEvent::ItemFailed { error }) => {
res.push(Err(self.0.api().decode_error(error).into()))
}
_ => (),
}
}
if res.len() == amount {
Ok((res, tx.block_hash()))
} else {
Err(Error::IncompleteBatchResult(res.len(), amount))
}
}
/// Send a message containing a byte slice `payload` to the `destination`.
///
/// The message also contains the maximum `gas_limit` that can be spent and
/// the `value` to be transferred to the `destination`'s account.
///
/// Sends the
/// [`pallet_gear::send_message`](https://docs.gear.rs/pallet_gear/pallet/struct.Pallet.html#method.send_message)
/// extrinsic.
///
/// This function returns a tuple with a new message identifier and a hash
/// of the block with the message enqueuing transaction.
///
/// # See also
///
/// - [`send_message`](Self::send_message) function sends a message with an
/// encoded payload.
/// - [`send_message_bytes_batch`](Self::send_message_bytes_batch) function
/// sends a batch of messages.
pub async fn send_message_bytes(
&self,
destination: ProgramId,
payload: impl AsRef<[u8]>,
gas_limit: u64,
value: u128,
) -> Result<(MessageId, H256)> {
let payload = payload.as_ref().to_vec();
let tx = self
.0
.calls
.send_message(destination, payload, gas_limit, value)
.await?;
for event in tx.wait_for_success().await?.iter() {
if let Event::Gear(GearEvent::MessageQueued {
id,
entry: MessageEntry::Handle,
..
}) = event?.as_root_event::<Event>()?
{
return Ok((id.into(), tx.block_hash()));
}
}
Err(Error::EventNotFound)
}
/// Send a batch of messages.
///
/// A batch is a set of messages to be sent within one function call. Every
/// entry of the `args` iterator is a tuple of parameters used in the
/// [`send_message_bytes`](Self::send_message_bytes) function. It is useful
/// when invoking several programs at once or sending a sequence of messages
/// to one program.
pub async fn send_message_bytes_batch(
&self,
args: impl IntoIterator<Item = (ProgramId, impl AsRef<[u8]>, u64, u128)>,
) -> Result<(Vec<Result<(MessageId, ProgramId)>>, H256)> {
let calls: Vec<_> = args
.into_iter()
.map(|(destination, payload, gas_limit, value)| {
RuntimeCall::Gear(GearCall::send_message {
destination: destination.into(),
payload: payload.as_ref().to_vec(),
gas_limit,
value,
keep_alive: false,
})
})
.collect();
let amount = calls.len();
let tx = self.0.calls.force_batch(calls).await?;
let mut res = Vec::with_capacity(amount);
for event in tx.wait_for_success().await?.iter() {
match event?.as_root_event::<Event>()? {
Event::Gear(GearEvent::MessageQueued {
id,
destination,
entry: MessageEntry::Handle,
..
}) => res.push(Ok((id.into(), destination.into()))),
Event::Utility(UtilityEvent::ItemFailed { error }) => {
res.push(Err(self.0.api().decode_error(error).into()))
}
_ => (),
}
}
if res.len() == amount {
Ok((res, tx.block_hash()))
} else {
Err(Error::IncompleteBatchResult(res.len(), amount))
}
}
/// Same as [`send_message_bytes`](Self::send_message_bytes), but sends a
/// message with encoded `payload`.
pub async fn send_message(
&self,
destination: ProgramId,
payload: impl Encode,
gas_limit: u64,
value: u128,
) -> Result<(MessageId, H256)> {
self.send_message_bytes(destination, payload.encode(), gas_limit, value)
.await
}
/// Send a reply containing a byte slice `payload` to the message identified
/// by `reply_to_id`.
///
/// The reply also contains the maximum `gas_limit` that can be spent and
/// the `value` to be transferred to the destination's account.
///
/// Sends the
/// [`pallet_gear::send_reply`](https://docs.gear.rs/pallet_gear/pallet/struct.Pallet.html#method.send_reply)
/// extrinsic.
///
/// This function returns a tuple with a new message identifier, transferred
/// value, and a hash of the block with the message enqueuing transaction.
///
/// # See also
///
/// - [`send_reply`](Self::send_reply) function sends a reply with an
/// encoded payload.
/// - [`send_reply_bytes_batch`](Self::send_reply_bytes_batch) function send
/// a batch of replies.
pub async fn send_reply_bytes(
&self,
reply_to_id: MessageId,
payload: impl AsRef<[u8]>,
gas_limit: u64,
value: u128,
) -> Result<(MessageId, u128, H256)> {
let payload = payload.as_ref().to_vec();
let data = self.get_mailbox_message(reply_to_id).await?;
let tx = self
.0
.calls
.send_reply(reply_to_id, payload, gas_limit, value)
.await?;
let events = tx.wait_for_success().await?;
let (message, _interval) = data.expect("Data appearance guaranteed above");
for event in events.iter() {
if let Event::Gear(GearEvent::MessageQueued {
id,
entry: MessageEntry::Reply(_),
..
}) = event?.as_root_event::<Event>()?
{
return Ok((id.into(), message.value(), tx.block_hash()));
}
}
Err(Error::EventNotFound)
}
/// Send a batch of replies.
///
/// A batch is a set of replies to be sent within one function call. Every
/// entry of the `args` iterator is a tuple of parameters used in the
/// [`send_reply_bytes`](Self::send_reply_bytes) function. It is useful when
/// replying to several programs at once.
///
/// The output for each call slightly differs from
/// [`send_reply_bytes`](Self::send_reply_bytes) as the destination
/// program id is also returned in the resulting tuple.
pub async fn send_reply_bytes_batch(
&self,
args: impl IntoIterator<Item = (MessageId, impl AsRef<[u8]>, u64, u128)> + Clone,
) -> Result<(Vec<Result<(MessageId, ProgramId, u128)>>, H256)> {
let message_ids: Vec<_> = args.clone().into_iter().map(|(mid, _, _, _)| mid).collect();
let messages = futures::future::try_join_all(
message_ids.iter().map(|mid| self.get_mailbox_message(*mid)),
)
.await?;
let mut values: BTreeMap<_, _> = messages
.into_iter()
.flatten()
.map(|(msg, _interval)| (msg.id(), msg.value()))
.collect();
let calls: Vec<_> = args
.into_iter()
.map(|(reply_to_id, payload, gas_limit, value)| {
RuntimeCall::Gear(GearCall::send_reply {
reply_to_id: reply_to_id.into(),
payload: payload.as_ref().to_vec(),
gas_limit,
value,
keep_alive: false,
})
})
.collect();
let amount = calls.len();
let tx = self.0.calls.force_batch(calls).await?;
let mut res = Vec::with_capacity(amount);
for event in tx.wait_for_success().await?.iter() {
match event?.as_root_event::<Event>()? {
Event::Gear(GearEvent::MessageQueued {
id,
entry: MessageEntry::Reply(reply_to_id),
destination,
..
}) => res.push(Ok((
id.into(),
destination.into(),
values
.remove(&reply_to_id.into())
.expect("Data appearance guaranteed above"),
))),
Event::Utility(UtilityEvent::ItemFailed { error }) => {
res.push(Err(self.0.api().decode_error(error).into()))
}
_ => (),
}
}
if res.len() == amount {
Ok((res, tx.block_hash()))
} else {
Err(Error::IncompleteBatchResult(res.len(), amount))
}
}
/// Same as [`send_reply_bytes`](Self::send_reply_bytes), but sends a reply
/// with encoded `payload`.
pub async fn send_reply(
&self,
reply_to_id: MessageId,
payload: impl Encode,
gas_limit: u64,
value: u128,
) -> Result<(MessageId, u128, H256)> {
self.send_reply_bytes(reply_to_id, payload.encode(), gas_limit, value)
.await
}
/// Upload Wasm `code` to be used for creating a new program.
///
/// Sends the
/// [`pallet_gear::upload_code`](https://docs.gear.rs/pallet_gear/pallet/struct.Pallet.html#method.upload_code)
/// extrinsic.
///
/// This function returns a tuple with a code identifier and a hash of the
/// block with the code uploading transaction. The code identifier can be
/// used when creating a program using the
/// [`create_program`](Self::create_program) function.
///
/// # See also
///
/// - [`create_program`](Self::create_program) function creates a program
/// from a previously uploaded code and initializes it.
/// - [`upload_program`](Self::upload_program) function uploads a new
/// program and initialize it.
pub async fn upload_code(&self, code: impl AsRef<[u8]>) -> Result<(CodeId, H256)> {
let tx = self.0.calls.upload_code(code.as_ref().to_vec()).await?;
for event in tx.wait_for_success().await?.iter() {
if let Event::Gear(GearEvent::CodeChanged {
id,
change: CodeChangeKind::Active { .. },
}) = event?.as_root_event::<Event>()?
{
return Ok((id.into(), tx.block_hash()));
}
}
Err(Error::EventNotFound)
}
/// Upload a batch of codes.
///
/// A batch is a set of codes to be uploaded within one function call. Every
/// entry of the `args` iterator is a byte slice used in the
/// [`upload_code`](Self::upload_code) function. It is useful when deploying
/// a multi-program dApp.
pub async fn upload_code_batch(
&self,
args: impl IntoIterator<Item = impl AsRef<[u8]>>,
) -> Result<(Vec<Result<CodeId>>, H256)> {
let calls: Vec<_> = args
.into_iter()
.map(|code| {
RuntimeCall::Gear(GearCall::upload_code {
code: code.as_ref().to_vec(),
})
})
.collect();
let amount = calls.len();
let tx = self.0.calls.force_batch(calls).await?;
let mut res = Vec::with_capacity(amount);
for event in tx.wait_for_success().await?.iter() {
match event?.as_root_event::<Event>()? {
Event::Gear(GearEvent::CodeChanged {
id,
change: CodeChangeKind::Active { .. },
}) => {
res.push(Ok(id.into()));
}
Event::Utility(UtilityEvent::ItemFailed { error }) => {
res.push(Err(self.0.api().decode_error(error).into()))
}
_ => (),
}
}
if res.len() == amount {
Ok((res, tx.block_hash()))
} else {
Err(Error::IncompleteBatchResult(res.len(), amount))
}
}
/// Upload Wasm code from the file referenced by `path` to be used for
/// creating a new program.
///
/// Same as [`upload_code`](Self::upload_code), but reads the code from a
/// file instead of using a byte vector.
///
/// Works with absolute and relative paths (relative to the root dir of the
/// repo).
pub async fn upload_code_by_path(&self, path: impl AsRef<Path>) -> Result<(CodeId, H256)> {
let code = utils::code_from_os(path)?;
self.upload_code(code).await
}
/// Upload a new program and initialize it with a byte slice `payload`.
///
/// Sends the
/// [`pallet_gear::upload_program`](https://docs.gear.rs/pallet_gear/pallet/struct.Pallet.html#method.upload_program)
/// extrinsic.
///
/// Parameters:
///
/// - `code` is the byte slice containing a binary Wasm code of the program;
/// - `salt` is the arbitrary data needed to generate an address for a new
/// program (control of salt uniqueness is entirely on the function
/// caller’s side);
/// - `payload` vector contains data to be processed in the `init` function
/// of the newly deployed "child" program;
/// - `gas_limit` is the maximum gas amount allowed to spend for the program
/// creation and initialization;
/// - `value` to be transferred to the program's account during
/// initialization.
///
/// # See also
///
/// - [`create_program_bytes`](Self::create_program_bytes) function creates
/// a program from a previously uploaded code.
/// - [`upload_code`](Self::upload_code) function uploads a code and returns
/// its identifier.
/// - [`upload_program`](Self::upload_program) function uploads a program
/// and initializes it with an encoded payload.
pub async fn upload_program_bytes(
&self,
code: impl AsRef<[u8]>,
salt: impl AsRef<[u8]>,
payload: impl AsRef<[u8]>,
gas_limit: u64,
value: u128,
) -> Result<(MessageId, ProgramId, H256)> {
let code = code.as_ref().to_vec();
let salt = salt.as_ref().to_vec();
let payload = payload.as_ref().to_vec();
let tx = self
.0
.calls
.upload_program(code, salt, payload, gas_limit, value)
.await?;
for event in tx.wait_for_success().await?.iter() {
if let Event::Gear(GearEvent::MessageQueued {
id,
destination,
entry: MessageEntry::Init,
..
}) = event?.as_root_event::<Event>()?
{
return Ok((id.into(), destination.into(), tx.block_hash()));
}
}
Err(Error::EventNotFound)
}
/// Upload a batch of programs.
///
/// A batch is a set of programs to be uploaded within one function call.
/// Every entry of the `args` iterator is a tuple used in the
/// [`upload_program_bytes`](Self::upload_program_bytes) function. It is
/// useful when deploying a multi-program dApp.
pub async fn upload_program_bytes_batch(
&self,
args: impl IntoIterator<
Item = (
impl AsRef<[u8]>,
impl AsRef<[u8]>,
impl AsRef<[u8]>,
u64,
u128,
),
>,
) -> Result<(Vec<Result<(MessageId, ProgramId)>>, H256)> {
let calls: Vec<_> = args
.into_iter()
.map(|(code, salt, payload, gas_limit, value)| {
RuntimeCall::Gear(GearCall::upload_program {
code: code.as_ref().to_vec(),
salt: salt.as_ref().to_vec(),
init_payload: payload.as_ref().to_vec(),
gas_limit,
value,
keep_alive: false,
})
})
.collect();
let amount = calls.len();
let tx = self.0.calls.force_batch(calls).await?;
let mut res = Vec::with_capacity(amount);
for event in tx.wait_for_success().await?.iter() {
match event?.as_root_event::<Event>()? {
Event::Gear(GearEvent::MessageQueued {
id,
destination,
entry: MessageEntry::Init,
..
}) => res.push(Ok((id.into(), destination.into()))),
Event::Utility(UtilityEvent::ItemFailed { error }) => {
res.push(Err(self.0.api().decode_error(error).into()))
}
_ => (),
}
}
if res.len() == amount {
Ok((res, tx.block_hash()))
} else {
Err(Error::IncompleteBatchResult(res.len(), amount))
}
}
/// Upload a new program from the file referenced by `path` and initialize
/// it with a byte slice `payload`.
///
/// Same as [`upload_program_bytes`](Self::upload_program_bytes), but reads
/// the program from a file instead of using a byte vector.
///
/// Works with absolute and relative paths (relative to the root dir of the
/// repo).
pub async fn upload_program_bytes_by_path(
&self,
path: impl AsRef<Path>,
salt: impl AsRef<[u8]>,
payload: impl AsRef<[u8]>,
gas_limit: u64,
value: u128,
) -> Result<(MessageId, ProgramId, H256)> {
let code = utils::code_from_os(path)?;
self.upload_program_bytes(code, salt, payload, gas_limit, value)
.await
}
/// Same as [`upload_program_bytes`](Self::upload_program_bytes), but
/// initializes a newly uploaded program with an encoded `payload`.
///
/// # See also
///
/// - [`create_program`](Self::create_program) function creates a program
/// from a previously uploaded code.
/// - [`upload_code`](Self::upload_code) function uploads a code and returns
/// its identifier.
pub async fn upload_program(
&self,
code: impl AsRef<[u8]>,
salt: impl AsRef<[u8]>,
payload: impl Encode,
gas_limit: u64,
value: u128,
) -> Result<(MessageId, ProgramId, H256)> {
self.upload_program_bytes(code, salt, payload.encode(), gas_limit, value)
.await
}
/// Upload a new program from the file referenced by `path` and initialize
/// it with an encoded `payload`.
///
/// Same as [`upload_program`](Self::upload_program), but reads the program
/// from a file instead of using a byte vector.
///
/// Works with absolute and relative paths (relative to the root dir of the
/// repo).
pub async fn upload_program_by_path(
&self,
path: impl AsRef<Path>,
salt: impl AsRef<[u8]>,
payload: impl Encode,
gas_limit: u64,
value: u128,
) -> Result<(MessageId, ProgramId, H256)> {
let code = utils::code_from_os(path)?;
self.upload_program(code, salt, payload, gas_limit, value)
.await
}
fn process_set_code(&self, events: &ExtrinsicEvents<GearConfig>) -> Result<()> {
for event in events.iter() {
let event = event?.as_root_event::<Event>()?;
if let Event::System(SystemEvent::CodeUpdated) = event {
return Ok(());
}
}
Err(Error::EventNotFound)
}
/// Upgrade the runtime with the `code` containing the Wasm code of the new
/// runtime.
///
/// Sends the
/// [`pallet_system::set_code`](https://crates.parity.io/frame_system/pallet/struct.Pallet.html#method.set_code)
/// extrinsic.
pub async fn set_code(&self, code: impl AsRef<[u8]>) -> Result<H256> {
let (block_hash, events) = self
.0
.calls
.sudo_unchecked_weight(
RuntimeCall::System(SystemCall::set_code {
code: code.as_ref().to_vec(),
}),
Weight {
ref_time: 0,
proof_size: 0,
},
)
.await?;
self.process_set_code(&events)?;
Ok(block_hash)
}
/// Upgrade the runtime by reading the code from the file located at the
/// `path`.
///
/// Same as [`set_code`](Self::set_code), but reads the runtime code from a
/// file instead of using a byte vector.
pub async fn set_code_by_path(&self, path: impl AsRef<Path>) -> Result<H256> {
let code = utils::code_from_os(path)?;
self.set_code(code).await
}
/// Upgrade the runtime with the `code` containing the Wasm code of the new
/// runtime but **without** checks.
///
/// Sends the
/// [`pallet_system::set_code_without_checks`](https://crates.parity.io/frame_system/pallet/struct.Pallet.html#method.set_code_without_checks)
/// extrinsic.
pub async fn set_code_without_checks(&self, code: impl AsRef<[u8]>) -> Result<H256> {
let (block_hash, events) = self
.0
.calls
.sudo_unchecked_weight(
RuntimeCall::System(SystemCall::set_code_without_checks {
code: code.as_ref().to_vec(),
}),
Weight {
ref_time: 0,
proof_size: 0,
},
)
.await?;
self.process_set_code(&events)?;
Ok(block_hash)
}
/// Upgrade the runtime by reading the code from the file located at the
/// `path`.
///
/// Same as [`set_code_without_checks`](Self::set_code_without_checks), but
/// reads the runtime code from a file instead of using a byte vector.
pub async fn set_code_without_checks_by_path(&self, path: impl AsRef<Path>) -> Result<H256> {
let code = utils::code_from_os(path)?;
self.set_code_without_checks(code).await
}
/// Set the free balance of the `to` account to `new_free`.
///
/// Sends the [`pallet_balances::set_balance`](https://crates.parity.io/pallet_balances/pallet/struct.Pallet.html#method.set_balance) extrinsic.
pub async fn force_set_balance(
&self,
to: impl Into<MultiAddress<AccountId32, ()>>,
new_free: u128,
) -> Result<H256> {
let events = self
.0
.calls
.sudo_unchecked_weight(
RuntimeCall::Balances(BalancesCall::force_set_balance {
who: to.into().convert(),
new_free,
}),
Weight {
ref_time: 0,
// # TODO
//
// Check this field
proof_size: Default::default(),
},
)
.await?;
Ok(events.0)
}
/// Same as [`upload_code`](Self::upload_code), but upload code
/// using voucher.
pub async fn upload_code_with_voucher(
&self,
voucher_id: VoucherId,
code: impl AsRef<[u8]>,
) -> Result<(CodeId, H256)> {
let tx = self
.0
.calls
.upload_code_with_voucher(voucher_id, code.as_ref().to_vec())
.await?;
for event in tx.wait_for_success().await?.iter() {
if let Event::Gear(GearEvent::CodeChanged {
id,
change: CodeChangeKind::Active { .. },
}) = event?.as_root_event::<Event>()?
{
return Ok((id.into(), tx.block_hash()));
}
}
Err(Error::EventNotFound)
}
/// Same as [`send_message_bytes`](Self::send_message_bytes), but sends a
/// message using voucher.
pub async fn send_message_bytes_with_voucher(
&self,
voucher_id: VoucherId,
destination: ProgramId,
payload: impl AsRef<[u8]>,
gas_limit: u64,
value: u128,
keep_alive: bool,
) -> Result<(MessageId, H256)> {
let payload = payload.as_ref().to_vec();
let tx = self
.0
.calls
.send_message_with_voucher(
voucher_id,
destination,
payload,
gas_limit,
value,
keep_alive,
)
.await?;
for event in tx.wait_for_success().await?.iter() {
if let Event::Gear(GearEvent::MessageQueued {
id,
entry: MessageEntry::Handle,
..
}) = event?.as_root_event::<Event>()?
{
return Ok((id.into(), tx.block_hash()));
}
}
Err(Error::EventNotFound)
}
/// Same as [`send_message_bytes_with_voucher`](Self::send_message_bytes_with_voucher), but sends a
/// message with encoded `payload`.
pub async fn send_message_with_voucher(
&self,
voucher_id: VoucherId,
destination: ProgramId,
payload: impl Encode,
gas_limit: u64,
value: u128,
keep_alive: bool,
) -> Result<(MessageId, H256)> {
self.send_message_bytes_with_voucher(
voucher_id,
destination,
payload.encode(),
gas_limit,
value,
keep_alive,
)
.await
}
/// Same as [`send_reply_bytes`](Self::send_reply_bytes), but sends a reply
/// using voucher.
pub async fn send_reply_bytes_with_voucher(
&self,
voucher_id: VoucherId,
reply_to_id: MessageId,
payload: impl AsRef<[u8]>,
gas_limit: u64,
value: u128,
keep_alive: bool,
) -> Result<(MessageId, u128, H256)> {
let payload = payload.as_ref().to_vec();
let data = self.get_mailbox_message(reply_to_id).await?;
let tx = self
.0
.calls
.send_reply_with_voucher(
voucher_id,
reply_to_id,
payload,
gas_limit,
value,
keep_alive,
)
.await?;
let events = tx.wait_for_success().await?;
let (message, _interval) = data.expect("Data appearance guaranteed above");
for event in events.iter() {
if let Event::Gear(GearEvent::MessageQueued {
id,
entry: MessageEntry::Reply(_),
..
}) = event?.as_root_event::<Event>()?
{
return Ok((id.into(), message.value(), tx.block_hash()));
}
}
Err(Error::EventNotFound)
}
/// Same as [`send_reply_bytes_with_voucher`](Self::send_reply_bytes_with_voucher), but sends a reply
/// with encoded `payload`.
pub async fn send_reply_with_voucher(
&self,
voucher_id: VoucherId,
reply_to_id: MessageId,
payload: impl Encode,
gas_limit: u64,
value: u128,
keep_alive: bool,
) -> Result<(MessageId, u128, H256)> {
self.send_reply_bytes_with_voucher(
voucher_id,
reply_to_id,
payload.encode(),
gas_limit,
value,
keep_alive,
)
.await
}
}