예제 #1
0
def sign_txn_array(messages, private_key):
    message_dict = {}
    for message in messages:
        signed_message =\
            binascii.hexlify(Account.signHash(message['txn']['sha256'], private_key=private_key)['signature']).decode()
        message_dict[message['id']] = '0x' + signed_message
    return message_dict
예제 #2
0
def sign_create_deposit(deposit_params, private_key):
    """
    Function to sign the deposit parameters required by the Switcheo API.
    Execution of this function is as follows::

        sign_create_deposit(deposit_params=signable_params, private_key=eth_private_key)

    The expected return result for this function is as follows::

        {
            'blockchain': 'eth',
            'asset_id': 'ETH',
            'amount': '10000000000000000',
            'timestamp': 1542089346249,
            'contract_hash': '0x607af5164d95bd293dbe2b994c7d8aef6bec03bf',
            'address': '0x32c46323b51c977814e05ef5e258ee4da0e4c3c3',
            'signature': 'd4b8491d6514bff28b9f2caa440f51a93f31d....'
        }

    :param deposit_params: Parameters needed to deposit to the Switcheo API and signed in this function.
    :type deposit_params: dict
    :param private_key: The Ethereum private key to sign the deposit parameters.
    :type private_key: str
    :return: Dictionary of signed message to send to the Switcheo API.
    """
    hash_message = defunct_hash_message(text=stringify_message(deposit_params))
    hex_message = binascii.hexlify(hash_message).decode()
    signed_message = binascii.hexlify(Account.signHash(hex_message, private_key=private_key)['signature']).decode()
    create_params = deposit_params.copy()
    create_params['address'] = to_normalized_address(Account.privateKeyToAccount(private_key=private_key).address)
    create_params['signature'] = signed_message
    return create_params
예제 #3
0
def registerhook(ctx_obj, url):
    contract = ctx_obj['contract_address']
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json'
    }
    msg = 'dummystring'
    message_hash = defunct_hash_message(text=msg)
    sig_msg = Account.signHash(message_hash, ctx_obj['private_key'])
    method_args = {
        "msg": msg,
        "sig": sig_msg.signature.hex(),
        "key": ctx_obj['api_key'],
        "type": "web",
        "contract": contract,
        "web": url
    }
    r = requests.post(url=f'{ctx_obj["internal_api_endpoint"]}/hooks/add',
                      json=method_args,
                      headers=headers)
    click.echo(r.text)
    if r.status_code == requests.codes.ok:
        r = r.json()
        if not r['success']:
            click.echo('Failed to register webhook with MaticVigil API...')
        else:
            hook_id = r["data"]["id"]
            click.echo(
                'Succeeded in registering webhook with MaticVigil API...')
            click.echo(f'MaticVigil Hook ID: {hook_id}')
    else:
        click.echo('Failed to register webhook with MaticVigil API...')
예제 #4
0
def deploy_acl_contract(entity_uuid, chain_id):
    msg = "Trying to deploy"
    message_hash = defunct_hash_message(text=msg)
    sig_msg = Account.signHash(message_hash, settings['privatekey'])
    with open('./contracts/ACLDispatcher.sol', 'r') as f:
        contract_code = f.read()
    constructor_inputs = []
    company_uuid_hash = '0x' + keccak(text=entity_uuid).hex()
    constructor_inputs.append(company_uuid_hash)
    constructor_inputs.append(chain_id)
    deploy_params = {
        'msg': msg,
        'sig': sig_msg.signature.hex(),
        'name': 'ACLDispatchHub',
        'inputs': constructor_inputs,
        'code': contract_code
    }
    print('Deploying with constructor arguments: ')
    print(constructor_inputs)
    # API call to deploy
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json'
    }
    r = requests.post(settings['REST_API_ENDPOINT'] + '/deploy',
                      json=deploy_params,
                      headers=headers)
    rj = r.json()
    print('Deployed contract results')
    print(rj)
    if r.status_code == requests.codes.ok:
        return rj['data']['contract'], rj['data']['txhash']
    else:
        return None
