Exemplo n.º 1
0
    def test_generate_address2_with_proxy(self):
        deployer_account = self.ethereum_test_account
        proxy_factory_contract = get_proxy_factory_contract(self.w3)
        nonce = self.w3.eth.getTransactionCount(deployer_account.address, block_identifier='pending')
        tx = proxy_factory_contract.constructor().buildTransaction({'nonce': nonce,
                                                                    'from': deployer_account.address})
        signed_tx = deployer_account.sign_transaction(tx)
        tx_hash = self.w3.eth.sendRawTransaction(signed_tx.rawTransaction)
        tx_receipt = self.w3.eth.waitForTransactionReceipt(tx_hash)
        proxy_factory_contract = get_proxy_factory_contract(self.w3, address=tx_receipt['contractAddress'])

        initializer = b''  # Should be the safe `setup()` call with `owners`, `threshold`, `payment`...
        salt_nonce = 0  # Random. For sure. I used a dice

        master_copy = Account.create().address
        tx = proxy_factory_contract.functions.createProxyWithNonce(master_copy,
                                                                   initializer,
                                                                   salt_nonce
                                                                   ).buildTransaction({'nonce': nonce + 1,
                                                                                       'from': deployer_account.address,
                                                                                       })
        signed_tx = deployer_account.sign_transaction(tx)
        tx_hash = self.w3.eth.sendRawTransaction(signed_tx.rawTransaction)
        tx_receipt = self.w3.eth.waitForTransactionReceipt(tx_hash)
        logs = proxy_factory_contract.events.ProxyCreation().processReceipt(tx_receipt)
        log = logs[0]
        self.assertEqual(log['event'], 'ProxyCreation')
        proxy_address = log['args']['proxy']

        proxy_creation_code = proxy_factory_contract.functions.proxyCreationCode().call()
        salt = self.w3.keccak(encode_abi_packed(['bytes', 'uint256'], [self.w3.keccak(initializer), salt_nonce]))
        deployment_data = encode_abi_packed(['bytes', 'uint256'], [proxy_creation_code, int(master_copy, 16)])
        address2 = generate_address_2(proxy_factory_contract.address, salt, deployment_data)
        self.assertEqual(proxy_address, address2)
Exemplo n.º 2
0
 def calculate_create2_address(self, safe_setup_data: bytes,
                               salt_nonce: int):
     proxy_creation_code = self.proxy_factory_contract.functions.proxyCreationCode(
     ).call()
     salt = self.w3.keccak(
         encode_abi_packed(['bytes', 'uint256'],
                           [self.w3.keccak(safe_setup_data), salt_nonce]))
     deployment_data = encode_abi_packed(
         ['bytes', 'uint256'],
         [proxy_creation_code,
          int(self.master_copy_address, 16)])
     return generate_address_2(self.proxy_factory_contract.address, salt,
                               deployment_data)
Exemplo n.º 3
0
    def test_generate_address2_with_proxy(self):
        deployer_account = self.ethereum_test_account
        proxy_factory_contract = get_proxy_factory_contract(self.w3)
        nonce = self.w3.eth.get_transaction_count(deployer_account.address,
                                                  block_identifier="pending")
        tx = proxy_factory_contract.constructor().buildTransaction({
            "nonce":
            nonce,
            "from":
            deployer_account.address
        })
        signed_tx = deployer_account.sign_transaction(tx)
        tx_hash = self.w3.eth.send_raw_transaction(signed_tx.rawTransaction)
        tx_receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash)
        proxy_factory_contract = get_proxy_factory_contract(
            self.w3, address=tx_receipt["contractAddress"])

        initializer = b""  # Should be the safe `setup()` call with `owners`, `threshold`, `payment`...
        salt_nonce = 0  # Random. For sure. I used a dice

        master_copy = Account.create().address
        tx = proxy_factory_contract.functions.createProxyWithNonce(
            master_copy, initializer, salt_nonce).buildTransaction({
                "nonce":
                nonce + 1,
                "from":
                deployer_account.address,
            })
        signed_tx = deployer_account.sign_transaction(tx)
        tx_hash = self.w3.eth.send_raw_transaction(signed_tx.rawTransaction)
        tx_receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash)
        logs = proxy_factory_contract.events.ProxyCreation().processReceipt(
            tx_receipt)
        log = logs[0]
        self.assertEqual(log["event"], "ProxyCreation")
        proxy_address = log["args"]["proxy"]

        proxy_creation_code = (
            proxy_factory_contract.functions.proxyCreationCode().call())
        salt = self.w3.keccak(
            encode_abi_packed(["bytes", "uint256"],
                              [self.w3.keccak(initializer), salt_nonce]))
        deployment_data = encode_abi_packed(
            ["bytes", "uint256"],
            [proxy_creation_code, int(master_copy, 16)])
        address2 = generate_address_2(proxy_factory_contract.address, salt,
                                      deployment_data)
        self.assertEqual(proxy_address, address2)
