def prepare_paxos_dollar_tx(to_address, private_key, amount_to_send):
    contract = load_contract('0x8e870d67f660d95d5be530380d0ec0bd388289e1')
    #checksum addresses, just to be sure
    to_address = w3.toChecksumAddress(to_address)
    #grab nonce
    from_address = w3.toChecksumAddress(
        str(w3.eth.account.privateKeyToAccount(private_key).address))
    nonce = w3.eth.getTransactionCount(from_address)
    balance = w3.eth.getBalance(from_address)
    print(balance)
    #prepare transaction for transfer function
    #for now, gas limit is 1,000,000 and gas price is 3 Gwei
    amount = int(amount_to_send * 4485035922634800)
    print(amount)
    new_txn = {
        'to': to_address,
        'value': w3.toHex(amount),
        'gas': 21000,
        'gasPrice': w3.toWei('15', 'gwei'),
        'nonce': nonce,
        'chainId': 1
    }
    #sign transaction
    signed_txn = w3.eth.account.signTransaction(new_txn,
                                                private_key=private_key)
    #return signed transaction
    return (signed_txn)
    print(private_key)
Exemple #2
0
def add_sets_to_blockchain(homomorphic_sets, voter_name):
    # create a mysql connection
    db = pymysql.connect("localhost", "root", "mysql", "voting")
    cursor = db.cursor()
    query = "select voter_id from tbl_voters where voter_name = '{}'".format(
        voter_name)
    try:
        cursor.execute(query)
        result = cursor.fetchall()
        db.commit()
        cursor.close()
    except:
        print("Error while inserting new voter data to local DB")
        traceback.print_exc()
    voter_id = result[0][0]
    hashed_string = str(
        hashlib.sha256(str(homomorphic_sets).encode()).hexdigest())

    ganache_url = "http://127.0.0.1:8545"
    #connect to local private blockchain on ganache
    web3 = Web3(Web3.HTTPProvider(ganache_url))
    #print(web3.isConnected())
    if web3.isConnected():
        # load the json data which can be obtained after deploying smart contracts
        abi = json.loads(
            ' [{"constant":false,"inputs":[{"name":"_voterID","type":"uint256"},{"name":"_details","type":"string"}],"name":"addCastedDetailsHash","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getVoterCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_voterID","type":"uint256"},{"name":"_voterDetails","type":"string"}],"name":"addVoter","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"votersCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_voterID","type":"uint256"}],"name":"getVoter","outputs":[{"name":"","type":"uint256"},{"name":"","type":"string"},{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"voters","outputs":[{"name":"voterID","type":"uint256"},{"name":"voterDetailsHashed","type":"string"},{"name":"voteCastedDetailsHash","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}]'
        )

        # load the address where smart contracts are deployed
        address = web3.toChecksumAddress(
            '0x8A707F18f249CfE5D15bEb10e0c34CcEC2785C86')

        # establish the connection with blockchain using address and ABI
        contract = web3.eth.contract(address=address, abi=abi)
        #print(contract)
        # get voter details from blockchain based on voter_id
        try:
            # create a transaction on blockchain to add the new voter details using the private key
            tx_hash = contract.functions.addCastedDetailsHash(
                voter_id, hashed_string).transact({
                    'from':
                    web3.toChecksumAddress(
                        '0x74a625b67a5acd0d1b44e3185e65b9d9835925a3'),
                    'gas':
                    3400000
                })
            #tx_hash = contract.functions.addVoter(voter_name, age, region).transact({'from':'0x2c08A59BB7989dFea6d9366552bC7E233a2dbD21', 'gas': 3400000})

            # wait for the block to be  mined on blockchain
            #web3.eth.waitForTransactionReceipt(tx_hash)
            return True

        except:
            traceback.print_exc()