예제 #5
0
def main():
    contract = "0xcontractAddress"
    api_key = '1122-122-23443-1133'
    headers = {'accept': 'application/json', 'Content-Type': 'application/json',
               'X-API-KEY': api_key}
    private_key = "0xprivatekeyhexstring"
    api_endpoint = "https://beta.ethvigil.com/api"
    msg = 'dummystring'
    message_hash = defunct_hash_message(text=msg)
    sig_msg = Account.signHash(message_hash, private_key)
    method_args = {
        "msg": msg,
        "sig": sig_msg.signature.hex(),
        "key": api_key,
        "type": "web",
        "contract": contract,
        "web": "https://randomstring.ngrok.io"
    }
    r = requests.post(url=f'{api_endpoint}/hooks/add', json=method_args, headers=headers)
    print(r.text)
    if r.status_code == requests.codes.ok:
        r = r.json()
        if not r['success']:
            print('Failed to register webhook with Ethvigil API...')
        else:
            hook_id = r["data"]["id"]
            print('Succeeded in registering webhook with Ethvigil API...')
            print(f'EthVigil Hook ID: {hook_id}')
    else:
        print('Failed to register webhook with Ethvigil API...')
예제 #6
0
    def signHash(self, message_hash):
        '''
        Sign the hash provided.

        .. WARNING:: *Never* sign a hash that you didn't generate,
            it can be an arbitrary transaction. For example, it might
            send all of your account's ether to an attacker.

        If you would like compatibility with
        :meth:`w3.eth.sign() <web3.eth.Eth.sign>`
        you can use :meth:`~eth_account.messages.defunct_hash_message`.

        Several other message standards are proposed, but none have a clear
        consensus. You'll need to manually comply with any of those message standards manually.

        :param message_hash: the 32-byte message hash to be signed
        :type message_hash: hex str, bytes or int
        :param private_key: the key to sign the message with
        :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey`
        :returns: Various details about the signature - most
          importantly the fields: v, r, and s
        :rtype: ~eth_account.datastructures.AttributeDict
        '''

        rawtuple = bip32_deserialize(self.__key)

        if rawtuple[0] in PRIVATE:
            # slice the last byte, since it is the WIF-Compressed information
            return Account.signHash(message_hash, rawtuple[5][:-1])

        if bip32_deserialize(self.__key)[0] not in PRIVATE:
            raise RuntimeError("Cannot sign, only the public key is available")
예제 #7
0
 def activate_integration(self, hook_id):
     msg = 'dummystring'
     message_hash = defunct_hash_message(text=msg)
     sig_msg = Account.signHash(message_hash,
                                self._ev_settings['PRIVATEKEY'])
     method_args = {
         "msg": msg,
         "sig": sig_msg.signature.hex(),
         "key": self._api_write_key,
         "type": "web",
         "contract": self._contract_address,
         "id": hook_id
     }
     integration_response = make_http_call(
         request_type='post',
         url=self._ev_settings['INTERNAL_API_ENDPOINT'] + '/hooks/activate',
         params=method_args,
         headers={
             'accept': 'application/json',
             'Content-Type': 'application/json'
         })
     if not integration_response['success']:
         return False
     else:
         return True
예제 #8
0
def enabletxmonitor(ctx_obj, contractaddress, hookid):
    # enable tx monitoring on contract
    msg = 'dummystring'
    message_hash = defunct_hash_message(text=msg)
    sig_msg = Account.signHash(message_hash, ctx_obj['settings']['PRIVATEKEY'])
    method_args = {
        "msg": msg,
        "sig": sig_msg.signature.hex(),
        "key": ctx_obj['settings']['ETHVIGIL_API_KEY'],
        "type": "web",
        "contract": contractaddress,
        "id": hookid,
        "action": "set"
    }
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json',
        'X-API-KEY': ctx_obj["settings"]["ETHVIGIL_API_KEY"]
    }
    r = requests.post(
        url=
        f'{ctx_obj["settings"]["INTERNAL_API_ENDPOINT"]}/hooks/transactions',
        json=method_args,
        headers=headers)
    click.echo(r.text)
    if r.status_code == requests.codes.ok:
        r = r.json()
        if r['success']:
            click.echo('Succeded in adding hook to monitor all contract txs')
        else:
            click.echo('Failed to add hook to monitor on all contract txs...')
    else:
        click.echo('Failed to add hook to monitor on all contract txs...')
