Ejemplo n.º 1
0
def test_deploy(w3, account, path, name):
    print('deploy contract: ', end='')

    tx_hash, contract_interface = deploy_contract(w3, account, path, name)
    contract_address = wait_contract_address(w3, tx_hash)
    contract = get_contract(w3, contract_address, contract_interface['abi'])
    assert w3.isAddress(contract_address), 'failed to deploy contract'

    print('contract deployed at address: {}: SUCCESS'.format(contract_address))
    return contract
Ejemplo n.º 2
0
def create_ERC20Token_network(w3, account, contract, *args):
    contract_interface = compile_contract('../contracts/TokenNetwork.sol',
                                          'TokenNetwork')
    transactor = contract.functions["createERC20TokenNetwork"](args[0],
                                                               args[1],
                                                               args[2])
    tx_hash = transact_function(w3, account, transactor)
    result = wait_event(w3, contract, tx_hash, "TokenNetworkCreated")
    contract = get_contract(w3, result[0]['args']['token_network_address'],
                            contract_interface['abi'])
    return contract
Ejemplo n.º 3
0
    def transfer_from_multisig_wallet(self, ticker, quantity, destination,
                                      multisig):
        contract = util.get_contract(self.session, ticker)
        if destination == "onlinecash":
            address = yield self.get_current_address("multisigcash", ticker)
        elif destination == "offlinecash":
            address = contract.cold_wallet_address
        else:
            raise NotImplementedError

        result = yield self.send_to_address(ticker,
                                            address,
                                            quantity,
                                            multisig=multisig)
        txid = result['txid']
        fee = result['fee']

        # Record fees
        fee_uid = util.get_uid()
        note = "%s: %s" % (address, txid)

        # CREDIT the from account
        fee_d1 = self.accountant.transfer_position('multisigcash', ticker,
                                                   'credit', fee, note,
                                                   fee_uid)

        # DEBIT the customer account
        fee_d2 = self.accountant.transfer_position('customer', ticker, 'debit',
                                                   fee, note, fee_uid)
        yield defer.gatherResults([fee_d1, fee_d2], consumeErrors=True)

        if destination == "offlinecash":
            # Record the transfer
            uid = util.get_uid()
            # CREDIT the from account
            d1 = self.accountant.transfer_position('multisigcash', ticker,
                                                   'credit', quantity, note,
                                                   uid)
            # DEBIT the to account
            d2 = self.accountant.transfer_position('offlinecash', ticker,
                                                   'debit', quantity, note,
                                                   uid)
            yield defer.gatherResults([d1, d2])
        else:
            # If going to online cash the transfer will get recorded when the btc arrives
            pass

        returnValue(txid)
Ejemplo n.º 4
0
def deploy_token(w3, account):
    contract_interface = compile_contract('../contracts/Token.sol', 'Token')
    contract = w3.eth.contract(abi=contract_interface['abi'],
                               bytecode=contract_interface['bin'])
    transaction = contract.constructor().buildTransaction({
        'nonce':
        w3.eth.getTransactionCount(account.address),
        'from':
        account.address
    })
    signed_transaction = w3.eth.account.signTransaction(
        transaction, account.privateKey)
    tx_hash = w3.eth.sendRawTransaction(signed_transaction.rawTransaction)
    contract_address = wait_contract_address(w3, tx_hash)
    contract = get_contract(w3, contract_address, contract_interface['abi'])

    return contract
Ejemplo n.º 5
0
def deploy_Ballot_contract(w3, account, proposalNames):

    contract_interface = compile_contract(_PATH + '/smartContract/Ballot.sol',
                                          "Ballot")
    contract = w3.eth.contract(abi=contract_interface['abi'],
                               bytecode=contract_interface['bin'])
    transaction = contract.constructor(proposalNames).buildTransaction({
        'nonce':
        w3.eth.getTransactionCount(account.address),
        'from':
        account.address
    })
    signed_transaction = w3.eth.account.signTransaction(
        transaction, account.privateKey)
    tx_hash = w3.eth.sendRawTransaction(signed_transaction.rawTransaction)
    contract_address = wait_contract_address(w3, tx_hash)
    contract = get_contract(w3, contract_address, contract_interface['abi'])

    return contract