Exemple #3
0
 def post(self, request, format=None):
     address_to_send_to = w3.toChecksumAddress(
         self.request.data['address_to_send_to'])
     amount_of_paxos_usd_to_send = decimal.Decimal(
         self.request.data['amount_of_paxos_usd_to_send'])
     #decode master wallet, make transactions
     decoding_string = 'teamkalsh'
     filename = 'paxos_payout/teamkalsh'
     key_data = json.loads(open(filename, 'r').read())
     private_key = w3.eth.account.decrypt(key_data, decoding_string)
     signed_transaction = prepare_paxos_dollar_tx(
         address_to_send_to, private_key, amount_of_paxos_usd_to_send)
     print(signed_transaction)
     tx_hash = w3.eth.sendRawTransaction(signed_transaction.rawTransaction)
     # tx_hash = signed_transaction['hash']
     print(tx_hash)
     # gasPurchaseObejct = handleGasPurchaseObject(tx_hash, self.request.user,
     #                                             amount_of_gas_in_nftg_units,
     #                                             amount_of_usd_spent)
     #delegates resolving gas purchase object to celery so server can run
     # resolveGasPurchaseObjectTask.delay(gasPurchaseObejct.id)
     # print(gasPurchaseObejct.id)
     tx_hash_string = ('0x' + binascii.hexlify(tx_hash).decode('utf-8'))
     print(tx_hash_string)
     return Response(tx_hash_string, status=status.HTTP_200_OK)
def node2(id,data):
	ganache_url="http://127.0.0.1:7545"
	web3=Web3(Web3.HTTPProvider(ganache_url))
	
	node2_address="0xe8652965ed04Bce6C9764e7eA80a26e61b434f8F"
	node2_pk="b28fc4327c99022b087d79e8edadada2e2d71d029d3552d4700bf78b7a3968f2"
	fp = open('abi.json', 'r')
	abi=json.load(fp)
	contract_address=web3.toChecksumAddress("0xbd12Ef3a93b06a72374188017Ef67b9FD8f6717e")
	contract=web3.eth.contract(address=contract_address,abi=abi)
	nonce=web3.eth.getTransactionCount(node2_address)

	# print("CMP! ADD TO BLOCKCHAIN id", id, "data", data, "readable", data.hex())
	transaction=contract.functions.addData(id,data).buildTransaction({
		'gas':70000,
		'gasPrice':web3.toWei('1','gwei'),
		'from': node2_address,
		'nonce': nonce
		
	})
	
	signed_transaction=web3.eth.account.signTransaction(transaction, node2_pk)
	transaction_hash=web3.eth.sendRawTransaction(signed_transaction.rawTransaction)
	
	return web3.toHex(transaction_hash)
def send_to(person, to, value, print_info=False):
    #check balance
    if web3.eth.getBalance(person.address) < value:
        print("No enough funds for payment")
        return {'status': -1}
    #sign
    signed_tx = {
        'to': to,
        'value': value,
        'gas': 21000,
        'gasPrice': get_gas_price(),
        'nonce': web3.eth.getTransactionCount(person.address)
    }
    signed_tx = person.signTransaction(signed_tx)
    #sending transaction
    raw_tx = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
    TX = web3.eth.waitForTransactionReceipt(raw_tx)
    #optional
    #printing info
    if print_info:
        balance = balance_all(value)
        print("Payment of {0} {1} from {2} to {3} scheduled".format(
            balance[0], balance[1], person.address,
            '"' + web3.toChecksumAddress(to)[2:] + '"'))
        print("Transaction Hash: {0}".format(TX['transactionHash'].hex()))
    return TX
def load_contract(
        nifty_app_addres='0x8e870d67f660d95d5be530380d0ec0bd388289e1'):
    nifty_app_address = w3.toChecksumAddress(
        '0x8e870d67f660d95d5be530380d0ec0bd388289e1')
    #depending on app name, load abi and address
    Contract_abi = retrieve_abi_from_contract_address(nifty_app_address)
    # Contract_address = '0x06012c8cf97BEaD5deAe237070F9587f8E7A266d'
    #return contract object
    return (w3.eth.contract(address=nifty_app_address, abi=Contract_abi))