예제 #9
0
def sign_create_cancellation(cancellation_params, private_key):
    """
    Function to sign the parameters required to create a cancellation request from the Switcheo Exchange.
    Execution of this function is as follows::

        sign_create_cancellation(cancellation_params=signable_params, private_key=eth_private_key)

    The expected return result for this function is as follows::

        {
            'order_id': '3125550a-04f9-4475-808b-42b5f89d6693',
            'timestamp': 1542088842108,
            'address': '0x32c46323b51c977814e05ef5e258ee4da0e4c3c3',
            'signature': 'dac70ca711bcfbeefbdead2158ef8b15fab1a1....'
        }

    :param cancellation_params: Dictionary with Order ID and timestamp to sign for creating the cancellation.
    :type cancellation_params: dict
    :param private_key: The Ethereum private key to sign the deposit parameters.
    :type private_key: str
    :return: Dictionary of signed message to send to the Switcheo API.
    """
    hash_message = defunct_hash_message(text=stringify_message(cancellation_params))
    hex_message = binascii.hexlify(hash_message).decode()
    signed_message = binascii.hexlify(Account.signHash(hex_message, private_key=private_key)['signature']).decode()
    create_params = cancellation_params.copy()
    create_params['address'] = to_normalized_address(Account.privateKeyToAccount(private_key=private_key).address)
    create_params['signature'] = signed_message
    return create_params
예제 #10
0
def sign_create_withdrawal(withdrawal_params, private_key):
    """
    Function to create a withdrawal from the Switcheo Smart Contract.
    Execution of this function is as follows::

        sign_create_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key)

    The expected return result for this function is as follows::

        {
            'blockchain': 'eth',
            'asset_id': 'ETH',
            'amount': '10000000000000000',
            'timestamp': 1542090476102,
            'contract_hash': '0x607af5164d95bd293dbe2b994c7d8aef6bec03bf',
            'address': '0x32c46323b51c977814e05ef5e258ee4da0e4c3c3',
            'signature': '375ddce62e5b3676d5e94ebb9f9a8af5963b....'
        }

    :param withdrawal_params: The parameters to be signed and create a withdraw from Switcheo.
    :type withdrawal_params: dict
    :param private_key: The Ethereum private key to sign the deposit parameters.
    :type private_key: str
    :return: Dictionary of the signed transaction to initiate the withdrawal of ETH via the Switcheo API.
    """
    hash_message = defunct_hash_message(text=stringify_message(withdrawal_params))
    hex_message = binascii.hexlify(hash_message).decode()
    signed_message = binascii.hexlify(Account.signHash(hex_message, private_key=private_key)['signature']).decode()
    create_params = withdrawal_params.copy()
    create_params['address'] = to_normalized_address(Account.privateKeyToAccount(private_key=private_key).address)
    create_params['signature'] = signed_message
    return create_params
예제 #11
0
def registerhook(ctx_obj, contract, url):
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json',
        'X-API-KEY': ctx_obj['settings']['ETHVIGIL_API_KEY']
    }
    msg = 'dummystring'
    message_hash = defunct_hash_message(text=msg)
    sig_msg = Account.signHash(message_hash, ctx_obj['settings']['PRIVATEKEY'])
    method_args = {
        "msg": msg,
        "sig": sig_msg.signature.hex(),
        "key": ctx_obj['settings']['ETHVIGIL_API_KEY'],
        "type": "web",
        "contract": contract,
        "web": url
    }
    r = requests.post(
        url=f'{ctx_obj["settings"]["INTERNAL_API_ENDPOINT"]}/hooks/add',
        json=method_args,
        headers=headers)
    click.echo(r.text)
    if r.status_code == requests.codes.ok:
        r = r.json()
        if not r['success']:
            click.echo('Failed to register webhook with Ethvigil API...')
        else:
            hook_id = r["data"]["id"]
            click.echo('Succeeded in registering webhook with Ethvigil API...')
            click.echo(f'EthVigil Hook ID: {hook_id}')
    else:
        click.echo('Failed to register webhook with Ethvigil API...')
