How to transfer tokens between wallets using geth - python

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")

Related

Adding nonce to run multiple contract transactions with web3 python

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})

Open and Close positions on python trading_ig

I am new to trading_ig library.
I have connected to my live IG account.
from trading_ig import IGService
from trading_ig_config import config
ig_service = IGService(config.username, config.password, config.api_key, config.acc_type)
ig_service.create_session()
#account_info = ig_service.switch_account(config.acc_number, False) # not necessary
#print(account_info)
open_positions = ig_service.fetch_open_positions()
print("open_positions:\n%s" % open_positions)
print("")
I have been able to download the latest 100 days of an index:
epic = 'IX.D.SPTRD.DAILY.IP'
resolution = 'D'
num_points = 100
response = ig_service.fetch_historical_prices_by_epic_and_num_points(epic, resolution, num_points)
df_ask = response['prices']['ask']
print("ask prices:\n%s" % df_ask)
Now, based on an algorithm that I have created, I want to be able to open and close a position automatically by letting the python code continuously run?
Do I need to use Lightstreamer?
How I open and close a position in Python?
Again, I am new to this and the IG documentation didn't provide much information.
Thanks for your help.

Binance API Issue - Python

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

How can i set up credentials as an environmental variable in windows?

I'm currently working on an academic project in my university and im trying to access IEX Cloud API (iexfinance) for financial data extraction using python but i keep running into an authentication error.
When i checked the documentation of the package it recommends to set Secret Authentication Key as an environmental variable using 'IEX_TOKEN' to authenticate my request which i dont know how to do.
Also, i should note that i'm very new to the world of programming so thank you in advance for any assistance.
Here's a snippet of the script i use:
tickerSymbol = input("Ticker Symbol: ")
companyInfo = Stock(tickerSymbol)
stockPrice = companyInfo.get_price()
start = datetime(sy,sm,sd)
end = datetime(ey, em,ed)
historicalPrices = get_historical_intraday(tickerSymbol, start, end)
stockHistoricals = pd.DataFrame(historicalPrices).T
Assuming you know the secret authentication key. Try:
#import os module in first line of your code
import os
#set the env vairable in 2nd line
os.environ['IEX_TOKEN'] = 'TheSecretAuthenticationKey'
#other imports
...
...
...
...
#remaining code

transcrypt connectionpool error

