Skip to content

Commit

Permalink
Update Python example (#1105)
Browse files Browse the repository at this point in the history
  • Loading branch information
overcat authored Dec 9, 2024
1 parent ecd6989 commit 76482f7
Showing 1 changed file with 40 additions and 85 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -158,97 +158,52 @@ pip install stellar-sdk
:::

```py
import time
from typing import Optional, Union

from stellar_sdk import scval, MuxedAccount, Keypair, Network
from stellar_sdk.contract import AssembledTransaction, ContractClient


# `IncrementContractClient` is automatically generated by stellar-contract-bindings, and you do not need to write it manually.
# See https://github.com/lightsail-network/stellar-contract-bindings
# stellar-contract-bindings python --contract-id CDMARRPKAZEZMASLYONRI4LJI6X3QLDJQ647YGQANG2PDCP746BD5U73 --rpc-url https://soroban-testnet.stellar.org
class IncrementContractClient(ContractClient):
def increment(
self,
source: Union[str, MuxedAccount],
signer: Optional[Keypair] = None,
base_fee: int = 100,
transaction_timeout: int = 300,
submit_timeout: int = 30,
simulate: bool = True,
restore: bool = True,
) -> AssembledTransaction[int]:
"""Increment increments an internal counter, and returns the value."""
return self.invoke(
"increment",
[],
parse_result_xdr_fn=lambda v: scval.from_uint32(v),
source=source,
signer=signer,
base_fee=base_fee,
transaction_timeout=transaction_timeout,
submit_timeout=submit_timeout,
simulate=simulate,
restore=restore,
)

from stellar_sdk import Keypair, Network, SorobanServer, TransactionBuilder, xdr as stellar_xdr
from stellar_sdk.exceptions import PrepareTransactionException
from stellar_sdk.soroban_rpc import GetTransactionStatus, SendTransactionStatus

# The source account will be used to sign and send the transaction.
# GCWY3M4VRW4NXJRI7IVAU3CC7XOPN6PRBG6I5M7TAOQNKZXLT3KAH362
source_keypair = Keypair.from_secret('SCQN3XGRO65BHNSWLSHYIR4B65AHLDUQ7YLHGIWQ4677AZFRS77TCZRB')

# Configure SorobanClient to use the `stellar-rpc` instance of your choosing.
soroban_server = SorobanServer('https://soroban-testnet.stellar.org')

# Here we will use a deployed instance of the `increment` example contract.
contract_address = 'CBEOJUP5FU6KKOEZ7RMTSKZ7YLBS5D6LVATIGCESOGXSZEQ2UWQFKZW6'

# Transactions require a valid sequence number (which varies from one account to
# another). We fetch this sequence number from the RPC server.
source_account = soroban_server.load_account(source_keypair.public_key)

# The transaction begins as pretty standard. The source account, minimum fee,
# and network passphrase are provided.
built_transaction = (
TransactionBuilder(
source_account=source_account,
base_fee=100,
network_passphrase=Network.TESTNET_NETWORK_PASSPHRASE,
)
# The invocation of the `increment` function of our contract is added to the
# transaction. Note: `increment` doesn't require any parameters, but many
# contract functions do. You would need to provide those here.
.append_invoke_contract_function_op(
contract_id=contract_address,
function_name="increment",
parameters=[],
)
# This transaction will be valid for the next 30 seconds
.set_timeout(30)
.build()
)

# We use the RPC server to "prepare" the transaction. This simulating the
# transaction, discovering the storage footprint, and updating the transaction
# to include that footprint. If you know the footprint ahead of time, you could
# manually use `addFootprint` and skip this step.
try:
prepared_transaction = soroban_server.prepare_transaction(built_transaction)
except PrepareTransactionException as e:
print(f"Exception preparing transaction: {e}")
raise e

# Sign the transaction with the source account's keypair.
prepared_transaction.sign(source_keypair)

# Let's see the base64-encoded XDR of the transaction we just built.
print(f"Signed prepared transaction XDR: {prepared_transaction.to_xdr()}")

# Submit the transaction to the Stellar-RPC server. The RPC server will then
# submit the transaction into the network for us. Then we will have to wait,
# polling `getTransaction` until the transaction completes.
send_response = soroban_server.send_transaction(prepared_transaction)
print(f"Sent transaction: {send_response}")

if send_response.status != SendTransactionStatus.PENDING:
raise Exception("sending transaction failed")

# Poll `getTransaction` until the status is not "NOT_FOUND"
while True:
print("Waiting for transaction confirmation...")
# See if the transaction is complete
get_response = soroban_server.get_transaction(send_response.hash)
if get_response.status != GetTransactionStatus.NOT_FOUND:
break
# Wait one second
time.sleep(1)

print(f"get_transaction response: {get_response}")

if get_response.status == GetTransactionStatus.SUCCESS:
# Make sure the transaction's resultMetaXDR is not empty
assert get_response.result_meta_xdr is not None

# Find the return value from the contract and return it
transaction_meta = stellar_xdr.TransactionMeta.from_xdr(
get_response.result_meta_xdr
)
return_value = transaction_meta.v3.soroban_meta.return_value
output = return_value.u32.uint32
print(f"Transaction result: {output}")
else:
print(f"Transaction failed: {get_response.result_xdr}")
rpc_server_url = "https://soroban-testnet.stellar.org:443"
network_passphrase = Network.TESTNET_NETWORK_PASSPHRASE
contract_address = 'CDMARRPKAZEZMASLYONRI4LJI6X3QLDJQ647YGQANG2PDCP746BD5U73'

client = IncrementContractClient(contract_address, rpc_server_url, network_passphrase)
result = client.increment(source_keypair.public_key).sign_and_submit(source_keypair)
print(result)
```

</TabItem>
Expand Down

0 comments on commit 76482f7

Please sign in to comment.