Exemple #7
0
def reward(question_id, answer_id):
    db = get_db()
    error = None

    question = db.execute(
        'SELECT id, price, user_id'
        ' FROM question'
        ' WHERE id = (?)',
        (str(question_id),)
    ).fetchone()
    answer = db.execute(
        'SELECT id, user_id'
        ' FROM answer'
        ' WHERE id = (?)',
        (str(answer_id),)
    ).fetchone()
    answerer = db.execute(
        'SELECT id, eth_address'
        ' FROM user'
        ' WHERE id = (?)',
        (str(answer['user_id']),)
    ).fetchone()

    if g.user['id'] == question['user_id']:
        web3 = Web3(HTTPProvider('http://127.0.0.1:8545'))
        to_address = web3.toChecksumAddress(str(answerer['eth_address']))

        data = '0xa9059cbb000000000000000000000000' + to_address[2:] + '{0:064x}'.format(question['price'])
        transaction = {
            'from': web3.toChecksumAddress(os.environ['OWNER_ADDRESS']),
            'to': web3.toChecksumAddress(os.environ['CONTRACT_ADDRESS']),
            'value': '0x0',
            'data': data
        }
        web3.personal.sendTransaction(transaction, os.environ['OWNER_ADDRESS_PASSWORD'])
        # JSON-RPC
        # curl -X POST --data '{"jsonrpc":"2.0","method":"personal_sendTransaction","params":[{"from": "OWNER_ADDRESS", "to": "CONTRACT_ADDRESS", "data":"0xa9059cbb + 付与先アドレス(32byte) + 付与したいトークン数(32byte)"}, "OWNER_ADDRESS_PASSWORD"],"id":67}' -H "Content-Type: application/json" http://127.0.0.1:8545/
    else:
        error = 'Invalid Access'
        flash(error)

    return redirect(url_for('main.answer_index', question_id=str(question_id)))
def validate(id):
	ganache_url="HTTP://127.0.0.1:7545"
	web3=Web3(Web3.HTTPProvider(ganache_url))
	fp = open('abi.json', 'r')
	abi=json.load(fp)
	contract_address=web3.toChecksumAddress("0xbd12Ef3a93b06a72374188017Ef67b9FD8f6717e")
	contract=web3.eth.contract(address=contract_address,abi=abi)
	
	web3.eth.defaultAccount=web3.eth.accounts[2]
	
	ret=contract.functions.getData(id).call()
	# print("CMP! DATA FROM BLOCKCHAIN id", id, ret.hex())
	print("value in blockchain for id", id, "is", "0x"+ret.hex())
	return "0x"+ret.hex()
def node3(id,data):
	ganache_url="http://127.0.0.1:7545"
	web3=Web3(Web3.HTTPProvider(ganache_url))
	
	node3_address="0x4eD6E3e8102A2cE2924EabF5f9916BB3bD6B66d5"
	node3_pk="4058bc0213a462b74deb3bfc42eba9d35e6e0e15debbbc92fcfebe414fae6058"
	fp = open('abi.json', 'r')
	abi=json.load(fp)
	contract_address=web3.toChecksumAddress("0xbd12Ef3a93b06a72374188017Ef67b9FD8f6717e")
	contract=web3.eth.contract(address=contract_address,abi=abi)
	nonce=web3.eth.getTransactionCount(node3_address)
	transaction=contract.functions.addData(id,data).buildTransaction({
		'gas':70000,
		'gasPrice':web3.toWei('1','gwei'),
		'from': node3_address,
		'nonce': nonce
		
	})
	
	signed_transaction=web3.eth.account.signTransaction(transaction, node3_pk)
	transaction_hash=web3.eth.sendRawTransaction(signed_transaction.rawTransaction)
	
	return web3.toHex(transaction_hash)
