Skip to content

Commit

Permalink
Merge pull request #160 from multiversx/library-config
Browse files Browse the repository at this point in the history
Added library config
  • Loading branch information
popenta authored Nov 29, 2024
2 parents 1755514 + 7315a63 commit 057c29f
Show file tree
Hide file tree
Showing 28 changed files with 214 additions and 62 deletions.
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
project = 'multiversx-sdk'
copyright = '2024, MultiversX'
author = 'MultiversX'
release = '0.11.0'
release = '0.19.0'

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
Expand Down
16 changes: 16 additions & 0 deletions docs/multiversx_sdk.abi.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ multiversx\_sdk.abi.bytes\_value module
:undoc-members:
:show-inheritance:

multiversx\_sdk.abi.code\_metadata\_value module
------------------------------------------------

.. automodule:: multiversx_sdk.abi.code_metadata_value
:members:
:undoc-members:
:show-inheritance:

multiversx\_sdk.abi.codec module
--------------------------------

Expand All @@ -92,6 +100,14 @@ multiversx\_sdk.abi.enum\_value module
:undoc-members:
:show-inheritance:

multiversx\_sdk.abi.explicit\_enum\_value module
------------------------------------------------

.. automodule:: multiversx_sdk.abi.explicit_enum_value
:members:
:undoc-members:
:show-inheritance:

multiversx\_sdk.abi.fields module
---------------------------------

Expand Down
8 changes: 8 additions & 0 deletions docs/multiversx_sdk.core.rst
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ multiversx\_sdk.core.codec module
:undoc-members:
:show-inheritance:

multiversx\_sdk.core.config module
----------------------------------

.. automodule:: multiversx_sdk.core.config
:members:
:undoc-members:
:show-inheritance:

multiversx\_sdk.core.contract\_query module
-------------------------------------------

Expand Down
8 changes: 8 additions & 0 deletions docs/multiversx_sdk.network_providers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,14 @@ multiversx\_sdk.network\_providers.transactions module
:undoc-members:
:show-inheritance:

multiversx\_sdk.network\_providers.user\_agent module
-----------------------------------------------------

.. automodule:: multiversx_sdk.network_providers.user_agent
:members:
:undoc-members:
:show-inheritance:

multiversx\_sdk.network\_providers.utils module
-----------------------------------------------

Expand Down
43 changes: 42 additions & 1 deletion examples/Cookbook.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,47 @@
"print(\"Is contract:\", address.is_smart_contract())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Changing the default hrp\n",
"\n",
"We have a configuration class, called `LibraryConfig`, that only stores (for the moment) the **default hrp** of the addresses. The default value is `erd`. The hrp can be changed when instantiating an address, or it can be changed in the `LibraryConfig` class, and all the addresses created will have the newly set hrp. "
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"erd\n",
"erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th\n",
"test1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ss5hqhtr\n"
]
}
],
"source": [
"from multiversx_sdk import Address\n",
"from multiversx_sdk import LibraryConfig\n",
"\n",
"\n",
"print(LibraryConfig.default_address_hrp)\n",
"address = Address.new_from_hex(\"0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1\")\n",
"print(address.to_bech32())\n",
"\n",
"LibraryConfig.default_address_hrp = \"test\"\n",
"address = Address.new_from_hex(\"0139472eff6886771a982f3083da5d421f24c29181e63888228dc81ca60d69e1\")\n",
"print(address.to_bech32())\n",
"\n",
"# setting back the default value\n",
"LibraryConfig.default_address_hrp = \"erd\""
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down Expand Up @@ -2249,7 +2290,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.4"
"version": "3.12.3"
},
"orig_nbformat": 4,
"vscode": {
Expand Down
4 changes: 3 additions & 1 deletion multiversx_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from multiversx_sdk.core.address import (Address, AddressComputer,
AddressFactory)
from multiversx_sdk.core.code_metadata import CodeMetadata
from multiversx_sdk.core.config import LibraryConfig
from multiversx_sdk.core.contract_query import ContractQuery
from multiversx_sdk.core.contract_query_builder import ContractQueryBuilder
from multiversx_sdk.core.message import Message, MessageComputer
Expand Down Expand Up @@ -84,5 +85,6 @@
"UserWallet", "UserPEM", "QueryRunnerAdapter", "TransactionsConverter", "DelegationTransactionsOutcomeParser",
"find_events_by_identifier", "find_events_by_first_topic", "SmartContractTransactionsOutcomeParser", "TransactionAwaiter",
"SmartContractQueriesController", "SmartContractQuery", "SmartContractQueryResponse",
"TransactionDecoder", "TransactionMetadata", "TransactionEventsParser", "NetworkProviderConfig"
"TransactionDecoder", "TransactionMetadata", "TransactionEventsParser", "NetworkProviderConfig",
"LibraryConfig"
]
4 changes: 3 additions & 1 deletion multiversx_sdk/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from multiversx_sdk.core.address import (Address, AddressComputer,
AddressFactory)
from multiversx_sdk.core.code_metadata import CodeMetadata
from multiversx_sdk.core.config import LibraryConfig
from multiversx_sdk.core.contract_query import ContractQuery
from multiversx_sdk.core.contract_query_builder import ContractQueryBuilder
from multiversx_sdk.core.message import Message, MessageComputer
Expand Down Expand Up @@ -54,5 +55,6 @@
"SmartContractTransactionsFactory", "TransferTransactionsFactory",
"RelayedTransactionsFactory", "AccountTransactionsFactory", "DelegationTransactionsOutcomeParser",
"find_events_by_identifier", "find_events_by_first_topic", "SmartContractTransactionsOutcomeParser",
"SmartContractQueriesController", "SmartContractQuery", "SmartContractQueryResponse", "TransactionEventsParser"
"SmartContractQueriesController", "SmartContractQuery", "SmartContractQueryResponse", "TransactionEventsParser",
"LibraryConfig"
]
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 in exotic use cases.
It can be seen as a collection of constants or, more precisely, variables that are rarely changed and used throughout the library.
Never alter the configuration within a library!
Only alter the configuration, if needed, within a final 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
Loading

0 comments on commit 057c29f

Please sign in to comment.