Examples for python in algov2

I want compiled code examples for hash time lock, indexer, transaction fee, read and write transaction in python programming in algoversion2.Where can I get?Can anyone help me?

Most tutorials are using algodv2.
If you find a tutorial that is using algodv1, let us know on this thread so that we can fix it.

To get started, there are many ways:

Specifically for:

I want correctly working code for hash time lock, limit order in python. Where can I get it?

While it is V1, Hash Time Lock Contract Template With Python | Algorand Developer Portal should still work nowadays as it does not use indexer v1 which is the main issue.

Let us know if there is an issue.

When turning it into production, you need to switch to v2.

code:


Error:

What i have to change?

PureStake does not support v1 anymore.

Use algoexplorer api:

from algosdk import algod

algod_token = ""
algod_address = "https://testnet.algoexplorerapi.io"
headers = {"User-Agent": "DoYouLoveMe?"}

client = algod.AlgodClient(algod_token, algod_address, headers)

print(client.suggested_params())

PS: You can write code and output between triple backquotes ``` instead of snapshots. This makes search easier.

what i have to put in algod_token variable and header variable

You can directly use the code I wrote. No need for a personal token.

is I put DoYouLoveMe in useragent? :grinning:

Yes :slight_smile:
The goal is to bypass CloudFlare’s issues: Requests need to merge headers · Issue #169 · algorand/py-algorand-sdk · GitHub

Error:

Traceback (most recent call last):
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\algosdk\algod.py", line 75, in algod_request
    resp = urlopen(req)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
    response = meth(req, response)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response   
    response = self.parent.error(
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
    return self._call_chain(*args)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain     
    result = func(*args)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "d:\pyalg\hash1.py", line 60, in <module>
    txid = client.send_transaction(logicsig_txn, headers={'content-type': 'application/x-binary'})
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\algosdk\algod.py", line 290, in send_transaction
    return self.send_raw_transaction(encoding.msgpack_encode(txn),
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\algosdk\algod.py", line 277, in send_raw_transaction
    return self.algod_request("POST", req, data=txn, headers=tx_headers, **kwargs)["txId"]
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\algosdk\algod.py", line 83, in algod_request
    raise error.AlgodHTTPError(raisex)
algosdk.error.AlgodHTTPError: transaction {_struct:{} Sig:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Msig:{_struct:{} Version:0 Threshold:0 Subsigs:[]} Lsig:{_struct:{} Logic:[1 32 4 208 15 1 0 192 150 177 2 38 3 32 229 212 184 181 209 48 181 110 105 208 
140 137 125 14 71 219 36 82 217 241 69 115 100 147 81 226 91 182 112 155 66 115 32 67 54 33 171 210 101 97 185 246 65 211 140 174 28 177 86 83 109 54 55 178 191 34 92 252 143 29 241 80 6 124 103 32 79 117 126 163 147 199 88 139 
14 230 124 106 63 192 81 197 35 24 163 5 199 32 19 21 164 103 198 162 81 253 157 138 49 1 34 14 49 16 35 18 16 49 
7 50 3 18 16 49 8 36 18 16 49 9 40 18 45 1 41 18 16 49 9 42 18 49 2 37 13 16 17 16] Sig:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Msig:{_struct:{} Version:0 Threshold:0 Subsigs:[]} Args:[[104 101 114 111 32 119 105 115 100 111 109 32 103 114 101 101 110 
32 115 112 108 105 116 32 108 111 111 112 32 101 108 101 109 101 110 116 32 118 111 116 101 32 98 101 108 116]]} Txn:{_struct:{} Type:pay Header:{_struct:{} Sender:DJHV2ACKWRWOAPYBO2XL5FNRHIJ2WRSOAMAE5DPSFQ5UNVEXV4LOTNXT3A Fee:{Raw:1000} FirstValid:15368574 LastValid:15369574 Note:[] GenesisID:testnet-v1.0 GenesisHash:JBR3KGFEWPEE5SAQ6IWU6EEBZMHXD4CZU6WCBXWGF57XBZIJHIRA Group:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Lease:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] RekeyTo:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ} KeyregTxnFields:{_struct:{} VotePK:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] SelectionPK:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] VoteFirst:0 VoteLast:0 VoteKeyDilution:0 Nonparticipation:false} PaymentTxnFields:{_struct:{} Receiver:4XKLRNORGC2W42OQRSEX2DSH3MSFFWPRIVZWJE2R4JN3M4E3IJZUQCIPJM Amount:{Raw:0} CloseRemainderTo:42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE} AssetConfigTxnFields:{_struct:{} ConfigAsset:0 AssetParams:{_struct:{} Total:0 Decimals:0 DefaultFrozen:false UnitName: AssetName: URL: MetadataHash:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Manager:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ Reserve:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ Freeze:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ Clawback:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ}} AssetTransferTxnFields:{_struct:{} XferAsset:0 AssetAmount:0 AssetSender:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ AssetReceiver:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ AssetCloseTo:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ} AssetFreezeTxnFields:{_struct:{} FreezeAccount:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ FreezeAsset:0 AssetFrozen:false} ApplicationCallTxnFields:{_struct:{} ApplicationID:0 OnCompletion:NoOpOC ApplicationArgs:[] Accounts:[] ForeignApps:[] ForeignAssets:[] LocalStateSchema:{_struct:{} NumUint:0 NumByteSlice:0} GlobalStateSchema:{_struct:{} NumUint:0 NumByteSlice:0} ApprovalProgram:[] ClearStateProgram:[] ExtraProgramPages:0} CompactCertTxnFields:{_struct:{} CertRound:0 CertType:0 Cert:{_struct:{} SigCommit:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA SignedWeight:0 SigProofs:[] PartProofs:[] Reveals:map[]}}} AuthAddr:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ} invalid : transaction ALNSSM27M3BZRVZVXPCIPPO2FEQI66QBXPYAU5IBV4OAZJXOTZEA: rejected by logic
PS D:\pyalg> & C:/Users/Dell/AppData/Local/Programs/Python/Python39/python.exe d:/pyalg/hash1.py
Escrow Address: DJHV2ACKWRWOAPYBO2XL5FNRHIJ2WRSOAMAE5DPSFQ5UNVEXV4LOTNXT3A

Traceback (most recent call last):
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\algosdk\algod.py", line 75, in algod_request
    resp = urlopen(req)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
    response = meth(req, response)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response   
    response = self.parent.error(
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
    return self._call_chain(*args)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain     
    result = func(*args)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "d:\pyalg\hash1.py", line 60, in <module>
    txid = client.send_transaction(logicsig_txn, headers={'content-type': 'application/x-binary'})
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\algosdk\algod.py", line 290, in send_transaction
    return self.send_raw_transaction(encoding.msgpack_encode(txn),
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\algosdk\algod.py", line 277, in send_raw_transaction
    return self.algod_request("POST", req, data=txn, headers=tx_headers, **kwargs)["txId"]
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\algosdk\algod.py", line 83, in algod_request
    raise error.AlgodHTTPError(raisex)
algosdk.error.AlgodHTTPError: transaction {_struct:{} Sig:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Msig:{_struct:{} Version:0 Threshold:0 Subsigs:[]} Lsig:{_struct:{} Logic:[1 32 4 208 15 1 0 192 150 177 2 38 3 32 229 212 184 181 209 48 181 110 105 208 
140 137 125 14 71 219 36 82 217 241 69 115 100 147 81 226 91 182 112 155 66 115 32 67 54 33 171 210 101 97 185 246 65 211 140 174 28 177 86 83 109 54 55 178 191 34 92 252 143 29 241 80 6 124 103 32 79 117 126 163 147 199 88 139 
14 230 124 106 63 192 81 197 35 24 163 5 199 32 19 21 164 103 198 162 81 253 157 138 49 1 34 14 49 16 35 18 16 49 
7 50 3 18 16 49 8 36 18 16 49 9 40 18 45 1 41 18 16 49 9 42 18 49 2 37 13 16 17 16] Sig:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Msig:{_struct:{} Version:0 Threshold:0 Subsigs:[]} Args:[[104 101 114 111 32 119 105 115 100 111 109 32 103 114 101 101 110 
32 115 112 108 105 116 32 108 111 111 112 32 101 108 101 109 101 110 116 32 118 111 116 101 32 98 101 108 116]]} Txn:{_struct:{} Type:pay Header:{_struct:{} Sender:DJHV2ACKWRWOAPYBO2XL5FNRHIJ2WRSOAMAE5DPSFQ5UNVEXV4LOTNXT3A Fee:{Raw:1000} FirstValid:15368595 LastValid:15369595 Note:[] GenesisID:testnet-v1.0 GenesisHash:JBR3KGFEWPEE5SAQ6IWU6EEBZMHXD4CZU6WCBXWGF57XBZIJHIRA Group:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Lease:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] RekeyTo:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ} KeyregTxnFields:{_struct:{} VotePK:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] SelectionPK:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] VoteFirst:0 VoteLast:0 VoteKeyDilution:0 Nonparticipation:false} PaymentTxnFields:{_struct:{} Receiver:4XKLRNORGC2W42OQRSEX2DSH3MSFFWPRIVZWJE2R4JN3M4E3IJZUQCIPJM Amount:{Raw:0} CloseRemainderTo:42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE} AssetConfigTxnFields:{_struct:{} ConfigAsset:0 AssetParams:{_struct:{} Total:0 Decimals:0 DefaultFrozen:false UnitName: AssetName: URL: MetadataHash:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Manager:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ Reserve:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ Freeze:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ Clawback:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ}} AssetTransferTxnFields:{_struct:{} XferAsset:0 AssetAmount:0 AssetSender:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ AssetReceiver:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ AssetCloseTo:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ} AssetFreezeTxnFields:{_struct:{} FreezeAccount:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ FreezeAsset:0 AssetFrozen:false} ApplicationCallTxnFields:{_struct:{} ApplicationID:0 OnCompletion:NoOpOC ApplicationArgs:[] Accounts:[] ForeignApps:[] ForeignAssets:[] LocalStateSchema:{_struct:{} NumUint:0 NumByteSlice:0} GlobalStateSchema:{_struct:{} NumUint:0 NumByteSlice:0} ApprovalProgram:[] ClearStateProgram:[] ExtraProgramPages:0} CompactCertTxnFields:{_struct:{} CertRound:0 CertType:0 Cert:{_struct:{} SigCommit:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA SignedWeight:0 SigProofs:[] PartProofs:[] Reveals:map[]}}} AuthAddr:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ} invalid : transaction PPG7ILRDXWMN4NLH5GP6TZR6OH62YXRP753DDRUIVC5KDSE4AYLA: rejected by logic

This is the hash lock extended program which makes above error.Then first set of hash time lock program is compiled succesfully

from algosdk import algod, transaction, template
# Create an algod client
algod_token = ""
algod_address = "https://testnet.algoexplorerapi.io"
headers = {"User-Agent": "DoYouLoveMe?"}

client = algod.AlgodClient(algod_token, algod_address, headers)
# Get suggested parameters from the network
tx_params = client.suggested_params()
# Specify TLHC-related template params.
template_data = {
    "owner": "J52X5I4TY5MIWDXGPRVD7QCRYURRRIYFY4QBGFNEM7DKEUP5TWFOQPD3SY",
    "receiver": "4XKLRNORGC2W42OQRSEX2DSH3MSFFWPRIVZWJE2R4JN3M4E3IJZUQCIPJM",
    "hash_function": "sha256",
    "hash_image": "QzYhq9JlYbn2QdOMrhyxVlNtNjeyvyJc/I8d8VAGfGc=",
    "expiry_round": 5000000,
    "max_fee": 2000
}
## Inject template data into HTLC template
c = template.HTLC(**template_data)
# Get the address for the escrow account associated with the logic
addr = c.get_address()
print("Escrow Address: {}\n".format(addr))

# Retrieve the program bytes
program = c.get_program()
# Get the program and parameters and use them to create an lsig
# For the contract account to be used in a transaction
# In this example 'hero wisdom green split loop element vote belt'
# hashed with sha256 will produce our image hash
# This is the passcode for the HTLC 
args = [
    "hero wisdom green split loop element vote belt".encode()
]
# Add the program bytes and args to a LogicSig object 
lsig = transaction.LogicSig(program, args)

# Before submitting this transaction, you must first make sure the escrow 
# account is sufficiently funded. Once it is funded, create and submit
# transactions from the escrow account like the transaction below.
# Transaction data
tx_data = {
    "sender": addr,
    "receiver": "4XKLRNORGC2W42OQRSEX2DSH3MSFFWPRIVZWJE2R4JN3M4E3IJZUQCIPJM",
    "amt": 0,
    "close_remainder_to": "42NJMHTPFVPXVSDGA6JGKUV6TARV5UZTMPFIREMLXHETRKIVW34QFSDFRE",
    "fee": 1000,
    "flat_fee": True,
    "first": tx_params.get('lastRound'),
    "last": tx_params.get('lastRound') + 1000,
    "gen": tx_params.get('genesisID'),
    "gh": tx_params.get('genesishashb64')
}
# Instantiate a payment transaction type
txn = transaction.PaymentTxn(**tx_data)
# Instantiate a LogicSigTransaction with the payment txn and the logicsig
logicsig_txn = transaction.LogicSigTransaction(txn, lsig)

# Send the transaction to the network.
txid = client.send_transaction(logicsig_txn, headers={'content-type': 'application/x-binary'})
print("Transaction ID: {}".format(txid))

To debug this kind of issues, you want to write the transaction to file, by writing:

transaction.write_to_file([logicsig_txn], "htlc.tx")

just before

# Send the transaction to the network.

And then you can debug using the Algorand software in bash:

$ goal clerk dryrun -t htlc.tx

You see that the issue is:

121 txn Receiver => (e5d4b8b5d130b56e69d08c897d0e47db2452d9f14573649351e25bb6709b4273)
123 global ZeroAddress => (0000000000000000000000000000000000000000000000000000000000000000)
125 == => (0 0x0)

which means the smart contract expect the Receiver to be the ZeroAddress.

The issue is that you changed the wrong address.
You should have changed close_remainder_to instead of receiver.
receiver should be AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ, the zero address.
Concretely, you want:

tx_data = {
    "sender": addr,
    "receiver": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY5HFKQ",
    "amt": 0,
    "close_remainder_to": "4XKLRNORGC2W42OQRSEX2DSH3MSFFWPRIVZWJE2R4JN3M4E3IJZUQCIPJM",
    "fee": 1000,
    "flat_fee": True,
    "first": tx_params.get('lastRound'),
    "last": tx_params.get('lastRound') + 1000,
    "gen": tx_params.get('genesisID'),
    "gh": tx_params.get('genesishashb64')
}

You’ll get another error because the escrow account is not funded. You need to fund it using the dispenser: https://bank.testnet.algorand.network/

Thank you.It works.Is limit order program which is in the link:LimitOrder Contract with Python | Algorand Developer Portal work properly?
Can i use the code link code?Is it work?

Should work too.
Essentially v1 examples should work unless they involve indexer v1, that is unless they try to search for old transactions.

The only limitation is that you cannot use PureStake API when use v1 examples.