Skip to content

Instantly share code, notes, and snippets.

@YannBouyeron
Last active October 21, 2019 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YannBouyeron/48c179df2f245f94a7185d784782992e to your computer and use it in GitHub Desktop.
Save YannBouyeron/48c179df2f245f94a7185d784782992e to your computer and use it in GitHub Desktop.
import vyper.compiler as cp
from web3 import Web3, HTTPProvider
from web3.contract import ConciseContract
from crypto import HDPrivateKey, HDKey
from mnemonic import mnemonic as mn
import requests
import json
import time
from attrdict import AttrDict
# indiquez ci dessous votre clé Infura
w3 = Web3(HTTPProvider("https://ropsten.infura.io/v3/<Infura Key>"))
def mint(user):
"""
Mine des éthers de test ropsten au profit de l’account user passé en paramètre (objet account)
Attention , utiliser cette fonction avec parcimonie sinon vous allez vous faire bannir quelques dizaine de minutes du faucet ropsten.
"""
url = "https://faucet.ropsten.be/donate/{0}".format(user.address)
headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4'}
r = requests.get(url, data=None, headers=headers)
return r.json()
def creatAccount(n=1):
"""
Création d’un (ou plusieurs) nouvel account. Retourne dictionnaire contenant la mnemonic et les clés.
Argument facultatif: n le nombre d’account créé.
"""
x = mn.Mnemonic("english")
mnemo = x.generate()
master_key = HDPrivateKey.master_key_from_mnemonic(mnemo)
root_keys = HDKey.from_path(master_key,"m/44'/60'/0'")
acct_priv_key = root_keys[-1]
k = []
for i in range(n):
keys = HDKey.from_path(acct_priv_key,'{change}/{index}'.format(change=0, index=i))
private_key = keys[-1]
pub = private_key.public_key.address()
priv = private_key._key.to_hex()
k.append(AttrDict({'pub':pub, 'priv':priv}))
if len(k) == 1:
k[0]["mnemo"] = mnemo
return k[0]
return AttrDict({"mnemonic": mnemo, "key":k})
def creatUser(pub = None, priv = None):
"""
Création d’un objet account
Arguments:
pub: public key
priv: private key
Si pub ou priv == None, un nouvel account est créé.
Retourne un objet account
"""
if pub == None or priv == None:
a = creatAccount(n=1)
pub = a.pub
priv = a.priv
return w3.eth.account.privateKeyToAccount(priv)
# account creation
tom = w3.eth.account.privateKeyToAccount("<privante key")
jo = w3.eth.account.privateKeyToAccount("<private key")
w3.eth.defaultAccount = tom.address
def compile(path):
"""Compile le smart contract vyper situé au path passé en argument. Retourne le bytecode, et le abi."""
with open(path, 'rb') as c:
code = c.read()
code = code.decode()
r = cp.compile_code(code, output_formats=['bytecode', 'abi'])
return r['bytecode'], r['abi']
def makeTransaction(_from, _gas, _value, _to = ""):
"""
Construit une transaction
_from: account object
_gas: gas
_value: valeur en wei
_to: address (facultatif)
Retourne la transaction (dict)
"""
transaction = {
'from':_from.address,
'to': _to,
'value': _value,
'gas': _gas,
'gasPrice': w3.eth.gasPrice,
'nonce': w3.eth.getTransactionCount(_from.address)
}
if _to == "":
del(transaction['to'])
return transaction
def saveDeployedContract(path, bytecode, abi, address):
"""Sauvegarde dans le path passé en argument, le bytecode, abi et address d’un contract déjà déployé pour facilité son instantiation"""
c = {"bytecode":bytecode, "abi":abi, "address":address}
with open(path, "w") as js:
json.dump(c, js)
def creatInstance(address, abi):
"""
Création d’une instance d’un contrat à partir de son address et de son abi passés en argument.
Retourne l’instance du contract et ConciseContract
"""
contract = w3.eth.contract(address=address, abi=abi)
return contract, ConciseContract(contract)
def importContract(path):
"""
Création d’une instance d’un contract a partir de son address et de son abi jsonisé dans le path passé en argument
Retourne l’instance du contract et ConciseContract
"""
with open(path, "r") as js:
c = json.load(js)
contract = w3.eth.contract(address=c["address"], abi=c["abi"])
return contract, ConciseContract(contract)
def deploy(_bytecode, _abi, _from, _gas):
"""
Déploiement d’un contract
Arguments:
_bytecode
_abi
_from: account object
_gas
Retourne instance du contract et ConciseContract
"""
instance = w3.eth.contract(abi=_abi, bytecode=_bytecode)
tx_data = instance.constructor().__dict__.get("data_in_transaction")
transaction = {
'from': _from.address,
'value': 0,
'gas': _gas,
'gasPrice': w3.eth.gasPrice,
'nonce': w3.eth.getTransactionCount(_from.address),
'data': tx_data,
}
# Sign the transaction using your private key
signed = w3.eth.account.signTransaction(transaction, _from.privateKey)
tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction)
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
contract = w3.eth.contract(address=tx_receipt.contractAddress, abi=_abi,)
return contract, ConciseContract(contract)
def sendt(_from, _to, _value, _gas, _data=""):
"""
Make, signe et send transaction
Retourne tx_receipt
"""
transaction = {
'from': _from.address,
'to': _to,
'value': _value,
'gas': _gas,
'gasPrice': w3.eth.gasPrice,
'nonce': w3.eth.getTransactionCount(_from.address),
'data': _data,
}
signed = w3.eth.account.signTransaction(transaction, _from.privateKey)
tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction)
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
return tx_receipt
def signeSend(_transaction, _from):
"""
Signe sendRaw Wait & receipt transaction
_transaction: dict
_from: account objet
Retourne tx_receipt
"""
signed = w3.eth.account.signTransaction(_transaction, _from.privateKey)
tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction)
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
return tx_receipt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment