I am trying to create an ERC-1155 minter in Python that can mint hundreds (or more) NFTs, so I don't want to wait for each to be successful. How can I add nonce to the contract_instance transact() function? I can't seem to find this in the web3 py docs, or is there a better way to do this? I'm also wondering if I should expect some transactions to fail and maybe have some verification step. I did try with "wait_for_transaction_receipt" between each, but it takes about 10~ seconds for each individual mint which may be too slow, and it seems to randomly fail after about 20-30 mints.
With my current code I'm getting this error after about 20+ mints:
ValueError: {'code': -32000, 'message': 'replacement transaction underpriced'}
Appreciate any help you can offer!
Here's my code:
from web3 import Web3
from decouple import config
from eth_account import Account
from eth_account.signers.local import LocalAccount
from web3.auto import w3
from web3.middleware import geth_poa_middleware,construct_sign_and_send_raw_middleware
infura_url = config('INFURA_URL')
print(infura_url)
private_key=Private_Key
account: LocalAccount = Account.from_key(private_key)
w3 = Web3(Web3.HTTPProvider(infura_url))
w3.middleware_onion.add(construct_sign_and_send_raw_middleware(account))
print(f"Your hot wallet address is {account.address}")
w3.eth.defaultAccount = 'MYADDRESS'
#added for testnet
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
res = w3.isConnected()
for x in range(200):
address = 'CONTRACT_ADDRESS'
abi = 'ABI_HERE'
contract_instance = w3.eth.contract(address=address, abi=abi)
thisvar = contract_instance.functions.symbol().call()
print(thisvar)
print(x)
#generate a random address for simulating a large list of addresses
mint2acc = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
print(mint2acc.address)
thistx = contract_instance.functions.mint(mint2acc.address,1,1).transact()
in the transact you can put params like that
nonce = w3.eth.get_transaction_count(mint2acc.address)
contract_instance.functions.mint(mint2acc.address,1,1).transact({"nonce":nonce})
Related
Network_Devices = dashboard.networks.getNetworkDevices('xxx')
I am working on GET Requests with the Cisco Meraki API and Module in Python. The function above accepts only one 'input' ('xxx') above. Also, it will not accept a list.
Is there any way to automate this request in a python script? I have 50+ inputs I would like to run through the function.
Simply use a for loop. You said you have 50+ input, so you have a couple of options in this case:
Define a list in the .py file that holds all the networkd IDs (Not recommended).
Create a file that contains all the network IDs (Recommended).
I'll illustrate option 2:
I assume you are using Meraki SDK v1.12.0 downloaded by running pip install meraki
from pprint import pprint
import meraki
API_KEY = ""
dashboard = meraki.DashboardAPI(API_KEY)
with open(file=r"network_ids.txt", mode="rt", newline="") as f:
network_ids = [id.strip() for id in f.read().splitlines() if id.strip()]
for network_id in network_ids:
network_device = dashboard.networks.getNetworkDevices(network_id)
pprint(network_device)
The network_ids.txt file should be like: (each id on a seperate line)
L_123456
L_789101
L_111213
To minimize the step of collecting network IDs and adding each ID on a seperate line in a file, you can get the IDs from an organization ID:
from pprint import pprint
import meraki
API_KEY = ""
dashboard = meraki.DashboardAPI(API_KEY)
# Any organization id
org_id = "549236"
# Get all networks for an organization
networks = dashboard.organizations.getOrganizationNetworks(org_id, total_pages="all")
# pprint(networks)
# loop through networks
for network in networks:
# Get network devices for each network ID
network_devices = dashboard.networks.getNetworkDevices(network["id"])
# Check if the network has devices
if network_devices:
print(f"*** Devices in Network: {network['name']} ({network['id']}) ***")
for device in network_devices:
pprint(device)
else:
print(
f"!!! No devices found for network: {network['name']} ({network['id']}) !!!"
)
How do I get block data by block hash? I'm interested in getting block timestamp for each new block.
from web3 import Web3
avalanche_url = 'https://api.avax.network/ext/bc/C/rpc'
provider = Web3(Web3.HTTPProvider(avalanche_url))
new_block_filter = provider.eth.filter('latest')
while True:
block_hashes = new_block_filter.get_new_entries()
for block_hash in block_hashes:
block = provider.eth.get_block(block_hash.hex())
print(block)
This causes an error:
web3.exceptions.ExtraDataLengthError: The field extraData is 80 bytes, but should be 32. It is quite likely that you are connected to a POA chain. Refer to http://web3py.readthedocs.io/en/stable/middleware.html#geth-style-proof-of-authority for more details. The full extraData is: HexBytes('0x0000000000000000000000000001edd400000000000000000000000000000000000000000000000000000000002cb3970000000000000000000000000005902b00000000000000000000000000000000')
The same query works on Ethereum.
Adding geth_poa_middleware worked for me:
from web3 import Web3
from web3.middleware import geth_poa_middleware
w3 = Web3(Web3.HTTPProvider('https://api.avax.network/ext/bc/C/rpc'))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
APIError(code=-2015): Invalid API-key, IP, or permissions for action
I keep getting the above issue.
I am not sure what the issue is.
I am able to access the client.get_all_tickers() command no problem but when I try to place an order or access user_data (both which require a signature) I get the error
APIError(code=-2015): Invalid API-key, IP, or permissions for action
I think the issue has something to do with the signature. I checked to see if I have the relevant permissions enabled and I do. Furthermore, I tried to create a new API key and I still go the same issue.
NOTE: I am using binance.us not binance.com because I am located in the US so I cannot make an account on binance.com
Therefore, another idea I had was to create a VPN that places me in England so I can make an account through binance.com and maybe that will work.
import time
import datetime
import json
from time import sleep
from binance.client import Client
from binance.enums import *
import sys
import requests, json, time, hashlib
import urllib3
import logging
from urllib3 import PoolManager
from binance.exceptions import BinanceAPIException, BinanceWithdrawException
r = requests.get('https://www.binance.us/en/home')
client = Client(API_key,Secret_key,tld="us")
prices = client.get_all_tickers()
#Def to get location
def crypto_location(sym):
count = 0
for i in prices:
count += 1
ticker = i.get('symbol')
if ticker == sym:
val = i.get('price')
count = count-1
return count
bitcoin_location = crypto_location('BTCUSDT')
ethereum_location = crypto_location('ETHUSDT')
stable_coin_location = crypto_location('BUSDUSDT')
bitcoin_as_BUSD_location = crypto_location('BTCBUSD')
#%% Where to quickly get bitcoin price
t_min = time.localtime().tm_min
prices = client.get_all_tickers()
bitcoin_price = prices[bitcoin_location].get('price')
print(bitcoin_price)
ethereum_price = prices[ethereum_location].get('price')
print(ethereum_price)
stable_coin_price = prices[stable_coin_location].get('price')
print(stable_coin_price)
bitcoin_as_BUSD = prices[bitcoin_as_BUSD_location].get('price')
print(bitcoin_as_BUSD)
client.session.headers.update({ 'X-MBX-APIKEY': API_key})
client.get_account()
error occurs at client.get_account()
I had the same problem, the binance APIs without any IP restrictions, expire every 90 days. I have restricted the API to my IP and it works!
Still, you're sure to find it all here:
https://python-binance.readthedocs.io/en/latest/index.html
I'm having an issue recently with some values returned from item.sender - attached is a screen dump
As you can see in the lower portion of the graphic, it's not the usual form returned by item.sender which usually is of form:
Mailbox(name='ReCircle Recycling', email_address='aldoushicks#recirclerecycling.com', routing_type='SMTP', mailbox_type='OneOff')
Has anyone else seen this?
How do you deal with it?
i.e. even though I am using try/except clause, this result still causes my IDE to freeze.
I re-ran the script today using exactly the same date filter and it didn't happen. So I’m forced to ask, what did happen? Why is it not occurring again?
Its weird behaviour. It could jam up a script in future so wondering how to prevent it.
Code:
from collections import defaultdict
from datetime import datetime
import logging
from exchangelib import DELEGATE, Account, Credentials, \
EWSDateTime, EWSTimeZone, Configuration
from exchangelib.util import PrettyXmlHandler
logging.basicConfig(level=logging.DEBUG, handlers=[PrettyXmlHandler()])
gusername="" #deleted :/
gpassword="" #deleted :/
gprimary_smtp_address="bspks#lunet.lboro.ac.uk"
em_dict = defaultdict(list)
def contactServer(pusername, ppassword,pprimary_smtp_address):
creds = Credentials(pusername, ppassword)
config = Configuration(server='outlook.office365.com/EWS/Exchange.asmx', \
credentials=creds)
return Account(
primary_smtp_address=pprimary_smtp_address,
autodiscover=False,
config = config,
access_type=DELEGATE
)
print ("connecting to server\n")
account = contactServer(gusername, gpassword, gprimary_smtp_address)
dt_string = "2018-11-01 12:41:19+00:00" #usually comes out from db, stringified for debugging
dt = datetime.strptime(dt_string, '%Y-%m-%d %H:%M:%S+00:00')
tz = EWSTimeZone.timezone('Europe/London')
last_datetime = tz.localize(dt)
for item in account.inbox.filter(datetime_received__gt=last_datetime):
if isinstance(item, Message):
em_dict["username"].append(gusername)
em_dict["gprimary_smtp_address"].append(gprimary_smtp_address)
em_dict["datetime_received"].append(item.datetime_received)
em_dict["subject"].append(item.subject)
em_dict["body"].append(item.body)
em_dict["item_id"].append(item.item_id)
em_dict["sender"].append(item.sender)
# extract the email address from item.sender
emailaddr = item.sender.email_address
print ("debug email addr: ", emailaddr)
print ("downloaded emails\n")
I've been struggling for the last couple of days trying to make a transfer of a customized token between 2 ethereum wallets.
I am using populus (python) and It seems to be quite easy to make an ETH transfer but I couldn't understand how to do the same with a custom token.
This is my python code:
from decimal import Decimal
import populus
from populus.utils.accounts import is_account_locked
from populus.utils.cli import request_account_unlock
from eth_utils import from_wei
from ico.utils import check_succesful_tx
# Which network we deployed our contract
chain_name = "horton"
# Owner account on geth
owner_address = "0xaeCb8415d5553F080d351e82b2000f123BFBc23C"
# Where did we deploy our token
contract_address = "0x15f173b7aca7cd4a01d5f8360e65fb4491d270c1"
receiver = "0x4c042bf285689891117AED16005004a6de2cC4FB"
amount = Decimal("1.0")
project = populus.Project()
with project.get_chain(chain_name) as chain:
web3 = chain.web3
print("Web3 provider is", web3.currentProvider)
print("Owner address is", owner_address)
print("Owner balance is", from_wei(web3.eth.getBalance(owner_address), "ether"), "ETH")
# Goes through geth account unlock process if needed
if is_account_locked(web3, owner_address):
request_account_unlock(chain, owner_address, None)
transaction = {"from": owner_address}
FractionalERC20 = chain.contract_factories.FractionalERC20
token = FractionalERC20(address=contract_address)
decimals = token.call().decimals()
decimal_multiplier = 10 ** decimals
decimals = 18
decimal_multiplier = 10 ** decimals
print("Token has", decimals, "decimals")
print("Owner token balance is", token.call().balanceOf(owner_address) / decimal_multiplier)
# Use lowest denominator amount
normalized_amount = int(amount * decimal_multiplier)
# Transfer the tokens
txid = token.transact({"from": owner_address}).transfer(receiver, normalized_amount)
print("TXID is", txid)
check_succesful_tx(web3, txid)
But I'm getting an error while executing the above code:
File "ICO_transfering_tokens.py", line 39, in <module>
FractionalERC20 = chain.contract_factories.FractionalERC20
AttributeError: 'LocalGethChain' object has no attribute 'contract_factories'
I understand the error but not how to fix it.
Apparently you have copied this code from ICO project. To make it easier for users to answer, it makes sense to tell where did you get the source code. This project has its own chat group here.
The reason for the exception is that in some versions of Populous the API was changed and the example you are using is for the old version of an API. Please upgrade both ICO repository and Populous to the latest compatible version configuration which you can find in ICO repo Travis output.
Please replace this line:
FractionalERC20 = chain.contract_factories.FractionalERC20
With this:
from ico.utils import get_contract_by_name
FractionalERC20 = = get_contract_by_name(chain, "FractionalERC20")