예제 #12
0
 def add_contract_monitoring_integration(self,
                                         callback_url,
                                         integration_channel='web'):
     hook_id = self._register_integration(callback_url)
     if not hook_id:
         return None
     if not integration_channel == 'web':
         err_msg = 'Only integrations of type \'web\' are supported by SDK currently'
         ev_core_logger.error(err_msg)
         raise EVBaseException(err_msg)
     msg = 'dummystring'
     message_hash = defunct_hash_message(text=msg)
     sig_msg = Account.signHash(message_hash,
                                self._ev_settings['PRIVATEKEY'])
     method_args = {
         "msg": msg,
         "sig": sig_msg.signature.hex(),
         "key": self._api_write_key,
         "type": "web",
         "contract": self._contract_address,
         "id": hook_id,
         "action": "set"
     }
     integration_response = make_http_call(
         request_type='post',
         url=self._ev_settings['INTERNAL_API_ENDPOINT'] +
         '/hooks/transactions',
         params=method_args,
         headers={
             'accept': 'application/json',
             'Content-Type': 'application/json'
         })
     return hook_id if integration_response.get('success', False) else None
예제 #13
0
 def _register_integration(self, url):
     headers = {
         'accept': 'application/json',
         'Content-Type': 'application/json',
         'X-API-KEY': self._api_write_key
     }
     msg = 'dummystring'
     message_hash = defunct_hash_message(text=msg)
     sig_msg = Account.signHash(message_hash, self._ev_private_key)
     method_args = {
         "msg": msg,
         "sig": sig_msg.signature.hex(),
         "key": self._ev_private_key,
         "type": "web",
         "contract": self._contract_address,
         "web": url
     }
     reg_webhook_args = dict(
         url=self._ev_settings['INTERNAL_API_ENDPOINT'] + '/hooks/add',
         params=method_args,
         headers=headers)
     ev_core_logger.debug('Registering webhook')
     ev_core_logger.debug(reg_webhook_args)
     r = make_http_call(request_type='post', **reg_webhook_args)
     ev_core_logger.debug('Registration response')
     ev_core_logger.debug(r)
     if not r['success']:
         return None
     else:
         hook_id = r["data"]["id"]
         return hook_id
예제 #14
0
 def integrations(self):
     if not self._initialized:
         return None
     url = self._ev_settings['INTERNAL_API_ENDPOINT'] + '/hooks/list'
     msg = 'dummystring'
     message_hash = defunct_hash_message(text=msg)
     sig_msg = Account.signHash(message_hash,
                                self._ev_settings['PRIVATEKEY'])
     method_args = {
         "msg": msg,
         "sig": sig_msg.signature.hex(),
         "key": self._api_write_key,
         "type": "web",
         "contract": self._contract_address
     }
     list_response = make_http_call(request_type='post',
                                    url=url,
                                    params=method_args,
                                    headers={
                                        'accept': 'application/json',
                                        'Content-Type': 'application/json'
                                    })
     if list_response['success']:
         return list_response['data']
     else:
         return None
