From 4f66444fb60b051ee8ee88000d046cc4da6af85c Mon Sep 17 00:00:00 2001 From: Marc Garreau <3621728+marcgarreau@users.noreply.github.com> Date: Thu, 28 Jan 2021 15:01:11 -0700 Subject: [PATCH] add docs for contract fn struct args --- docs/contracts.rst | 61 ++++++++++++++++++++++++++++++++++++-- newsfragments/1860.doc.rst | 1 + 2 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 newsfragments/1860.doc.rst diff --git a/docs/contracts.rst b/docs/contracts.rst index 8d33576538..98259badba 100644 --- a/docs/contracts.rst +++ b/docs/contracts.rst @@ -5,13 +5,14 @@ Contracts .. py:module:: web3.contract -It is worth taking your time to understand all about contracts. To get started, -check out this example: +Smart contracts are programs deployed to the Ethereum network. See the +`ethereum.org docs `_ +for a proper introduction. .. _contract_example: Contract Deployment Example ----------------------------------------------- +--------------------------- To run this example, you will need to install a few extra features: @@ -1211,3 +1212,57 @@ provides methods to interact with contract functions. Positional and keyword arguments supplied to the contract caller subclass will be used to find the contract function by signature, and forwarded to the contract function when applicable. + + +Contract FAQs +------------- + +How do I pass in a struct as a function argument? +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Web3.py accepts struct arguments as dictionaries. This format also supports nested structs. +Let's take a look at a quick example. Given the following Solidity contract: + +.. code-block:: none + + contract Example { + address addr; + + struct S1 { + address a1; + address a2; + } + + struct S2 { + bytes32 b1; + bytes32 b2; + } + + struct X { + S1 s1; + S2 s2; + address[] users; + } + + function update(X memory x) public { + addr = x.s1.a2; + } + + function retrieve() public view returns (address) { + return addr; + } + } + +You can interact with Web3.py contract API as follows: + +.. code-block:: python + + # deploy or lookup the deployed contract, then: + + >>> deployed_contract.functions.retrieve().call() + '0x0000000000000000000000000000000000000000' + + >>> deployed_contract.functions.update({'s1': ['0x0000000000000000000000000000000000000001', '0x0000000000000000000000000000000000000002'], 's2': [b'0'*32, b'1'*32], 'users': []}).transact() + + >>> deployed_contract.functions.retrieve().call() + '0x0000000000000000000000000000000000000002' diff --git a/newsfragments/1860.doc.rst b/newsfragments/1860.doc.rst new file mode 100644 index 0000000000..a13c638ac4 --- /dev/null +++ b/newsfragments/1860.doc.rst @@ -0,0 +1 @@ +Document passing a struct into a contract function.