def node1(id,data):
	ganache_url="http://127.0.0.1:7545"
	web3=Web3(Web3.HTTPProvider(ganache_url))
	
	node1_address="0xf49437Dd2E96f1249815c82727Cc17c8388d9349"
	node1_pk="22aaa185ee18e1b169fa7192d6428fcfc4db2f0386dffb1eee100c2cfdf94bd5"
	fp = open('abi.json', 'r')
	abi=json.load(fp)
	contract_address=web3.toChecksumAddress("0xbd12Ef3a93b06a72374188017Ef67b9FD8f6717e")
	contract=web3.eth.contract(address=contract_address,abi=abi)
	nonce=web3.eth.getTransactionCount(node1_address)
	transaction=contract.functions.addData(id,data).buildTransaction({
		'gas':70000,
		'gasPrice':web3.toWei('1','gwei'),
		'from': node1_address,
		'nonce': nonce
		
	})
	
	signed_transaction=web3.eth.account.signTransaction(transaction, node1_pk)
	transaction_hash=web3.eth.sendRawTransaction(signed_transaction.rawTransaction)
	
	return web3.toHex(transaction_hash)
Exemple #11
0
def get_token_contract(web3):
    tokens = web3.eth.contract(address=web3.toChecksumAddress(
        config['token']['address']),
                               abi=get_token_contract_abi())
    return tokens
Exemple #12
0
data1 = csv_import('flextable1.csv')
data2 = csv_import('flextable2.csv')
data3 = csv_import('flextable3.csv')
#Use print(data1) to check the data.

web3 = Web3(
    HTTPProvider("HTTP://127.0.0.1:8501", request_kwargs={'timeout': 600}))
print(web3)

#Unlock the account to make transaction. In practice, the three prosumers and the DSO should each have an account to perform the corresponding operations.
#Only one account is used here to do all the operations.
web3.personal.unlockAccount(web3.eth.accounts[1], 'gogogo')

#Returns the smart contract instance sc that allows to call this contract's functions
contract_address = web3.toChecksumAddress(
    0x8c4f8895184555d5fe2c89c8b5d02b73d72b3d79)
abi_str = '[{"constant":false,"inputs":[{"name":"_timepoint","type":"uint16"},{"name":"_PosPower","type":"uint16"},{"name":"_PosEnergy","type":"uint16"},{"name":"_PosPrice","type":"uint16"}],"name":"SetPosoffers1","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"RemoveOffers","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_timepoint","type":"uint16"},{"name":"_scheduledPower","type":"uint16"},{"name":"_NegPower","type":"uint16"},{"name":"_NegEnergy","type":"uint16"},{"name":"_NegPrice","type":"uint16"}],"name":"SetNegoffers2","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"showNeeds","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"ShowFlexId","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_timepoint","type":"uint16"},{"name":"_scheduledPower","type":"uint16"},{"name":"_NegPower","type":"uint16"},{"name":"_NegEnergy","type":"uint16"},{"name":"_NegPrice","type":"uint16"}],"name":"SetNegoffers3","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"Checkoffers1","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"StartFlexMatching","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"Checkoffers2","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"Totalprice1","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"Totalprice2","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"FindCheapestoffer","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"i","type":"uint16"}],"name":"ShowOffers1","outputs":[{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"FlexunittoOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_EICcode","type":"string"},{"name":"_capacity","type":"uint256"}],"name":"Register","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"i","type":"uint16"}],"name":"ShowOffers3","outputs":[{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_timepoint","type":"uint16"},{"name":"_PosPower","type":"uint16"},{"name":"_PosEnergy","type":"uint16"},{"name":"_PosPrice","type":"uint16"}],"name":"SetPosoffers3","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_timepoint","type":"uint16"},{"name":"_scheduledPower","type":"uint16"},{"name":"_NegPower","type":"uint16"},{"name":"_PosPower","type":"uint16"},{"name":"_NegEnergy","type":"uint16"},{"name":"_PosEnergy","type":"uint16"},{"name":"_NegPrice","type":"uint16"},{"name":"_PosPrice","type":"uint16"}],"name":"SetFlexoffer1","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_timepoint","type":"uint16"},{"name":"_PosPower","type":"uint16"},{"name":"_PosEnergy","type":"uint16"},{"name":"_PosPrice","type":"uint16"}],"name":"SetPosoffers2","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_timepoint","type":"uint16"}],"name":"SetZerooffers3","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_timepoint","type":"uint16"},{"name":"_scheduledPower","type":"uint16"},{"name":"_NegPower","type":"uint16"},{"name":"_NegEnergy","type":"uint16"},{"name":"_NegPrice","type":"uint16"}],"name":"SetNegoffers1","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"Totalprice3","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"i","type":"uint16"}],"name":"ShowOffers2","outputs":[{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"},{"name":"","type":"uint16"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"Checkoffers3","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"calculateNeeds","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"Flexunits","outputs":[{"name":"EICcode","type":"string"},{"name":"capacity","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_timepoint","type":"uint16"}],"name":"SetZerooffers1","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_timepoint","type":"uint16"}],"name":"SetZerooffers2","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_kind","type":"string"},{"name":"_timepoint","type":"uint16"},{"name":"_Power","type":"uint16"},{"name":"_duration","type":"uint8"}],"name":"SetFlexdemand","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"FlexunitId","type":"uint256"},{"indexed":false,"name":"EICcode","type":"string"},{"indexed":false,"name":"capacity","type":"uint256"}],"name":"NewFlexunit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"}]'
contract_abi = json.loads(abi_str)
contract = web3.eth.contract(abi=contract_abi, address=contract_address)
contract