예제 #15
0
def deploy(ctx_obj):
    """
    Deploys a new instance of ERC20Mintable.sol on EthVigil.
    When prompted, enter a JSON-compatible list of constructor inputs to be passed on to the ERC20Mintable contract.

    For example, ["My Token", "SYMBOL", 18] corresponding to ERC20 standards: token name, token symbol, token decimals
    NOTE: Enter double quoted strings. Single quoted strings are not supported as JSON serialized.

    Check deploy.py for a code example
    """
    msg = "Trying to deploy"
    message_hash = defunct_hash_message(text=msg)
    private_key = ctx_obj['private_key']
    contract_addr = ctx_obj['contract_address']
    if contract_addr != '':
        if click.confirm('You already have a contract address specified in the settings file. '
                         'Do you want to proceed with deploying another contract? '):
            pass
        else:
            return
    click.echo('Enter the list of constructor inputs: ')
    constructor_inputs = input()
    if constructor_inputs.strip() == "":
        if click.confirm('Do you want to use the defaults ["My Token", "SYMBOL", 18]'):
            constructor_inputs = ["My Token", "SYMBOL", 18]
        else:
            return
    else:
        try:
            constructor_inputs = json.loads(constructor_inputs)
        except json.JSONDecodeError:
            click.echo("Enter a valid JSON list for constructor inputs")
            if click.confirm('Do you want to use the defaults ["My Token", "SYMBOL", 18]'):
                constructor_inputs = ["My Token", "SYMBOL", 18]
            else:
                return
    sig_msg = Account.signHash(message_hash, private_key)
    with open('./ERC20Mintable.sol', 'r') as f:
        contract_code = f.read()
    deploy_params = {
        'msg': msg,
        'sig': sig_msg.signature.hex(),
        'name': 'ERC20Mintable',
        'inputs': constructor_inputs,
        'code': contract_code
    }
    click.echo('Deploying with constructor arguments: ')
    click.echo(constructor_inputs)
    # API call to deploy
    headers = {'accept': 'application/json', 'Content-Type': 'application/json'}
    r = requests.post(ctx_obj['internal_api_endpoint']+'/deploy', json=deploy_params, headers=headers)
    rj = r.json()
    click.echo('Deployed contract results')
    click.echo(rj)
    if rj['success']:
        click.echo('Copy the contract address into settings.json')
def sign_confirmation(unique_id, contractaddr, private_key):
    print('Signing data with settlementid, contractaddr...')
    print(unique_id)
    print(contractaddr)
    hash = solidityKeccak(abi_types=['uint256', 'address'], values=[unique_id, contractaddr], validity_check=True)
    msg_hash = defunct_hash_message(hexstr=hash.hex())
    signed_msg_hash = Account.signHash(msg_hash, private_key)
    click.echo(f'Signed message hash: {signed_msg_hash.signature.hex()}')
    # return bytes.fromhex(s=signed_msg_hash.signature.hex())
    return signed_msg_hash.signature.hex()
def ev_login(api_endpoint, private_key):
    msg = "Trying to login"
    message_hash = defunct_hash_message(text=msg)
    signed_msg = Account.signHash(message_hash, private_key)
    # --MaticVigil API CALL---
    headers = {'accept': 'application/json', 'Content-Type': 'application/json'}
    r = requests.post(api_endpoint + '/login', json={'msg': msg, 'sig': signed_msg.signature.hex()}, headers=headers)
    if r.status_code == requests.codes.ok:
        r = r.json()
        return r['data']['key']
    else:
        return None
예제 #18
0
def extract_abi(ev_settings, parsed_sources):
    msg = "Trying to signup"
    message_hash = defunct_hash_message(text=msg)
    signed_msg = Account.signHash(message_hash, ev_settings['PRIVATEKEY'])
    compile_params = {'msg': msg, 'sig': signed_msg.signature.hex()}
    compile_params.update(parsed_sources)
    _resp = make_http_call(
        request_type='post',
        url=ev_settings['INTERNAL_API_ENDPOINT'] + '/compile',
        params=compile_params
    )
    return _resp['data']['contract']['abi']
예제 #19
0
def deploy(ctx_obj, contract_name, inputs, verbose, contract):
    """
    Deploys a smart contract from the solidity source code specified

    CONTRACT: path to the solidity file

    Usage example: ev-cli deploy ../token.sol --contractName=FixedSupplyToken --constructorInputs='JSON representation of the constructor arguments'
    """
    contract_src = ""
    if verbose:
        click.echo('Got constructor inputs: ')
        click.echo(inputs)
    if inputs:
        c_inputs = json.loads(inputs)
    else:
        c_inputs = list()  # an empty list
    while True:
        chunk = contract.read(1024)
        if not chunk:
            break
        contract_src += chunk

    msg = "Trying to deploy"
    message_hash = defunct_hash_message(text=msg)
    # deploy from alpha account
    signed_msg = Account.signHash(message_hash,
                                  ctx_obj['settings']['PRIVATEKEY'])
    deploy_json = {
        'msg': msg,
        'sig': signed_msg.signature.hex(),
        'name': contract_name,
        'inputs': c_inputs,
        'code': contract_src
    }
    # --ETHVIGIL API CALL---
    r = requests.post(ctx_obj['settings']['INTERNAL_API_ENDPOINT'] + '/deploy',
                      json=deploy_json)
    if verbose:
        click.echo('EthVigil deploy response: ')
        click.echo(r.text)
    if r.status_code == requests.codes.ok:
        click.echo(f'Contract {contract_name} deployed successfully')
        r = r.json()
        click.echo(f'Contract Address: {r["data"]["contract"]}')
        click.echo(f'Deploying tx: {r["data"]["hash"]}')
    else:
        click.echo('Contract deployment failed')
