Skip to content

Commit

Permalink
feat: add service methods and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
cdummett committed Oct 25, 2024
1 parent b8ac2d4 commit 838e505
Show file tree
Hide file tree
Showing 5 changed files with 271 additions and 4 deletions.
75 changes: 75 additions & 0 deletions tests/integration/test_vault.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import pytest
import logging
import datetime

import vega_protos as protos
from vega_sim.null_service import VegaServiceNull
from tests.integration.utils.fixtures import vega_service

logger = logging.getLogger(__name__)

ASSET = "asset"
PROPOSER = "proposer"
OWNER = "owner"
FUNDER = "funder"
AUX_BID = "bid"
AUX_ASK = "ask"


@pytest.fixture(scope="function")
def init_tests(vega_service):
# Create a key for proposals.
vega: VegaServiceNull = vega_service

# Create proposer key and initialise network and market
vega.create_key(PROPOSER)
vega.create_key(OWNER)
vega.create_key(FUNDER)
vega.mint(PROPOSER, vega.find_asset_id(symbol="VOTE", enabled=True), 1000)
vega.create_asset(PROPOSER, ASSET, ASSET, 18, quantum=1)
vega.wait_for_total_catchup()
asset_id = vega.find_asset_id(symbol=ASSET, raise_on_missing=True)
vega.mint(OWNER, asset_id, 10000)
vega.mint(FUNDER, asset_id, 10000)
yield vega, asset_id


