Skip to content

Commit d9c9da1

Browse files
committed
Generate Identity from account
1 parent b95e640 commit d9c9da1

2 files changed

Lines changed: 30 additions & 4 deletions

File tree

src/soroban/models.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
import pathlib
2+
13
from pydantic import model_validator, HttpUrl, BaseModel
24
from pydantic_settings import BaseSettings, SettingsConfigDict
35
from stellar_sdk import Keypair, Network
46

5-
__all__ = ["Identity"]
7+
__all__ = ["Identity", "NetworkConfig"]
68

79

810
class Identity(BaseSettings):
@@ -23,6 +25,23 @@ def load_keys(self) -> "Identity":
2325
self.public_key = self.keypair.public_key
2426
return self
2527

28+
@classmethod
29+
def from_source_account(
30+
cls, account: Keypair | str | pathlib.Path | None = None
31+
) -> "Identity":
32+
if account is None:
33+
identity = Identity()
34+
elif isinstance(account, (str, pathlib.Path)):
35+
fname = (
36+
account
37+
if pathlib.Path(account).is_file()
38+
else pathlib.Path(".soroban/identity") / account / ".toml"
39+
)
40+
identity = Identity(_env_file=fname)
41+
else:
42+
identity = Identity(keypair=account)
43+
return identity
44+
2645

2746
class NetworkConfig(BaseSettings):
2847
soroban_rpc_url: HttpUrl = HttpUrl("https://soroban-testnet.stellar.org:443")
@@ -33,4 +52,4 @@ class NetworkConfig(BaseSettings):
3352

3453
class SorobanConfig(BaseModel):
3554
network: NetworkConfig = NetworkConfig()
36-
keys: list[Identity] = [Identity()]
55+
keys: list[Identity] = None

tests/test_models.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,21 @@
88
class TestIdentity:
99

1010
def test_file(self):
11-
alice_fname = pathlib.Path(__file__).parent
12-
soroban.Identity(_env_file=alice_fname / "alice.toml")
11+
alice_fname = pathlib.Path(__file__).parent / "alice.toml"
12+
soroban.Identity(_env_file=alice_fname)
1313

1414
def test_from_pk(self):
1515
keypair = Keypair.random()
1616
soroban.Identity(secret_key=keypair.secret)
1717
soroban.Identity(keypair=keypair)
1818

19+
def test_from_source_account(self):
20+
alice_fname = pathlib.Path(__file__).parent / "alice.toml"
21+
soroban.Identity.from_source_account(account=alice_fname)
22+
23+
keypair = Keypair.random()
24+
soroban.Identity.from_source_account(account=keypair)
25+
1926
def test_raises(self):
2027
with pytest.raises(ValueError, match="provide a secret key or a Keypair"):
2128
soroban.Identity()

0 commit comments

Comments
 (0)