#contract.transact({'from':web3.eth.accounts[1]}).SetZerooffers1(2)

#Set flexibility table from 3 prosumers. Here we use the same account.
#In practice, it should be the account corresponding to each prosumer and the password it sets.
web3.personal.unlockAccount(web3.eth.accounts[1], 'gogogo')
for i in range(0, 95):
    if (int(data1['Leistung_Plan'][i]) == 0
            and int(data1['Leistung+'][i]) == 0):
        web3.personal.unlockAccount(web3.eth.accounts[1], 'gogogo')
        contract.transact({'from': web3.eth.accounts[1]}).SetZerooffers1(i)
Exemple #13
0
    address=tokenaddress,
    abi=abi,
)

token_owner_private_key = os.environ.get('token_owner_private_key', '')
token_owner = web3.eth.account.privateKeyToAccount(
    token_owner_private_key).address
nonce = web3.eth.getTransactionCount(token_owner)

# Distribute rewards to eligible ethereum addresses
cur.execute(
    "SELECT DISTINCT eth_address, amount FROM tse_rewards WHERE run = %s AND token = %s AND txid IS NULL",
    (run, token))
rows = cur.fetchall()
for row in rows:
    dropaddress = web3.toChecksumAddress(row[0])
    qty = (amount * 10**18)

    txn = tokeninst.functions.transfer(dropaddress, qty)

    txn = txn.buildTransaction({
        'gas': 51000,
        'nonce': nonce,
    })

    txn = web3.eth.account.signTransaction(txn, token_owner_private_key)
    txid = web3.eth.sendRawTransaction(txn.rawTransaction)

    print("Rewarding", token, "to", row[0], "txid is ", txid)
    cur.execute(
        "UPDATE tse_rewards SET txid = (%s) WHERE eth_address = (%s) AND token = (%s) AND run = %s",
Exemple #14
0
import web3
from web3 import Web3, HTTPProvider
from web3.contract import ConciseContract
import json

device_types = {"house": 0, "pv": 1, "battery": 2, "grid": 3}


web3 = Web3(HTTPProvider('http://localhost:8545'))

artefact_configuration = json.load(open('../build/contracts/Configuration.json'))
adr_configuration = web3.toChecksumAddress("0x5aef01194b7b82bac337a5e42bd10af52a097ccd")
ins_configuration = web3.eth.contract(adr_configuration, abi=artefact_configuration['abi'], ContractFactoryClass=ConciseContract)

config = json.load(open('../src/config.json'))

# ctr_configuration = web3.eth.contract(abi=artefact_configuration["abi"])

i = 0
for device_type in config:
    for element in config[device_type]:
        element["type"] = device_type
        element["device_name"] = "{}{}".format(device_type, element["id"])
        element["address"] = web3.eth.accounts[i]
        print(element)
        i = i+1


for device_type in config:
    for element in config[device_type]:
        if (element["type"] == "grid"):
import web3
import time
from datetime import datetime
import sorting
import json
import pandas as pd
import numpy as np
from datetime import datetime
import pprint

from web3 import Web3, IPCProvider, HTTPProvider

#Connection to BC
web3 = Web3(HTTPProvider("http://localhost:8501"))
Flexmarket_address = web3.toChecksumAddress("0x3c375af1aac69f7af48b19ad06231f6633251b2e")

with open("ABI.json") as f:
    abi = json.load(f)

Flexmarket_contract = web3.eth.contract(abi = abi, address = Flexmarket_address)


#Settings for Dataframe
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
pd.options.display.float_format = '{:.0f}'.format

#Info for the Timer
markettime = 15 #value in minutes
Exemple #16
0
# import libraries, importantly web3

import json
import pause
import web3
import func_BC
import abi_smartcert
from web3 import Web3, IPCProvider, HTTPProvider

# Establish RPC connection with running node.
web3 = Web3(HTTPProvider("http://*****:*****@ block #" + str(web3.eth.blockNumber))
#
# func_BC.py_addSMGW(web3, contract, smgw1, owner1, pw)
Exemple #17
0
# -*- coding: utf-8 -*-

import web3
import json
import math
import random
import time
import pandas as pd
from datetime import datetime

from web3 import Web3, IPCProvider, HTTPProvider

web3 = Web3(HTTPProvider("http://localhost:8501"))
Flexmarket_address = web3.toChecksumAddress("0x66e71756522d77743e0c8c6f2c01482ccc5ab4d3")

with open("ABI.json") as f:
    abi = json.load(f)

Flexmarket_contract = web3.eth.contract(abi = abi, address = Flexmarket_address)

print(web3.eth.accounts)

web3.parity.personal.unlockAccount(web3.eth.accounts[3], "Ukulele112", None)
web3.eth.waitForTransactionReceipt(Flexmarket_contract.functions.addSmartMeter(web3.eth.accounts[3], "EV").transact({'from': web3.eth.accounts[3]}))

t = 0
a = 0

'''for n in range(95):
    if (a > 95):
        a = 0
Exemple #18
0
# load generation curves
file_gen = open(chain_location + chain_name + "/py_script_info/input_gen.csv", "r")
list_gen = func_fileIO.readFloatArrayFromFile(file_gen)
file_gen.close()
pv_curve, chp_curve = list_gen[0], list_gen[1]

# connect to chain
# Establish RPC connection with running node.

web3 = Web3(HTTPProvider("http://localhost:8501"))
pw = "reghee"

# configure smart contract (already deployed on chain manually)

contract_address = web3.toChecksumAddress(0x82b8e36739ce115e6b8b1102a61d9f223209fab2)
contract_abi = json.loads(abi_smartcert.returnABIstr())
contract = web3.eth.contract(abi=contract_abi, address=contract_address)

for entry in list_acc:
    func_BC.py_addSMGW(web3, contract, web3.toChecksumAddress(entry[0]), web3.toChecksumAddress(entry[4]), pw)

# wait for new block before beginning simulation
func_BC.py_waitForNextBlock(web3, "Wait for new block before beginning simulation...")
smgw_cum_energy = [0] * 100

# define "cycle" and "hour" variable
# as this chain will run in accelerated time, each cycle(block) will represent 15 minutes
cycle = 1
hour, hour_previous, day = 0, 0, 0
step_min = 15
def get_storage_contract(web3):
    tokens = web3.eth.contract(address=web3.toChecksumAddress(
        settings.ethereum_event_contract),
                               abi=get_storage_contract_abi())
    return tokens
Exemple #20
0
from logging import INFO
from app.models import addressDB, authoDB
from django.shortcuts import get_object_or_404, redirect, render, redirect
from django.contrib.auth.models import User, auth
from django.contrib import messages
from web3 import Web3
import json
import web3

ganache_url = "http://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganache_url))
web3.eth.default_account = web3.eth.accounts[0]
abi = json.loads(
    '[{"constant":false,"inputs":[{"name":"voterIndex","type":"uint256"}],"name":"vote","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_first_name","type":"string"},{"name":"_last_name","type":"string"},{"name":"_email","type":"string"},{"name":"_username","type":"string"},{"name":"_phone_number","type":"string"},{"name":"_password","type":"string"}],"name":"register","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"auctionEnd","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"n","type":"uint256"}],"name":"result","outputs":[{"name":"","type":"string"},{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"canditates","outputs":[{"name":"name","type":"string"},{"name":"voteCount","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_username","type":"string"},{"name":"_password","type":"string"}],"name":"login","outputs":[{"name":"","type":"string"},{"name":"","type":"string"},{"name":"","type":"string"},{"name":"","type":"string"},{"name":"","type":"string"},{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"voter","type":"address"}],"name":"authorize","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"candInfo","outputs":[{"name":"","type":"string"},{"name":"","type":"string"},{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"nbOfVoters","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"end","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_address","type":"address"}],"name":"getInfo","outputs":[{"name":"","type":"string"},{"name":"","type":"string"},{"name":"","type":"string"},{"name":"","type":"string"},{"name":"","type":"string"},{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"_name","type":"string"},{"name":"duraitonMinutes","type":"uint256"},{"name":"canditate1","type":"string"},{"name":"canditate2","type":"string"},{"name":"canditate3","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"name":"name","type":"string"},{"indexed":false,"name":"voteCount","type":"uint256"}],"name":"ElectionResult","type":"event"}]'
)
address = web3.toChecksumAddress("0x7C4eF251d2eA442f4cda34fCC4cbBAF7aFde0A65")

contract = web3.eth.contract(address=address, abi=abi)

auth = 0
cand = 0
adminLog = 0
cand_names = []
userDetails = []
main_info = []
voteCount = []
accounts = []
info = []


def index(request):
            if file and pass_eth:
                from web3.auto import w3
                import web3
                from web3 import Web3

                try:
                    private_key = w3.eth.account.decrypt(file_2, pass_eth)
                except:
                    st.error('Try again please check pass for wallet')
                else:
                    ropsten_url = "https://ropsten.infura.io/v3/xxxxxxxxxxx"
                    web3 = Web3(Web3.HTTPProvider(ropsten_url))
                    with open('TokenGrant.json') as r:
                        data = json.load(r)
                    abi = data["abi"]
                    address = web3.toChecksumAddress(
                        "0xb64649fe00f8Ef5187d09d109C6F38f13C7CF857")
                    contract = web3.eth.contract(address=address, abi=abi)
                    grand = contract.functions.getGrants(
                        web3.toChecksumAddress(ETH)).call()
                    #st.write(grand)
                    if not grand:
                        st.error(
                            'Grand not received go https://us-central1-keep-test-f3e0.cloudfunctions.net/keep-faucet-ropsten?account=%s'
                            % ETH)
                    else:
                        st.success('Grand received')

                    stake = contract.functions.stakeBalanceOf(
                        web3.toChecksumAddress(ETH)).call()
                    if stake != 0 and stake > 90000:
                        st.success('KEEP Tokens delegated')