Exemplo n.º 4
0
def main():
    with Path('data.json').open() as fp:
        data = json.load(fp)['addresses']

    total_distribution = (250000000 * 10**18) // 52
    total_vecrv = sum(data.values())
    balances = {
        k: int(v * total_distribution / total_vecrv)
        for k, v in data.items()
    }

    elements = [(index, account, amount)
                for index, (account, amount) in enumerate(balances.items())]
    nodes = [
        encode_hex(encode_abi_packed(['uint', 'address', 'uint'], el))
        for el in elements
    ]
    tree = MerkleTree(nodes)
    distribution = {
        'merkleRoot': encode_hex(tree.root),
        'tokenTotal': hex(sum(balances.values())),
        'claims': {
            user: {
                'index': index,
                'amount': hex(amount),
                'proof': tree.get_proof(nodes[index])
            }
            for index, user, amount in elements
        },
    }
    print(f'merkle root: {encode_hex(tree.root)}')
    with Path('distribution.json').open('w') as fp:
        json.dump(distribution, fp)
def test_encode_abi(type_str, python_value, _, packed_encoding):
    abi_type = parse(type_str)
    if abi_type.arrlist is not None:
        pytest.skip('ABI coding functions do not support array types')

    types = [t.to_type_str() for t in abi_type.components]

    actual = encode_abi_packed(types, python_value)
    assert actual == packed_encoding
Exemplo n.º 6
0
def test_encode_abi(type_str, python_value, _, packed_encoding):
    abi_type = parse(type_str)
    if abi_type.arrlist is not None:
        pytest.skip('ABI coding functions do not support array types')

    types = [str(t) for t in abi_type.components]

    actual = encode_abi_packed(types, python_value)
    assert actual == packed_encoding
Exemplo n.º 7
0
 def calculate_pair_address(self, token_address: str, token_address_2: str):
     """
     Calculate pair address without querying blockchain.
     https://uniswap.org/docs/v2/smart-contract-integration/getting-pair-addresses/#docs-header
     :param token_address:
     :param token_address_2:
     :return: Checksummed address for token pair. It could be not created yet
     """
     if token_address.lower() > token_address_2.lower():
         token_address, token_address_2 = token_address_2, token_address
     salt = Web3.keccak(
         encode_abi_packed(['address', 'address'],
                           [token_address, token_address_2]))
     address = Web3.keccak(
         encode_abi_packed(['bytes', 'address', 'bytes', 'bytes'], [
             HexBytes('ff'), self.factory_address, salt, self.pair_init_code
         ]))[-20:]
     return Web3.toChecksumAddress(address)