@pytest.mark.integration
def test_standard_vault(init_tests):
vega: VegaServiceNull = init_tests[0]
asset_id = init_tests[1]
vault_id = vega.create_vault(
key_name=PROPOSER,
asset=asset_id,
fee_period=datetime.timedelta(seconds=1),
management_fee_factor=0.001,
performance_fee_factor=0.001,
redemption_dates=[
protos.vega.vega.RedemptionDate(
redemption_date=int(vega.get_blockchain_time(in_seconds=True) + 5),
redemption_type=protos.vega.vega.RedemptionType.REDEMPTION_TYPE_NORMAL,
max_fraction="1.0",
)
],
cut_off_period_length=datetime.timedelta(seconds=1),
)
vault_id = vault_id.lower()
accs = vega.list_accounts()
for acc in accs:
if acc.owner == vega.wallet.public_key(FUNDER):
og_balance = acc.balance
vega.deposit_to_vault(
key_name=FUNDER,
vault_id=vault_id,
asset_id=asset_id,
amount=500,
)
vega.wait_fn(1)
vega.wait_for_total_catchup()
accs = vega.list_accounts()
for acc in accs:
if acc.owner == vault_id:
assert acc.balance > 0
if acc.owner == vega.wallet.public_key(FUNDER):
ad_balance = acc.balance
assert ad_balance < og_balance
69 changes: 69 additions & 0 deletions vega_sim/builders/commands/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,3 +368,72 @@ def cancel_amm(
return vega_protos.commands.v1.commands.CancelAMM(
market_id=market_id, method=method
)


@raise_custom_build_errors
def create_vault(
asset: str,
vault_metadata: vega_protos.vega.VaultMetaData,
fee_period: int,
management_fee_factor: float,
performance_fee_factor: float,
redemption_dates: List[vega_protos.vega.RedemptionDate],
cut_off_period_length: int,
) -> vega_protos.commands.v1.commands.CreateVault:
transaction = vega_protos.commands.v1.commands.CreateVault(
asset=asset,
vault_metadata=vault_metadata,
fee_period=f"{24*7}h",
management_fee_factor=str(management_fee_factor),
performance_fee_factor=str(performance_fee_factor),
redemption_dates=redemption_dates,
cut_off_period_length=cut_off_period_length,
)
return transaction


@raise_custom_build_errors
def update_vault(
vault_id: str,
vault_metadata: Optional[vega_protos.vega.VaultMetaData] = None,
fee_period: Optional[int] = None,
management_fee_factor: Optional[float] = None,
redemption_dates: Optional[List[vega_protos.vega.RedemptionDate]] = None,
cut_off_period_length: Optional[int] = None,
) -> vega_protos.commands.v1.commands.UpdateVault:
return vega_protos.commands.v1.commands.UpdateVault(
vault_id=vault_id,
vault_metadata=vault_metadata,
fee_period=fee_period,
management_fee_factor=(
str(management_fee_factor) if management_fee_factor else None
),
redemption_dates=redemption_dates,
cut_off_period_length=cut_off_period_length,
)


@raise_custom_build_errors
def deposit_to_vault(
vault_id: str,
amount: float,
asset_id: str,
asset_decimals: Dict[str, int],
) -> vega_protos.commands.v1.commands.DepositToVault:
return vega_protos.commands.v1.commands.DepositToVault(
vault_id=vault_id,
amount=str(num_to_padded_int(amount, asset_decimals[asset_id])),
)


@raise_custom_build_errors
def withdraw_from_vault(
vault_id: str,
amount: float,
asset_id: str,
asset_decimals: Dict[str, int],
) -> vega_protos.commands.v1.commands.WithdrawFromVault:
return vega_protos.commands.v1.commands.WithdrawFromVault(
vault_id=vault_id,
amount=str(num_to_padded_int(amount, asset_decimals[asset_id])),
)
122 changes: 122 additions & 0 deletions vega_sim/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ def __init__(
self._market_to_settlement_asset = None
self._market_to_base_asset = None
self._market_to_quote_asset = None
self._key_to_vault_map = None
self._listen_for_high_volume_stream_updates = (
listen_for_high_volume_stream_updates
)
Expand Down Expand Up @@ -4328,3 +4329,124 @@ def new_protocol_automated_purchase_program(
self.wait_fn(int(time_to_enactment / self.seconds_per_block) + 1)
self.wait_for_thread_catchup()
return proposal_id

def create_vault(
self,
key_name: str,
asset: str,
fee_period: datetime.timedelta,
management_fee_factor: float,
performance_fee_factor: float,
redemption_dates: List[vega_protos.vega.RedemptionDate],
cut_off_period_length: datetime.timedelta,
wallet_name: Optional[str] = None,
) -> str:

# Currently no APIs exist for the vault. We need to create a
# temporary event stream and listen for vault creation events
# in order to extract the vault id.
transaction = build.commands.commands.create_vault(
asset=asset,
vault_metadata=vega_protos.vega.VaultMetaData(
name="MyVault",
description="MyVault",
url="MyVault",
image_url="MyVault",
),
fee_period=int(fee_period.total_seconds()),
management_fee_factor=management_fee_factor,
performance_fee_factor=performance_fee_factor,
redemption_dates=redemption_dates,
cut_off_period_length=int(cut_off_period_length.total_seconds()),
)
return self.wallet.submit_transaction(
key_name=key_name,
wallet_name=wallet_name,
transaction=transaction,
transaction_type="create_vault",
)

def update_vault(
self,
key_name: str,
vault_id: str,
fee_period: datetime.timedelta,
management_fee_factor: float,
performance_fee_factor: float,
redemption_dates: List[vega_protos.vega.RedemptionDate],
cut_off_period_length: datetime.timedelta,
wallet_name: Optional[str] = None,
) -> str:
transaction = build.commands.commands.update_vault(
vault_id=vault_id,
fee_period=int(fee_period.total_seconds()),
management_fee_factor=management_fee_factor,
performance_fee_factor=performance_fee_factor,
redemption_dates=redemption_dates,
cut_off_period_length=int(cut_off_period_length.total_seconds()),
)
return self.wallet.submit_transaction(
key_name=key_name,
wallet_name=wallet_name,
transaction=transaction,
transaction_type="update_vault",
)

def change_vault_ownership(
self,
key_name: str,
vault_id: str,
new_owner: str,
wallet_name: Optional[str] = None,
):
transaction = build.commands.commands.change_vault_ownership(
vault_id=vault_id, new_owner=new_owner
)
self.wallet.submit_transaction(
key_name=key_name,
wallet_name=wallet_name,
transaction=transaction,
transaction_type="change_vault_ownership",
)

def deposit_to_vault(
self,
key_name: str,
vault_id: str,
amount: float,
asset_id: str,
wallet_name: Optional[str] = None,
):
transaction = build.commands.commands.deposit_to_vault(
vault_id=vault_id,
amount=amount,
asset_id=asset_id,
asset_decimals=self.asset_decimals,
)
self.wallet.submit_transaction(
transaction=transaction,
transaction_type="deposit_to_vault",
key_name=key_name,
wallet_name=wallet_name,
)

def withdraw_from_vault(
self,
key_name: str,
vault_id: str,
amount: float,
asset_id: str,
wallet_name: Optional[str] = None,
):
transaction = build.commands.commands.withdraw_from_vault(
vault_id=vault_id,
amount=amount,
asset_id=asset_id,
asset_decimals=self.asset_decimals,
)
self.wallet.submit_transaction(
transaction=transaction,
transaction_type="withdraw_from_vault",
key_name=key_name,
wallet_name=wallet_name,
)
5 changes: 3 additions & 2 deletions vega_sim/wallet/slim_wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def submit_transaction(
transaction: Any,
transaction_type: str,
wallet_name: Optional[str] = None,
):
) -> str:
# if self.remaining_until_height_update <= 0:
# self.block_height = self.core_client.LastBlockHeight(
# core_proto.LastBlockHeightRequest()
Expand Down Expand Up @@ -180,8 +180,9 @@ def submit_transaction(
)

submit_future = self.core_client.SubmitTransaction.future(request)
self.pool.submit(lambda: submit_future.result())
result = self.pool.submit(lambda: submit_future.result()).result()
self.remaining_until_height_update -= 1
return result.tx_hash.lower()

def submit_raw_transaction(self, transaction: core_proto.SubmitTransactionRequest):
submit_future = self.core_client.SubmitTransaction.future(transaction)
Expand Down
4 changes: 2 additions & 2 deletions vega_sim/wallet/vega_wallet.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def submit_transaction(
transaction_type: str,
wallet_name: Optional[int] = None,
max_retries: int = 20,
):
) -> str:
wallet_name = (
wallet_name if wallet_name is not None else self.vega_default_wallet_name
)
Expand Down Expand Up @@ -310,7 +310,7 @@ def submit_transaction(
with self._mutex:
response = requests.post(url, headers=headers, json=submission)
response.raise_for_status()
return
return response.json()["result"]["transactionHash"]
except requests.exceptions.HTTPError as e:
exception = e
if 400 <= exception.response.status_code < 500:
Expand Down

0 comments on commit 838e505

Please sign in to comment.