Skip to content

Commit

Permalink
feat: add support for Soroban Preview 11 (#777)
Browse files Browse the repository at this point in the history
  • Loading branch information
overcat authored Sep 16, 2023
1 parent 5068c18 commit 134a86b
Show file tree
Hide file tree
Showing 71 changed files with 1,148 additions and 1,244 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ xdr/Stellar-contract-config-setting.x

XDRGEN_REPO=overcat/xdrgen
XDRGEN_COMMIT=c98916346eeea7e37aaea039de03c1e5ea0a116a
XDRNEXT_COMMIT=e372df9f677961aac04c5a4cc80a3667f310b29f
XDRNEXT_COMMIT=9ac02641139e6717924fdad716f6e958d0168491

UNAME := $(shell uname)
SED := sed
Expand Down Expand Up @@ -87,7 +87,7 @@ xdr/%.x:
.PHONY: xdr

xdr-clean:
rm .xdr/*.x || true
rm xdr/*.x || true
rm stellar_sdk/xdr/*.py || true
.PHONY: xdr-clean

Expand Down
55 changes: 22 additions & 33 deletions docs/en/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1158,6 +1158,10 @@ ConfigSettingContractComputeV0
------------------------------
.. autoclass:: stellar_sdk.xdr.config_setting_contract_compute_v0.ConfigSettingContractComputeV0

ConfigSettingContractEventsV0
-----------------------------
.. autoclass:: stellar_sdk.xdr.config_setting_contract_events_v0.ConfigSettingContractEventsV0

ConfigSettingContractExecutionLanesV0
-------------------------------------
.. autoclass:: stellar_sdk.xdr.config_setting_contract_execution_lanes_v0.ConfigSettingContractExecutionLanesV0
Expand All @@ -1170,10 +1174,6 @@ ConfigSettingContractLedgerCostV0
---------------------------------
.. autoclass:: stellar_sdk.xdr.config_setting_contract_ledger_cost_v0.ConfigSettingContractLedgerCostV0

ConfigSettingContractMetaDataV0
-------------------------------
.. autoclass:: stellar_sdk.xdr.config_setting_contract_meta_data_v0.ConfigSettingContractMetaDataV0

ConfigSettingEntry
------------------
.. autoclass:: stellar_sdk.xdr.config_setting_entry.ConfigSettingEntry
Expand All @@ -1194,10 +1194,6 @@ ContractCodeEntry
-----------------
.. autoclass:: stellar_sdk.xdr.contract_code_entry.ContractCodeEntry

ContractCodeEntryBody
---------------------
.. autoclass:: stellar_sdk.xdr.contract_code_entry_body.ContractCodeEntryBody

ContractCostParamEntry
----------------------
.. autoclass:: stellar_sdk.xdr.contract_cost_param_entry.ContractCostParamEntry
Expand All @@ -1218,22 +1214,6 @@ ContractDataEntry
-----------------
.. autoclass:: stellar_sdk.xdr.contract_data_entry.ContractDataEntry

ContractDataEntryBody
---------------------
.. autoclass:: stellar_sdk.xdr.contract_data_entry_body.ContractDataEntryBody

ContractDataEntryData
---------------------
.. autoclass:: stellar_sdk.xdr.contract_data_entry_data.ContractDataEntryData

ContractDataFlags
-----------------
.. autoclass:: stellar_sdk.xdr.contract_data_flags.ContractDataFlags

ContractEntryBodyType
---------------------
.. autoclass:: stellar_sdk.xdr.contract_entry_body_type.ContractEntryBodyType

ContractEvent
-------------
.. autoclass:: stellar_sdk.xdr.contract_event.ContractEvent
Expand Down Expand Up @@ -1370,6 +1350,14 @@ ErrorCode
---------
.. autoclass:: stellar_sdk.xdr.error_code.ErrorCode

EvictionIterator
----------------
.. autoclass:: stellar_sdk.xdr.eviction_iterator.EvictionIterator

ExpirationEntry
---------------
.. autoclass:: stellar_sdk.xdr.expiration_entry.ExpirationEntry

ExtensionPoint
--------------
.. autoclass:: stellar_sdk.xdr.extension_point.ExtensionPoint
Expand Down Expand Up @@ -1506,6 +1494,10 @@ Integer
-------
.. autoclass:: stellar_sdk.xdr.base.Integer

InvokeContractArgs
------------------
.. autoclass:: stellar_sdk.xdr.invoke_contract_args.InvokeContractArgs

InvokeHostFunctionOp
--------------------
.. autoclass:: stellar_sdk.xdr.invoke_host_function_op.InvokeHostFunctionOp
Expand Down Expand Up @@ -1642,6 +1634,10 @@ LedgerKeyData
-------------
.. autoclass:: stellar_sdk.xdr.ledger_key_data.LedgerKeyData

LedgerKeyExpiration
-------------------
.. autoclass:: stellar_sdk.xdr.ledger_key_expiration.LedgerKeyExpiration

LedgerKeyLiquidityPool
----------------------
.. autoclass:: stellar_sdk.xdr.ledger_key_liquidity_pool.LedgerKeyLiquidityPool
Expand Down Expand Up @@ -2114,10 +2110,6 @@ SCSpecTypeResult
----------------
.. autoclass:: stellar_sdk.xdr.sc_spec_type_result.SCSpecTypeResult

SCSpecTypeSet
-------------
.. autoclass:: stellar_sdk.xdr.sc_spec_type_set.SCSpecTypeSet

SCSpecTypeTuple
---------------
.. autoclass:: stellar_sdk.xdr.sc_spec_type_tuple.SCSpecTypeTuple
Expand Down Expand Up @@ -2274,10 +2266,6 @@ SorobanAuthorizationEntry
-------------------------
.. autoclass:: stellar_sdk.xdr.soroban_authorization_entry.SorobanAuthorizationEntry

SorobanAuthorizedContractFunction
---------------------------------
.. autoclass:: stellar_sdk.xdr.soroban_authorized_contract_function.SorobanAuthorizedContractFunction

SorobanAuthorizedFunction
-------------------------
.. autoclass:: stellar_sdk.xdr.soroban_authorized_function.SorobanAuthorizedFunction
Expand Down Expand Up @@ -2602,7 +2590,6 @@ Constants
.. autodata:: stellar_sdk.xdr.constants.MASK_ACCOUNT_FLAGS
.. autodata:: stellar_sdk.xdr.constants.MASK_ACCOUNT_FLAGS_V17
.. autodata:: stellar_sdk.xdr.constants.MASK_CLAIMABLE_BALANCE_FLAGS
.. autodata:: stellar_sdk.xdr.constants.MASK_CONTRACT_DATA_FLAGS_V20
.. autodata:: stellar_sdk.xdr.constants.MASK_LEDGER_HEADER_FLAGS
.. autodata:: stellar_sdk.xdr.constants.MASK_OFFERENTRY_FLAGS
.. autodata:: stellar_sdk.xdr.constants.MASK_TRUSTLINE_FLAGS
Expand All @@ -2614,3 +2601,5 @@ Constants
.. autodata:: stellar_sdk.xdr.constants.SC_SPEC_DOC_LIMIT
.. autodata:: stellar_sdk.xdr.constants.TX_ADVERT_VECTOR_MAX_SIZE
.. autodata:: stellar_sdk.xdr.constants.TX_DEMAND_VECTOR_MAX_SIZE
(stellar-sdk-py3.10) py-stellar-base [soroban-update●●]

1 change: 0 additions & 1 deletion examples/soroban_bump_footprint_expiration.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
contract=Address(contract_id).to_xdr_sc_address(),
key=stellar_xdr.SCVal(stellar_xdr.SCValType.SCV_LEDGER_KEY_CONTRACT_INSTANCE),
durability=stellar_xdr.ContractDataDurability.PERSISTENT,
body_type=stellar_xdr.ContractEntryBodyType.DATA_ENTRY,
),
)
soroban_data = SorobanDataBuilder().set_read_only([ledger_key]).build()
Expand Down
1 change: 0 additions & 1 deletion examples/soroban_restore_footprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
contract=Address(contract_id).to_xdr_sc_address(),
key=stellar_xdr.SCVal(stellar_xdr.SCValType.SCV_LEDGER_KEY_CONTRACT_INSTANCE),
durability=stellar_xdr.ContractDataDurability.PERSISTENT,
body_type=stellar_xdr.ContractEntryBodyType.DATA_ENTRY,
),
)
soroban_data = SorobanDataBuilder().set_read_only([ledger_key]).build()
Expand Down
7 changes: 1 addition & 6 deletions stellar_sdk/soroban_data_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ def __init__(self):
read_only=[],
read_write=[],
),
extended_meta_data_size_bytes=stellar_xdr.Uint32(0),
read_bytes=stellar_xdr.Uint32(0),
write_bytes=stellar_xdr.Uint32(0),
instructions=stellar_xdr.Uint32(0),
Expand Down Expand Up @@ -84,7 +83,7 @@ def set_read_write(
return self

def set_resources(
self, instructions: int, read_bytes: int, write_bytes: int, metadata_bytes: int
self, instructions: int, read_bytes: int, write_bytes: int
) -> SorobanDataBuilder:
"""Sets up the resource metrics.
Expand All @@ -94,15 +93,11 @@ def set_resources(
:param instructions: Number of CPU instructions (uint32)
:param read_bytes: Number of bytes being read (uint32)
:param write_bytes: Number of bytes being written (uint32)
:param metadata_bytes: Number of extended metadata bytes (uint32)
:return: This builder.
"""
self._data.resources.instructions = stellar_xdr.Uint32(instructions)
self._data.resources.read_bytes = stellar_xdr.Uint32(read_bytes)
self._data.resources.write_bytes = stellar_xdr.Uint32(write_bytes)
self._data.resources.extended_meta_data_size_bytes = stellar_xdr.Uint32(
metadata_bytes
)
return self

def build(self):
Expand Down
32 changes: 23 additions & 9 deletions stellar_sdk/soroban_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ class EventFilterType(Enum):

class EventFilter(BaseModel):
event_type: Optional[EventFilterType] = Field(alias="type", default=None)
contract_ids: Optional[List[str]] = Field(alias="contractIds", default=None)
topics: Optional[List[List[str]]] = None
contract_ids: Optional[Sequence[str]] = Field(alias="contractIds", default=None)
topics: Optional[Sequence[Sequence[str]]] = None
model_config = ConfigDict(populate_by_name=True)


Expand All @@ -65,7 +65,7 @@ class EventInfo(BaseModel):
contract_id: str = Field(alias="contractId")
id: str = Field(alias="id")
paging_token: str = Field(alias="pagingToken")
topic: Sequence[str] = Field(alias="topic")
topic: List[str] = Field(alias="topic")
value: EventInfoValue = Field(alias="value")
in_successful_contract_call: bool = Field(alias="inSuccessfulContractCall")

Expand Down Expand Up @@ -94,7 +94,7 @@ class GetEventsResponse(BaseModel):
more information.
"""

events: Sequence[EventInfo] = Field(alias="events")
events: List[EventInfo] = Field(alias="events")
latest_ledger: int = Field(alias="latestLedger")


Expand All @@ -105,7 +105,7 @@ class GetLedgerEntriesRequest(BaseModel):
See `getLedgerEntries documentation <https://soroban.stellar.org/api/methods/getLedgerEntries#parameters>`__ for
more information."""

keys: List[str]
keys: Sequence[str]


class LedgerEntryResult(BaseModel):
Expand Down Expand Up @@ -175,19 +175,33 @@ class SimulateHostFunctionResult(BaseModel):
xdr: str


class RestorePreamble(BaseModel):
transaction_data: str = Field(alias="transactionData")
min_resource_fee: int = Field(alias="minResourceFee")


class SimulateTransactionResponse(BaseModel):
"""Response for JSON-RPC method simulateTransaction.
See `simulateTransaction documentation <https://soroban.stellar.org/api/methods/simulateTransaction#returns>`__ for
more information."""

error: Optional[str] = None
# Empty string?
transaction_data: str = Field(alias="transactionData")
transaction_data: Optional[str] = Field(alias="transactionData", default=None)
# SorobanTransactionData XDR in base64
min_resource_fee: Optional[int] = Field(alias="minResourceFee", default=None)
events: Optional[List[str]] = None
min_resource_fee: int = Field(alias="minResourceFee")
# DiagnosticEvent XDR in base64
results: Optional[List[SimulateHostFunctionResult]] = None
cost: SimulateTransactionCost
# an array of the individual host function call results.
# This will only contain a single element if present, because only a single invokeHostFunctionOperation
# is supported per transaction.
cost: Optional[SimulateTransactionCost] = None
# the effective cpu and memory cost of the invoked transaction execution.
restore_preamble: Optional[RestorePreamble] = Field(
alias="restorePreamble", default=None
)
# If present, it indicates that a prior RestoreFootprint is required
latest_ledger: int = Field(alias="latestLedger")


Expand Down
35 changes: 13 additions & 22 deletions stellar_sdk/soroban_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import copy
import json
import uuid
from typing import TYPE_CHECKING, Type
from typing import TYPE_CHECKING, Sequence, Type

from . import Keypair
from . import xdr as stellar_xdr
Expand Down Expand Up @@ -260,7 +260,6 @@ def get_contract_data(
contract=sc_address,
key=key,
durability=xdr_durability,
body_type=stellar_xdr.ContractEntryBodyType.DATA_ENTRY,
),
)
resp = self.get_ledger_entries([contract_key])
Expand Down Expand Up @@ -309,10 +308,6 @@ def prepare_transaction(
"Simulation transaction failed, the response contains error information.",
resp,
)
if not resp.results or len(resp.results) != 1:
raise PrepareTransactionException(
f'Simulation transaction failed, the "results" field is invalid.', resp
)
te = _assemble_transaction(transaction_envelope, resp)
return te

Expand Down Expand Up @@ -358,30 +353,26 @@ def _assemble_transaction(
"type RestoreFootprint, InvokeHostFunction or BumpFootprintExpiration"
)

if not simulation.results or len(simulation.results) != 1:
raise ValueError(f"Simulation results invalid: {simulation.results}")

min_resource_fee = simulation.min_resource_fee
assert simulation.transaction_data is not None
soroban_data = stellar_xdr.SorobanTransactionData.from_xdr(
simulation.transaction_data
)

# TODO: https://discord.com/channels/897514728459468821/1112853306881081354/1112853306881081354
# soroban_data.resources.instructions = stellar_xdr.Uint32(soroban_data.resources.instructions.uint32 * 2)

te = copy.deepcopy(transaction_envelope)
te.signatures = []
assert min_resource_fee is not None
te.transaction.fee += min_resource_fee
te.transaction.soroban_data = soroban_data

op = te.transaction.operations[0]
if (
isinstance(op, InvokeHostFunction)
and not op.auth
and simulation.results[0].auth
):
op.auth = [
stellar_xdr.SorobanAuthorizationEntry.from_xdr(xdr)
for xdr in simulation.results[0].auth
]

if isinstance(op, InvokeHostFunction):
if not simulation.results or len(simulation.results) != 1:
raise ValueError(f"Simulation results invalid: {simulation.results}")

if not op.auth and simulation.results[0].auth:
op.auth = [
stellar_xdr.SorobanAuthorizationEntry.from_xdr(xdr)
for xdr in simulation.results[0].auth
]
return te
17 changes: 7 additions & 10 deletions stellar_sdk/transaction_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -1249,18 +1249,15 @@ def append_invoke_contract_function_op(
if not StrKey.is_valid_contract(contract_id):
raise ValueError("`contract_id` is invalid.")

invoke_params = [
Address(contract_id).to_xdr_sc_val(),
stellar_xdr.SCVal(
stellar_xdr.SCValType.SCV_SYMBOL,
sym=stellar_xdr.SCSymbol(sc_symbol=function_name.encode("utf-8")),
),
*parameters,
]

host_function = stellar_xdr.HostFunction(
stellar_xdr.HostFunctionType.HOST_FUNCTION_TYPE_INVOKE_CONTRACT,
invoke_contract=stellar_xdr.SCVec(invoke_params),
invoke_contract=stellar_xdr.InvokeContractArgs(
contract_address=Address(contract_id).to_xdr_sc_address(),
function_name=stellar_xdr.SCSymbol(
sc_symbol=function_name.encode("utf-8")
),
args=list(parameters),
),
)
op = InvokeHostFunction(host_function=host_function, auth=auth, source=source)
return self.append_operation(op)
Expand Down
Loading

0 comments on commit 134a86b

Please sign in to comment.