Ejemplo n.º 6
0
    def transfer_from_multisig_wallet(self, ticker, quantity, destination, multisig):
        contract = util.get_contract(self.session, ticker)
        if destination == "onlinecash":
            address = yield self.get_current_address("multisigcash", ticker)
        elif destination == "offlinecash":
            address = contract.cold_wallet_address
        else:
            raise NotImplementedError

        result = yield self.send_to_address(ticker, address, quantity, multisig=multisig)
        txid = result['txid']
        fee = result['fee']

        # Record fees
        fee_uid = util.get_uid()
        note = "%s: %s" % (address, txid)

        # CREDIT the from account
        fee_d1 = self.accountant.transfer_position('multisigcash', ticker, 'credit', fee, note, fee_uid)

        # DEBIT the customer account
        fee_d2 = self.accountant.transfer_position('customer', ticker, 'debit', fee, note, fee_uid)
        yield defer.gatherResults([fee_d1, fee_d2], consumeErrors=True)

        if destination == "offlinecash":
            # Record the transfer
            uid = util.get_uid()
            # CREDIT the from account
            d1=self.accountant.transfer_position('multisigcash', ticker, 'credit', quantity,
                                              note, uid)
            # DEBIT the to account
            d2=self.accountant.transfer_position('offlinecash', ticker, 'debit', quantity, note, uid)
            yield defer.gatherResults([d1, d2])
        else:
            # If going to online cash the transfer will get recorded when the btc arrives
            pass

        returnValue(txid)
Ejemplo n.º 7
0
    def send_to_address(self, ticker, address, amount, multisig={}):
        if self.testnet:
            network = "XTN"
        else:
            network = "BTC"

        if is_address_valid(address) != network:
            raise INVALID_ADDRESS

        contract = util.get_contract(self.session, ticker)
        if not multisig:
            withdrawal_amount = float(util.quantity_from_wire(contract, amount))
            try:
                result = yield self.bitcoinrpc[ticker].getbalance()
            except Exception as e:
                log.err("Unable to get wallet balance: %s" % str(e))
                raise e

            balance = result['result']
            if balance >= withdrawal_amount:
                try:
                    result = yield self.bitcoinrpc[ticker].sendtoaddress(address, withdrawal_amount)
                    txid = result['result']
                    tx = yield self.bitcoinrpc[ticker].gettransaction(txid)
                    # The fee shows up from gettransaction as a negative number,
                    # but we want a positive number
                    fee = abs(long(round(tx['result']['fee'] * contract.denominator)))

                except Exception as e:
                    log.err("Unable to send to address: %s" % str(e))
                    raise e
            else:
                raise INSUFFICIENT_FUNDS
        else:
            self.bitgo.token = multisig['token'].encode('utf-8')
            try:
                yield self.bitgo.unlock(multisig['otp'])
            except Exception as e:
                log.err("Unable to unlock multisig")
                raise OTP_INVALID

            wallet_id = contract.multisig_wallet_address
            try:
                wallet = yield self.bitgo.wallets.get(wallet_id)
            except Exception as e:
                log.err("Unable to get wallet details")
                log.err(e)
                raise e

            balance = wallet.balance
            if balance < amount:
                raise INSUFFICIENT_FUNDS

            if not os.path.exists(self.bitgo_private_key_file):
                raise NO_KEY_FILE
            else:
                with open(self.bitgo_private_key_file, "rb") as f:
                    key_data = json.load(f)
                    passphrase = key_data['passphrase']

            try:
                result = yield wallet.sendCoins(address=address, amount=amount,
                        passphrase=passphrase)
                txid = result['tx']
                fee = result['fee']
            except Exception as e:
                log.err("Unable to sendCoins")
                log.err(e)
                raise e

        returnValue({'txid': txid,
                     'fee': fee})
