Skip to content

Commit ed052f1

Browse files
statChristopher Gerber
and
Christopher Gerber
authoredNov 25, 2024··
feat: export wallet address (#48)
* first pass implementing wallet address private key export as a hex string * formatting * implementing feedback * adding additional check for key bytes --------- Co-authored-by: Christopher Gerber <christopher.gerber@coinbase.com>
1 parent 550e459 commit ed052f1

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
 

‎cdp/wallet_address.py

+20
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,26 @@ def can_sign(self) -> bool:
7272
"""
7373
return self.key is not None
7474

75+
def export(self) -> str:
76+
"""Export the wallet address's private key as a hex string.
77+
78+
Returns:
79+
str: The wallet address's private key as a hex string.
80+
81+
Raises:
82+
ValueError: If the wallet address does not have a private key.
83+
84+
"""
85+
local_account = self.key
86+
if local_account is None:
87+
raise ValueError("Private key is unavailable")
88+
89+
key_bytes = local_account.key
90+
if key_bytes is None:
91+
raise ValueError("Private key is empty")
92+
93+
return key_bytes.hex()
94+
7595
def transfer(
7696
self,
7797
amount: Number | Decimal | str,

‎tests/test_wallet_address.py

+19
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,25 @@ def test_key_setter_raises_error_when_already_set(wallet_address_factory):
8181
wallet_address_with_key.key = new_key
8282

8383

84+
def test_export(wallet_address_factory):
85+
"""Test export method success for a WalletAddress."""
86+
wallet_address_with_key = wallet_address_factory(True)
87+
88+
key_hex = wallet_address_with_key.export()
89+
90+
assert key_hex is not None
91+
assert key_hex != ""
92+
assert key_hex.startswith("0x")
93+
94+
95+
def test_export_raises_error_when_local_account_is_none(wallet_address_factory):
96+
"""Test export method failure for a WalletAddress with no LocalAccount."""
97+
wallet_address_without_key = wallet_address_factory()
98+
99+
with pytest.raises(ValueError, match="Private key is unavailable"):
100+
wallet_address_without_key.export()
101+
102+
84103
@patch("cdp.wallet_address.Transfer")
85104
@patch("cdp.Cdp.api_clients")
86105
@patch("cdp.Cdp.use_server_signer", True)

0 commit comments

Comments
 (0)
Please sign in to comment.