Skip to content

Commit

Permalink
add library config to use hrp from
Browse files Browse the repository at this point in the history
  • Loading branch information
popenta committed Nov 29, 2024
1 parent 1755514 commit e53b49c
Show file tree
Hide file tree
Showing 20 changed files with 132 additions and 57 deletions.
15 changes: 8 additions & 7 deletions multiversx_sdk/core/address.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import logging
from typing import Protocol, Tuple
from typing import Optional, Protocol, Tuple

from Cryptodome.Hash import keccak

from multiversx_sdk.core import bech32
from multiversx_sdk.core.constants import DEFAULT_HRP, METACHAIN_ID
from multiversx_sdk.core.config import LibraryConfig
from multiversx_sdk.core.constants import METACHAIN_ID
from multiversx_sdk.core.errors import ErrBadAddress, ErrBadPubkeyLength

SC_HEX_PUBKEY_PREFIX = "0" * 16
Expand All @@ -26,7 +27,7 @@ def get_hrp(self) -> str:
class Address:
"""An Address, as an immutable object."""

def __init__(self, pubkey: bytes, hrp: str) -> None:
def __init__(self, pubkey: bytes, hrp: Optional[str] = None) -> None:
"""Creates an address object, given a sequence of bytes and the human readable part(hrp).
Args:
Expand All @@ -36,7 +37,7 @@ def __init__(self, pubkey: bytes, hrp: str) -> None:
raise ErrBadPubkeyLength(len(pubkey), PUBKEY_LENGTH)

self.pubkey = bytes(pubkey)
self.hrp = hrp
self.hrp = hrp if hrp else LibraryConfig.default_address_hrp

@classmethod
def new_from_bech32(cls, value: str) -> 'Address':
Expand All @@ -53,7 +54,7 @@ def from_bech32(cls, value: str) -> 'Address':
return Address.new_from_bech32(value)

@classmethod
def new_from_hex(cls, value: str, hrp: str) -> 'Address':
def new_from_hex(cls, value: str, hrp: Optional[str] = None) -> 'Address':
"""Creates an address object from the hexed sequence of bytes and the human readable part(hrp).
Args:
Expand Down Expand Up @@ -110,12 +111,12 @@ def __bytes__(self) -> bytes:
class AddressFactory:
"""A factory used to create address objects."""

def __init__(self, hrp: str = DEFAULT_HRP) -> None:
def __init__(self, hrp: Optional[str] = None) -> None:
"""All the addresses created with the factory have the same human readable part
Args:
hrp (str): the human readable part of the address (default: erd)"""
self.hrp = hrp
self.hrp = hrp if hrp else LibraryConfig.default_address_hrp

def create_from_bech32(self, value: str) -> Address:
"""Creates an address object from the bech32 representation of an address"""
Expand Down
11 changes: 11 additions & 0 deletions multiversx_sdk/core/address_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from multiversx_sdk.core.address import (Address, AddressComputer,
AddressFactory, is_valid_bech32)
from multiversx_sdk.core.config import LibraryConfig
from multiversx_sdk.core.errors import ErrBadAddress, ErrBadPubkeyLength


Expand Down Expand Up @@ -71,3 +72,13 @@ def test_compute_contract_address():
contract_address = address_computer.compute_contract_address(deployer, deployment_nonce=1)
assert contract_address.to_hex() == "000000000000000005006e4f90488e27342f9a46e1809452c85ee7186566bd5e"
assert contract_address.to_bech32() == "erd1qqqqqqqqqqqqqpgqde8eqjywyu6zlxjxuxqfg5kgtmn3setxh40qen8egy"


def test_address_with_library_config_hrp():
address = Address(bytes.fromhex("0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1"))
assert address.to_bech32() == "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"

LibraryConfig.default_address_hrp = "test"
address = Address(bytes.fromhex("0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1"))
assert address.to_bech32() == "test1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ss5hqhtr"
LibraryConfig.default_address_hrp = "erd"
17 changes: 17 additions & 0 deletions multiversx_sdk/core/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from dataclasses import dataclass


@dataclass
class LibraryConfig:
"""
Global configuration of the library.
Generally speaking, this configuration should only be altered on exotic use cases
it can be seen as a collection of constants (or , to be more precise, rarely changed variables) that are used throughout the library.
Never alter the configuration within a library!
Only alter the configuration(if needed) within an(end) application that uses this library.
"""

# The human-readable part of the bech32 addresses
default_address_hrp: str = "erd"
10 changes: 10 additions & 0 deletions multiversx_sdk/core/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,19 @@
EGLD_TOKEN_IDENTIFIER = "EGLD"
EGLD_NUM_DECIMALS = 18

