Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cookbook for v1 #143

Open
wants to merge 21 commits into
base: feat/next
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fixes
  • Loading branch information
popenta committed Dec 11, 2024
commit 38c3a443fbffe0dade61fdce9e2dce2299c18172
31 changes: 17 additions & 14 deletions examples/v1.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -425,8 425,7 @@
"entrypoint = DevnetEntrypoint()\n",
"api = entrypoint.create_network_provider()\n",
"\n",
"args = GetBlockArguments(block_hash=bytes.fromhex(\n",
" \"1147e111ce8dd860ae43a0f0d403da193a940bfd30b7d7f600701dd5e02f347a\"))\n",
"args = GetBlockArguments(block_hash=bytes.fromhex(\"1147e111ce8dd860ae43a0f0d403da193a940bfd30b7d7f600701dd5e02f347a\"))\n",
"block = api.get_block(arguments=args)"
]
},
Expand Down Expand Up @@ -674,8 673,7 @@
" chain_id=\"D\",\n",
" data=b\"add@07\"\n",
")\n",
"\n",
"transaction_hash = api.simulate_transaction(transaction)"
"transaction_on_network = api.simulate_transaction(transaction)"
]
},
{
Expand All @@ -701,15 699,18 @@
"alice = Address.new_from_bech32(\"erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th\")\n",
"contract = Address.new_from_bech32(\"erd1qqqqqqqqqqqqqpgqccmyzj9sade2495w78h42erfrw7qmqxpd8sss6gmgn\")\n",
"\n",
"nonce = entrypoint.recall_account_nonce(alice)\n",
"\n",
"transaction = Transaction(\n",
" sender=alice,\n",
" receiver=contract,\n",
" gas_limit=5000000,\n",
" chain_id=\"D\",\n",
" data=b\"add@07\"\n",
" data=b\"add@07\",\n",
" nonce=nonce\n",
")\n",
"\n",
"transaction_hash = api.estimate_transaction_cost(transaction)"
"transaction_cost_response = api.estimate_transaction_cost(transaction)"
]
},
{
Expand Down Expand Up @@ -812,6 813,7 @@
"\n",
"alice = Address.new_from_bech32(\"erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th\")\n",
"\n",
"# these tokens are just for the example, they do not belong to Alice\n",
"token = Token(identifier=\"TEST-123456\") # ESDT\n",
"token_on_network = api.get_token_of_account(address=alice, token=token)\n",
"\n",
Expand All @@ -825,7 827,7 @@
"source": [
"### Fetching all fungible tokens of an account\n",
"\n",
"Fetches all fungible tokens held by an account. This method does not handle pagination, but can be achieved by using `do_get_generic`."
"Fetches all fungible tokens held by an account. This method does not handle pagination, that can be achieved by using `do_get_generic`."
]
},
{
Expand All @@ -840,7 842,7 @@
"api = entrypoint.create_network_provider()\n",
"\n",
"alice = Address.new_from_bech32(\"erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th\")\n",
"fungible_token = api.get_fungible_tokens_of_account(address=alice)"
"fungible_tokens = api.get_fungible_tokens_of_account(address=alice)"
]
},
{
Expand All @@ -864,7 866,7 @@
"api = entrypoint.create_network_provider()\n",
"\n",
"alice = Address.new_from_bech32(\"erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th\")\n",
"fungible_token = api.get_non_fungible_tokens_of_account(address=alice)"
"nfts = api.get_non_fungible_tokens_of_account(address=alice)"
]
},
{
Expand Down Expand Up @@ -916,8 918,8 @@
"api = entrypoint.create_network_provider()\n",
"\n",
"query = SmartContractQuery(\n",
" contract=Address.new_from_bech32(\"erd1qqqqq...\"),\n",
" function=\"testFunction\",\n",
" contract=Address.new_from_bech32(\"erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen\"),\n",
" function=\"getSum\",\n",
" arguments=[]\n",
")\n",
"response = api.query_contract(query=query)"
Expand Down Expand Up @@ -1140,7 1142,9 @@
" nonce=alice.get_nonce_then_increment(),\n",
" receiver=Address.new_from_bech32(\"erd1spyavw0956vq68xj8y4tenjpq2wd5a9p2c6j8gsz7ztyrnpxrruqzu66jx\"),\n",
" token_transfers=[first_transfer, second_transfer, third_transfer]\n",
")"
")\n",
"\n",
"tx_hash = entrypoint.send_transaction(transaction)"
]
},
{
Expand Down Expand Up @@ -1400,8 1404,7 @@
")\n",
"\n",
"# broadcasting the transaction\n",
"tx_hash = entrypoint.send_transaction(deploy_transaction)\n",
"print(tx_hash.hex())"
"tx_hash = entrypoint.send_transaction(deploy_transaction)"
]
},
{
Expand Down
2 changes: 1 addition & 1 deletion multiversx_sdk/accounts/account.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 28,7 @@ def new_from_pem(cls, file_path: Path, index: int = 0, hrp: Optional[str] = None
def new_from_keystore(cls,
file_path: Path,
password: str,
address_index: int = 0,
address_index: Optional[int] = None,
hrp: Optional[str] = None) -> "Account":
secret_key = UserWallet.load_secret_key(file_path, password, address_index)
return Account(secret_key, hrp)
Expand Down
18 changes: 13 additions & 5 deletions multiversx_sdk/network_providers/api_network_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 61,11 @@ def get_network_status(self, shard: int = METACHAIN_ID) -> NetworkStatus:
return self.backing_proxy.get_network_status(shard)

def get_block(self, arguments: GetBlockArguments) -> BlockOnNetwork:
"""Fetches a block by nonce or by hash."""
"""Fetches a block by hash."""
if not arguments.block_hash:
raise Exception("Block hash not provided. Please set the `block_hash` in the arguments.")

result = self.do_get_generic(f"blocks/{arguments.block_hash.decode()}")
result = self.do_get_generic(f"blocks/{arguments.block_hash.hex()}")
return block_from_response(result)

def get_latest_block(self, shard: Optional[int] = None) -> BlockOnNetwork:
Expand All @@ -80,7 80,10 @@ def get_account(self, address: Address) -> AccountOnNetwork:
return account

def get_account_storage(self, address: Address) -> AccountStorage:
"""Fetches the storage (key-value pairs) of an account."""
"""
Fetches the storage (key-value pairs) of an account.
When decoding the keys, the errors are ignored. Use the raw values if needed.
"""
response: dict[str, Any] = self.do_get_generic(f"address/{address.to_bech32()}/keys")
return account_storage_from_response(response.get("data", {}))

Expand Down Expand Up @@ -112,9 115,14 @@ def send_transaction(self, transaction: Transaction) -> bytes:
response = self.do_post_generic("transactions", transaction.to_dictionary())
return bytes.fromhex(response.get('txHash', ''))

def simulate_transaction(self, transaction: Transaction) -> TransactionOnNetwork:
def simulate_transaction(self, transaction: Transaction, check_signature: bool = False) -> TransactionOnNetwork:
"""Simulates a transaction."""
response: dict[str, Any] = self.do_post_generic('transaction/simulate', transaction.to_dictionary())
url = 'transaction/simulate?checkSignature=false'

if check_signature:
url = 'transaction/simulate'

response: dict[str, Any] = self.do_post_generic(url, transaction.to_dictionary())
return transaction_from_simulate_response(transaction, response.get("data", {}).get("result", {}))

def estimate_transaction_cost(self, transaction: Transaction) -> TransactionCostResponse:
Expand Down
23 changes: 17 additions & 6 deletions multiversx_sdk/network_providers/api_network_provider_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 47,7 @@ def test_get_block(self):
self.api.get_block(args)

args = GetBlockArguments(
block_hash="ded535cc0afb2dc5f9787e9560dc48d0b83564a3f994a390b228d894d854699f".encode()
block_hash=bytes.fromhex("ded535cc0afb2dc5f9787e9560dc48d0b83564a3f994a390b228d894d854699f")
)
result_by_hash = self.api.get_block(args)

Expand Down Expand Up @@ -192,25 192,36 @@ def test_simulate_transaction(self):
chain_id="D",
)
nonce = self.api.get_account(Address.new_from_bech32(bob.label)).nonce

transaction.nonce = nonce
transaction.signature = bob.secret_key.sign(tx_computer.compute_bytes_for_signing(transaction))

tx_on_network = self.api.simulate_transaction(transaction)
assert tx_on_network.status == TransactionStatus("success")

transaction.signature = bob.secret_key.sign(tx_computer.compute_bytes_for_signing(transaction))

tx_on_network = self.api.simulate_transaction(transaction=transaction, check_signature=True)
assert tx_on_network.status == TransactionStatus("success")

transaction = Transaction(
sender=Address.new_from_bech32(bob.label),
receiver=Address.new_from_bech32("erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"),
gas_limit=10000000,
chain_id="D",
data=b"add@07"
data=b"add@07",
nonce=nonce
)
transaction.nonce = nonce
tx_on_network = self.api.simulate_transaction(transaction)

assert tx_on_network.status == TransactionStatus("success")
assert len(tx_on_network.smart_contract_results) == 1
assert tx_on_network.smart_contract_results[0].sender.to_bech32(
) == "erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"
assert tx_on_network.smart_contract_results[0].receiver.to_bech32() == bob.label
assert tx_on_network.smart_contract_results[0].data == b"@6f6b"

transaction.signature = bob.secret_key.sign(tx_computer.compute_bytes_for_signing(transaction))

tx_on_network = self.api.simulate_transaction(transaction)
tx_on_network = self.api.simulate_transaction(transaction=transaction, check_signature=True)

assert tx_on_network.status == TransactionStatus("success")
assert len(tx_on_network.smart_contract_results) == 1
Expand Down
2 changes: 1 addition & 1 deletion multiversx_sdk/network_providers/http_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 454,7 @@ def account_storage_from_response(raw_response: dict[str, Any]) -> AccountStorag
entries.append(
AccountStorageEntry(
raw={key: value},
key=decoded_key.decode(),
key=decoded_key.decode(errors="ignore"),
value=decoded_value
)
)
Expand Down
17 changes: 12 additions & 5 deletions multiversx_sdk/network_providers/proxy_network_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 74,7 @@ def get_block(self, arguments: GetBlockArguments) -> BlockOnNetwork:
raise Exception("Shard not provided. Please set the shard in the arguments.")

if arguments.block_hash:
response = self.do_get_generic(f"block/{arguments.shard}/by-hash/{arguments.block_hash.decode()}")
response = self.do_get_generic(f"block/{arguments.shard}/by-hash/{arguments.block_hash.hex()}")
elif arguments.block_nonce:
response = self.do_get_generic(f"block/{arguments.shard}/by-nonce/{arguments.block_nonce}")
else:
Expand Down Expand Up @@ -108,7 108,10 @@ def _get_guardian_data(self, address: Address, return_data: dict[str, bool]):
return_data["is_guarded"] = bool(guardian_data.get("guardianData", {}).get("guarded"))

def get_account_storage(self, address: Address) -> AccountStorage:
"""Fetches the storage (key-value pairs) of an account."""
"""
Fetches the storage (key-value pairs) of an account.
When decoding the keys, the errors are ignored. Use the raw values if needed.
"""
response = self.do_get_generic(f"address/{address.to_bech32()}/keys")
return account_storage_from_response(response.to_dictionary())

Expand Down Expand Up @@ -141,10 144,14 @@ def send_transaction(self, transaction: Transaction) -> bytes:
'transaction/send', transaction.to_dictionary())
return bytes.fromhex(response.get('txHash', ''))