Exemplo n.º 8
0
 def add_value_txn(self, acct, l2nonce, balance, deposit):
     chainid = 100
     tokenid = '0x0000000000000000000000000000000000000000'
     amount = int((balance + deposit) * pow(10, 18))
     adjust = int(deposit * pow(10, 18))
     lock = retrieve = 0
     refill = 1
     acstat = seller.functions.read(acct.address).call()
     print(f"acstat: {acstat}")
     l3nonce = int(('0' * 16 + hex(acstat)[2:])[-16:], 16)
     print(f"l3nonce: {l3nonce}")
     #        msg = encode_abi_packed(['bytes1', 'bytes1', 'address', 'uint256', 'uint64', 'address', 'uint256', 'int256', 'int256', 'uint256', 'uint128'],
     #                         [b'\x19', b'\x00', testdata['seller']['address'], chainid, l3nonce, tokenid, amount, adjust, lock, retrieve, refill])
     msg = encode_abi_packed([
         'uint256', 'uint64', 'address', 'uint256', 'int256', 'int256',
         'uint256', 'uint256'
     ], [chainid, l3nonce, tokenid, amount, adjust, lock, retrieve, refill])
     message = encode_intended_validator(
         validator_address=testdata['seller']['address'], primitive=msg)
     sig = w3.eth.account.sign_message(message, private_key=acct.key)
     txn = {
         "from":
         acct.address,
         "to":
         testdata['seller']['address'],
         "gas":
         hex(175000),
         "gasPrice":
         hex(pow(10, 9)),
         "value":
         hex(int((balance + deposit) * pow(10, 18))),
         "chainId":
         chainid,
         "nonce":
         l2nonce,
         "data":
         seller.encodeABI(fn_name='edit',
                          args=[
                              acct.address, sig.v,
                              bytearray.fromhex(hex(sig.r)[2:]),
                              bytearray.fromhex(hex(sig.s)[2:]), l3nonce,
                              adjust, lock, retrieve, refill
                          ]),
     }
     txstr = json.dumps(txn)
     txmsg = encode_defunct(text=txstr)
     print(txmsg)
     txsig = w3.eth.account.sign_message(
         txmsg, private_key=acct.key).signature.hex()
     print(txsig)
     return txstr, txsig
Exemplo n.º 9
0
    def calculate_pair_adress(self, tokenA, tokenB):
        tokenA = Web3.toChecksumAddress(tokenA)
        tokenB = Web3.toChecksumAddress(tokenB)

        tokenA_hex = bytes.fromhex(tokenA[2:])
        tokenB_hex = bytes.fromhex(tokenB[2:])
        if tokenA_hex < tokenB_hex:
            token0 = tokenA
            token1 = tokenB
        else:
            token1 = tokenA
            token0 = tokenB

        b_salt = Web3.keccak(encode_abi_packed(['address', 'address'], [token0, token1]))

        pre = '0xff'
        b_pre = bytes.fromhex(pre[2:])
        b_address = bytes.fromhex(self.factory_address[2:])
        b_init_code = bytes.fromhex(self.init_code_hash[2:])
        b_result = Web3.keccak(
            encode_abi_packed(['bytes', 'bytes', 'bytes', 'bytes'], [b_pre, b_address, b_salt, b_init_code]))
        result_address = Web3.toChecksumAddress(b_result[12:].hex())
        return result_address, token0, token1
Exemplo n.º 10
0
def sign_score(key, validator, game_id, user, score):
    game_id = HexBytes(game_id)
    types = ['bytes32', 'address', 'uint256']
    values = [game_id, user, score]
    encoded_values = encode_abi_packed(types, values)
    message = encode_intended_validator(
        validator_address=validator,
        primitive=encoded_values,
    )
    signed = Account.sign_message(message, key)
    vrs = {
        'v': signed['v'],
        'r': HexBytes(signed['r']).hex(),
        's': HexBytes(signed['s']).hex(),
    }
    return vrs
Exemplo n.º 11
0
    def get_dispute_by(self, miner, request_id,
                       timestamp) -> Optional[Dispute]:
        """
        Args:
            miner: Disputed miner address
            request_id: Disputed request id
            timestamp: Disputed value timestamp

        Returns:
            Detailed info about a :py:class:`~tellor.dispute.Dispute`.
        """
        dispute_hash = w3.keccak(
            encode_abi_packed(["address", "uint256", "uint256"],
                              [miner, request_id, timestamp]))
        dispute_id = self.call.getDisputeIdByDisputeHash(dispute_hash)
        if dispute_id:
            return self.get_dispute(dispute_id)
Exemplo n.º 12
0
def step_07(balances):
    elements = [(index, account, amount)
                for index, (account, amount) in enumerate(balances.items())]
    nodes = [encode_hex(encode_abi_packed(
        ['uint', 'address', 'uint'], el)) for el in elements]
    tree = MerkleTree(nodes)
    distribution = {
        'merkleRoot': encode_hex(tree.root),
        'tokenTotal': hex(sum(balances.values())),
        'claims': {
            user: {'index': index, 'amount': hex(
                amount), 'proof': tree.get_proof(nodes[index])}
            for index, user, amount in elements
        },
    }
    print(f'merkle root: {encode_hex(tree.root)}')
    return distribution