# left it for compatibility reasons, will be deleted in the future
DELEGATION_MANAGER_SC_ADDRESS = "erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqylllslmq6y6"

# left it for compatibility reasons, will be deleted in the future
DEFAULT_HRP = "erd"

# left it for compatibility reasons, will be deleted in the future
CONTRACT_DEPLOY_ADDRESS = "erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu"

DELEGATION_MANAGER_SC_ADDRESS_HEX = "000000000000000000010000000000000000000000000000000000000004ffff"
CONTRACT_DEPLOY_ADDRESS_HEX = "0000000000000000000000000000000000000000000000000000000000000000"
ESDT_CONTRACT_ADDRESS_HEX = "000000000000000000010000000000000000000000000000000000000002ffff"

TRANSACTION_OPTIONS_TX_GUARDED = 0b0010
TRANSACTION_OPTIONS_TX_HASH_SIGN = 0b0001

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from multiversx_sdk.core.interfaces import (IAddress, IChainID, IGasPrice,
ITransactionValue)

from multiversx_sdk.core.constants import CONTRACT_DEPLOY_ADDRESS_HEX, ESDT_CONTRACT_ADDRESS_HEX


@dataclass
class DefaultTransactionBuildersConfiguration:
Expand All @@ -19,5 +21,5 @@ class DefaultTransactionBuildersConfiguration:
additional_gas_for_esdt_transfer = 100000
additional_gas_for_esdt_nft_transfer = 800000

esdt_contract_address: IAddress = Address.new_from_bech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u")
deployment_address: IAddress = Address.new_from_bech32("erd1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6gq4hu")
esdt_contract_address: IAddress = Address.new_from_hex(ESDT_CONTRACT_ADDRESS_HEX)
deployment_address: IAddress = Address.new_from_hex(CONTRACT_DEPLOY_ADDRESS_HEX)
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ def _prepare_inner_transaction(self) -> str:
tx["sndUserName"] = base64.b64encode(self.inner_transaction.sender_username.encode()).decode()

if self.inner_transaction.receiver_username:
tx[f"rcvUserName"] = base64.b64encode(self.inner_transaction.receiver_username.encode()).decode()
tx["rcvUserName"] = base64.b64encode(self.inner_transaction.receiver_username.encode()).decode()

return json.dumps(tx, separators=(",", ":"))

Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Protocol, Sequence

from multiversx_sdk.core.address import Address
from multiversx_sdk.core.constants import DELEGATION_MANAGER_SC_ADDRESS
from multiversx_sdk.core.constants import DELEGATION_MANAGER_SC_ADDRESS_HEX
from multiversx_sdk.core.errors import ErrListsLengthMismatch
from multiversx_sdk.core.interfaces import IAddress, IValidatorPublicKey
from multiversx_sdk.core.serializer import arg_to_string
Expand Down Expand Up @@ -41,7 +41,7 @@ def create_transaction_for_new_delegation_contract(self,
transaction = TransactionBuilder(
config=self.config,
sender=sender,
receiver=Address.new_from_bech32(DELEGATION_MANAGER_SC_ADDRESS),
receiver=Address.new_from_hex(DELEGATION_MANAGER_SC_ADDRESS_HEX),
data_parts=parts,
gas_limit=self.config.gas_limit_create_delegation_contract + self.config.additional_gas_for_delegation_operations,
add_data_movement_gas=True,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from multiversx_sdk.core.address import Address
from multiversx_sdk.core.constants import DELEGATION_MANAGER_SC_ADDRESS
from multiversx_sdk.core.constants import DELEGATION_MANAGER_SC_ADDRESS_HEX
from multiversx_sdk.core.transactions_factories.delegation_transactions_factory import \
DelegationTransactionsFactory
from multiversx_sdk.core.transactions_factories.transactions_factory_config import \
Expand All @@ -20,7 +20,7 @@ def test_create_transaction_for_new_delegation_contract(self):
)

assert transaction.sender == "erd18s6a06ktr2v6fgxv4ffhauxvptssnaqlds45qgsrucemlwc8rawq553rt2"
assert transaction.receiver == DELEGATION_MANAGER_SC_ADDRESS
assert transaction.receiver == Address.new_from_hex(DELEGATION_MANAGER_SC_ADDRESS_HEX).to_bech32()
assert transaction.data
assert transaction.data.decode() == "createNewDelegationContract@010f0cf064dd59200000@0a"
assert transaction.gas_limit == 60126500
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from multiversx_sdk.abi.biguint_value import BigUIntValue
from multiversx_sdk.abi.small_int_values import U32Value
from multiversx_sdk.core.address import Address
from multiversx_sdk.core.constants import CONTRACT_DEPLOY_ADDRESS
from multiversx_sdk.core.constants import CONTRACT_DEPLOY_ADDRESS_HEX
from multiversx_sdk.core.tokens import Token, TokenTransfer
from multiversx_sdk.core.transactions_factories.smart_contract_transactions_factory import \
SmartContractTransactionsFactory
Expand Down Expand Up @@ -55,7 +55,7 @@ def test_create_transaction_for_deploy(self):
)