Ejemplo n.º 8
0
    def send_to_address(self, ticker, address, amount, multisig={}):
        if self.testnet:
            network = "XTN"
        else:
            network = "BTC"

        if is_address_valid(address) != network:
            raise INVALID_ADDRESS

        contract = util.get_contract(self.session, ticker)
        if not multisig:
            withdrawal_amount = float(util.quantity_from_wire(
                contract, amount))
            try:
                result = yield self.bitcoinrpc[ticker].getbalance()
            except Exception as e:
                log.err("Unable to get wallet balance: %s" % str(e))
                raise e

            balance = result['result']
            if balance >= withdrawal_amount:
                try:
                    result = yield self.bitcoinrpc[ticker].sendtoaddress(
                        address, withdrawal_amount)
                    txid = result['result']
                    tx = yield self.bitcoinrpc[ticker].gettransaction(txid)
                    # The fee shows up from gettransaction as a negative number,
                    # but we want a positive number
                    fee = abs(
                        long(round(tx['result']['fee'] *
                                   contract.denominator)))

                except Exception as e:
                    log.err("Unable to send to address: %s" % str(e))
                    raise e
            else:
                raise INSUFFICIENT_FUNDS
        else:
            self.bitgo.token = multisig['token'].encode('utf-8')
            try:
                yield self.bitgo.unlock(multisig['otp'])
            except Exception as e:
                log.err("Unable to unlock multisig")
                raise OTP_INVALID

            wallet_id = contract.multisig_wallet_address
            try:
                wallet = yield self.bitgo.wallets.get(wallet_id)
            except Exception as e:
                log.err("Unable to get wallet details")
                log.err(e)
                raise e

            balance = wallet.balance
            if balance < amount:
                raise INSUFFICIENT_FUNDS

            if not os.path.exists(self.bitgo_private_key_file):
                raise NO_KEY_FILE
            else:
                with open(self.bitgo_private_key_file, "rb") as f:
                    key_data = json.load(f)
                    passphrase = key_data['passphrase']

            try:
                result = yield wallet.sendCoins(address=address,
                                                amount=amount,
                                                passphrase=passphrase)
                txid = result['tx']
                fee = result['fee']
            except Exception as e:
                log.err("Unable to sendCoins")
                log.err(e)
                raise e

        returnValue({'txid': txid, 'fee': fee})
Ejemplo n.º 9
0
    '0x2C749426ff936a1B522fFdc8dcBf9eb8d78b3D00',
    '0x0697875dc0ae871809f049211d85b939b7B75A75',
    '0xdB66F629495c5B1d17d28A35ccEd5ECB6F494BD3'
]
contract_address = "0x9066fb184a051382a4773B15416C39AD41E35E27"

for i in range(len(password)):
    privKey = extract_key_from_keyfile(
        _PATH + '/keyFile/' + password[i] + '.json', password[i].encode())

    account_list.append(account(privKey, address[i]))

w3.geth.miner.setEtherbase(account_list[0].address)
w3.geth.miner.start(1)

contract_interface = compile_contract('../smartContract/Coin.sol', "Coin")
contract = get_contract(w3, contract_address, contract_interface['abi'])

mint(w3, account_list[0], contract, account_list[1].address, 100)
_from, _to, _amount = send(w3, account_list[1], contract,
                           account_list[2].address, 10)
print("{} -> {} amount : {}".format(_from, _to, _amount))

balance = get_balance(account_list[1], contract)
print("{} balance : {}".format(account_list[1].address, balance))

balance = get_balance(account_list[2], contract)
print("{} balance : {}".format(account_list[1].address, balance))

w3.geth.miner.stop()