def simulate_transaction(self, transaction: Transaction) -> TransactionOnNetwork:
def simulate_transaction(self, transaction: Transaction, check_signature: bool = False) -> TransactionOnNetwork:
"""Simulates a transaction."""
response = self.do_post_generic(
'transaction/simulate', transaction.to_dictionary())
url = 'transaction/simulate?checkSignature=false'

if check_signature:
url = 'transaction/simulate'

response = self.do_post_generic(url, transaction.to_dictionary())
return transaction_from_simulate_response(transaction, response.to_dictionary().get("result", {}))

def estimate_transaction_cost(self, transaction: Transaction) -> TransactionCostResponse:
Expand Down
23 changes: 17 additions & 6 deletions multiversx_sdk/network_providers/proxy_network_provider_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 46,7 @@ def test_get_block(self):
self.proxy.get_block(args)

args = GetBlockArguments(
shard=1, block_hash="ded535cc0afb2dc5f9787e9560dc48d0b83564a3f994a390b228d894d854699f".encode()
shard=1, block_hash=bytes.fromhex("ded535cc0afb2dc5f9787e9560dc48d0b83564a3f994a390b228d894d854699f")
)
result_by_hash = self.proxy.get_block(args)

Expand Down Expand Up @@ -301,25 301,36 @@ def test_simulate_transaction(self):
chain_id="D",
)
nonce = self.proxy.get_account(Address.new_from_bech32(bob.label)).nonce