Exemplo n.º 13
0
def main():
    with Path('data.json').open() as fp:
        data = json.load(fp)['addresses']

    total_distribution = (250000000 * 10**18) // 52
    total_vecrv = sum(data.values())
    balances = {
        k: int(Fraction(v * total_distribution, total_vecrv))
        for k, v in data.items()
    }
    balances = {k: v for k, v in balances.items() if v}

    # handle any rounding errors
    addresses = deque(balances)
    while sum(balances.values()) < total_distribution:
        balances[addresses[0]] += 1
        addresses.rotate()

    assert sum(balances.values()) == total_distribution

    elements = [(index, account, balances[account])
                for index, account in enumerate(sorted(balances))]
    nodes = [
        encode_hex(encode_abi_packed(['uint', 'address', 'uint'], el))
        for el in elements
    ]
    tree = MerkleTree(nodes)
    distribution = {
        'merkleRoot': encode_hex(tree.root),
        'tokenTotal': hex(sum(balances.values())),
        'claims': {
            user: {
                'index': index,
                'amount': hex(amount),
                'proof': tree.get_proof(nodes[index])
            }
            for index, user, amount in elements
        },
    }
    print(f'merkle root: {encode_hex(tree.root)}')
    with Path('distribution.json').open('w') as fp:
        json.dump(distribution, fp)
Exemplo n.º 14
0
def prepare_merkle_tree(balances):
    elements = [(index, account, amount)
                for index, (account, amount) in enumerate(balances.items())]
    nodes = [
        encode_abi_packed(["uint", "address", "uint"], el) for el in elements
    ]
    tree = MerkleTree(nodes)
    distribution = {
        "merkleRoot": encode_hex(tree.root),
        "tokenTotal": str(sum(balances.values())),
        "claims": {
            user: {
                "index": index,
                "amount": str(amount),
                "proof": tree.get_proof(nodes[index]),
            }
            for index, user, amount in elements
        },
    }
    return distribution
Exemplo n.º 15
0
def distribution(accounts):
    balances = {i.address: c * 10**18 for c, i in enumerate(accounts, start=1)}
    elements = [(index, account, amount)
                for index, (account, amount) in enumerate(balances.items())]
    nodes = [
        encode_hex(encode_abi_packed(['uint', 'address', 'uint'], el))
        for el in elements
    ]
    tree = MerkleTree(nodes)
    return {
        'merkleRoot': encode_hex(tree.root),
        'tokenTotal': hex(sum(balances.values())),
        'claims': {
            user: {
                'index': index,
                'amount': hex(amount),
                'proof': tree.get_proof(nodes[index])
            }
            for index, user, amount in elements
        },
    }
Exemplo n.º 16
0
def test_sign_score(user, owner, monkeypatch):
    expected_signer = owner.address
    sig = sign_score(owner.key, CONTRACT, GAME_ID, user.address, SCORE)
    types = ['bytes32', 'address', 'uint256']
    values = [
        HexBytes(GAME_ID),
        user.address,
        SCORE,
    ]
    encoded_values = encode_abi_packed(types, values)
    message = encode_intended_validator(
        validator_address=CONTRACT,
        primitive=encoded_values,
    )
    vrs = (sig['v'], sig['r'], sig['s'])
    actual_signer = Account.recover_message(
        message,
        vrs=vrs,
    )

    assert actual_signer == expected_signer
Exemplo n.º 17
0
def get_proof(balances, snapshot_block):
    total_distribution = (250000000 * 10**18) // 52
    total_vecrv = sum(balances.values())
    balances = {
        k: int(Fraction(v * total_distribution, total_vecrv))
        for k, v in balances.items()
    }
    balances = {k: v for k, v in balances.items() if v}

    # handle any rounding errors
    addresses = deque(balances)
    while sum(balances.values()) < total_distribution:
        balances[addresses[0]] += 1
        addresses.rotate()

    assert sum(balances.values()) == total_distribution

    elements = [(index, account, balances[account])
                for index, account in enumerate(sorted(balances))]
    nodes = [
        encode_hex(encode_abi_packed(['uint', 'address', 'uint'], el))
        for el in elements
    ]
    tree = MerkleTree(nodes)
    distribution = {
        'merkleRoot': encode_hex(tree.root),
        'tokenTotal': hex(sum(balances.values())),
        'blockHeight': snapshot_block,
        'claims': {
            user: {
                'index': index,
                'amount': hex(amount),
                'proof': tree.get_proof(nodes[index])
            }
            for index, user, amount in elements
        },
    }
    print(f'merkle root: {encode_hex(tree.root)}')
    return distribution