예제 #20
0
 def signup(self, invite_code):
     msg = "Trying to signup"
     message_hash = defunct_hash_message(text=msg)
     signed_msg = Account.signHash(message_hash,
                                   self._settings['PRIVATEKEY'])
     request_json = {
         'msg': msg,
         'sig': signed_msg.signature.hex(),
         'code': invite_code
     }
     # --MATICVIGIL API CALL to /signup---
     ev_core_logger.debug('Attempting to signup with MaticVigil')
     signup_url = self._settings['INTERNAL_API_ENDPOINT'] + '/signup'
     r = make_http_call(request_type='post',
                        url=signup_url,
                        params=request_json)
     return r
def main():
    contract = "0xcontractAddress"
    api_key = '1122-122-23443-1133'
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json',
        'X-API-KEY': api_key
    }
    private_key = "0xprivatekeyhexstring"
    api_endpoint = "https://beta.ethvigil.com/api"
    events_to_be_registered_on = ['Approval', 'Transfer']
    hook_id = 12  # hook ID as registered on EthVigil
    msg = 'dummystring'
    message_hash = defunct_hash_message(text=msg)
    sig_msg = Account.signHash(message_hash, private_key)
    method_args = {
        "msg": msg,
        "sig": sig_msg.signature.hex(),
        "key": api_key,
        "type": "web",
        "contract": contract,
        "id": hook_id,
        "events": events_to_be_registered_on
    }
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json'
    }
    print(
        f'Registering | hook ID: {hook_id} | events: {events_to_be_registered_on} | contract: {contract}'
    )
    r = requests.post(url=f'{api_endpoint}/hooks/updateEvents',
                      json=method_args,
                      headers=headers)
    print(r.text)
    if r.status_code == requests.codes.ok:
        r = r.json()
        if r['success']:
            print('Succeeded in adding hook')
        else:
            print('Failed to add hook')
            return
    else:
        print('Failed to add hook')
        return
예제 #22
0
def addhooktoevent(ctx_obj, hookid, events):
    msg = 'dummystring'
    message_hash = defunct_hash_message(text=msg)
    contract_address = ctx_obj['contract_address']
    private_key = ctx_obj['private_key']
    api_key = ctx_obj['api_key']
    api_endpoint = ctx_obj['internal_api_endpoint']
    sig_msg = Account.signHash(message_hash, private_key)
    events_to_be_registered_on = list()
    if not events:
        events_to_be_registered_on.append('*')
    else:
        for each in events.split(','):
            events_to_be_registered_on.append(each)
    method_args = {
        "msg": msg,
        "sig": sig_msg.signature.hex(),
        "key": api_key,
        "type": "web",
        "contract": contract_address,
        "id": hookid,
        "events": events_to_be_registered_on
    }
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json'
    }
    click.echo(
        f'Registering | hook ID: {hookid} | events: {events_to_be_registered_on} | contract: {contract_address}'
    )
    r = requests.post(url=f'{api_endpoint}/hooks/updateEvents',
                      json=method_args,
                      headers=headers)
    click.echo(r.text)
    if r.status_code == requests.codes.ok:
        r = r.json()
        if r['success']:
            click.echo('Succeeded in adding hook')
        else:
            click.echo('Failed to add hook')
            return
    else:
        click.echo('Failed to add hook')
        return
