Skip to content

Commit

Permalink
feat: add a helper function to convert SCVal to native types.
Browse files Browse the repository at this point in the history
  • Loading branch information
overcat committed May 14, 2024
1 parent ac59063 commit 964e01f
Showing 1 changed file with 63 additions and 1 deletion.
64 changes: 63 additions & 1 deletion stellar_sdk/scval.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Dict, List, Optional, Sequence, Tuple, Union
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union

from . import xdr as stellar_xdr
from .address import Address
Expand Down Expand Up @@ -49,6 +49,68 @@
]


def native_from_sc_val(
sc_val: Union[stellar_xdr.SCVal, bytes, str]
) -> Union[
bool,
None,
int,
str,
bytes,
Address,
stellar_xdr.SCVal,
List[Any],
Dict[str, Any],
]:
sc_val = _parse_sc_val(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_BOOL:
return sc_val.b
if sc_val.type == stellar_xdr.SCValType.SCV_VOID:
return None
if sc_val.type == stellar_xdr.SCValType.SCV_I32:
return from_int32(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_U32:
return from_uint32(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_I64:
return from_int64(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_U64:
return from_uint64(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_TIMEPOINT:
return from_timepoint(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_DURATION:
return from_duration(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_I128:
return from_int128(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_U128:
return from_uint128(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_I256:
return from_int256(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_U256:
return from_uint256(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_BYTES:
return from_bytes(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_STRING:
s = from_string(sc_val)
try:
return s.decode("utf-8")
except UnicodeDecodeError:
return s
if sc_val.type == stellar_xdr.SCValType.SCV_SYMBOL:
return from_symbol(sc_val)
if sc_val.type == stellar_xdr.SCValType.SCV_VEC:
assert sc_val.vec is not None
return [native_from_sc_val(val) for val in sc_val.vec.sc_vec]
if sc_val.type == stellar_xdr.SCValType.SCV_MAP:
assert sc_val.map is not None
return {
from_symbol(entry.key): native_from_sc_val(entry.val)
for entry in sc_val.map.sc_map
}
if sc_val.type == stellar_xdr.SCValType.SCV_ADDRESS:
return from_address(sc_val)
return sc_val


def to_address(data: Union[Address, str]) -> stellar_xdr.SCVal:
"""Creates a new :class:`stellar_sdk.xdr.SCVal` XDR object from an :class:`stellar_sdk.address.Address` object.
Expand Down

0 comments on commit 964e01f

Please sign in to comment.