I am very new to coding and web development. I am a Systems Engineer and looking to get into the Web Development side of things. I took some python tutorials and pieced together a (probably very) rough python application. I would now like to take that application and put it on a website I have created so that I can allow others in the office to use the utility as well.
To that end, I installed transcrypt with the goal of converting the python code to javascript. When running transcrypt I get the following output:
Error while compiling (offending file last):
File 'c:/Scripting/Transcrypt/Meraki.py', line 1, at import of:
File 'c:/users/dab404/appdata/local/programs/python/python36/lib/site-packages/requests/init.py', line 43, at import of:
File 'c:/users/dab404/appdata/local/programs/python/python36/lib/site-packages/urllib3/init.py', line 8, namely:
Attempt to import module: connectionpool
Can't find any of:
c:/Scripting/Transcrypt/connectionpool.py
c:/Scripting/Transcrypt/javascript/connectionpool.mod.js
The error goes on to list about 10 other files that it needs to run. I am not sure how to fix this issue and would appreciate any help anyone can give me.
Here is my code:
import requests
import json
from meraki import meraki
base_url = "https://dashboard.meraki.com/api/v0/"
def List_Orgs(apikey): #A FUNCTION FOR LISTING ORGANIZATION ADMINS
myOrgs = meraki.myorgaccess(apikey)
for orgs in myOrgs:
print(orgs)
def List_Admins(URL_admin, headers):
x = requests.get(URL_admin, headers = headers)
myAdmins = x.json()
for admins in myAdmins:
print(admins)
def Add_Admin(URL, admin_data, headers): #FUNCTION FOR ADDING NEW ADMIN
TO AN ORGANIZATION
r = requests.request("POST", URL, data = admin_data, headers = headers)
print(r.status_code)
if (r.status_code) == 201:
print()
print()
print("Administrator successfully added!")
print()
else:
print()
print("Administrator was NOT successfully added. Please try again!")
print()
def Del_Admin(URL_del, headers): #FUNCTION FOR DELETING AN ADMIN FROM AN
ORGANIZATION
r = requests.request("DELETE", URL_del, headers = headers)
print(r.status_code)
if (r.status_code) == 204:
print()
print()
print("Administrator successfully deleted!")
print()
else:
print()
print("Administrator was NOT successfully deleted. Please try again!")
print()
apikey = input("What is your Meraki API key? ")
print()
print("******************************************")
print()
print("Here is a list of your Organizations. You will need the ID to answer
the next set of questions.")
print()
print()
List_Orgs(apikey)
print()
print()
headers = {
'X-Cisco-Meraki-API-Key': apikey,
'Content-Type': "application/json"
}
add_or_del = input("Would you like to add or delete an admin? ")
if add_or_del == ("add" or "Add" or "ADD"):
orgid = input("Which Organization would you like to add an admin to? ")
admin_name = input("What is the new Admin's First and Last name? ")
admin_email = input("What is " + admin_name + "'s email address? ")
admin_access = input("What level of access would you like " + admin_name +
" to have? (full or read-only) ")
admin_data = '{\n\t\"name\":\"' + admin_name + '\",\n\t\"email\":\"' +
admin_email + '\",\n\t\"orgAccess\":\"' + admin_access + '\"}'
URL = (base_url + 'organizations/' + orgid + '/admins')
Add_Admin(URL, admin_data, headers)
elif add_or_del == ("delete" or "Delete" or "DELETE"):
orgid = input("Which Organization would you like to delete an admin from?
")
URL_admin = (base_url + 'organizations/' + orgid + '/admins/')
print()
print("Here is a list of Admins in this Organization. You will need to
admin ID to answer the next question.")
print()
print()
List_Admins(URL_admin, headers)
print()
print()
adminid = input ("What is the admin's Meraki portal ID? ")
URL_del = (base_url + 'organizations/' + orgid + '/admins/' + adminid)
Del_Admin(URL_del, headers)
else:
print("Please type add or delete and try again.")'
Thanks!
David
The problem lies with the imports:
import requests
import json
from meraki import meraki
A module like requests is a standard Python module that isn't supported by Transcrypt, since it uses code written in C, that doesn't run in a browser.
For json there's a JavaScript counterpart that can be used directly from Transcrypt without problems.
Module meraki I don't know, so can't judge about.
Although a growing number of standard modules is supplied in the Transcrypt distribution, in general it makes use of JavaScript modules, since these are specially geared toward functionality that makes sense in a browser.
E.g. local file access is generally prohibited in a browser, so any module using that cannot do it's 'thing'.
See also:
http://www.transcrypt.org/docs/html/what_why.html#the-ecosystem-different-batteries
So in Transcrypt you program in Python, but the libs you use are mainly JavaScript. The exception are very common libs like math, cmath, random (partially), time, datetime, itertools, re etc.
To get an impression of how to use JavaScript libs from Transcrypt, take a look at:
http://www.transcrypt.org/examples
and also at:
http://www.transcrypt.org/docs/html/integration_javascript.html#mixed-examples
[EDIT]
I've taken another good look at your application, and I notice that it's a typical console application, using things like input and print. While these are supported in Transcrypt in a limited way, see
http://www.transcrypt.org/docs/html/integration_javascript.html#example-using-input-and-print-in-a-dom-terminal-element-in-your-browser
in general web applications work somewhat differently.
In general they are event driven, meaning that a number of GUI elements are pieced together, sometimes in HTML, sometimes in a script. These GUI elements then trigger events, that in turn trigger certain pieces of code (event handlers) to be run.
So a good next step may be to study this way of working. A nice, simple example in Transcrypt, of HTML/DOM and a script cooperating in this way is this one:
http://www.transcrypt.org/docs/html/installation_use.html#your-first-transcrypt-program
In many cases with a web application there's also interaction with a webserver, so part of the processing is done on the server.
You can e.g. use Bottle or Django for that, as is demoed at:
https://github.com/Michael-F-Ellis/NearlyPurePythonWebAppDemo

Categories