예제 #23
0
def addhooktoevent(ctx_obj, contractaddress, hookid, events):
    msg = 'dummystring'
    message_hash = defunct_hash_message(text=msg)
    sig_msg = Account.signHash(message_hash, ctx_obj['settings']['PRIVATEKEY'])
    events_to_be_registered_on = list()
    if not events:
        events_to_be_registered_on.append('*')
    else:
        for each in events.split(','):
            events_to_be_registered_on.append(each)
    method_args = {
        "msg": msg,
        "sig": sig_msg.signature.hex(),
        "key": ctx_obj['settings']['ETHVIGIL_API_KEY'],
        "type": "web",
        "contract": contractaddress,
        "id": hookid,
        "events": events_to_be_registered_on
    }
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json',
        'X-API-KEY': ctx_obj['settings']['ETHVIGIL_API_KEY']
    }
    click.echo(
        f'Registering | hook ID: {hookid} | events: {events_to_be_registered_on} | contract: {contractaddress}'
    )
    r = requests.post(
        url=
        f'{ctx_obj["settings"]["INTERNAL_API_ENDPOINT"]}/hooks/updateEvents',
        json=method_args,
        headers=headers)
    click.echo(r.text)
    if r.status_code == requests.codes.ok:
        r = r.json()
        if r['success']:
            click.echo('Succeeded in adding hook')
        else:
            click.echo('Failed to add hook')
            return
    else:
        click.echo('Failed to add hook')
        return
예제 #24
0
def ev_signup(internal_api_endpoint, invite_code, private_key):
    msg = "Trying to signup"
    message_hash = defunct_hash_message(text=msg)
    signed_msg = Account.signHash(message_hash, private_key)
    # --ETHVIGIL API CALL to /signup---
    try:
        r = requests.post(internal_api_endpoint + '/signup',
                          json={
                              'msg': msg,
                              'sig': signed_msg.signature.hex(),
                              'code': invite_code
                          })
    except:
        return False
    else:
        print(r.url)
        print(r.text)
        if r.status_code == requests.codes.ok:
            return r.json()
        else:
            return False
예제 #25
0
def sign_create_order(order_params, private_key):
    """
    Function to sign the create order parameters and send to the Switcheo API.
    Execution of this function is as follows::

        sign_create_order(order_params=signable_params, private_key=eth_private_key)

    The expected return result for this function is as follows::

        {
            'blockchain': 'eth',
            'pair': 'JRC_ETH',
            'side': 'buy',
            'price': '0.00000003',
            'want_amount': '3350000000000000000000000',
            'use_native_tokens': False,
            'order_type': 'limit',
            'timestamp': 1542089785915,
            'contract_hash': '0x607af5164d95bd293dbe2b994c7d8aef6bec03bf',
            'signature': '536306a2f2aee499ffd6584027029ee585293b3686....',
            'address': '0x32c46323b51c977814e05ef5e258ee4da0e4c3c3'
        }

    :param order_params: Parameters to create an order to be submitted to the Switcheo Order Book.
    :type order_params: dict
    :param private_key: The Ethereum private key to sign the deposit parameters.
    :type private_key: str
    :return: Dictionary of signed message to send to the Switcheo API.
    """
    hash_message = defunct_hash_message(text=stringify_message(order_params))
    hex_message = binascii.hexlify(hash_message).decode()
    create_params = order_params.copy()
    signed_message = binascii.hexlify(
        Account.signHash(hex_message,
                         private_key=private_key)['signature']).decode()
    create_params['signature'] = signed_message
    create_params['address'] = to_normalized_address(
        Account.privateKeyToAccount(private_key=private_key).address)
    return create_params
예제 #26
0
def sign_execute_withdrawal(withdrawal_params, private_key):
    """
    Function to execute the withdrawal request by signing the transaction generated from the create withdrawal function.
    Execution of this function is as follows::

        sign_execute_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key)

    The expected return result for this function is as follows::

        {
            'signature': '0x33656f88b364d344e5b04f6aead01cdd3ac084489c39a9efe88c9873249bf1954525b1....'
        }

    :param withdrawal_params: The parameters generated by the create function that now require signing.
    :type withdrawal_params: dict
    :param private_key: The Ethereum private key to sign the deposit parameters.
    :type private_key: str
    :return: Dictionary of the signed transaction hash and initiate the withdrawal of ETH via the Switcheo API.
    """
    withdrawal_sha256 = withdrawal_params['transaction']['sha256']
    signed_sha256 = binascii.hexlify(Account.signHash(withdrawal_sha256, private_key=private_key)['signature']).decode()
    return {'signature': '0x' + signed_sha256}