transaction.nonce = nonce
transaction.signature = bob.secret_key.sign(tx_computer.compute_bytes_for_signing(transaction))

tx_on_network = self.proxy.simulate_transaction(transaction)
assert tx_on_network.status == TransactionStatus("success")

transaction.signature = bob.secret_key.sign(tx_computer.compute_bytes_for_signing(transaction))

tx_on_network = self.proxy.simulate_transaction(transaction=transaction, check_signature=True)
assert tx_on_network.status == TransactionStatus("success")

transaction = Transaction(
sender=Address.new_from_bech32(bob.label),
receiver=Address.new_from_bech32("erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"),
gas_limit=10000000,
chain_id="D",
data=b"add@07"
data=b"add@07",
nonce=nonce
)
transaction.nonce = nonce
tx_on_network = self.proxy.simulate_transaction(transaction)

assert tx_on_network.status == TransactionStatus("success")
assert len(tx_on_network.smart_contract_results) == 1
assert tx_on_network.smart_contract_results[0].sender.to_bech32(
) == "erd1qqqqqqqqqqqqqpgq076flgeualrdu5jyyj60snvrh7zu4qrg05vqez5jen"
assert tx_on_network.smart_contract_results[0].receiver.to_bech32() == bob.label
assert tx_on_network.smart_contract_results[0].data == b"@6f6b"

transaction.signature = bob.secret_key.sign(tx_computer.compute_bytes_for_signing(transaction))

tx_on_network = self.proxy.simulate_transaction(transaction)
tx_on_network = self.proxy.simulate_transaction(transaction=transaction, check_signature=True)

assert tx_on_network.status == TransactionStatus("success")
assert len(tx_on_network.smart_contract_results) == 1
Expand Down
Loading