assert transaction.sender == "erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th"
assert transaction.receiver == CONTRACT_DEPLOY_ADDRESS
assert transaction.receiver == Address.new_from_hex(CONTRACT_DEPLOY_ADDRESS_HEX).to_bech32()
assert transaction.data == f"{self.bytecode.hex()}@0500@0504@01".encode()
assert transaction.gas_limit == gas_limit
assert transaction.value == 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from multiversx_sdk.core.address import Address
from multiversx_sdk.core.code_metadata import CodeMetadata
from multiversx_sdk.core.constants import (ARGS_SEPARATOR,
CONTRACT_DEPLOY_ADDRESS,
CONTRACT_DEPLOY_ADDRESS_HEX,
VM_TYPE_WASM_VM)
from multiversx_sdk.core.interfaces import IAddress
from multiversx_sdk.core.serializer import arg_to_string, args_to_buffers
Expand Down Expand Up @@ -72,7 +72,7 @@ def create_transaction_for_deploy(self,
return TransactionBuilder(
config=self.config,
sender=sender,
receiver=Address.new_from_bech32(CONTRACT_DEPLOY_ADDRESS),
receiver=Address.new_from_hex(CONTRACT_DEPLOY_ADDRESS_HEX),
data_parts=parts,
gas_limit=gas_limit,
add_data_movement_gas=False,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from multiversx_sdk.core.address import Address
from multiversx_sdk.core.constants import DEFAULT_HRP
from multiversx_sdk.core.config import LibraryConfig
from multiversx_sdk.core.constants import ESDT_CONTRACT_ADDRESS_HEX
from multiversx_sdk.core.interfaces import IAddress


class TransactionsFactoryConfig:
def __init__(self, chain_id: str) -> None:
# General-purpose configuration
self.chain_id = chain_id
self.address_hrp = DEFAULT_HRP
self.address_hrp = LibraryConfig.default_address_hrp
self.min_gas_limit = 50_000
self.gas_limit_per_byte = 1_500

Expand All @@ -34,7 +35,7 @@ def __init__(self, chain_id: str) -> None:
self.gas_limit_update_token_id = 60_000_000
self.gas_limit_register_dynamic = 60_000_000
self.issue_cost = 50_000_000_000_000_000
self.esdt_contract_address: IAddress = Address.new_from_bech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u")
self.esdt_contract_address: IAddress = Address.new_from_hex(ESDT_CONTRACT_ADDRESS_HEX, self.address_hrp)

# Configuration for delegation operations
self.gas_limit_stake = 5_000_000
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from typing import List

from multiversx_sdk.core.address import Address
from multiversx_sdk.core.config import LibraryConfig
from multiversx_sdk.core.errors import ParseTransactionOutcomeError
from multiversx_sdk.core.transactions_outcome_parsers.delegation_transactions_outcome_parser_types import \
CreateNewDelegationContractOutcome
from multiversx_sdk.core.transactions_outcome_parsers.resources import (
TransactionEvent, TransactionOutcome, find_events_by_identifier)
from multiversx_sdk.network_providers.constants import DEFAULT_ADDRESS_HRP


class DelegationTransactionsOutcomeParser:
Expand Down Expand Up @@ -34,4 +34,4 @@ def _extract_contract_address(self, event: TransactionEvent) -> str:
if not event.topics[0]:
return ""

return Address(event.topics[0], DEFAULT_ADDRESS_HRP).to_bech32()
return Address(event.topics[0], LibraryConfig.default_address_hrp).to_bech32()
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from multiversx_sdk.core.address import Address
from multiversx_sdk.core.config import LibraryConfig
from multiversx_sdk.core.transactions_outcome_parsers.resources import (
TransactionEvent, TransactionOutcome, find_events_by_identifier)
from multiversx_sdk.core.transactions_outcome_parsers.smart_contract_transactions_outcome_parser_types import (
DeployedSmartContract, SmartContractDeployOutcome)
from multiversx_sdk.network_providers.constants import DEFAULT_ADDRESS_HRP


class SmartContractTransactionsOutcomeParser:
Expand All @@ -22,8 +22,8 @@ def _parse_sc_deploy_event(self, event: TransactionEvent) -> DeployedSmartContra
owner_address_topic = event.topics[1] if event.topics[1] else b''
code_hash_topic = event.topics[2] if event.topics[2] else b''

contract_address = Address(contract_address_topic, DEFAULT_ADDRESS_HRP).to_bech32() if len(contract_address_topic) else ""
owner_address = Address(owner_address_topic, DEFAULT_ADDRESS_HRP).to_bech32() if len(owner_address_topic) else ""
contract_address = Address(contract_address_topic, LibraryConfig.default_address_hrp).to_bech32() if len(contract_address_topic) else ""
owner_address = Address(owner_address_topic, LibraryConfig.default_address_hrp).to_bech32() if len(owner_address_topic) else ""
code_hash = code_hash_topic

return DeployedSmartContract(contract_address, owner_address, code_hash)
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from multiversx_sdk.core.address import Address
from multiversx_sdk.core.codec import decode_unsigned_number
from multiversx_sdk.core.constants import DEFAULT_HRP
from multiversx_sdk.core.config import LibraryConfig
from multiversx_sdk.core.errors import ParseTransactionOutcomeError
from multiversx_sdk.core.transactions_outcome_parsers.resources import (
TransactionEvent, TransactionOutcome, find_events_by_identifier)
Expand Down Expand Up @@ -247,4 +247,4 @@ def _extract_address(self, event: TransactionEvent) -> str:
if not event.topics[3]:
return ""

return Address(event.topics[3], DEFAULT_HRP).to_bech32()
return Address(event.topics[3], LibraryConfig.default_address_hrp).to_bech32()
13 changes: 5 additions & 8 deletions multiversx_sdk/network_providers/api_network_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
import requests
from requests.auth import AuthBase

from multiversx_sdk.converters.transactions_converter import \
TransactionsConverter
from multiversx_sdk.network_providers.accounts import (AccountOnNetwork,
GuardianData)
from multiversx_sdk.network_providers.config import (DefaultPagination,
NetworkProviderConfig)
from multiversx_sdk.network_providers.constants import (BASE_USER_AGENT,
DEFAULT_ADDRESS_HRP)
from multiversx_sdk.network_providers.constants import BASE_USER_AGENT
from multiversx_sdk.network_providers.contract_query_requests import \
ContractQueryRequest
from multiversx_sdk.network_providers.contract_query_response import \
Expand All @@ -33,7 +30,8 @@
from multiversx_sdk.network_providers.transaction_status import \
TransactionStatus
from multiversx_sdk.network_providers.transactions import (
ITransaction, TransactionInMempool, TransactionOnNetwork)
ITransaction, TransactionInMempool, TransactionOnNetwork,
transaction_to_dictionary)
from multiversx_sdk.network_providers.user_agent import extend_user_agent
from multiversx_sdk.network_providers.utils import decimal_to_padded_hex

Expand All @@ -43,7 +41,7 @@ def __init__(
self,
url: str,
auth: Union[AuthBase, None] = None,
address_hrp: str = DEFAULT_ADDRESS_HRP,
address_hrp: Optional[str] = None,
config: Optional[NetworkProviderConfig] = None
) -> None:
self.url = url
Expand Down Expand Up @@ -173,8 +171,7 @@ def get_transaction_status(self, tx_hash: str) -> TransactionStatus:

def send_transaction(self, transaction: ITransaction) -> str:
url = 'transactions'
transactions_converter = TransactionsConverter()
response = self.do_post_generic(url, transactions_converter.transaction_to_dictionary(transaction))
response = self.do_post_generic(url, transaction_to_dictionary(transaction))
tx_hash: str = response.get('txHash', '')
return tx_hash

Expand Down
4 changes: 4 additions & 0 deletions multiversx_sdk/network_providers/constants.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
from multiversx_sdk.core.address import Address

# left for compatibility reasons; will be deleted in the future
ESDT_CONTRACT_ADDRESS = Address.new_from_bech32("erd1qqqqqqqqqqqqqqqpqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqzllls8a5w6u")

METACHAIN_ID = 4294967295
MAX_UINT64 = 18446744073709551615

# left for compatibility reasons; will be deleted in the future
DEFAULT_ADDRESS_HRP = "erd"

DEFAULT_TRANSACTION_AWAITING_POLLING_TIMEOUT_IN_MILLISECONDS = 6000
Expand Down
Loading

0 comments on commit e53b49c

Please sign in to comment.