### Install ethpm-types via setuptools Source: https://github.com/apeworx/ethpm-types/blob/main/README.md Install the most up-to-date version of ethpm-types by cloning the repository and using setuptools. ```bash git clone https://github.com/ApeWorX/ethpm-types.git cd ethpm-types python3 setup.py install ``` -------------------------------- ### Clone Repository and Setup Environment Source: https://github.com/apeworx/ethpm-types/blob/main/CONTRIBUTING.md Clone the ethpm-types repository, create and activate a Python virtual environment, and install the project with development dependencies. ```bash # clone the github repo and navigate into the folder git clone https://github.com/ApeWorX/ethpm-types.git cd ethpm-types # create and load a virtual environment python3 -m venv venv source venv/bin/activate # install ethpm-types into the virtual environment python setup.py install # install the developer dependencies (-e is interactive mode) pip install -e .'[dev]' ``` -------------------------------- ### PackageMeta Example Usage Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/manifest.md Instantiates a PackageMeta object with example author, license, description, keywords, and links. This demonstrates how to populate package metadata. ```python from ethpm_types.manifest import PackageMeta meta = PackageMeta( authors=["Alice Dev", "Bob Security"], license="MIT", description="A token contract with advanced features", keywords=["erc20", "token", "defi"], links={ "github": "https://github.com/example/token-contract", "docs": "https://docs.example.com", } ) ``` -------------------------------- ### Compiler Class Instantiation Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/source.md Provides examples of creating Compiler instances for both 'solc' and 'vyper', demonstrating how to specify compiler name, version, settings, and contract types. ```python from ethpm_types.source import Compiler compiler = Compiler( name="solc", version="0.8.19", settings={ "optimizer": {"enabled": True, "runs": 200}, "evmVersion": "london", }, contractTypes=["ERC20Token", "Vault"], ) compiler2 = Compiler( name="vyper", version="0.3.4", contractTypes=["MyVyperContract"], ) ``` -------------------------------- ### Install and Configure Pre-Commit Hooks Source: https://github.com/apeworx/ethpm-types/blob/main/CONTRIBUTING.md Install the pre-commit package and set up the local pre-commit hooks to ensure consistent code formatting and linting before committing. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Create and Use ABIList Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/contract-types.md Example of creating an ABIList from MethodABI objects and accessing/checking items. ```python from ethpm_types.abi import MethodABI, ABIType from ethpm_types.contract_type import ABIList # Create ABIList from methods methods = ABIList([ MethodABI( name="transfer", inputs=[ ABIType(name="to", type="address"), ABIType(name="amount", type="uint256"), ] ), MethodABI(name="balanceOf", inputs=[ABIType(name="account", type="address")]) ]) # Access by various methods transfer = methods["transfer"] by_selector = methods["transfer(address,uint256)"] first = methods[0] # Check membership if "balanceOf" in methods: print(methods["balanceOf"]) # Iterate for method in methods: print(method.name) ``` -------------------------------- ### Example Usage of ContractInstance Class Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/contract-types.md Demonstrates creating a ContractInstance object with deployment details. The example shows how to set contract type, address, transaction, and block. ```python from ethpm_types.contract_type import ContractInstance instance = ContractInstance( contractType="ERC20Token", address="0x1234567890123456789012345678901234567890", transaction="0x" + "a" * 64, block="0x" + "b" * 64, ) print(instance.contract_type) # "ERC20Token" print(instance.address) # 0x1234567890123456789012345678901234567890 ``` -------------------------------- ### PCMap Usage Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/sourcemap.md Demonstrates how to create a PCMap instance from raw data, check for the existence of a program counter, and iterate through the parsed PCMap items. This example illustrates common use cases for the PCMap class. ```python from ethpm_types.sourcemap import PCMap # Create from raw data pcmap = PCMap({ "0": [10, 0, 10, 20], # List format (location) "10": {"location": [12, 0, 12, 25], "dev": "loop"}, "20": {"location": [15, 4, 18, 4]}, }) # Check membership if 0 in pcmap: print(pcmap[0]) # Iterate and parse for pc, item in pcmap.parse().items(): print(f"PC {pc}: line {item.line_start}-{item.line_end}") # Output: # PC 0: line 10-10 # PC 10: line 12-12 # PC 20: line 15-18 ``` -------------------------------- ### Example Usage of ContractSource Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/source.md Demonstrates creating a ContractSource and then looking up a function using its source location. ```python from ethpm_types.source import ContractSource, Source from ethpm_types.contract_type import ContractType from ethpm_types.ast import ASTNode from pathlib import Path contract_type = ContractType( name="Token", source_id="contracts/token.sol", ast=ASTNode(...), # From compilation ) source = Source(content="contract Token { ... }") contract_source = ContractSource.create( contract_type=contract_type, source=source, base_path=Path(".") ) # Look up function func = contract_source.lookup_function( location=(10, 0, 15, 0), method_id=None ) ``` -------------------------------- ### MethodABI Usage Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/abi-types.md Demonstrates creating MethodABI instances both from explicit parameter objects and from a signature string, showing selector and signature properties. ```python from ethpm_types.abi import MethodABI, ABIType # Create from objects method = MethodABI( name="transfer", inputs=[ ABIType(name="to", type="address"), ABIType(name="amount", type="uint256"), ], outputs=[ABIType(type="bool")], ) print(method.selector) # "transfer(address,uint256)" print(method.signature) # "transfer(address to, uint256 amount) -> bool" print(method.is_stateful) # True (default nonpayable = stateful) # Create from signature string method2 = MethodABI.from_signature("balanceOf(address account) -> uint256") print(method2.name) # "balanceOf" print(len(method2.inputs)) # 1 ``` -------------------------------- ### Source Class Initialization and Validation Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/source.md Demonstrates creating Source objects with inlined content and URL-based sources, and validating their content. Shows how to fetch content and calculate checksums. ```python from ethpm_types.source import Source, Checksum, Algorithm from pathlib import Path # Inlined source source1 = Source( content="pragma solidity ^0.8.0;\ncontract Token {}" ) print(source1.content_is_valid()) # True # Source with URL source2 = Source( urls=["https://example.com/token.sol"], checksum=Checksum( algorithm=Algorithm.SHA256, hash="0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" ) ) # Fetch content try: content = source2.fetch_content() except ValueError: print("Failed to fetch content") # Calculate checksum checksum = source1.calculate_checksum(algorithm=Algorithm.SHA256) ``` -------------------------------- ### Example Usage of PCMapItem Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/sourcemap.md Demonstrates creating a PCMapItem object and accessing its 'location' property, which provides a tuple of source coordinates. ```python from ethpm_types.sourcemap import PCMapItem item = PCMapItem( line_start=10, column_start=4, line_end=10, column_end=20, dev="transfer function" ) print(item.location) # (10, 4, 10, 20) ``` -------------------------------- ### Example Usage of SourceMap.parse Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/sourcemap.md Demonstrates creating a SourceMap object from a string and iterating through its parsed SourceMapItems. ```python from ethpm_types.sourcemap import SourceMap # Create from source map string src_map_str = "1:2:0:i;;4:5:0:o;;;6:7:0:-" source_map = SourceMap(src_map_str) # Parse and iterate for item in source_map.parse(): print(f"start={item.start}, length={item.length}, jump={item.jump_code}") # Output: # start=1, length=2, jump=i # start=1, length=2, jump=i (empty entries copy previous) # start=1, length=2, jump=i # start=4, length=5, jump=o # start=4, length=5, jump=o # start=4, length=5, jump=o # start=6, length=7, jump=- ``` -------------------------------- ### Install ethpm-types via pip Source: https://github.com/apeworx/ethpm-types/blob/main/README.md Install the latest release of the ethpm-types library using pip. ```bash pip install ethpm-types ``` -------------------------------- ### ABIType Usage Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/abi-types.md Demonstrates creating and using ABIType instances for simple and tuple types, showing canonical type and signature properties. ```python from ethpm_types.abi import ABIType # Simple type uint_type = ABIType(name="amount", type="uint256") print(uint_type.canonical_type) # "uint256" print(uint_type.signature) # "uint256 amount" # Tuple type tuple_type = ABIType( name="data", type="tuple", components=[ ABIType(name="a", type="uint256"), ABIType(name="b", type="address"), ] ) print(tuple_type.canonical_type) # "(uint256,address)" ``` -------------------------------- ### PackageName Example Usage Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/manifest.md Illustrates valid and invalid package names according to EIP-2678 rules. Valid names must start with a lowercase letter and contain only lowercase letters, numbers, or hyphens. ```python from ethpm_types.manifest import PackageName # Valid names name1 = "erc20-token" name2 = "safe-math" name3 = "uniswap-v3" # Invalid names will raise validation error # name4 = "ERC20" # uppercase not allowed # name5 = "123token" # must start with a-z # name6 = "token_name" # underscore not allowed ``` -------------------------------- ### Checksum Class Methods Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/source.md Shows how to create Checksum objects from a file on disk or directly from bytes. It allows specifying the hashing algorithm, defaulting to MD5. ```python from ethpm_types.source import Checksum, Algorithm from pathlib import Path # From file checksum1 = Checksum.from_file("contracts/token.sol", algorithm=Algorithm.SHA256) # From bytes checksum2 = Checksum.from_bytes(b"contract content", algorithm=Algorithm.MD5) print(checksum1.algorithm) # Algorithm.SHA256 print(checksum1.hash) # "0x..." ``` -------------------------------- ### EventABIType Usage Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/abi-types.md Illustrates creating EventABIType instances for both indexed and non-indexed event parameters and accessing their signatures. ```python from ethpm_types.abi import EventABIType indexed_param = EventABIType(name="from", type="address", indexed=True) print(indexed_param.signature) # "address indexed from" non_indexed = EventABIType(name="value", type="uint256", indexed=False) print(non_indexed.signature) # "uint256 value" ``` -------------------------------- ### ASTNode Usage Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/ast.md Demonstrates how to create an ASTNode, iterate through its child nodes, find nodes at a specific line, and retrieve the defining function for a given source location. ```python from ethpm_types.ast import ASTNode, ASTClassification from ethpm_types.sourcemap import SourceMapItem # Create a function node func_node = ASTNode( name="transfer", ast_type="FunctionDef", classification=ASTClassification.FUNCTION, src=SourceMapItem.parse_str("100:200:0:"), lineno=5, end_lineno=10, col_offset=4, end_col_offset=0, ) # Iterate all nodes in tree for node in func_node.iter_nodes(): print(f"{node.ast_type}: {node.name}") # Find nodes at specific location nodes = func_node.get_nodes_at_line((7, 0, 8, 0)) # Find defining function def_func = func_node.get_defining_function((6, 0, 9, 0)) if def_func: print(f"Function: {def_func.name}") ``` -------------------------------- ### Full Package Manifest Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/manifest.md Illustrates the creation of a PackageManifest object with all its components, including meta, sources, contract types, compilers, and deployments. It also shows how to access contract types and compilers, and unpack sources. ```python from ethpm_types.manifest import PackageManifest, PackageMeta from ethpm_types.source import Source, Compiler from ethpm_types.contract_type import ContractType from eth_pydantic_types import Bip122Uri # Create a manifest manifest = PackageManifest( manifest="ethpm/3", name="erc20-token", version="1.0.0", meta=PackageMeta( authors=["Alice Dev"], license="MIT", description="A standard ERC20 token", ), sources={ "contracts/token.sol": Source( content="pragma solidity ^0.8.0;\ncontract ERC20 { ... }", ) }, contract_types={ "ERC20Token": ContractType( name="ERC20Token", source_id="contracts/token.sol", abi=[], ) }, compilers=[ Compiler( name="solc", version="0.8.19", settings={"optimizer": {"enabled": True}}, contractTypes=["ERC20Token"], ) ], deployments={ Bip122Uri("blockchain://1"): { "token-instance": ContractInstance( contractType="ERC20Token", address="0x1234567890123456789012345678901234567890", ) } } ) # Access contract type token_type = manifest.get_contract_type("ERC20Token") # Access by attribute token_type2 = manifest.ERC20Token # Get compiler compiler = manifest.get_compiler("solc", "0.8.19") # Unpack sources from pathlib import Path manifest.unpack_sources(Path("./src")) ``` -------------------------------- ### Example Usage of Bytecode Class Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/contract-types.md Demonstrates creating a Bytecode object with and without link references. The to_bytes method converts bytecode to HexBytes. ```python from ethpm_types.contract_type import Bytecode bytecode = Bytecode(bytecode="0x6080604052...") hex_bytes = bytecode.to_bytes() print(type(hex_bytes)) # # With link references from ethpm_types.contract_type import LinkReference bytecode_with_refs = Bytecode( bytecode="0x6080...", link_references=[ LinkReference(offsets=[32, 64], length=20, name="MyLibrary") ] ) ``` -------------------------------- ### Example Usage of SourceMapItem.parse_str Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/sourcemap.md Demonstrates parsing source map items with and without delta compression, showing how to access parsed attributes. ```python from ethpm_types.sourcemap import SourceMapItem # Parse source map items item1 = SourceMapItem.parse_str("1:2:0:i") # start:length:id:jump print(item1.start) # 1 print(item1.length) # 2 print(item1.contract_id) # 0 print(item1.jump_code) # "i" # With delta compression (empty values copy from previous) item2 = SourceMapItem.parse_str("::1:", previous=item1) print(item2.start) # 1 (copied from previous) print(item2.length) # 2 (copied from previous) print(item2.contract_id) # 1 (specified) print(item2.jump_code) # "i" (copied from previous) ``` -------------------------------- ### model_dump_json Method Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/base-model.md Provides an example of using the model_dump_json method to serialize a BaseModel instance into a canonical JSON string, excluding nulls by default. ```python contract = ContractType(name="Token", abi=[]) json_str = contract.model_dump_json() # '{"abi":[],"contractName":"Token"}' ``` -------------------------------- ### Content Class Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/source.md Demonstrates creating a Content object from a source code string and accessing its properties like begin_lineno, end_lineno, and individual lines. The as_list method returns all lines as a list of strings. ```python from ethpm_types.source import Content # Create from source code string source_code = """pragma solidity ^0.8.0; contract MyToken { uint256 public totalSupply; }""" content = Content(source_code) print(content.begin_lineno) # 1 print(content.end_lineno) # 4 print(content[2]) # "" print(content[3]) # "contract MyToken {" print(content.as_list()) # ["pragma...", "", "contract...", ...] ``` -------------------------------- ### model_dump Method Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/base-model.md Demonstrates the usage of the model_dump method to convert a BaseModel instance into a dictionary, with options for aliasing and null exclusion. ```python contract = ContractType(name="Token") data = contract.model_dump() # {"name": "Token"} data = contract.model_dump(by_alias=True) # {"contractName": "Token"} ``` -------------------------------- ### Safely Get ABI Item with Default Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/contract-types.md Retrieves an ABI item from the ABIList using the 'get' method, returning a default value if the item is not found. ```python method = abi_list.get("transfer", default=None) ``` -------------------------------- ### Get Compiler and Contract Information from Manifest Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/QUICK-REFERENCE.md Access specific compilers by name and version, retrieve the compiler used for a contract, and iterate through contract types and compilers available in the manifest. ```python compiler = manifest.get_compiler("solc", "0.8.19") compiler = manifest.get_contract_compiler("ERC20Token") for name, contract in manifest.contract_types.items(): print(name, contract.abi) for compiler in manifest.compilers or []: print(compiler.name, compiler.version) mainnet = manifest.deployments.get(Bip122Uri("blockchain://1")) if mainnet: token = mainnet.get("token") ``` -------------------------------- ### Parse Solidity Source Map String Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/QUICK-REFERENCE.md Create a SourceMap object from a string representation and iterate through its parsed items to access start, length, and jump code information. ```python sourcemap_str = "1:2:0:i;;4:5:0:o;;;6:7:0:-" sourcemap = SourceMap(sourcemap_str) for item in sourcemap.parse(): print(f"start={item.start}, length={item.length}, jump={item.jump_code}") ``` -------------------------------- ### SourceMapItem Class Definition Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/sourcemap.md Defines the structure for a single entry in a Solidity source map, including start, length, contract ID, and jump code. ```python from ethpm_types.sourcemap import SourceMapItem class SourceMapItem(BaseModel): start: int | None = None length: int | None = None contract_id: int | None = None jump_code: str ``` -------------------------------- ### Algorithm Enum Usage Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/source.md Demonstrates how to use the Algorithm enum to specify a checksum algorithm. The value attribute returns the string representation of the algorithm. ```python from ethpm_types.source import Algorithm algo = Algorithm.SHA256 print(algo.value) # "sha256" ``` -------------------------------- ### Create ConstructorABI Instance Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/abi-types.md Shows how to create a ConstructorABI instance with specified inputs and state mutability. ```python from ethpm_types.abi import ConstructorABI, ABIType constructor = ConstructorABI( inputs=[ABIType(name="initialSupply", type="uint256")], stateMutability="nonpayable" ) print(constructor.signature) # "constructor(initialSupply)" print(constructor.is_payable) # False ``` -------------------------------- ### Get Runtime Bytecode Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/contract-types.md Method to retrieve the runtime bytecode of a ContractType instance as HexBytes. ```python def get_runtime_bytecode(self) -> HexBytes | None: # ... implementation details ... ``` -------------------------------- ### Customize ContractType Hashing Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/OVERVIEW.md Subclass ContractType to customize the selector hash function, for example, using Blake2b. ```python from ethpm_types import ContractType from eth_utils import blake2b class Blake2bContractType(ContractType): @classmethod def _selector_hash_fn(cls, selector: str) -> bytes: return blake2b(selector.encode()).digest() ``` -------------------------------- ### PackageMeta Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/manifest.md Represents metadata about a package, such as authors, license, description, keywords, and links. This information is not essential for installation but is useful for publishing. ```APIDOC ## PackageMeta ### Description Metadata information about a package that is not integral to installation but should be included when publishing. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **authors** (list[str] | None) - Optional - Human-readable names of package authors. - **license** (str | None) - Optional - License string conforming to SPDX format. File-level licenses override this. - **description** (str | None) - Optional - Additional details about the package. - **keywords** (list[str] | None) - Optional - Relevant keywords associated with the package. - **links** (dict[str, AnyUrl] | None) - Optional - URIs to resources associated with the package (e.g., "github", "docs", "website"). ### Request Example ```json { "authors": ["Alice Dev", "Bob Security"], "license": "MIT", "description": "A token contract with advanced features", "keywords": ["erc20", "token", "defi"], "links": { "github": "https://github.com/example/token-contract", "docs": "https://docs.example.com" } } ``` ### Response #### Success Response (200) - **authors** (list[str] | None) - Human-readable names of package authors. - **license** (str | None) - License string conforming to SPDX format. File-level licenses override this. - **description** (str | None) - Additional details about the package. - **keywords** (list[str] | None) - Relevant keywords associated with the package. - **links** (dict[str, AnyUrl] | None) - URIs to resources associated with the package (e.g., "github", "docs", "website"). #### Response Example ```json { "authors": ["Alice Dev", "Bob Security"], "license": "MIT", "description": "A token contract with advanced features", "keywords": ["erc20", "token", "defi"], "links": { "github": "https://github.com/example/token-contract", "docs": "https://docs.example.com" } } ``` ``` -------------------------------- ### Basic Usage of ethpm-types Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/README.md Demonstrates creating and serializing a PackageManifest with contract types and method ABIs. Ensure necessary classes like PackageManifest, ContractType, MethodABI, and ABIType are imported. ```python from ethpm_types import PackageManifest, ContractType, MethodABI, ABIType # Create method ABI method = MethodABI( name="transfer", inputs=[ ABIType(name="to", type="address"), ABIType(name="amount", type="uint256"), ], outputs=[ABIType(type="bool")], ) # Create contract type contract = ContractType( name="ERC20", abi=[method], runtime_bytecode="0x6080...", ) # Create manifest manifest = PackageManifest( name="my-token", version="1.0.0", contract_types={"ERC20": contract}, ) # Serialize json_output = manifest.model_dump_json() ``` -------------------------------- ### Get Runtime Bytecode Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/contract-types.md Retrieves the runtime bytecode of a contract as HexBytes. This method is useful for obtaining the executable code of the contract. ```python def get_deployment_bytecode(self) -> HexBytes | None: pass ``` -------------------------------- ### Create PackageManifest Instance Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/OVERVIEW.md Shows how to create a PackageManifest, including metadata, sources, contract types, and compilers. The manifest can then be serialized to JSON. ```python from ethpm_types import PackageManifest, PackageMeta, Compiler from ethpm_types.source import Source manifest = PackageManifest( name="my-token", version="1.0.0", meta=PackageMeta( authors=["Alice Dev"], license="MIT", ), sources={"contracts/token.sol": Source(content="pragma solidity...")}, contract_types={"ERC20": contract}, compilers=[Compiler(name="solc", version="0.8.19")], ) # Serialize to JSON json_str = manifest.model_dump_json() ``` -------------------------------- ### Create ContractType Instance Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/OVERVIEW.md Demonstrates how to create a ContractType instance with a name, ABI, and runtime bytecode. The ABI is defined using MethodABI and ABIType. ```python from ethpm_types import ContractType, MethodABI, ABIType contract = ContractType( name="ERC20", abi=[ MethodABI( name="transfer", inputs=[ ABIType(name="to", type="address"), ABIType(name="amount", type="uint256"), ], outputs=[ABIType(type="bool")], ), ], runtime_bytecode="0x..." ) ``` -------------------------------- ### Create FallbackABI Instance Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/abi-types.md Demonstrates creating a FallbackABI instance, specifying its state mutability. ```python from ethpm_types.abi import FallbackABI fallback = FallbackABI(stateMutability="payable") print(fallback.signature) # "fallback()" print(fallback.is_payable) # True ``` -------------------------------- ### Create ReceiveABI Instance Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/abi-types.md Illustrates the creation of a ReceiveABI instance, which is always payable. ```python from ethpm_types.abi import ReceiveABI receive = ReceiveABI() print(receive.signature) # "receive()" print(receive.is_payable) # True ``` -------------------------------- ### Work with Source File Content Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/QUICK-REFERENCE.md Create Source objects from content, access specific lines or ranges of lines, validate content, and calculate checksums. ```python source = Source(content="pragma solidity ^0.8.0;...") line_5 = source[5] lines_5_to_10 = source[5:10] if source.content_is_valid(): print("Content is valid") checksum = source.calculate_checksum(algorithm=Algorithm.SHA256) ``` -------------------------------- ### Create and Inspect StructABI Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/abi-types.md Instantiate a StructABI object with a name and members, then access its selector and signature. ```python from ethpm_types.abi import StructABI, ABIType struct = StructABI( name="Point", members=[ ABIType(name="x", type="int256"), ABIType(name="y", type="int256"), ] ) print(struct.selector) # "Point(int256,int256)" print(struct.signature) # "Point(int256 x, int256 y)" ``` -------------------------------- ### Define SourceLocation Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/QUICK-REFERENCE.md Create a SourceLocation object using a tuple of start and end line and column numbers. Used to specify code locations. ```python from ethpm_types.utils import SourceLocation location: SourceLocation = (10, 0, 15, 20) # line_start, col_start, line_end, col_end ``` -------------------------------- ### Create MethodABI and EventABI from Signatures Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/OVERVIEW.md Demonstrates creating MethodABI and EventABI objects directly from their string signatures, including parameter names and types. ```python from ethpm_types import MethodABI, EventABI # Create from signature strings method = MethodABI.from_signature("transfer(address to, uint256 amount) -> bool") event = EventABI.from_signature("Transfer(address indexed from, address indexed to, uint256 value)") ``` -------------------------------- ### Parse and Iterate SourceMap Items Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/OVERVIEW.md Parses the sourcemap associated with a contract and iterates through its items, printing the start position and length of each source map entry. ```python if contract.sourcemap: for item in contract.sourcemap.parse(): print(f"Start: {item.start}, Length: {item.length}") ``` -------------------------------- ### ABIList Constructor Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/contract-types.md Initializes an ABIList with optional ABI items and configuration for selector ID size and hash function. ```APIDOC ## ABIList Constructor ### Description Initializes an ABIList with optional ABI items and configuration for selector ID size and hash function. ### Parameters - `iterable` (Iterable): Initial ABI items. Accepts list of ABI objects or JSON string. - `selector_id_size` (int): Size of selector ID in bytes (default 32 for events, 4 for methods). - `selector_hash_fn` (Callable): Optional custom hash function for selector lookups. ``` -------------------------------- ### Fetch Remote Source File Content Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/QUICK-REFERENCE.md Instantiate a Source object with URLs and attempt to fetch its content. Handle potential ValueErrors if fetching fails. ```python source = Source(urls=["https://example.com/token.sol"]) try: content = source.fetch_content() print(content) except ValueError as e: print(f"Could not fetch: {e}") ``` -------------------------------- ### Check for Content Addressed URL Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/utilities.md Checks if a given URL starts with a scheme that uses content addressing, such as IPFS. This is useful for identifying URIs where the checksum is built into the URI itself. ```python from ethpm_types.utils import CONTENT_ADDRESSED_SCHEMES url = "ipfs://QmXxxx..." if any(url.startswith(f"{scheme}://") for scheme in CONTENT_ADDRESSED_SCHEMES): print("Content addressed - checksum is in URI") ``` -------------------------------- ### Instantiate and Use ContractType Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/contract-types.md Demonstrates how to create a ContractType object with ABI, runtime bytecode, and access its methods, events, and NATSPEC documentation. Requires importing necessary classes from ethpm_types. ```python from ethpm_types.abi import MethodABI, ABIType from ethpm_types.contract_type import ContractType # Create a ContractType contract = ContractType( name="ERC20", abi=[ MethodABI( name="transfer", inputs=[ ABIType(name="to", type="address"), ABIType(name="amount", type="uint256"), ], outputs=[ABIType(type="bool")], stateMutability="nonpayable" ), MethodABI( name="balanceOf", inputs=[ABIType(name="account", type="address")], outputs=[ABIType(type="uint256")], stateMutability="view" ), ], runtime_bytecode="0x6080..." ) # Access methods transfer_method = contract.methods["transfer"] balance_method = contract.view_methods["balanceOf"] # Get bytecode runtime_bytes = contract.get_runtime_bytecode() # Iterate events for event in contract.events: print(event.name) # Get natspec docs = contract.natspecs ``` -------------------------------- ### Create and Encode EventABI Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/abi-types.md Demonstrates creating an EventABI instance from a signature and encoding input data for Ethereum log topics. ```python from ethpm_types.abi import EventABI # Create from signature event = EventABI.from_signature( "Transfer(address indexed from, address indexed to, uint256 value)" ) print(event.name) # "Transfer" print(event.selector) # "Transfer(address,address,uint256)" # Encode topics for log filtering topics = event.encode_topics({ "from": "0x1234...", "to": "0x5678...", "value": 1000 }) # First topic is event signature hash, rest are indexed parameter hashes ``` -------------------------------- ### Create a ContractInstance object Source: https://github.com/apeworx/ethpm-types/blob/main/README.md Build an EthPM typed object from a dictionary of attribute data, such as a contract instance. This demonstrates basic instantiation and attribute access. ```python from ethpm_types import ContractInstance contract = ContractInstance(contractType="ContractClassName", address="0x123...") print(contract.contract_type) ``` -------------------------------- ### Automatic Field Aliasing Example Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/base-model.md Demonstrates how BaseModel automatically handles field aliasing for EIP-2678 compliant JSON serialization, mapping Pythonic names to camelCase JSON keys. ```python from ethpm_types.contract_type import ContractType contract = ContractType( name="Token", source_id="contracts/token.sol", deployment_bytecode="0x...", # Python name ) # Serializes to JSON with aliases data = contract.model_dump(by_alias=True) # {"contractName": "Token", "sourceId": "contracts/token.sol", "deploymentBytecode": ...} ``` -------------------------------- ### Create ContractSource Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/source.md Creates a ContractSource instance. Optionally validates the source file's existence against a base path. ```python def create( cls, contract_type: ContractType, source: Source, base_path: Path | None = None, ) -> "ContractSource": ``` -------------------------------- ### Catching PackageNameError Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/errors.md Demonstrates how to catch a `PackageNameError` during `PackageManifest` instantiation when the package name is invalid. This error can occur due to incorrect type, length, starting character, or allowed characters in the package name. ```python from pydantic import ValidationError from ethpm_types.manifest import PackageManifest try: manifest = PackageManifest(name="123invalid", version="1.0.0") except ValidationError as e: for error in e.errors(): print(error['msg']) # "First character in name must be a-z" ``` -------------------------------- ### Access ABI Items in ABIList Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/contract-types.md Demonstrates various ways to access ABI items within an ABIList using indexing, slicing, names, selectors, and ABI objects. ```python # By index abi_list[0] # By slice abi_list[0:5] # By name (string) abi_list["transfer"] # By selector string abi_list["transfer(address,uint256)"] # By hex selector abi_list["0x1234abcd"] # By bytes abi_list[b'\x12\x34\xab\xcd'] # By ABI object abi_list[method_abi] ``` -------------------------------- ### Source Class Definition Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/source.md Defines the Source class for holding information about a source file within a package manifest. It includes URLs, checksum, content, install path, type, license, references, and imports. ```python from ethpm_types.source import Source class Source(BaseModel): urls: list[AnyUrl] = [] checksum: Checksum | None = None content: Content | None = None installPath: str | None = None type: str | None = None license: str | None = None references: list[str] | None = None imports: list[str] | None = None ``` -------------------------------- ### Create and Serialize Package Manifest Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/QUICK-REFERENCE.md Construct a PackageManifest object with contract types, sources, and compiler information, then serialize it to a JSON string. Supports pretty-printing the JSON output. ```python from ethpm_types import ( PackageManifest, PackageMeta, ContractType, MethodABI, ABIType, Source, Compiler ) from ethpm_types.source import Checksum, Algorithm import json # Create ABI transfer = MethodABI( name="transfer", inputs=[ ABIType(name="to", type="address"), ABIType(name="amount", type="uint256"), ], outputs=[ABIType(type="bool")], stateMutability="nonpayable" ) # Create contract type contract = ContractType( name="ERC20", source_id="contracts/erc20.sol", abi=[transfer], runtime_bytecode="0x6080..." ) # Create manifest manifest = PackageManifest( name="simple-token", version="1.0.0", meta=PackageMeta( authors=["Alice"], license="MIT" ), sources={ "contracts/erc20.sol": Source(content="pragma solidity ^0.8.0;...") }, contract_types={"ERC20": contract}, compilers=[ Compiler(name="solc", version="0.8.19") ] ) # Serialize to JSON json_output = manifest.model_dump_json() print(json_output) # Or pretty-print data = json.loads(json_output) print(json.dumps(data, indent=2)) ``` -------------------------------- ### Unpack Source Files from Manifest Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/QUICK-REFERENCE.md Use the unpack_sources method on a PackageManifest object to write all associated source files to a specified directory on disk. ```python from pathlib import Path manifest = PackageManifest(...) manifest.unpack_sources(Path("./src")) ``` -------------------------------- ### Data Flow for Ethereum Package Manifests Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/OVERVIEW.md Illustrates the typical data flow from source code to a serialized EIP-2678 package manifest, including compilation and deployment stages. ```text Source Code (Solidity/Vyper) ↓ Compiler (solc/vyper) ↓ Contract Type (ABI + bytecode + metadata) ├── ABI (methods, events, constructors, etc.) ├── Bytecode (creation + runtime) ├── AST (abstract syntax tree) ├── Source Map (source→bytecode mapping) └── PC Map (program counter→source mapping) ↓ Package Manifest (EIP-2678) ├── Sources (source files) ├── Contract Types (compiled contracts) ├── Compilers (compiler info) ├── Deployments (instances on chains) ├── Dependencies (other packages) └── Metadata (authors, license, links) ↓ Serialization (JSON/IPFS) ``` -------------------------------- ### Create PackageManifest Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/QUICK-REFERENCE.md Assemble a PackageManifest object, including metadata, sources, contract types, compilers, and deployment information. ```python from ethpm_types import PackageManifest, PackageMeta from ethpm_types.source import Source, Compiler from eth_pydantic_types import Bip122Uri manifest = PackageManifest( manifest="ethpm/3", # Always "ethpm/3" name="my-erc20", version="1.0.0", meta=PackageMeta( authors=["Alice Dev"], license="MIT", description="Standard ERC20 token", keywords=["token", "erc20"], links={ "github": "https://github.com/...", "docs": "https://docs.example.com" } ), sources={ "contracts/token.sol": Source( content="pragma solidity ^0.8.0;\n...", type="solidity" ), "contracts/lib.sol": Source( urls=["https://example.com/lib.sol"], checksum=Checksum( algorithm=Algorithm.SHA256, hash="0x..." ) ) }, contract_types={ "ERC20Token": contract, }, compilers=[ Compiler( name="solc", version="0.8.19", settings={ "optimizer": {"enabled": True, "runs": 200}, "evmVersion": "london" }, contractTypes=["ERC20Token"] ) ], deployments={ Bip122Uri("blockchain://1"): { "token": ContractInstance( contractType="ERC20Token", address="0x1234567890123456789012345678901234567890", transaction="0x" + "a" * 64, block="0x" + "b" * 64, ) } } ) ``` -------------------------------- ### Import ethpm-types Utilities Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/utilities.md Demonstrates various ways to import utility functions from the ethpm-types library, including from submodules and the main module. ```python # From utils submodule from ethpm_types.utils import ( Algorithm, compute_checksum, stringify_dict_for_hash, parse_signature, SourceLocation, AnyUrl, CONTENT_ADDRESSED_SCHEMES, ) # From specific submodules from ethpm_types.abi import encode_topic_value, is_dynamic_sized_type from ethpm_types.source import validate_source_id, validate_ast, validate_pcmap # Some from main module from ethpm_types import Checksum, Compiler, Source ``` -------------------------------- ### Track Deployments with ContractInstance Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/OVERVIEW.md Add deployment information to a PackageManifest, mapping blockchain URIs to deployed contract instances. ```python from ethpm_types import PackageManifest, ContractInstance from eth_pydantic_types import Bip122Uri manifest = PackageManifest(...) manifest.deployments = { Bip122Uri("blockchain://1"): { "token": ContractInstance( contractType="ERC20", address="0x...", transaction="0x...", ) } } ``` -------------------------------- ### Create MethodABI from signature Source: https://github.com/apeworx/ethpm-types/blob/main/README.md Initialize a MethodABI object using the .from_signature() classmethod. This is a convenient way to create ABI objects from function signatures. ```python from ethpm_types.abi import MethodABI, EventABI MethodABI.from_signature("function_name(uint256 arg1)") # => MethodABI(type='function', name='function_name', inputs=[...], ...) ``` -------------------------------- ### ABIList Constructor Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/contract-types.md Initializes an ABIList with optional iterable ABI items, selector ID size, and a custom hash function. ```python def __init__( self, iterable: Iterable[ABILIST_T] | None = None, *, selector_id_size: int = 32, selector_hash_fn: Callable[[str], bytes] | None = None, ): ``` -------------------------------- ### Create EventABI from signature Source: https://github.com/apeworx/ethpm-types/blob/main/README.md Initialize an EventABI object using the .from_signature() classmethod. This is a convenient way to create ABI objects from event signatures. ```python from ethpm_types.abi import MethodABI, EventABI EventABI.from_signature("Transfer(address indexed from, address indexed to, uint256 value)") # => EventABI(type='event', name='Transfer', inputs=[...], ...) ``` -------------------------------- ### Create Constructor ABI Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/QUICK-REFERENCE.md Define a ConstructorABI object, specifying input parameters and its state mutability. ```python constructor = ConstructorABI( inputs=[ABIType(name="initialSupply", type="uint256")], stateMutability="nonpayable" ) ``` -------------------------------- ### Define Custom Compiler Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/OVERVIEW.md Shows how to define a custom compiler by inheriting from the base Compiler class and adding compiler-specific fields. ```python class CairoCompiler(Compiler): name: str = "cairo" # Add cairo-specific fields ``` -------------------------------- ### Unpack Sources to Filesystem Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/manifest.md Unpacks inlined sources from the package manifest to a specified destination directory. Raises ValueError if the destination's parent path does not exist. ```python def unpack_sources(self, destination: Path): ``` -------------------------------- ### Import Core ethpm-types Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/QUICK-REFERENCE.md Import essential types for defining contracts, ABIs, and package manifests. ```python # Core types from ethpm_types import ( ContractType, ContractInstance, PackageManifest, MethodABI, EventABI, ConstructorABI, ABIType, Bytecode, Source, Checksum, Compiler ) # Utilities from ethpm_types.abi import ErrorABI, StructABI from ethpm_types.source import Content, Function, ContractSource from ethpm_types.sourcemap import SourceMap, PCMap, SourceMapItem, PCMapItem from ethpm_types.ast import ASTNode, ASTClassification from ethpm_types.utils import Algorithm, SourceLocation ``` -------------------------------- ### Create and Inspect ErrorABI Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/abi-types.md Instantiate an ErrorABI object with name and input types, then access its selector and signature. ```python from ethpm_types.abi import ErrorABI, ABIType error = ErrorABI( name="InsufficientBalance", inputs=[ABIType(name="have", type="uint256"), ABIType(name="want", type="uint256")], ) print(error.selector) # "InsufficientBalance(uint256,uint256)" print(error.signature) # "InsufficientBalance(uint256 have, uint256 want)" ``` -------------------------------- ### ContractSource.create Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/source.md Creates a ContractSource instance, optionally validating the source file's existence against a base path. ```APIDOC ## ContractSource.create ### Description Create a `ContractSource` with optional filesystem validation. ### Method `create` ### Parameters #### Path Parameters - `contract_type` (ContractType): Contract with source ID, AST, and PCMap. - `source` (Source): Source code. - `base_path` (Path): If provided, verifies source file exists at `base_path / source_id`. ### Returns `ContractSource` ### Raises `FileNotFoundError` if file validation fails. ``` -------------------------------- ### Import All Types from Main Module Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/types.md Import all available types, including ABI, contract, manifest, source, map, and AST types, directly from the main `ethpm_types` module. ```python from ethpm_types import ( # ABI types ABI, ConstructorABI, FallbackABI, ReceiveABI, MethodABI, EventABI, ErrorABI, StructABI, UnprocessedABI, # Contract types Bytecode, ContractInstance, ContractType, # Manifest types PackageManifest, PackageMeta, # Source types Source, Checksum, Compiler, # Map types SourceMap, SourceMapItem, PCMap, PCMapItem, # AST types ASTNode, # Base BaseModel, ) ``` -------------------------------- ### Serialize and Deserialize PackageManifest Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/api-reference/base-model.md Demonstrates serializing a PackageManifest object to JSON and then deserializing it back into a PackageManifest object. This is useful for data persistence and transfer. ```python from ethpm_types import PackageManifest import json manifest1 = PackageManifest(name="token", version="1.0.0") # Serialize to JSON json_str = manifest1.model_dump_json() # Deserialize from JSON data = json.loads(json_str) manifest2 = PackageManifest.model_validate(data) # Verify identical assert manifest1.name == manifest2.name ``` -------------------------------- ### ABI Classes Hierarchy Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/INDEX.md Illustrates the inheritance structure of ABI-related classes, all stemming from BaseABI. ```text BaseABI ├── ConstructorABI ├── FallbackABI ├── ReceiveABI ├── MethodABI ├── EventABI ├── ErrorABI ├── StructABI └── UnprocessedABI ``` -------------------------------- ### Create Method ABI Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/QUICK-REFERENCE.md Define a MethodABI object, either by providing its components or by parsing a signature string. ```python method = MethodABI( name="transfer", inputs=[ ABIType(name="to", type="address"), ABIType(name="amount", type="uint256"), ], outputs=[ABIType(type="bool")], stateMutability="nonpayable" ) # Or from signature method = MethodABI.from_signature("transfer(address to, uint256 amount) -> bool") ``` -------------------------------- ### Access Contract Elements Dynamically Source: https://github.com/apeworx/ethpm-types/blob/main/_autodocs/OVERVIEW.md Illustrates accessing contract elements like methods, events, and view methods using dynamic attribute and dictionary-style access. ```python contract = manifest.ERC20 # Dynamic attribute access transfer = contract.methods["transfer"] # ABIList selection all_events = contract.events # Get all events view_methods = contract.view_methods # Get read-only methods ```