def quote(self, from_token, to_token, quantity): if not self.config_check(): return one_inch_join = w3.eth.contract(address=one_inch_split_contract, abi=one_inch_split_abi) contract_response = one_inch_join.functions.getExpectedReturn( w3.toChecksumAddress(self.get_token_info(from_token)["address"]), w3.toChecksumAddress(self.get_token_info(to_token)["address"]), quantity, 100, 0).call( {'from': self.get_public_key()}) print("Swap Quote: {0}".format(contract_response)) return contract_response
def swap(self, from_token, to_token, quantity): if not self.config_check(): return account = w3.eth.account.privateKeyToAccount(privateKey) quote = self.quote(from_token, to_token, quantity) min_return = quote[0] distribution = quote[1] disable_flags = 0 one_inch_join = w3.eth.contract(address=one_inch_split_contract, abi=one_inch_split_abi) nonce = w3.eth.getTransactionCount(self.get_public_key()) print("From Token Info: {}".format(self.get_token_info(from_token))) print("To Token Info: {}".format(self.get_token_info(to_token))) if from_token.lower() == "eth": value = quantity else: value = 0 data = one_inch_join.encodeABI(fn_name="swap", args=[ w3.toChecksumAddress(self.get_token_info(from_token)["address"]), w3.toChecksumAddress(self.get_token_info(to_token)["address"]), quantity, min_return, distribution, disable_flags]) tx = { 'nonce': nonce, 'to': one_inch_split_contract, 'value': value, 'gasPrice': w3.toWei(40, 'gwei'), 'from': self.get_public_key(), 'data': data } try: gas = w3.eth.estimateGas(tx) print("Gas Supplied: {}".format(gas)) tx["gas"] = gas except Exception as e: print(e) return print('transaction data: {0}'.format(tx)) try: signed_tx = w3.eth.account.signTransaction(tx, account.privateKey) except Exception as e: print(e) return False try: tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction) print("TXID: {0}".format(w3.toHex(tx_hash))) except Exception as e: print(e) return False
def portfolio(address): try: address = web3.toChecksumAddress(address) except ValueError: raise InvalidAddressException(address) # TODO: check if the GraphQL queries can be merged into one eth_price = get_eth_price() positions = [] positions += get_liquidity_positions(address) positions += get_staking_positions(address) pair_addresses = [pair["pair"]["id"] for pair in positions] mints_burns = get_lp_transactions(address, pair_addresses) transaction_dict = clean_transactions(mints_burns) balance_usd = 0 pairs = [] for position in positions: balance = Decimal(position["liquidityTokenBalance"]) pair = position["pair"] pair_info = extract_pair_info(pair, balance, eth_price) contract_address = pair_info["contract_address"] # even though the pair exists, we may not find transactions history pair_info["transactions"] = transaction_dict.get(contract_address, []) balance_usd += pair_info["balance_usd"] pairs.append(pair_info) data = { "address": address, "pairs": pairs, "balance_usd": balance_usd, } return data
def get_oxt_balance(address=get_secret( key=os.environ['PAC_FUNDER_PUBKEY_SECRET'])) -> float: token_addr = w3.toChecksumAddress(os.environ['TOKEN']) token_contract = w3.eth.contract( abi=token_abi, address=token_addr, ) token_name = get_token_name(token_addr) token_symbol = get_token_symbol(token_addr) token_decimals = get_token_decimals(token_addr) DECIMALS = 10**token_decimals raw_balance = token_contract.functions.balanceOf(address).call() balance = raw_balance / DECIMALS logging.info( f"Balance of {address}: {balance} {token_name} ({token_symbol})") if is_true(os.environ.get('ENABLE_MONITORING', '')): lambda_metric(f"orchid.pac.balance.{token_symbol.lower()}", balance, tags=[ f'account:{address}', f'token_name:{token_name}', f'token_symbol:{token_symbol}', f'token_decimals:{token_decimals}', ]) return balance
def getAccountLiquidity(addy): caddress = w3.toChecksumAddress(addy) result = contract.functions.getAccountLiquidity(caddress).call() if result[0] != 0: return "There is an error Whoops" elif result[1] != 0: return colored("SAFU", 'green') elif result[2] != 0: return colored("NOT SAFU", 'red', attrs=['bold'])
def get_token_decimals(address: str): token_addr = w3.toChecksumAddress(address) token_contract = w3.eth.contract( abi=token_abi, address=token_addr, ) token_decimals = token_contract.functions.decimals().call() logging.debug(f'Token Decimals: {token_decimals}') return token_decimals
def get_token_symbol(address: str): token_addr = w3.toChecksumAddress(address) token_contract = w3.eth.contract( abi=token_abi, address=token_addr, ) token_symbol = token_contract.functions.symbol().call() logging.debug(f'Token Symbol: {token_symbol}') return token_symbol
def get_token_name(address: str): token_addr = w3.toChecksumAddress(address) token_contract = w3.eth.contract( abi=token_abi, address=token_addr, ) token_name = token_contract.functions.name().call() logging.debug(f'Token Name: {token_name}') return token_name
def look(funder: str, signer: str): lottery_addr = w3.toChecksumAddress(os.environ['LOTTERY']) edited_lottery_abi = lottery_abi.copy() for function in edited_lottery_abi: if function.get('name') == 'look': for output in function['outputs']: if output['type'] == 'bytes': output['type'] = 'uint256' break break lottery_contract = w3.eth.contract( abi=edited_lottery_abi, address=lottery_addr, ) amount, escrow, _, _, _ = lottery_contract.functions.look(w3.toChecksumAddress(funder), w3.toChecksumAddress(signer)).call() account_total = amount + escrow logging.debug(f'Account Total (funder: {funder}, signer: {signer}): {amount} (amount) + {escrow} (escrow) = {account_total} (total)') return account_total
def get_allowance(self, token): if not self.config_check(): print("Call load first to populate tokens") return token_info = self.get_token_info(token)["address"] token_address = w3.toChecksumAddress(token_info) mcd_contract = w3.eth.contract(address=token_address, abi=mcd_abi) allowance = mcd_contract.functions.allowance(self.get_public_key(), one_inch_split_contract).call() print("Current allowance: {0}".format(allowance)) return allowance
def print_current_token_balance(self, token): if not self.config_check(): return try: token_contract = w3.eth.contract(address=w3.toChecksumAddress(self.get_token_info(token)["address"]), abi=token_abi) token_balance = token_contract.functions.balanceOf(self.get_public_key()).call() token_balance_normalized = w3.fromWei(int(token_balance), 'ether') print("Current Balance: {} {}".format(token_balance_normalized, token)) except: print("Token not supported")
def refer(): w3 = web3.Web3( web3.HTTPProvider( "https://ropsten.infura.io/v3/55a7676bd3db4746a9a536918d9d448e")) contract_address = w3.toChecksumAddress( '0xa58aBB3D2e42191a3b8c927eD96D70A343e7B8c5'.lower()) advertiser_address = w3.toChecksumAddress( '0x5cBA0F3a23023B711C0d94527247a92eea9c982d'.lower()) adtract = w3.eth.contract(address=contract_address, abi=contract_abi.abi) refer_key = request.get_json()['account'] refer_address = w3.toChecksumAddress(refer_key.lower()) refer_txn = adtract.functions.refer(refer_address).buildTransaction() refer_txn['nonce'] = w3.eth.getTransactionCount(advertiser_address) print(refer_txn['nonce']) refer_txn['gas'] = 70000 signed_txn = w3.eth.account.signTransaction( refer_txn, private_key=os.environ['ETH_PRIV']) w3.eth.sendRawTransaction(signed_txn.rawTransaction) return json.dumps({'success': True}), 200, { 'ContentType': 'application/json' }
def generate_wallet() -> Dict[str, str]: keccak = sha3.keccak_256() priv = SigningKey.generate(curve=SECP256k1) pub = priv.get_verifying_key().to_string() keccak.update(pub) address = keccak.hexdigest()[24:] wallet = { 'private': priv.to_string().hex(), 'public': pub.hex(), 'address': w3.toChecksumAddress(address), } return wallet
def generate_transaction(self, to, ether, gas_price, gas_limit, nonce=None, chainId=1, denom='wei'): nonce = self.get_nonce() if not nonce else nonce value = w3.toWei(ether, denom) gasPrice = w3.toWei(gas_price, 'gwei') data = { 'to': w3.toChecksumAddress(to), 'from': self.address, 'value': value, 'gas': gas_limit, 'gasPrice': gasPrice, 'nonce': nonce, 'chainId': chainId } return data
def approve_tokens(self, token, amount): if not self.config_check(): return token_address = w3.toChecksumAddress(self.get_token_info(token)["address"]) mcd_contract = w3.eth.contract(address=token_address, abi=mcd_abi) self.get_allowance(token) base_account = w3.eth.account.privateKeyToAccount(privateKey) nonce = w3.eth.getTransactionCount(base_account.address) data = mcd_contract.encodeABI(fn_name="approve", args=[one_inch_split_contract, amount]) tx = { 'nonce': nonce, 'to': token_address, 'value': 0, 'gasPrice': w3.toWei(40, 'gwei'), 'from': base_account.address, 'data': data } try: gas = w3.eth.estimateGas(tx) print("Gas Supplied: {}".format(gas)) tx["gas"] = gas except Exception as e: print(e) return try: signed_tx = w3.eth.account.signTransaction(tx, privateKey) except Exception as e: print(e) return try: tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction) print("TXID from 1 Inch: {0}".format(w3.toHex(tx_hash))) except Exception as e: print(e) return
if __name__ == "__main__": assert (w3.isConnected()) run = True # aws aws_client = boto3.client( 'dynamodb', aws_access_key_id=config["AWS_ACCESS_KEY_ID"], aws_secret_access_key=config["AWS_SECRET_ACCESS_KEY"], region_name='us-east-2') # contract kleros_json = open(file='contracts/Kleros.json') abi = json.loads(kleros_json.read())['abi'] kleros_contract = w3.eth.contract(address=w3.toChecksumAddress( config['KLEROS_CONTRACT_ADDRESS']), abi=abi) # disputes cache closed_disputes = {} existing_session_data = {} def session_exists(session): if existing_session_data.get(session): return True session_data = aws_client.get_item( TableName='disputes', Key={'session': { "N": str(session) }}) if (session_data.get("Item")): existing_session_data[session] = True
def get_public_key(self): if not self.config_check(): return account = w3.eth.account.privateKeyToAccount(privateKey) return w3.toChecksumAddress(account.address)
def create_account(self, entropy): self.account = Account.create(entropy) self.pk = self.account.privateKey self.address = w3.toChecksumAddress(self.account.address)
def load_account(self, fname, password=None): self.decrypt_account(fname=fname, password=password) self.account = Account.privateKeyToAccount(self.pk) self.address = w3.toChecksumAddress(self.account.address)
os.environ['WEB3_INFURA_PROJECT_ID'] = '90af2ec8351c43f9b82b17026d01a9a1' os.environ['WEB3_INFURA_API_SECRET'] = '4c1dd095f5e7411c9b71668b6770e0be' from web3.auto.infura import w3 with open('Chi.abi', 'r') as chi_abi_file: chi_abi = json.load(chi_abi_file) with open('Gst2.abi', 'r') as gst2_abi_file: gst2_abi = json.load(gst2_abi_file) with open('PrivateKey') as privateKeyFile: privateKey = privateKeyFile.read() one_inch_split_abi = json.load(open('SplitContract.abi', 'r')) mcd_abi = json.load(open('JoinContract.abi', 'r')) token_abi = json.load(open('Token.abi', 'r')) chi_contract_address = w3.toChecksumAddress('0x0000000000004946c0e9F43F4Dee607b0eF1fA1c') gst2_contract_address = w3.toChecksumAddress('0x0000000000b3F879cb30FE243b4Dfee438691c04') one_inch_split_contract = w3.toChecksumAddress('0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E') loop = asyncio.get_event_loop() class OneInch: def __init__(self): # json list of tokens self.tokens = any def list_tokens(self): if not self.config_check(): return print("Tokens".format(self.tokens))
def fund_PAC_( signer: str, total: float, escrow: float, funder_pubkey: str, funder_privkey: str, nonce: int, ) -> str: print(f"Funding PAC signer: {signer}, total: {total}, escrow: {escrow} ") lottery_addr = w3.toChecksumAddress(os.environ['LOTTERY']) token_addr = w3.toChecksumAddress(os.environ['TOKEN']) verifier_addr = w3.toChecksumAddress(os.environ['VERIFIER']) lottery_main = w3.eth.contract( abi=lottery_abi, address=lottery_addr, ) token_main = w3.eth.contract( abi=token_abi, address=token_addr, ) print(f"Funder nonce: {nonce}") print(f"Assembling approve transaction:") approve_txn = token_main.functions.approve( lottery_addr, total, ).buildTransaction( { 'chainId': 1, 'from': funder_pubkey, 'gas': 50000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce, } ) print(approve_txn) print(f"Funder signed transaction:") approve_txn_signed = w3.eth.account.sign_transaction( approve_txn, private_key=funder_privkey) print(approve_txn_signed) print(f"Submitting approve transaction:") approve_txn_hash = w3.eth.sendRawTransaction( approve_txn_signed.rawTransaction) print(f"Submitted approve transaction with hash: {approve_txn_hash.hex()}") nonce = nonce + 1 print(f"Funder nonce: {nonce}") print(f"Assembling bind transaction:") bind_txn = lottery_main.functions.bind(signer, verifier_addr, w3.toBytes(0) ).buildTransaction({'chainId': 1, 'from': funder_pubkey, 'gas': 200000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce,} ) print(bind_txn) print(f"Funder signed transaction:") bind_txn_signed = w3.eth.account.sign_transaction(bind_txn, private_key=funder_privkey) print(bind_txn_signed) print(f"Submitting bind transaction:") bind_txn_hash = w3.eth.sendRawTransaction(bind_txn_signed.rawTransaction) print(f"Submitted bind transaction with hash: {bind_txn_hash.hex()}") nonce = nonce + 1 print(f"Funder nonce: {nonce}") print(f"Assembling funding transaction:") funding_txn = lottery_main.functions.push( signer, total, escrow ).buildTransaction( { 'chainId': 1, 'from': funder_pubkey, 'gas': 200000, 'gasPrice': w3.toWei('8', 'gwei'), 'nonce': nonce, } ) print(funding_txn) print(f"Funder signed transaction:") funding_txn_signed = w3.eth.account.sign_transaction( funding_txn, private_key=funder_privkey) print(funding_txn_signed) print(f"Submitting funding transaction:") txn_hash: str = w3.eth.sendRawTransaction( funding_txn_signed.rawTransaction).hex() print(f"Submitted funding transaction with hash: {txn_hash}") return txn_hash