hopli/safe_module.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 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
//! This module contains arguments and functions to manage safe and module.
//! [SafeModuleSubcommands] defines three subcommands: create, move, and migrate.
//! - [SafeModuleSubcommands::Create] creates staking wallets (safe and node management module)
//! and execute necessary on-chain transactions to setup a HOPR node.
//! Detailed breakdown of the steps:
//! - create a Safe proxy instance and HOPR node management module proxy instance
//! - include nodes configure default permissions on the created module proxy
//! - fund the node and Safe with some native tokens and HOPR tokens respectively
//! - approve HOPR tokens to be transferred from the Safe proxy instaces by Channels contract
//! - Use manager wallet to add nodes and staking safes to the Network Registry contract
//! - [SafeModuleSubcommands::Move] moves a node from to an existing Safe.
//! Note that the Safe should has a node management module attached and configured.
//! Note that the admin key of the old and new safes are the same. This command does not support
//! moving nodes to safes controled by a different admin key.
//! Note that all the safes involved (old and new) should have a threshold of 1
//! Detailed breakdown of the steps:
//! - use old safes to deregister nodes from Node-safe registry
//! - use the new safe to include nodes to the module
//! - use manager wallet to deregister nodes from the network registry
//! - use manager wallet to register nodes with new safes to the network regsitry
//! - [SafeModuleSubcommands::Migrate] migrates a node to a different network.
//! It performs the following steps:
//! - add the Channel contract of the new network to the module as target and set default permissions.
//! - add the Announcement contract as target to the module
//! - approve HOPR tokens of the Safe proxy to be transferred by the new Channels contract
//! - Use the manager wallet to add nodes and Safes to the Network Registry contract of the new network.
//! - [SafeModuleSubcommands::Debug] goes through a series of checks to debug the setup of a node and safe.
//!
//! It checks the following:
//! - node xDAI balance
//! - If node has been included on Network Registry
//! - If node and safe are associated on Node Safe Registry
//! - If Safe is owned by the correct owner(s)
//! - Safe’s wxHOPR balance and allowance
//! - if the module is enabled
//! - if node is included in the module
//! - Get all the targets of the safe (then check if channel and announcement are there)
//! - Get the owner of the module
//!
//! You need to enable the INFO level of the tracing logger to see the output of the debug command.
//!
//! Some sample commands
//! - Express creation of a safe and a module
//! ```text
//! hopli safe-module create \
//! --network anvil-localhost \
//! --contracts-root "../ethereum/contracts" \
//! --identity-directory "./test" \
//! --password-path "./test/pwd" \
//! --admin-address 0x47f2710069F01672D01095cA252018eBf08bF85e,0x0D07Eb66Deb54D48D004765E13DcC028cf56592b \
//! --allowance 10.5 \
//! --hopr-amount 10 \
//! --native-amount 0.1 \
//! --manager-private-key ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \
//! --private-key 59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d \
//! --provider-url "http://localhost:8545"
//!```
//!
//! - Migrate nodes and safe to a new network
//! ```text
//! hopli safe-module migrate \
//! --network anvil-localhost2 \
//! --contracts-root "../ethereum/contracts" \
//! --identity-directory "./test" \
//! --password-path "./test/pwd" \
//! --safe-address 0x6a64fe01c3aba5bdcd04b81fef375369ca47326f \
//! --module-address 0x5d46d0c5279fd85ce7365e4d668f415685922839 \
//! --manager-private-key ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \
//! --private-key 59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d \
//! --provider-url "http://localhost:8545"
//! ```
//!
//! - Move registered nodes to a different set of safe and module
//! ```text
//! hopli safe-module move \
//! --network anvil-localhost \
//! --contracts-root "../ethereum/contracts" \
//! --old-module-address 0x5d46d0c5279fd85ce7365e4d668f415685922839 \
//! --new-safe-address 0xce66d19a86600f3c6eb61edd6c431ded5cc92b21 \
//! --new-module-address 0x3086c20265cf742b169b05cd0eae1941455e4e9f \
//! --node-address 0x93a50B0fFF7b4ED36A3C6445e280E72AC2AEFc51,0x58033D3074D001a32bF379801eaf8969817fFfCf,0xeEDaab91158928647a9270Fe290897eBB1230250 \
//! --manager-private-key ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 \
//! --private-key 59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d \
//! --provider-url "http://localhost:8545"
//!
//! - Debug nodes and safe
//! ```text
//! hopli safe-module debug \
//! --network anvil-localhost2 \
//! --contracts-root "../ethereum/contracts" \
//! --identity-directory "./test" \
//! --password-path "./test/pwd" \
//! --safe-address 0x6a64fe01c3aba5bdcd04b81fef375369ca47326f \
//! --module-address 0x5d46d0c5279fd85ce7365e4d668f415685922839 \
//! --provider-url "http://localhost:8545"
//! ```
use crate::key_pair::{ArgEnvReader, ManagerPrivateKeyArgs};
use crate::methods::{debug_node_safe_module_setup_main, debug_node_safe_module_setup_on_balance_and_registries};
use crate::{
environment_config::NetworkProviderArgs,
key_pair::{IdentityFileArgs, PrivateKeyArgs},
methods::{
deploy_safe_module_with_targets_and_nodes, deregister_nodes_from_node_safe_registry_and_remove_from_module,
include_nodes_to_module, migrate_nodes, register_safes_and_nodes_on_network_registry, safe_singleton,
transfer_native_tokens, transfer_or_mint_tokens,
},
utils::{Cmd, HelperErrors},
};
use clap::{builder::RangedU64ValueParser, Parser};
use ethers::{
types::{H160, U256},
utils::parse_units,
};
use hopr_bindings::{
hopr_network_registry::HoprNetworkRegistry, hopr_node_safe_registry::HoprNodeSafeRegistry,
hopr_node_stake_factory::HoprNodeStakeFactory, hopr_token::HoprToken,
};
use hopr_crypto_types::keypairs::Keypair;
use safe_singleton::SafeSingleton;
use std::str::FromStr;
use tracing::{info, warn};
/// CLI arguments for `hopli safe-module`
#[derive(Clone, Debug, Parser)]
pub enum SafeModuleSubcommands {
/// Create safe and module proxy if nothing exists
#[command(visible_alias = "cr")]
Create {
/// Network name, contracts config file root, and customized provider, if available
#[command(flatten)]
network_provider: NetworkProviderArgs,
/// Arguments to locate identity file(s) of HOPR node(s)
#[command(flatten)]
local_identity: IdentityFileArgs,
/// node addresses
#[clap(
help = "Comma separated node Ethereum addresses",
long,
short = 'o',
default_value = None
)]
node_address: Option<String>,
/// admin addresses
#[clap(
help = "Comma separated node Ethereum addresses",
long,
short = 'a',
default_value = None
)]
admin_address: Option<String>,
/// Threshold for the generated safe
#[clap(
help = "Threshold for the generated safe, e.g. 1",
long,
short,
value_parser = RangedU64ValueParser::<u32>::new().range(1..),
default_value_t = 1
)]
threshold: u32,
/// Allowance of the channel contract to manage HOPR tokens on behalf of deployed safe
#[clap(
help = "Provide the allowance of the channel contract to manage HOPR tokens on behalf of deployed safe. Value in ether, e.g. 10",
long,
short = 'l',
value_parser = clap::value_parser!(f64),
)]
allowance: Option<f64>,
/// The amount of HOPR tokens (in floating number) to be funded to the new safe
#[clap(
help = "Hopr amount in ether, e.g. 10",
long,
short = 'm',
value_parser = clap::value_parser!(f64),
)]
hopr_amount: Option<f64>,
/// The amount of native tokens (in floating number) to be funded per node
#[clap(
help = "Native token amount in ether, e.g. 1",
long,
short = 'g',
value_parser = clap::value_parser!(f64),
)]
native_amount: Option<f64>,
/// Access to the private key, of which the wallet either contains sufficient assets
/// as the source of funds or it can mint necessary tokens
#[command(flatten)]
private_key: PrivateKeyArgs,
/// Access to the private key, of which the wallet has `MANAGER_ROLE` of network registry
/// If provided, this wallet will grant the created safe access to the network registry
#[command(flatten, name = "manager_private_key")]
manager_private_key: ManagerPrivateKeyArgs,
},
/// Migrate safe and module to a new network
#[command(visible_alias = "mg")]
Migrate {
/// Network name, contracts config file root, and customized provider, if available
#[command(flatten)]
network_provider: NetworkProviderArgs,
/// Arguments to locate identity file(s) of HOPR node(s)
#[command(flatten)]
local_identity: IdentityFileArgs,
/// node addresses
#[clap(
help = "Comma separated node Ethereum addresses",
long,
short = 'o',
default_value = None
)]
node_address: Option<String>,
/// safe address that the nodes move to
#[clap(help = "New managing safe to which all the nodes move", long, short = 's')]
safe_address: String,
/// module address that the nodes move to
#[clap(help = "New managing module to which all the nodes move", long, short = 'm')]
module_address: String,
/// Allowance of the channel contract to manage HOPR tokens on behalf of deployed safe
#[clap(
help = "Provide the allowance of the channel contract to manage HOPR tokens on behalf of deployed safe. Value in ether, e.g. 10",
long,
short = 'l',
value_parser = clap::value_parser!(f64),
)]
allowance: Option<f64>,
/// Access to the private key, of which the wallet either contains sufficient assets
/// as the source of funds or it can mint necessary tokens
#[command(flatten)]
private_key: PrivateKeyArgs,
/// Access to the private key, of which the wallet has `MANAGER_ROLE` of network registry
/// If provided, this wallet will grant the created safe access to the network registry
#[command(flatten, name = "manager_private_key")]
manager_private_key: ManagerPrivateKeyArgs,
},
/// Move nodes to one single safe and module pair
#[command(visible_alias = "mv")]
Move {
/// Network name, contracts config file root, and customized provider, if available
#[command(flatten)]
network_provider: NetworkProviderArgs,
/// Arguments to locate identity file(s) of HOPR node(s)
#[command(flatten)]
local_identity: IdentityFileArgs,
/// node addresses
#[clap(
help = "Comma separated node Ethereum addresses",
long,
short = 'o',
default_value = None
)]
node_address: Option<String>,
/// old module addresses
#[clap(help = "Comma separated old module addresses", long, short = 'u')]
old_module_address: String,
/// safe address that the nodes move to
#[clap(help = "New managing safe to which all the nodes move", long, short = 's')]
new_safe_address: String,
/// module address that the nodes move to
#[clap(help = "New managing module to which all the nodes move", long, short = 'm')]
new_module_address: String,
/// Access to the private key, of which the wallet either contains sufficient assets
/// as the source of funds or it can mint necessary tokens
#[command(flatten)]
private_key: PrivateKeyArgs,
/// Access to the private key, of which the wallet has `MANAGER_ROLE` of network registry
/// If provided, this wallet will grant the created safe access to the network registry
#[command(flatten, name = "manager_private_key")]
manager_private_key: ManagerPrivateKeyArgs,
},
/// Debug safe and module setup
#[command(visible_alias = "dg")]
Debug {
/// Network name, contracts config file root, and customized provider, if available
#[command(flatten)]
network_provider: NetworkProviderArgs,
/// Arguments to locate identity file(s) of HOPR node(s)
#[command(flatten)]
local_identity: IdentityFileArgs,
/// node addresses
#[clap(
help = "Comma separated node Ethereum addresses",
long,
short = 'o',
default_value = None
)]
node_address: Option<String>,
/// safe address that the nodes move to
#[clap(help = "New managing safe to which all the nodes move", long, short = 's')]
safe_address: String,
/// module address that the nodes move to
#[clap(help = "New managing module to which all the nodes move", long, short = 'm')]
module_address: String,
},
}
impl SafeModuleSubcommands {
/// Execute the command, which quickly create necessary staking wallets
/// and execute necessary on-chain transactions to setup a HOPR node.
///
/// 1. Create a safe instance and a node management module instance:
/// 2. Set default permissions for the module
/// 3. Include node as a member with restricted permission on sending assets
/// 4. transfer some HOPR token to the new safe (directly)
/// 5. transfer some native tokens to nodes
#[allow(clippy::too_many_arguments)]
pub async fn execute_safe_module_creation(
network_provider: NetworkProviderArgs,
local_identity: IdentityFileArgs,
node_address: Option<String>,
admin_address: Option<String>,
threshold: u32,
allowance: Option<f64>,
hopr_amount: Option<f64>,
native_amount: Option<f64>,
private_key: PrivateKeyArgs,
manager_private_key: ManagerPrivateKeyArgs,
) -> Result<(), HelperErrors> {
// read all the node addresses
let mut node_eth_addresses: Vec<H160> = Vec::new();
if let Some(addresses) = node_address {
node_eth_addresses.extend(
addresses
.split(',')
.map(|addr| {
H160::from_str(addr)
.map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))
})
.collect::<Result<Vec<_>, _>>()?,
);
}
// if local identity dirs/path is provided, read addresses from identity files
node_eth_addresses.extend(
local_identity
.to_addresses()
.map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))?
.into_iter()
.map(H160::from),
);
let node_addresses = if node_eth_addresses.is_empty() {
None
} else {
Some(node_eth_addresses.clone())
};
// get allowance
let token_allowance = match allowance {
Some(allw) => U256::from(
parse_units(allw, "ether")
.map_err(|_| HelperErrors::ParseError("Failed to parse allowance units".into()))?,
),
None => U256::max_value(),
};
// read private key
let signer_private_key = private_key.read_default()?;
// get RPC provider for the given network and environment
let rpc_provider = network_provider.get_provider_with_signer(&signer_private_key).await?;
let contract_addresses = network_provider.get_network_details_from_name()?;
// read all the admin addresses
let admin_eth_addresses: Vec<H160> = match admin_address {
Some(admin_address_str) => admin_address_str
.split(',')
.map(|addr| H160::from_str(addr).unwrap())
.collect(),
None => vec![signer_private_key.clone().public().to_address().into()],
};
// within one multicall, as an owner of the safe
// deploy a safe proxy instance and a module proxy instance with multicall as an owner
// add announcement as a permitted target in the deployed module proxy
// approve token transfer to be done for the safe by channel contracts
// if node addresses are known, include nodes to the module by safe
// transfer safe ownership to actual admins
// set desired threshold
let hopr_stake_factory =
HoprNodeStakeFactory::new(contract_addresses.addresses.node_stake_v2_factory, rpc_provider.clone());
let (safe, node_module) = deploy_safe_module_with_targets_and_nodes(
hopr_stake_factory,
contract_addresses.addresses.token.into(),
contract_addresses.addresses.channels.into(),
contract_addresses.addresses.module_implementation.into(),
contract_addresses.addresses.announcements.into(),
token_allowance,
node_addresses,
admin_eth_addresses,
U256::from(threshold),
)
.await?;
println!("safe {:?}", safe.address());
println!("node_module {:?}", node_module.address());
// direct transfer of some HOPR tokens to the safe
if let Some(hopr_amount_for_safe) = hopr_amount {
let hopr_token = HoprToken::new(contract_addresses.addresses.token, rpc_provider.clone());
let hopr_to_be_transferred = U256::from(
parse_units(hopr_amount_for_safe, "ether")
.map_err(|_| HelperErrors::ParseError("Failed to parse HOPR amount units".into()))?,
);
transfer_or_mint_tokens(hopr_token, vec![safe.address()], vec![hopr_to_be_transferred]).await?;
info!(
"safe {:?} has received {:?} HOPR tokens",
safe.address(),
hopr_amount_for_safe
);
}
// distribute some native tokens to the nodes
if let Some(native_amount_for_node) = native_amount {
let native_to_be_transferred = U256::from(
parse_units(native_amount_for_node, "ether")
.map_err(|_| HelperErrors::ParseError("Failed to parse HOPR amount units".into()))?,
);
let native_amounts = vec![native_to_be_transferred; node_eth_addresses.len()];
transfer_native_tokens(rpc_provider.clone(), node_eth_addresses.clone(), native_amounts).await?;
info!(
"each node in {:?} has received {:?} native tokens",
node_eth_addresses, native_amount_for_node
);
}
// action around network registry
if node_eth_addresses.is_empty() {
info!("No nodes provided. Skip actions around network registry");
return Ok(());
}
// read private key
if let Ok(manager_private_key) = manager_private_key.read_default() {
// get RPC provider for the given network and environment
let manager_rpc_provider = network_provider.get_provider_with_signer(&manager_private_key).await?;
let hopr_network_registry = HoprNetworkRegistry::new(
contract_addresses.addresses.network_registry,
manager_rpc_provider.clone(),
);
// Overwrite any past registration of provided nodes in the network registry.
// This action is the same as calling `hopli network-registry manager-register`
let (removed_pairs_num, added_pairs_num) = register_safes_and_nodes_on_network_registry(
hopr_network_registry,
vec![safe.address(); node_eth_addresses.len()],
node_eth_addresses.clone(),
)
.await?;
info!(
"{:?} pairs have been removed and {:?} pairs have been added to the network registry.",
removed_pairs_num, added_pairs_num
);
} else {
info!("skipping inclusion to the network registry as no manager private key has been provided.");
}
Ok(())
}
/// Execute the command, which moves nodes to a new managing safe and module pair
/// Note that it does not register the node with the new safe on NodeSafeRegistry,
/// because it is an action that nodes need to do on-start.
#[allow(clippy::too_many_arguments)]
pub async fn execute_safe_module_moving(
network_provider: NetworkProviderArgs,
local_identity: IdentityFileArgs,
node_address: Option<String>,
old_module_address: String,
new_safe_address: String,
new_module_address: String,
private_key: PrivateKeyArgs,
manager_private_key: ManagerPrivateKeyArgs,
) -> Result<(), HelperErrors> {
// read all the node addresses
let mut node_eth_addresses: Vec<H160> = Vec::new();
if let Some(addresses) = node_address {
node_eth_addresses.extend(
addresses
.split(',')
.map(|addr| {
H160::from_str(addr)
.map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))
})
.collect::<Result<Vec<_>, _>>()?,
);
}
// if local identity dirs/path is provided, read addresses from identity files
node_eth_addresses.extend(
local_identity
.to_addresses()
.map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))?
.into_iter()
.map(H160::from),
);
// parse safe and module addresses
let safe_addr = H160::from_str(&new_safe_address)
.map_err(|_| HelperErrors::InvalidAddress(format!("Cannot parse safe address {:?}", new_safe_address)))?;
let module_addr = H160::from_str(&new_module_address).map_err(|_| {
HelperErrors::InvalidAddress(format!("Cannot parse module address {:?}", new_module_address))
})?;
let old_module_addr: Vec<H160> = old_module_address
.split(',')
.map(|addr| H160::from_str(addr).unwrap())
.collect();
// read private key
let signer_private_key = private_key.read_default()?;
// get RPC provider for the given network and environment
let rpc_provider = network_provider.get_provider_with_signer(&signer_private_key).await?;
let contract_addresses = network_provider.get_network_details_from_name()?;
// 1. Deregister the old node-safe from node-safe registry
// 2. Remove nodes from the old module
// 3. Include node to the new module
// 4. Remove node from network registry
// 5. Include node to network registry
let hopr_node_safe_registry =
HoprNodeSafeRegistry::new(contract_addresses.addresses.node_safe_registry, rpc_provider.clone());
let safe = SafeSingleton::new(safe_addr, rpc_provider.clone());
if !node_eth_addresses.is_empty() {
// first deregister nodes from their old safe
match deregister_nodes_from_node_safe_registry_and_remove_from_module(
hopr_node_safe_registry.clone(),
node_eth_addresses.clone(),
old_module_addr,
signer_private_key.clone(),
)
.await
{
Ok(_) => {
info!("Nodes are deregistered from old safes");
}
Err(e) => {
return Err(e);
}
};
// then include nodes to module
match include_nodes_to_module(
safe.clone(),
node_eth_addresses.clone(),
module_addr,
signer_private_key,
)
.await
{
Ok(_) => {
info!("Nodes are included to the new module");
}
Err(e) => {
return Err(e);
}
};
};
// action around network registry
if node_eth_addresses.is_empty() {
info!("No nodes provided. Skip actions around network registry");
return Ok(());
}
// read private key of network registry manager
if let Ok(manager_private_key) = manager_private_key.read_default() {
// get RPC provider for the given network and environment
let manager_rpc_provider = network_provider.get_provider_with_signer(&manager_private_key).await?;
let hopr_network_registry = HoprNetworkRegistry::new(
contract_addresses.addresses.network_registry,
manager_rpc_provider.clone(),
);
// Overwrite any past registration of provided nodes in the network registry.
// This action is the same as calling `hopli network-registry manager-register`
let (removed_pairs_num, added_pairs_num) = register_safes_and_nodes_on_network_registry(
hopr_network_registry,
vec![safe.address(); node_eth_addresses.len()],
node_eth_addresses.clone(),
)
.await?;
info!(
"{:?} pairs have been removed and {:?} pairs have been added to the network registry.",
removed_pairs_num, added_pairs_num
);
} else {
info!("skipping inclusion to the network registry as no manager private key has been provided.");
}
Ok(())
}
/// Execute the command, which migrates nodes to a new network
/// Note that it does not register the node with the new safe on NodeSafeRegistry,
/// because it is an action that nodes need to do on-start.
#[allow(clippy::too_many_arguments)]
pub async fn execute_safe_module_migration(
network_provider: NetworkProviderArgs,
local_identity: IdentityFileArgs,
node_address: Option<String>,
safe_address: String,
module_address: String,
allowance: Option<f64>,
private_key: PrivateKeyArgs,
manager_private_key: ManagerPrivateKeyArgs,
) -> Result<(), HelperErrors> {
// read all the node addresses
let mut node_eth_addresses: Vec<H160> = Vec::new();
if let Some(addresses) = node_address {
node_eth_addresses.extend(
addresses
.split(',')
.map(|addr| {
H160::from_str(addr)
.map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))
})
.collect::<Result<Vec<_>, _>>()?,
);
}
// if local identity dirs/path is provided, read addresses from identity files
node_eth_addresses.extend(
local_identity
.to_addresses()
.map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))?
.into_iter()
.map(H160::from),
);
// get allowance
let token_allowance = match allowance {
Some(allw) => U256::from(
parse_units(allw, "ether")
.map_err(|_| HelperErrors::ParseError("Failed to parse allowance units".into()))?,
),
None => U256::max_value(),
};
// parse safe and module addresses
let safe_addr = H160::from_str(&safe_address)
.map_err(|_| HelperErrors::InvalidAddress(format!("Cannot parse safe address {:?}", safe_address)))?;
let module_addr = H160::from_str(&module_address)
.map_err(|_| HelperErrors::InvalidAddress(format!("Cannot parse module address {:?}", module_address)))?;
// read private key
let signer_private_key = private_key.read_default()?;
// get RPC provider for the given network and environment
let rpc_provider = network_provider.get_provider_with_signer(&signer_private_key).await?;
let contract_addresses = network_provider.get_network_details_from_name()?;
let safe = SafeSingleton::new(safe_addr, rpc_provider.clone());
// Create a Safe tx to Multisend contract,
// 1. scope the Channel contract of the new network to the module as target and set default permissions.
// 2. scope the Announcement contract as target to the module
// 3. approve HOPR tokens of the Safe proxy to be transferred by the new Channels contract
migrate_nodes(
safe.clone(),
module_addr,
contract_addresses.addresses.channels.into(),
contract_addresses.addresses.token.into(),
contract_addresses.addresses.announcements.into(),
token_allowance,
signer_private_key,
)
.await?;
info!("a new network has been included due to the migration");
// action around network registry
if node_eth_addresses.is_empty() {
info!("No nodes provided. Skip actions around network registry");
return Ok(());
}
// read private key of network registry manager
if let Ok(manager_private_key) = manager_private_key.read_default() {
// get RPC provider for the given network and environment
let manager_rpc_provider = network_provider.get_provider_with_signer(&manager_private_key).await?;
let hopr_network_registry = HoprNetworkRegistry::new(
contract_addresses.addresses.network_registry,
manager_rpc_provider.clone(),
);
// Overwrite any past registration of provided nodes in the network registry.
// This action is the same as calling `hopli network-registry manager-register`
let (removed_pairs_num, added_pairs_num) = register_safes_and_nodes_on_network_registry(
hopr_network_registry,
vec![safe.address(); node_eth_addresses.len()],
node_eth_addresses.clone(),
)
.await?;
info!(
"{:?} pairs have been removed and {:?} pairs have been added to the network registry.",
removed_pairs_num, added_pairs_num
);
} else {
info!("skipping inclusion to the network registry as no manager private key has been provided.");
}
Ok(())
}
/// Execute the command to debug the following:
/// 1. node xDAI balance
/// 2. If node has been included on Network Registry
/// 3. If node and safe are associated on Node Safe Registry
/// 4. If Safe is owned by the correct owner(s)
/// 5. Safe’s wxHOPR balance and allowance
/// 6. if node is included in the module
/// 7. If the channel contract is included as a target
/// 8. If the announce contract is included as a target
/// 9. If safe is the owner of the module
#[allow(clippy::too_many_arguments)]
pub async fn execute_safe_module_debugging(
network_provider: NetworkProviderArgs,
local_identity: IdentityFileArgs,
node_address: Option<String>,
safe_address: String,
module_address: String,
) -> Result<(), HelperErrors> {
// read all the node addresses
info!("Reading all the node addresses...");
let mut node_eth_addresses: Vec<H160> = Vec::new();
if let Some(addresses) = node_address {
node_eth_addresses.extend(
addresses
.split(',')
.map(|addr| {
H160::from_str(addr)
.map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))
})
.collect::<Result<Vec<_>, _>>()?,
);
}
// if local identity dirs/path is provided, read addresses from identity files
node_eth_addresses.extend(
local_identity
.to_addresses()
.map_err(|e| HelperErrors::InvalidAddress(format!("Invalid node address: {:?}", e)))?
.into_iter()
.map(H160::from),
);
// parse safe and module addresses
let safe_addr = H160::from_str(&safe_address)
.map_err(|_| HelperErrors::InvalidAddress(format!("Cannot parse safe address {:?}", safe_address)))?;
let module_addr = H160::from_str(&module_address)
.map_err(|_| HelperErrors::InvalidAddress(format!("Cannot parse module address {:?}", module_address)))?;
// get RPC provider for the given network and environment
let rpc_provider = network_provider.get_provider_without_signer().await?;
let contract_addresses = network_provider.get_network_details_from_name()?;
let hopr_token = HoprToken::new(contract_addresses.addresses.token, rpc_provider.clone());
let network_registry =
HoprNetworkRegistry::new(contract_addresses.addresses.network_registry, rpc_provider.clone());
let node_safe_registry =
HoprNodeSafeRegistry::new(contract_addresses.addresses.node_safe_registry, rpc_provider.clone());
// loop through all the nodes and debug
for node in node_eth_addresses {
info!("Starting debug checks for node: {:?}", node);
info!("Checking node registration with network registry...");
let registered_safe = debug_node_safe_module_setup_on_balance_and_registries(
network_registry.clone(),
node_safe_registry.clone(),
&node,
)
.await
.map_err(|e| {
HelperErrors::MulticallError(
format!("failed in getting node balance their registration in network registry and node-safe registry: {:?}", e)
)
})?;
// compare the registered safe with the provided safe
if registered_safe != safe_addr {
warn!(
"Node {:?} is not registered with the provided safe {:?}",
node, safe_addr
);
}
info!("Checking node and safe association in node-safe registry...");
debug_node_safe_module_setup_main(
hopr_token.clone(),
&module_addr,
&node,
&safe_addr,
&contract_addresses.addresses.channels.into(),
&contract_addresses.addresses.announcements.into(),
)
.await
.map_err(|e| HelperErrors::MulticallError(format!("failed in debugging safe and module: {:?}", e)))?;
}
Ok(())
}
}
impl Cmd for SafeModuleSubcommands {
/// Run the execute_safe_module_creation function
fn run(self) -> Result<(), HelperErrors> {
// self.execute_safe_module_creation()
Ok(())
}
async fn async_run(self) -> Result<(), HelperErrors> {
match self {
SafeModuleSubcommands::Create {
network_provider,
local_identity,
node_address,
admin_address,
threshold,
allowance,
hopr_amount,
native_amount,
private_key,
manager_private_key,
} => {
SafeModuleSubcommands::execute_safe_module_creation(
network_provider,
local_identity,
node_address,
admin_address,
threshold,
allowance,
hopr_amount,
native_amount,
private_key,
manager_private_key,
)
.await
}
SafeModuleSubcommands::Move {
network_provider,
local_identity,
node_address,
old_module_address,
new_safe_address,
new_module_address,
private_key,
manager_private_key,
} => {
SafeModuleSubcommands::execute_safe_module_moving(
network_provider,
local_identity,
node_address,
old_module_address,
new_safe_address,
new_module_address,
private_key,
manager_private_key,
)
.await
}
SafeModuleSubcommands::Migrate {
network_provider,
local_identity,
node_address,
safe_address,
module_address,
allowance,
private_key,
manager_private_key,
} => {
SafeModuleSubcommands::execute_safe_module_migration(
network_provider,
local_identity,
node_address,
safe_address,
module_address,
allowance,
private_key,
manager_private_key,
)
.await
}
SafeModuleSubcommands::Debug {
network_provider,
local_identity,
node_address,
safe_address,
module_address,
} => {
SafeModuleSubcommands::execute_safe_module_debugging(
network_provider,
local_identity,
node_address,
safe_address,
module_address,
)
.await
}
}
}
}