This example demonstrates a smart contract application running on localhost. Using the Python Ledger API and a running ledger node, we will show you how to:
First, spin up a local node on
standalone. You can find detailed instructions for this here: v. 0.1
With a local node running, let's download and install the Python library that will allow us to interact with the running node ledger.
git clone email@example.com:fetchai/ledger-api-py.git -b master
Make sure you are on the
master branch in order to have all the latest features.
Install the library with the following command:
python3 setup.py install
To use the library, simply import it into a project and reference it. The demo script is in the examples folder; you can see the entirety of the script this example describes under:
First, import the necessary packages and define the network host and port:
from fetchai.ledger.api import LedgerApi from fetchai.ledger.crypto import Entity HOST = '127.0.0.1' PORT = 8000
The code imports the
LedgerApi from the
fetchai.ledger.api We use the classes in this package to connect to the ledger over HTTP.
Similarly, we import
fetchai.ledger.crypto to gain access to the functionality for creating and managing cryptographic accounts.
The code runs in
First, we create the
LedgerApi. Next, we create two
Entity() objects which represent two account holders on the ledger. An
Identity is a wrapper class around a public and private key pair with a bunch of useful functions such as accessing the values in different formats, i.e. hexadecimal or base64 string.
We print the balance from one entity.
Next, we give one account 1000 FET tokens:
Now, the account holder transfers 250 FET tokens to the other account:
api.sync(api.tokens.transfer(identity1, identity2, 250, 20)).
def main(): # create the APIs api = LedgerApi(HOST, PORT) # generate a random identity identity1 = Entity() identity2 = Entity() print('Balance Before:', api.tokens.balance(identity1)) # create the balance print('Submitting wealth creation...') api.sync(api.tokens.wealth(identity1, 1000)) # submit and wait for the transfer to be complete print('Submitting transfer...') api.sync(api.tokens.transfer(identity1, identity2, 250, 20)) print('Balance 1:', api.tokens.balance(identity1)) print('Balance 2:', api.tokens.balance(identity2))
The console should print the following result:
Balance Before: 0 Submitting wealth creation... Submitting transfer... Balance 1: 749 Balance 2: 250
The missing FET token is the fee charged to the account initiating the transaction.
# generate a random identity your_identity = Identity() other_identity = Identity()
You can run the example with:
That concludes the demo. Feel free to have a look around the classes in the API. Why not try and run
create_and_send.py? If you have any questions or feedback, get in touch at