예제 #27
0
    def sign(self, transaction: Any, use_tron: bool = True):
        """Sign the transaction, the api has the risk of leaking the private key,
        please make sure to call the api in a secure environment

        Args:
            transaction (Any): transaction details
            use_tron (bool): is Tron header

        """

        if is_string(transaction):
            if not is_hex(transaction):
                raise TronError('Expected hex message input')

            # Determine which header to attach to the message
            # before encrypting or decrypting
            header = TRX_MESSAGE_HEADER if use_tron else ETH_MESSAGE_HEADER
            message_hash = self.tron.sha3(text=header + transaction)
            signed_message = EthAccount.signHash(
                message_hash, private_key=self.tron.private_key)

            return signed_message

        if 'signature' in transaction:
            raise TronError('Transaction is already signed')

        address = self.tron.address.from_private_key(
            self.tron.private_key).hex.lower()
        owner_address = transaction['raw_data']['contract'][0]['parameter'][
            'value']['owner_address']

        if address != owner_address:
            raise ValueError(
                'Private key does not match address in transaction')

        return self.tron.manager.request('/wallet/gettransactionsign', {
            'transaction': transaction,
            'privateKey': self.tron.private_key
        })
예제 #28
0
 def _login(self, internal_api_endpoint, private_key):
     msg = "Trying to login"
     message_hash = defunct_hash_message(text=msg)
     signed_msg = Account.signHash(message_hash, private_key)
     # --MATICVIGIL API CALL---
     headers = {
         'accept': 'application/json',
         'Content-Type': 'application/json'
     }
     r = requests.post(internal_api_endpoint + '/login',
                       json={
                           'msg': msg,
                           'sig': signed_msg.signature.hex()
                       },
                       headers=headers)
     if self._verbose:
         print(r.text)
     if r.status_code == requests.codes.ok:
         r = r.json()
         return r['data']
     else:
         return None
예제 #29
0
def sign_execute_cancellation(cancellation_params, private_key):
    """
    Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange.
    Execution of this function is as follows::

        sign_execute_cancellation(cancellation_params=signable_params, private_key=eth_private_key)

    The expected return result for this function is as follows::

        {
            'signature': '0x65986ed2cb631d4999ce8b9c895a43f....'
        }

    :param cancellation_params: Parameters the Switcheo Exchange returns from the create cancellation.
    :type cancellation_params: dict
    :param private_key: The Ethereum private key to sign the deposit parameters.
    :type private_key: str
    :return: Dictionary of signed message to send to the Switcheo API.
    """
    cancellation_sha256 = cancellation_params['transaction']['sha256']
    signed_sha256 = binascii.hexlify(
        Account.signHash(cancellation_sha256, private_key=private_key)['signature']).decode()
    return {'signature': '0x' + signed_sha256}
def main():
    msg = "Trying to deploy"
    message_hash = defunct_hash_message(text=msg)
    private_key = "0xprivatekeyhexstring"
    constructor_inputs = ['My Token', 'SYMBOL', 18]
    sig_msg = Account.signHash(message_hash, private_key)
    with open('./ERC20Mintable.sol', 'r') as f:
        contract_code = f.read()
    deploy_params = {
        'msg': msg,
        'sig': sig_msg.signature.hex(),
        'name': 'ERC20Mintable',
        'inputs': constructor_inputs,
        'code': contract_code
    }
    print('Deploying with constructor arguments: ')
    print(constructor_inputs)
    # API call to deploy
    headers = {'accept': 'application/json', 'Content-Type': 'application/json'}
    api_endpoint = "https://mainnet-api.maticvigil.com/v1.0"
    r = requests.post(api_endpoint + '/deploy', json=deploy_params, headers=headers)
    rj = r.json()
    print('Deployed contract results')
    print(rj)