Skip to content

Commit b45f677

Browse files
authored
[CHIA-3604] Port easy CAT endpoints to @marshal (#19992)
* Port `spend_clawback_coins` to `@marshal` * fix tests * fix test again * how do I keep missing these? * Port `select_coins` to `@marshal` * fix tests * fix test * Port `get_spendable_coins` * Port `get_coin_records_by_names` * Port `send_notifications` to `@marshal` * Fixing the thing that is always broken * Remove accidental import * Port `get_default_cat_list` * Port `cat_set_name` * Port `cat_get_name` * Port `get_stray_cats` * Port `cat_get_asset_id` * Port `cat_asset_id_to_name` * Port `check_offer_validity` * Port `get_offers_count`
1 parent 6099c7c commit b45f677

File tree

9 files changed

+252
-137
lines changed

9 files changed

+252
-137
lines changed

chia/_tests/cmds/cmd_test_utils.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@
3333
from chia.wallet.util.tx_config import TXConfig
3434
from chia.wallet.util.wallet_types import WalletType
3535
from chia.wallet.wallet_request_types import (
36+
CATAssetIDToName,
37+
CATAssetIDToNameResponse,
38+
CATGetName,
39+
CATGetNameResponse,
3640
GetSyncStatusResponse,
3741
GetTransaction,
3842
GetTransactionResponse,
@@ -146,9 +150,9 @@ async def get_transaction(self, request: GetTransaction) -> GetTransactionRespon
146150
bytes32([2] * 32),
147151
)
148152

149-
async def get_cat_name(self, wallet_id: int) -> str:
150-
self.add_to_log("get_cat_name", (wallet_id,))
151-
return "test" + str(wallet_id)
153+
async def get_cat_name(self, request: CATGetName) -> CATGetNameResponse:
154+
self.add_to_log("get_cat_name", (request.wallet_id,))
155+
return CATGetNameResponse(request.wallet_id, "test" + str(request.wallet_id))
152156

153157
async def sign_message_by_address(self, request: SignMessageByAddress) -> SignMessageByAddressResponse:
154158
self.add_to_log("sign_message_by_address", (request.address, request.message))
@@ -182,15 +186,15 @@ async def sign_message_by_id(self, request: SignMessageByID) -> SignMessageByIDR
182186
signing_mode = SigningMode.CHIP_0002.value
183187
return SignMessageByIDResponse(pubkey, signature, bytes32.zeros, signing_mode)
184188

185-
async def cat_asset_id_to_name(self, asset_id: bytes32) -> Optional[tuple[Optional[uint32], str]]:
189+
async def cat_asset_id_to_name(self, request: CATAssetIDToName) -> CATAssetIDToNameResponse:
186190
"""
187191
if bytes32([1] * 32), return (uint32(2), "test1"), if bytes32([1] * 32), return (uint32(3), "test2")
188192
"""
189-
self.add_to_log("cat_asset_id_to_name", (asset_id,))
193+
self.add_to_log("cat_asset_id_to_name", (request.asset_id,))
190194
for i in range(256):
191-
if asset_id == get_bytes32(i):
192-
return uint32(i + 1), "test" + str(i)
193-
return None
195+
if request.asset_id == get_bytes32(i):
196+
return CATAssetIDToNameResponse(uint32(i + 1), "test" + str(i))
197+
return CATAssetIDToNameResponse(wallet_id=None, name=None)
194198

195199
async def get_nft_info(self, request: NFTGetInfo) -> NFTGetInfoResponse:
196200
self.add_to_log("get_nft_info", (request.coin_id, request.latest))

chia/_tests/cmds/wallet/test_wallet.py

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@
4343
from chia.wallet.wallet_request_types import (
4444
BalanceResponse,
4545
CancelOfferResponse,
46+
CATAssetIDToName,
47+
CATAssetIDToNameResponse,
48+
CATSetName,
49+
CATSetNameResponse,
4650
CATSpendResponse,
4751
ClawbackPuzzleDecoratorOverride,
4852
CreateOfferForIDsResponse,
@@ -683,8 +687,9 @@ async def create_wallet_for_existing_cat(self, asset_id: bytes) -> dict[str, int
683687
self.add_to_log("create_wallet_for_existing_cat", (asset_id,))
684688
return {"wallet_id": 3}
685689

686-
async def set_cat_name(self, wallet_id: int, name: str) -> None:
687-
self.add_to_log("set_cat_name", (wallet_id, name))
690+
async def set_cat_name(self, request: CATSetName) -> CATSetNameResponse:
691+
self.add_to_log("set_cat_name", (request.wallet_id, request.name))
692+
return CATSetNameResponse(wallet_id=request.wallet_id)
688693

689694
inst_rpc_client = AddTokenRpcClient()
690695
test_rpc_clients.wallet_rpc_client = inst_rpc_client
@@ -1051,14 +1056,14 @@ async def take_offer(
10511056
),
10521057
)
10531058

1054-
async def cat_asset_id_to_name(self, asset_id: bytes32) -> Optional[tuple[Optional[uint32], str]]:
1055-
self.add_to_log("cat_asset_id_to_name", (asset_id,))
1056-
if asset_id == cat_offered_id:
1057-
return uint32(2), "offered cat"
1058-
elif asset_id == cat_requested_id:
1059-
return uint32(3), "requested cat"
1059+
async def cat_asset_id_to_name(self, request: CATAssetIDToName) -> CATAssetIDToNameResponse:
1060+
self.add_to_log("cat_asset_id_to_name", (request.asset_id,))
1061+
if request.asset_id == cat_offered_id:
1062+
return CATAssetIDToNameResponse(uint32(2), "offered cat")
1063+
elif request.asset_id == cat_requested_id:
1064+
return CATAssetIDToNameResponse(uint32(3), "requested cat")
10601065
else:
1061-
return None
1066+
return CATAssetIDToNameResponse(wallet_id=None, name=None)
10621067

10631068
inst_rpc_client = TakeOfferRpcClient()
10641069
test_rpc_clients.wallet_rpc_client = inst_rpc_client

chia/_tests/core/cmds/test_wallet.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
from __future__ import annotations
22

3-
from typing import Any, Optional
3+
from typing import Any
44

55
import pytest
66
from chia_rs.sized_bytes import bytes32
77
from chia_rs.sized_ints import uint32
88

99
from chia.cmds.wallet_funcs import print_offer_summary
10+
from chia.wallet.wallet_request_types import CATAssetIDToName, CATAssetIDToNameResponse
1011

1112
TEST_DUCKSAUCE_ASSET_ID = "1000000000000000000000000000000000000000000000000000000000000001"
1213
TEST_CRUNCHBERRIES_ASSET_ID = "1000000000000000000000000000000000000000000000000000000000000002"
@@ -19,8 +20,8 @@
1920
}
2021

2122

22-
async def cat_name_resolver(asset_id: bytes32) -> Optional[tuple[Optional[uint32], str]]:
23-
return TEST_ASSET_ID_NAME_MAPPING.get(asset_id)
23+
async def cat_name_resolver(request: CATAssetIDToName) -> CATAssetIDToNameResponse:
24+
return CATAssetIDToNameResponse(*TEST_ASSET_ID_NAME_MAPPING.get(request.asset_id, (None, None)))
2425

2526

2627
@pytest.mark.anyio

chia/_tests/core/data_layer/test_data_rpc.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373
from chia.wallet.util.tx_config import DEFAULT_TX_CONFIG
7474
from chia.wallet.wallet import Wallet
7575
from chia.wallet.wallet_node import WalletNode
76-
from chia.wallet.wallet_request_types import DLLatestSingleton
76+
from chia.wallet.wallet_request_types import CheckOfferValidity, DLLatestSingleton
7777
from chia.wallet.wallet_rpc_api import WalletRpcApi
7878
from chia.wallet.wallet_service import WalletService
7979

@@ -222,7 +222,9 @@ async def check_singleton_confirmed(dl: DataLayer, store_id: bytes32) -> bool:
222222

223223
async def process_block_and_check_offer_validity(offer: TradingOffer, offer_setup: OfferSetup) -> bool:
224224
await offer_setup.full_node_api.farm_blocks_to_puzzlehash(count=1, guarantee_transaction_blocks=True)
225-
return (await offer_setup.maker.data_layer.wallet_rpc.check_offer_validity(offer=offer))[1]
225+
return (
226+
await offer_setup.maker.data_layer.wallet_rpc.check_offer_validity(CheckOfferValidity(offer=offer.to_bech32()))
227+
).valid
226228

227229

228230
async def run_cli_cmd(*args: str, root_path: Path) -> asyncio.subprocess.Process:
@@ -1825,9 +1827,11 @@ async def test_make_and_cancel_offer(offer_setup: OfferSetup, reference: MakeAnd
18251827
for _ in range(10):
18261828
if not (
18271829
await offer_setup.maker.data_layer.wallet_rpc.check_offer_validity(
1828-
offer=TradingOffer.from_bytes(hexstr_to_bytes(maker_response["offer"]["offer"])),
1830+
CheckOfferValidity(
1831+
offer=TradingOffer.from_bytes(hexstr_to_bytes(maker_response["offer"]["offer"])).to_bech32()
1832+
),
18291833
)
1830-
)[1]:
1834+
).valid:
18311835
break
18321836
await offer_setup.full_node_api.farm_blocks_to_puzzlehash(count=1, guarantee_transaction_blocks=True)
18331837
await asyncio.sleep(0.5)

chia/_tests/wallet/rpc/test_wallet_rpc.py

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,12 @@
104104
from chia.wallet.wallet_protocol import WalletProtocol
105105
from chia.wallet.wallet_request_types import (
106106
AddKey,
107+
CATAssetIDToName,
108+
CATGetAssetID,
109+
CATGetName,
110+
CATSetName,
107111
CheckDeleteKey,
112+
CheckOfferValidity,
108113
ClawbackPuzzleDecoratorOverride,
109114
CombineCoins,
110115
DefaultCAT,
@@ -1203,25 +1208,23 @@ async def test_cat_endpoints(wallet_environments: WalletTestFramework, wallet_ty
12031208
env_0.wallet_states[uint32(env_0.wallet_aliases["cat0"])].balance.to_json_dict().items()
12041209
<= (await env_0.rpc_client.get_wallet_balance(GetWalletBalance(cat_0_id))).wallet_balance.to_json_dict().items()
12051210
)
1206-
asset_id = await env_0.rpc_client.get_cat_asset_id(cat_0_id)
1207-
assert (await env_0.rpc_client.get_cat_name(cat_0_id)) == wallet_type.default_wallet_name_for_unknown_cat(
1208-
asset_id.hex()
1209-
)
1210-
await env_0.rpc_client.set_cat_name(cat_0_id, "My cat")
1211-
assert (await env_0.rpc_client.get_cat_name(cat_0_id)) == "My cat"
1212-
result = await env_0.rpc_client.cat_asset_id_to_name(asset_id)
1213-
assert result is not None
1214-
wid, name = result
1215-
assert wid == cat_0_id
1216-
assert name == "My cat"
1217-
result = await env_0.rpc_client.cat_asset_id_to_name(bytes32.zeros)
1218-
assert result is None
1211+
asset_id = (await env_0.rpc_client.get_cat_asset_id(CATGetAssetID(cat_0_id))).asset_id
1212+
assert (
1213+
await env_0.rpc_client.get_cat_name(CATGetName(cat_0_id))
1214+
).name == wallet_type.default_wallet_name_for_unknown_cat(asset_id.hex())
1215+
await env_0.rpc_client.set_cat_name(CATSetName(cat_0_id, "My cat"))
1216+
assert (await env_0.rpc_client.get_cat_name(CATGetName(cat_0_id))).name == "My cat"
1217+
asset_to_name_response = await env_0.rpc_client.cat_asset_id_to_name(CATAssetIDToName(asset_id))
1218+
assert asset_to_name_response.wallet_id == cat_0_id
1219+
assert asset_to_name_response.name == "My cat"
1220+
asset_to_name_response = await env_0.rpc_client.cat_asset_id_to_name(CATAssetIDToName(bytes32.zeros))
1221+
assert asset_to_name_response.name is None
12191222
verified_asset_id = next(iter(DEFAULT_CATS.items()))[1]["asset_id"]
1220-
result = await env_0.rpc_client.cat_asset_id_to_name(bytes32.from_hexstr(verified_asset_id))
1221-
assert result is not None
1222-
should_be_none, name = result
1223-
assert should_be_none is None
1224-
assert name == next(iter(DEFAULT_CATS.items()))[1]["name"]
1223+
asset_to_name_response = await env_0.rpc_client.cat_asset_id_to_name(
1224+
CATAssetIDToName(bytes32.from_hexstr(verified_asset_id))
1225+
)
1226+
assert asset_to_name_response.wallet_id is None
1227+
assert asset_to_name_response.name == next(iter(DEFAULT_CATS.items()))[1]["name"]
12251228

12261229
# Creates a second wallet with the same CAT
12271230
res = await env_1.rpc_client.create_wallet_for_existing_cat(asset_id)
@@ -1395,8 +1398,8 @@ async def test_cat_endpoints(wallet_environments: WalletTestFramework, wallet_ty
13951398
await env_0.wallet_state_manager.interested_store.add_unacknowledged_token(
13961399
asset_id, "Unknown", uint32(10000), bytes32(b"\00" * 32)
13971400
)
1398-
cats = await env_0.rpc_client.get_stray_cats()
1399-
assert len(cats) == 1
1401+
stray_cats_response = await env_0.rpc_client.get_stray_cats()
1402+
assert len(stray_cats_response.stray_cats) == 1
14001403

14011404
# Test CAT coin selection
14021405
select_coins_response = await env_0.rpc_client.select_coins(
@@ -1564,8 +1567,9 @@ async def test_offer_endpoints(wallet_environments: WalletTestFramework, wallet_
15641567
}
15651568
assert advanced_summary == summary
15661569

1567-
id, _valid = await env_1.rpc_client.check_offer_validity(offer)
1568-
assert id == offer.name()
1570+
offer_validity_response = await env_1.rpc_client.check_offer_validity(CheckOfferValidity(offer.to_bech32()))
1571+
assert offer_validity_response.id == offer.name()
1572+
assert offer_validity_response.valid
15691573

15701574
all_offers = await env_1.rpc_client.get_all_offers(file_contents=True)
15711575
assert len(all_offers) == 1

chia/cmds/wallet_funcs.py

Lines changed: 25 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@
4545
from chia.wallet.vc_wallet.vc_store import VCProofs
4646
from chia.wallet.wallet_coin_store import GetCoinRecords
4747
from chia.wallet.wallet_request_types import (
48+
CATAssetIDToName,
49+
CATAssetIDToNameResponse,
50+
CATGetName,
51+
CATSetName,
4852
CATSpendResponse,
4953
ClawbackPuzzleDecoratorOverride,
5054
DeleteNotifications,
@@ -92,7 +96,7 @@
9296
)
9397
from chia.wallet.wallet_rpc_client import WalletRpcClient
9498

95-
CATNameResolver = Callable[[bytes32], Awaitable[Optional[tuple[Optional[uint32], str]]]]
99+
CATNameResolver = Callable[[CATAssetIDToName], Awaitable[CATAssetIDToNameResponse]]
96100

97101
transaction_type_descriptions = {
98102
TransactionType.INCOMING_TX: "received",
@@ -184,7 +188,7 @@ async def get_unit_name_for_wallet_id(
184188
}:
185189
name: str = config["network_overrides"]["config"][config["selected_network"]]["address_prefix"].upper()
186190
elif wallet_type in {WalletType.CAT, WalletType.CRCAT, WalletType.RCAT}:
187-
name = await wallet_client.get_cat_name(wallet_id=wallet_id)
191+
name = (await wallet_client.get_cat_name(CATGetName(wallet_id=uint32(wallet_id)))).name
188192
else:
189193
raise LookupError(f"Operation is not supported for Wallet type {wallet_type.name}")
190194

@@ -469,21 +473,19 @@ async def add_token(
469473
root_path: pathlib.Path, wallet_rpc_port: Optional[int], fp: Optional[int], asset_id: bytes32, token_name: str
470474
) -> None:
471475
async with get_wallet_client(root_path, wallet_rpc_port, fp) as (wallet_client, fingerprint, _):
472-
existing_info: Optional[tuple[Optional[uint32], str]] = await wallet_client.cat_asset_id_to_name(asset_id)
473-
if existing_info is None:
474-
wallet_id = None
475-
old_name = None
476-
else:
477-
wallet_id, old_name = existing_info
476+
existing_info = await wallet_client.cat_asset_id_to_name(CATAssetIDToName(asset_id))
478477

479-
if wallet_id is None:
478+
if existing_info.wallet_id is None:
480479
response = await wallet_client.create_wallet_for_existing_cat(asset_id)
481480
wallet_id = response["wallet_id"]
482-
await wallet_client.set_cat_name(wallet_id, token_name)
481+
await wallet_client.set_cat_name(CATSetName(wallet_id, token_name))
483482
print(f"Successfully added {token_name} with wallet id {wallet_id} on key {fingerprint}")
484483
else:
485-
await wallet_client.set_cat_name(wallet_id, token_name)
486-
print(f"Successfully renamed {old_name} with wallet_id {wallet_id} on key {fingerprint} to {token_name}")
484+
await wallet_client.set_cat_name(CATSetName(existing_info.wallet_id, token_name))
485+
print(
486+
f"Successfully renamed {existing_info.name} with wallet_id {existing_info.wallet_id}"
487+
f" on key {fingerprint} to {token_name}"
488+
)
487489

488490

489491
async def make_offer(
@@ -512,9 +514,9 @@ async def make_offer(
512514
try:
513515
b32_id = bytes32.from_hexstr(name)
514516
id: Union[uint32, str] = b32_id.hex()
515-
result = await wallet_client.cat_asset_id_to_name(b32_id)
516-
if result is not None:
517-
name = result[1]
517+
result = await wallet_client.cat_asset_id_to_name(CATAssetIDToName(b32_id))
518+
if result.name is not None:
519+
name = result.name
518520
else:
519521
name = "Unknown CAT"
520522
unit = units["cat"]
@@ -570,7 +572,7 @@ async def make_offer(
570572
name = "XCH"
571573
unit = units["chia"]
572574
else:
573-
name = await wallet_client.get_cat_name(id)
575+
name = (await wallet_client.get_cat_name(CATGetName(id))).name
574576
unit = units["cat"]
575577
if item in offers:
576578
fungible_assets.append(FungibleAsset(name, uint64(abs(int(Decimal(amount) * unit)))))
@@ -678,10 +680,10 @@ async def print_offer_summary(
678680
description = " [Typically represents change returned from the included fee]"
679681
else:
680682
unit = units["cat"]
681-
result = await cat_name_resolver(bytes32.from_hexstr(asset_id))
682-
if result is not None:
683-
wid = str(result[0])
684-
name = result[1]
683+
result = await cat_name_resolver(CATAssetIDToName(bytes32.from_hexstr(asset_id)))
684+
if result.name is not None:
685+
wid = str(result.wallet_id)
686+
name = result.name
685687
output: str = f" - {name}"
686688
mojo_str: str = f"{mojo_amount} {'mojo' if mojo_amount == 1 else 'mojos'}"
687689
if len(wid) > 0:
@@ -844,9 +846,9 @@ async def take_offer(
844846
if fungible_asset_id is None:
845847
nft_royalty_currency = network_xch
846848
else:
847-
result = await wallet_client.cat_asset_id_to_name(fungible_asset_id)
848-
if result is not None:
849-
nft_royalty_currency = result[1]
849+
result = await wallet_client.cat_asset_id_to_name(CATAssetIDToName(fungible_asset_id))
850+
if result.name is not None:
851+
nft_royalty_currency = result.name
850852
fungible_assets.append(
851853
FungibleAsset(nft_royalty_currency, uint64(requested[fungible_asset_id_str]))
852854
)

0 commit comments

Comments
 (0)