Exemplo n.º 18
0
    def encode_route_to_path(route: Route, exact_output: bool) -> str:
        """ Convert a route to a hex encoded path"""
        assert (isinstance(route, Route))
        assert (isinstance(exact_output, bool))

        route_input_token = route.input

        path_to_encode = {}
        path_to_encode["input_token"] = route_input_token

        for i, pool in enumerate(route.pools):
            output_token = pool.token_1 if pool.token_0 == path_to_encode[
                "input_token"] else pool.token_0
            if i == 0:
                path_to_encode["input_token"] = output_token
                path_to_encode["types"] = ['address', 'uint24', 'address']
                path_to_encode["path"] = [
                    route_input_token.address.address, pool.fee,
                    output_token.address.address
                ]
            else:
                path_to_encode["input_token"] = output_token
                path_to_encode["types"] = path_to_encode["types"] + [
                    'uint24', 'address'
                ]
                path_to_encode["path"] = path_to_encode["path"] + [
                    pool.fee, output_token.address.address
                ]

        # encode
        if exact_output:
            path_to_encode["types"].reverse()
            path_to_encode["path"].reverse()

        encoded_path = encode_abi_packed(path_to_encode["types"],
                                         path_to_encode["path"])

        return bytes_to_hexstring(encoded_path)
Exemplo n.º 19
0
 def encode_path(self, path):
     types = [type for _, type in zip(path, cycle(['address', 'uint24']))]
     return encode_abi_packed(types, path)
Exemplo n.º 20
0
    def to_node_entry(self, user, userData, cycle, index):
        nodeEntry = {
            "user": user,
            "tokens": [],
            "cumulativeAmounts": [],
            "cycle": cycle,
            "index": index,
        }
        intAmounts = []
        for tokenAddress, cumulativeAmount in userData.items():
            nodeEntry["tokens"].append(tokenAddress)
            nodeEntry["cumulativeAmounts"].append(str(cumulativeAmount))
            intAmounts.append(int(cumulativeAmount))

        # print(
        #     int(nodeEntry["index"]),
        #     nodeEntry["user"],
        #     int(nodeEntry["cycle"]),
        #     nodeEntry["tokens"],
        #     intAmounts,
        # )

        address = nodeEntry["tokens"][0]
        # print(address, address[2:])

        bytearray.fromhex(address[2:])

        encoded = encode_hex(
            encode_abi_packed(
                ["uint", "address", "uint", "address", "uint[]"],
                (
                    int(nodeEntry["index"]),
                    nodeEntry["user"],
                    int(nodeEntry["cycle"]),
                    address,
                    intAmounts,
                ),
            )
        )

        surgeryIndex = 64 + 40 + 64 + 2

        after = encoded[surgeryIndex:]
        before = encoded[0:surgeryIndex]
        before = before + "000000000000000000000000"

        postSurgery = before + after
        # print("post", postSurgery)

        # encoder = ClaimEncoder.at("0x19be80e976cb397ae584d350153914ced7c1b1d2")

        # claim = encoder.encodeClaim(
        #     nodeEntry["tokens"],
        #     nodeEntry["cumulativeAmounts"],
        #     nodeEntry["index"],
        #     nodeEntry["cycle"],
        #     nodeEntry["user"],
        # )[0]

        # local = encoder.encodeClaim.encode_input(
        #     nodeEntry["tokens"],
        #     nodeEntry["cumulativeAmounts"],
        #     nodeEntry["index"],
        #     nodeEntry["cycle"],
        #     nodeEntry["user"],
        # )

        # print("claim", claim)
        # print("encoded", encoded)

        # encoded = encode_hex(postSurgery)
        # print("encoded", encoded)

        # console.log("nodeEntry", nodeEntry)
        # console.log("encoded", encoded)
        return (nodeEntry, postSurgery)