Skip to content

Commit

Permalink
chore: Rename EmergencyWithdrawalAddress: LiquidityRefundAddress (#3970)
Browse files Browse the repository at this point in the history
Co-authored-by: Daniel <daniel@chainflip.io>
Co-authored-by: dandanlen <3168260+dandanlen@users.noreply.github.com>
  • Loading branch information
3 people committed Sep 28, 2023
1 parent 2d64f81 commit c03d046
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 74 deletions.
11 changes: 4 additions & 7 deletions api/bin/chainflip-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,12 @@ async fn run_cli() -> Result<()> {
println!("Deposit Address: {address}");
},
LiquidityProvider(
LiquidityProviderSubcommands::RegisterEmergencyWithdrawalAddress {
chain,
address,
},
LiquidityProviderSubcommands::RegisterLiquidityRefundAddress { chain, address },
) => {
let ewa_address = chainflip_api::clean_foreign_chain_address(chain, &address)?;
let lra_address = chainflip_api::clean_foreign_chain_address(chain, &address)?;
let tx_hash =
api.lp_api().register_emergency_withdrawal_address(ewa_address).await?;
println!("Emergency Withdrawal Address registered. Tx hash: {tx_hash}");
api.lp_api().register_liquidity_refund_address(lra_address).await?;
println!("Liquidity Refund address registered. Tx hash: {tx_hash}");
},
Redeem { amount, eth_address, executor } => {
request_redemption(api, amount, eth_address, executor).await?;
Expand Down
4 changes: 2 additions & 2 deletions api/bin/chainflip-cli/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,9 @@ pub enum LiquidityProviderSubcommands {
/// Asset to deposit.
asset: Asset,
},
/// Register an Emergency Withdrawal Address for the given chain. An address must be
/// Register an Liquidity Refund Address for the given chain. An address must be
/// registered to request a deposit address for the given chain.
RegisterEmergencyWithdrawalAddress { chain: ForeignChain, address: String },
RegisterLiquidityRefundAddress { chain: ForeignChain, address: String },
}

#[derive(Parser, Clone, Debug)]
Expand Down
4 changes: 2 additions & 2 deletions api/bin/chainflip-lp-api/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,11 @@ Return:
- Hex encoded deposit address.


### `lp_registerEmergencyWithdrawalAddress`
### `lp_registerLiquidityRefundAddress`

Parameters:
- Chain: the forein chain where the address belongs to
- Address: Address to be used as Emergency Withdrawal Address.
- Address: Address refunded liquidity will be send to.

e.g. ["Ethereum", "1594300cbd587694AffD70c933B9eE9155B186d9"]

Expand Down
8 changes: 4 additions & 4 deletions api/bin/chainflip-lp-api/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ pub trait Rpc {
asset: Asset,
) -> Result<String, AnyhowRpcError>;

#[method(name = "registerEmergencyWithdrawalAddress")]
async fn register_emergency_withdrawal_address(
#[method(name = "registerLiquidityRefundAddress")]
async fn register_liquidity_refund_address(
&self,
chain: ForeignChain,
address: &str,
Expand Down Expand Up @@ -170,13 +170,13 @@ impl RpcServer for RpcServerImpl {
.map(|address| address.to_string())?)
}

async fn register_emergency_withdrawal_address(
async fn register_liquidity_refund_address(
&self,
chain: ForeignChain,
address: &str,
) -> Result<Hash, AnyhowRpcError> {
let ewa_address = chainflip_api::clean_foreign_chain_address(chain, address)?;
Ok(self.api.lp_api().register_emergency_withdrawal_address(ewa_address).await?)
Ok(self.api.lp_api().register_liquidity_refund_address(ewa_address).await?)
}

/// Returns an egress id
Expand Down
6 changes: 3 additions & 3 deletions api/lib/src/lp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,15 @@ impl LpApi for StateChainClient {}

#[async_trait]
pub trait LpApi: SignedExtrinsicApi {
async fn register_emergency_withdrawal_address(&self, address: EncodedAddress) -> Result<H256> {
async fn register_liquidity_refund_address(&self, address: EncodedAddress) -> Result<H256> {
let (tx_hash, ..) = self
.submit_signed_extrinsic(RuntimeCall::from(
pallet_cf_lp::Call::register_emergency_withdrawal_address { address },
pallet_cf_lp::Call::register_liquidity_refund_address { address },
))
.await
.until_finalized()
.await
.context("Registration for Emergency Withdrawal address failed.")?;
.context("Registration for Liquidity Refund Address failed.")?;
Ok(tx_hash)
}

Expand Down
13 changes: 6 additions & 7 deletions bouncer/shared/provide_liquidity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,22 @@ export async function provideLiquidity(ccy: Asset, amount: number) {
const lpUri = process.env.LP_URI || '//LP_1';
const lp = keyring.createFromUri(lpUri);

// If no emergency withdrawal address is registered, then do that now
// If no liquidity refund address is registered, then do that now
if (
(
await chainflip.query.liquidityProvider.emergencyWithdrawalAddress(
await chainflip.query.liquidityProvider.liquidityRefundAddress(
lp.address,
chainContractIds[assetChains[ccy]],
)
).toJSON() === null
) {
let emergencyAddress = await newAddress(assetToChain(ccy).toUpperCase() as Asset, 'LP_1');
emergencyAddress =
ccy === 'DOT' ? decodeDotAddressForContract(emergencyAddress) : emergencyAddress;
let refundAddress = await newAddress(assetToChain(ccy).toUpperCase() as Asset, 'LP_1');
refundAddress = ccy === 'DOT' ? decodeDotAddressForContract(refundAddress) : refundAddress;

console.log('Registering Emergency Withdrawal Address for ' + ccy + ': ' + emergencyAddress);
console.log('Registering Liquidity Refund Address for ' + ccy + ': ' + refundAddress);
await lpMutex.runExclusive(async () => {
await chainflip.tx.liquidityProvider
.registerEmergencyWithdrawalAddress({ [assetToChain(ccy)]: emergencyAddress })
.registerLiquidityRefundAddress({ [assetToChain(ccy)]: refundAddress })
.signAndSend(lp, { nonce: -1 }, handleSubstrateError(chainflip));
});
}
Expand Down
4 changes: 2 additions & 2 deletions bouncer/tests/double_deposit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ async function main(): Promise<void> {
},
});

// Register Emergency Withdrawal Address before requesting reposit address.
// Register Liquidity Refund Address before requesting reposit address.
const encodedEthAddr = chainflip.createType('EncodedAddress', {
Eth: hexStringToBytesArray(await newAddress('ETH', 'LP_1')),
});
await chainflip.tx.liquidityProvider
.registerEmergencyWithdrawalAddress(encodedEthAddr)
.registerLiquidityRefundAddress(encodedEthAddr)
.signAndSend(lp);

await chainflip.tx.liquidityProvider.requestLiquidityDepositAddress('Eth').signAndSend(lp);
Expand Down
8 changes: 4 additions & 4 deletions state-chain/pallets/cf-lp/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ benchmarks! {
let caller: T::AccountId = whitelisted_caller();
<T as frame_system::Config>::OnNewAccount::on_new_account(&caller);
<T as Chainflip>::AccountRoleRegistry::register_as_liquidity_provider(&caller).unwrap();
let _ = Pallet::<T>::register_emergency_withdrawal_address(
let _ = Pallet::<T>::register_liquidity_refund_address(
RawOrigin::Signed(caller.clone()).into(),
EncodedAddress::Eth(Default::default()),
);
Expand Down Expand Up @@ -46,7 +46,7 @@ benchmarks! {
let caller: T::AccountId = whitelisted_caller();
<T as frame_system::Config>::OnNewAccount::on_new_account(&caller);
let _ = Pallet::<T>::register_lp_account(RawOrigin::Signed(caller.clone()).into());
let _ = Pallet::<T>::register_emergency_withdrawal_address(
let _ = Pallet::<T>::register_liquidity_refund_address(
RawOrigin::Signed(caller.clone()).into(),
EncodedAddress::Eth(Default::default()),
);
Expand All @@ -72,13 +72,13 @@ benchmarks! {
assert_eq!(crate::LpTTL::<T>::get(), ttl);
}

register_emergency_withdrawal_address {
register_liquidity_refund_address {
let caller: T::AccountId = whitelisted_caller();
<T as frame_system::Config>::OnNewAccount::on_new_account(&caller);
<T as Chainflip>::AccountRoleRegistry::register_as_liquidity_provider(&caller).unwrap();
}: _(RawOrigin::Signed(caller.clone()), EncodedAddress::Eth([0x01; 20]))
verify {
assert_eq!(EmergencyWithdrawalAddress::<T>::get(caller, ForeignChain::Ethereum), Some(ForeignChainAddress::Eth([0x01; 20].into())));
assert_eq!(LiquidityRefundAddress::<T>::get(caller, ForeignChain::Ethereum), Some(ForeignChainAddress::Eth([0x01; 20].into())));
}

impl_benchmark_test_suite!(
Expand Down
29 changes: 13 additions & 16 deletions state-chain/pallets/cf-lp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ pub mod pallet {
InvalidEgressAddress,
// Then given encoded address cannot be decoded into a valid ForeignChainAddress.
InvalidEncodedAddress,
// An emergency withdrawal address must be set by the user for the chain before
// An liquidity refund address must be set by the user for the chain before
// deposit address can be requested.
NoEmergencyWithdrawalAddressRegistered,
NoLiquidityRefundAddressRegistered,
// Liquidity deposit is disabled due to Safe Mode.
LiquidityDepositDisabled,
// Withdrawals are disabled due to Safe Mode.
Expand Down Expand Up @@ -128,7 +128,7 @@ pub mod pallet {
LpTtlSet {
ttl: BlockNumberFor<T>,
},
EmergencyWithdrawalAddressRegistered {
LiquidityRefundAddressRegistered {
account_id: T::AccountId,
chain: ForeignChain,
address: ForeignChainAddress,
Expand Down Expand Up @@ -175,7 +175,7 @@ pub mod pallet {

/// Stores the registered energency withdrawal address for an Account
#[pallet::storage]
pub type EmergencyWithdrawalAddress<T: Config> = StorageDoubleMap<
pub type LiquidityRefundAddress<T: Config> = StorageDoubleMap<
_,
Identity,
T::AccountId,
Expand Down Expand Up @@ -203,11 +203,8 @@ pub mod pallet {
let account_id = T::AccountRoleRegistry::ensure_liquidity_provider(origin)?;

ensure!(
EmergencyWithdrawalAddress::<T>::contains_key(
&account_id,
ForeignChain::from(asset)
),
Error::<T>::NoEmergencyWithdrawalAddressRegistered
LiquidityRefundAddress::<T>::contains_key(&account_id, ForeignChain::from(asset)),
Error::<T>::NoLiquidityRefundAddressRegistered
);

let expiry_block =
Expand Down Expand Up @@ -311,15 +308,15 @@ pub mod pallet {
Ok(())
}

/// Registers an Emergency Withdrawal Address (EWA) for an account.
/// To request deposit address for a chain, an EWA must be registered for that chain.
/// Registers an Liquidity Refund Address(LRA) for an account.
/// To request deposit address for a chain, an LRA must be registered for that chain.
///
/// ## Events
///
/// - [On Success](Event::EmergencyWithdrawalAddressRegistered)
/// - [On Success](Event::LiquidityRefundAddressRegistered)
#[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::register_emergency_withdrawal_address())]
pub fn register_emergency_withdrawal_address(
#[pallet::weight(T::WeightInfo::register_liquidity_refund_address())]
pub fn register_liquidity_refund_address(
origin: OriginFor<T>,
address: EncodedAddress,
) -> DispatchResult {
Expand All @@ -328,13 +325,13 @@ pub mod pallet {
let decoded_address = T::AddressConverter::try_from_encoded_address(address)
.map_err(|()| Error::<T>::InvalidEncodedAddress)?;

EmergencyWithdrawalAddress::<T>::insert(
LiquidityRefundAddress::<T>::insert(
&account_id,
decoded_address.chain(),
decoded_address.clone(),
);

Self::deposit_event(Event::<T>::EmergencyWithdrawalAddressRegistered {
Self::deposit_event(Event::<T>::LiquidityRefundAddressRegistered {
account_id,
chain: decoded_address.chain(),
address: decoded_address,
Expand Down
42 changes: 18 additions & 24 deletions state-chain/pallets/cf-lp/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{mock::*, EmergencyWithdrawalAddress, FreeBalances, LiquidityChannelExpiries, LpTTL};
use crate::{mock::*, FreeBalances, LiquidityChannelExpiries, LiquidityRefundAddress, LpTTL};

use cf_chains::{
address::{AddressConverter, EncodedAddress},
Expand Down Expand Up @@ -72,7 +72,7 @@ fn liquidity_providers_can_withdraw_asset() {
fn cannot_deposit_and_withdrawal_during_safe_mode() {
new_test_ext().execute_with(|| {
FreeBalances::<Test>::insert(AccountId::from(LP_ACCOUNT), Asset::Eth, 1_000);
assert_ok!(LiquidityProvider::register_emergency_withdrawal_address(
assert_ok!(LiquidityProvider::register_liquidity_refund_address(
RuntimeOrigin::signed(LP_ACCOUNT.into()),
EncodedAddress::Eth(Default::default()),
));
Expand Down Expand Up @@ -121,7 +121,7 @@ fn cannot_deposit_and_withdrawal_during_safe_mode() {
#[test]
fn deposit_channel_expires() {
new_test_ext().execute_with(|| {
assert_ok!(LiquidityProvider::register_emergency_withdrawal_address(
assert_ok!(LiquidityProvider::register_liquidity_refund_address(
RuntimeOrigin::signed(LP_ACCOUNT.into()),
EncodedAddress::Eth(Default::default()),
));
Expand Down Expand Up @@ -186,34 +186,28 @@ fn can_set_lp_ttl() {
}

#[test]
fn can_register_and_deregister_emergency_withdrawal_address() {
fn can_register_and_deregister_liquidity_refund_address() {
new_test_ext().execute_with(|| {
let account_id = AccountId::from(LP_ACCOUNT);
let encoded_address = EncodedAddress::Eth([0x01; 20]);
let decoded_address = ForeignChainAddress::Eth([0x01; 20].into());
assert!(
EmergencyWithdrawalAddress::<Test>::get(&account_id, ForeignChain::Ethereum).is_none()
);
assert!(LiquidityRefundAddress::<Test>::get(&account_id, ForeignChain::Ethereum).is_none());

// Can register EWA
assert_ok!(LiquidityProvider::register_emergency_withdrawal_address(
assert_ok!(LiquidityProvider::register_liquidity_refund_address(
RuntimeOrigin::signed(account_id.clone()),
encoded_address
));
assert_eq!(
EmergencyWithdrawalAddress::<Test>::get(&account_id, ForeignChain::Ethereum),
LiquidityRefundAddress::<Test>::get(&account_id, ForeignChain::Ethereum),
Some(decoded_address.clone())
);
// Other chain should be unaffected.
assert!(
EmergencyWithdrawalAddress::<Test>::get(&account_id, ForeignChain::Polkadot).is_none()
);
assert!(
EmergencyWithdrawalAddress::<Test>::get(&account_id, ForeignChain::Bitcoin).is_none()
);
assert!(LiquidityRefundAddress::<Test>::get(&account_id, ForeignChain::Polkadot).is_none());
assert!(LiquidityRefundAddress::<Test>::get(&account_id, ForeignChain::Bitcoin).is_none());

System::assert_last_event(RuntimeEvent::LiquidityProvider(
crate::Event::<Test>::EmergencyWithdrawalAddressRegistered {
crate::Event::<Test>::LiquidityRefundAddressRegistered {
account_id: account_id.clone(),
chain: ForeignChain::Ethereum,
address: decoded_address,
Expand All @@ -224,16 +218,16 @@ fn can_register_and_deregister_emergency_withdrawal_address() {
let encoded_address = EncodedAddress::Eth([0x05; 20]);
let decoded_address = ForeignChainAddress::Eth([0x05; 20].into());

assert_ok!(LiquidityProvider::register_emergency_withdrawal_address(
assert_ok!(LiquidityProvider::register_liquidity_refund_address(
RuntimeOrigin::signed(account_id.clone()),
encoded_address,
));
assert_eq!(
EmergencyWithdrawalAddress::<Test>::get(&account_id, ForeignChain::Ethereum),
LiquidityRefundAddress::<Test>::get(&account_id, ForeignChain::Ethereum),
Some(decoded_address.clone()),
);
System::assert_last_event(RuntimeEvent::LiquidityProvider(
crate::Event::<Test>::EmergencyWithdrawalAddressRegistered {
crate::Event::<Test>::LiquidityRefundAddressRegistered {
account_id,
chain: ForeignChain::Ethereum,
address: decoded_address,
Expand All @@ -243,15 +237,15 @@ fn can_register_and_deregister_emergency_withdrawal_address() {
}

#[test]
fn cannot_request_deposit_address_without_registering_emergency_withdrawal_address() {
fn cannot_request_deposit_address_without_registering_liquidity_refund_address() {
new_test_ext().execute_with(|| {
assert_noop!(LiquidityProvider::request_liquidity_deposit_address(
RuntimeOrigin::signed(LP_ACCOUNT.into()),
Asset::Eth,
), crate::Error::<Test>::NoEmergencyWithdrawalAddressRegistered);
), crate::Error::<Test>::NoLiquidityRefundAddressRegistered);

// Register EWA
assert_ok!(LiquidityProvider::register_emergency_withdrawal_address(
assert_ok!(LiquidityProvider::register_liquidity_refund_address(
RuntimeOrigin::signed(LP_ACCOUNT.into()),
EncodedAddress::Eth([0x01; 20])
));
Expand Down Expand Up @@ -282,10 +276,10 @@ fn cannot_request_deposit_address_without_registering_emergency_withdrawal_addre
assert_noop!(LiquidityProvider::request_liquidity_deposit_address(
RuntimeOrigin::signed(LP_ACCOUNT.into()),
Asset::Btc,
), crate::Error::<Test>::NoEmergencyWithdrawalAddressRegistered);
), crate::Error::<Test>::NoLiquidityRefundAddressRegistered);
assert_noop!(LiquidityProvider::request_liquidity_deposit_address(
RuntimeOrigin::signed(LP_ACCOUNT.into()),
Asset::Dot,
), crate::Error::<Test>::NoEmergencyWithdrawalAddressRegistered);
), crate::Error::<Test>::NoLiquidityRefundAddressRegistered);
});
}
6 changes: 3 additions & 3 deletions state-chain/pallets/cf-lp/src/weights.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub trait WeightInfo {
fn register_lp_account() -> Weight;
fn on_initialize(a: u32, ) -> Weight;
fn set_lp_ttl() -> Weight;
fn register_emergency_withdrawal_address() -> Weight;
fn register_liquidity_refund_address() -> Weight;
}

/// Weights for pallet_cf_lp using the Substrate node and recommended hardware.
Expand Down Expand Up @@ -98,7 +98,7 @@ impl<T: frame_system::Config> WeightInfo for PalletWeight<T> {
Weight::from_parts(14_000_000, 0)
.saturating_add(T::DbWeight::get().writes(1))
}
fn register_emergency_withdrawal_address() -> Weight {
fn register_liquidity_refund_address() -> Weight {
Weight::from_parts(1_000_000, 0)
}
}
Expand Down Expand Up @@ -162,7 +162,7 @@ impl WeightInfo for () {
Weight::from_parts(14_000_000, 0)
.saturating_add(RocksDbWeight::get().writes(1))
}
fn register_emergency_withdrawal_address() -> Weight {
fn register_liquidity_refund_address() -> Weight {
Weight::from_parts(1_000_000, 0)
}
}

0 comments on commit c03d046

Please sign in to comment.