Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 764 add new rpc endpoints metamask #765

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions backend/database_handler/accounts_manager.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# consensus/services/transactions_db_service.py

from eth_account import Account
from eth_account._utils.validation import is_valid_address
from eth_utils import is_address

from .models import CurrentState
from backend.database_handler.errors import AccountNotFoundError
Expand Down Expand Up @@ -38,7 +38,7 @@ def create_new_account_with_address(self, address: str):
self.session.commit()

def is_valid_address(self, address: str) -> bool:
return is_valid_address(address)
return is_address(address)

def get_account(self, account_address: str) -> CurrentState | None:
"""Private method to retrieve an account from the data base"""
Expand Down
50 changes: 49 additions & 1 deletion backend/database_handler/transactions_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from .models import Transactions
from sqlalchemy.orm import Session
from sqlalchemy import or_, and_
from sqlalchemy import or_, and_, desc

from .models import TransactionStatus
from eth_utils import to_bytes, keccak, is_address
Expand Down Expand Up @@ -366,3 +366,51 @@ def set_transaction_appeal_failed(self, transaction_hash: str, appeal_failed: in
self.session.query(Transactions).filter_by(hash=transaction_hash).one()
)
transaction.appeal_failed = appeal_failed

def get_highest_timestamp(self) -> int:
transaction = (
self.session.query(Transactions)
.order_by(desc(Transactions.timestamp_accepted))
.first()
)
if transaction is None:
return 0
return transaction.timestamp_accepted

def get_transactions_for_block(
self, block_number: int, include_full_tx: bool
) -> dict:
transactions = (
self.session.query(Transactions)
.filter(Transactions.timestamp_accepted == block_number)
.all()
)

if not transactions:
return None

block_hash = transactions[0].hash
parent_hash = "0x" + "0" * 64 # Placeholder for parent block hash
timestamp = transactions[0].timestamp_accepted or int(time.time())

if include_full_tx:
transaction_data = [self._parse_transaction_data(tx) for tx in transactions]
else:
transaction_data = [tx.hash for tx in transactions]

block_details = {
"number": hex(block_number),
"hash": block_hash,
"parentHash": parent_hash,
"nonce": "0x" + "0" * 16,
"transactions": transaction_data,
"timestamp": hex(int(timestamp)),
"miner": "0x" + "0" * 40,
"difficulty": "0x1",
"gasUsed": "0x0",
"gasLimit": "0x0",
"size": "0x0",
"extraData": "0x",
}

return block_details
135 changes: 133 additions & 2 deletions backend/protocol_rpc/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
TransactionAddressFilter,
TransactionsProcessor,
)
from backend.node.base import Node
from backend.node.base import Node, SIMULATOR_CHAIN_ID
from backend.node.types import ExecutionMode, ExecutionResultStatus
from backend.consensus.base import ConsensusAlgorithm

Expand Down Expand Up @@ -368,7 +368,7 @@ def get_balance(


def get_transaction_count(
transactions_processor: TransactionsProcessor, address: str
transactions_processor: TransactionsProcessor, address: str, block: str
) -> int:
return transactions_processor.get_transaction_count(address)

Expand All @@ -390,6 +390,11 @@ async def call(
from_address = params["from"] if "from" in params else None
data = params["data"]

if from_address is None:
return base64.b64encode(b"\x00' * 31 + b'\x01").decode(
"ascii"
) # Return '1' as a uint256
AgustinRamiroDiaz marked this conversation as resolved.
Show resolved Hide resolved

if from_address and not accounts_manager.is_valid_address(from_address):
raise InvalidAddressError(from_address)

Expand Down Expand Up @@ -531,6 +536,113 @@ def set_finality_window_time(consensus: ConsensusAlgorithm, time: int) -> None:
consensus.set_finality_window_time(time)


def get_chain_id() -> str:
return hex(SIMULATOR_CHAIN_ID)


def get_net_version() -> str:
return str(SIMULATOR_CHAIN_ID)


def get_block_number(transactions_processor: TransactionsProcessor) -> str:
transaction_count = transactions_processor.get_highest_timestamp()
return hex(transaction_count)


def get_block_by_number(
transactions_processor: TransactionsProcessor, block_number: str, full_tx: bool
) -> dict | None:
try:
block_number_int = int(block_number, 16)
except ValueError:
raise JSONRPCError(f"Invalid block number format: {block_number}")

block_details = transactions_processor.get_transactions_for_block(
block_number_int, include_full_tx=full_tx
)

if not block_details:
raise JSONRPCError(f"Block not found for number: {block_number}")

return block_details
Comment on lines +552 to +567
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is the signature dict | None? I don't see anywhere where it could return None



def get_gas_price() -> str:
gas_price_in_wei = 20 * 10**9
return hex(gas_price_in_wei)
AgustinRamiroDiaz marked this conversation as resolved.
Show resolved Hide resolved


def get_transaction_receipt(
transactions_processor: TransactionsProcessor,
transaction_hash: str,
) -> dict | None:

transaction = transactions_processor.get_transaction_by_hash(transaction_hash)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could probably take advantage of the Transaction type if we returned some dataclass instead of a dict. This way we wouldn't need to do so many transaction.get below


if not transaction:
return None

receipt = {
"transactionHash": transaction_hash,
"transactionIndex": hex(0),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why 0?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

because we just have one transaction per "block"

"blockHash": transaction_hash,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is a block the same as a transaction for us? a small explanation in a comment would be great

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't have a block table or block hash rn, so yes, at this moment I'm considering transaction = block

"blockNumber": hex(transaction.get("block_number", 0)),
"from": transaction.get("from_address"),
"to": transaction.get("to_address") if transaction.get("to_address") else None,
"cumulativeGasUsed": hex(transaction.get("gas_used", 21000)),
"gasUsed": hex(transaction.get("gas_used", 21000)),
"contractAddress": (
transaction.get("contract_address")
if transaction.get("contract_address")
else None
),
"logs": transaction.get("logs", []),
"logsBloom": "0x" + "00" * 256,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will we fill this with something at some point?

"status": hex(1 if transaction.get("status", True) else 0),
}

return receipt


def get_block_by_hash(
transactions_processor: TransactionsProcessor,
transaction_hash: str,
full_tx: bool = False,
) -> dict | None:

transaction = transactions_processor.get_transaction_by_hash(transaction_hash)

if not transaction:
return None

block_details = {
"hash": transaction_hash,
"parentHash": "0x" + "00" * 32,
"number": hex(transaction.get("block_number", 0)),
"timestamp": hex(transaction.get("timestamp", 0)),
"nonce": "0x" + "00" * 8,
"transactionsRoot": "0x" + "00" * 32,
"stateRoot": "0x" + "00" * 32,
"receiptsRoot": "0x" + "00" * 32,
"miner": "0x" + "00" * 20,
"difficulty": "0x1",
"totalDifficulty": "0x1",
"size": "0x0",
"extraData": "0x",
"gasLimit": hex(transaction.get("gas_limit", 8000000)),
"gasUsed": hex(transaction.get("gas_used", 21000)),
"logsBloom": "0x" + "00" * 256,
"transactions": [],
}

if full_tx:
block_details["transactions"].append(transaction)
else:
block_details["transactions"].append(transaction_hash)

return block_details


def get_contract(consensus_service: ConsensusService, contract_name: str) -> dict:
"""
Get contract instance by name
Expand Down Expand Up @@ -689,3 +801,22 @@ def register_all_rpc_endpoints(
partial(get_contract, consensus_service),
method_name="sim_getConsensusContract",
)
register_rpc_endpoint(get_chain_id, method_name="eth_chainId")
register_rpc_endpoint(get_net_version, method_name="net_version")
register_rpc_endpoint(
partial(get_block_number, transactions_processor),
method_name="eth_blockNumber",
)
register_rpc_endpoint(
partial(get_block_by_number, transactions_processor),
method_name="eth_getBlockByNumber",
)
register_rpc_endpoint(get_gas_price, method_name="eth_gasPrice")
register_rpc_endpoint(
partial(get_transaction_receipt, transactions_processor),
method_name="eth_getTransactionReceipt",
)
register_rpc_endpoint(
partial(get_block_by_hash, transactions_processor),
method_name="eth_getBlockByHash",
)
8 changes: 4 additions & 4 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"defu": "^6.1.4",
"dexie": "^4.0.4",
"floating-vue": "^5.2.2",
"genlayer-js": "^0.4.6",
"genlayer-js": "^0.5.0",
"hash-sum": "^2.0.0",
"jump.js": "^1.0.2",
"lodash-es": "^4.17.21",
Expand Down
18 changes: 11 additions & 7 deletions frontend/src/components/Simulator/AccountItem.vue
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
<script setup lang="ts">
import { useAccountsStore } from '@/stores';
import { useAccountsStore, type AccountInfo } from '@/stores';
import { notify } from '@kyvg/vue3-notification';
import { PowerCircle } from 'lucide-vue-next';
import { PowerCircle, Wallet } from 'lucide-vue-next';
import { ref } from 'vue';
import CopyTextButton from '../global/CopyTextButton.vue';
import { TrashIcon, CheckCircleIcon } from '@heroicons/vue/16/solid';
import type { Account } from 'genlayer-js/types';
const store = useAccountsStore();

const setCurentAddress = () => {
store.setCurrentAccount(props.privateKey);
store.setCurrentAccount(props.account as AccountInfo);
notify({
title: 'Active account changed',
type: 'success',
Expand All @@ -18,7 +17,7 @@ const setCurentAddress = () => {

const deleteAddress = () => {
try {
store.removeAccount(props.privateKey);
store.removeAccount(props.account as AccountInfo);
notify({
title: 'Account deleted',
type: 'success',
Expand All @@ -35,8 +34,7 @@ const deleteAddress = () => {

const props = defineProps<{
active?: Boolean;
account: Account;
privateKey: `0x${string}`;
account: AccountInfo;
canDelete?: Boolean;
}>();

Expand Down Expand Up @@ -65,6 +63,12 @@ const showConfirmDelete = ref(false);
{{ account.address }}
</span>

<Wallet
v-if="account.type === 'metamask'"
class="h-4 w-4 text-orange-500"
v-tooltip="'MetaMask Account'"
/>

<div
class="flex flex-row items-center gap-1 opacity-0 group-hover:opacity-100"
>
Expand Down
35 changes: 26 additions & 9 deletions frontend/src/components/Simulator/AccountSelect.vue
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
<script setup>
<script setup lang="ts">
import { useAccountsStore } from '@/stores';
import AccountItem from '@/components/Simulator/AccountItem.vue';
import { Dropdown } from 'floating-vue';
import { Wallet } from 'lucide-vue-next';
import { PlusIcon } from '@heroicons/vue/16/solid';
import { notify } from '@kyvg/vue3-notification';
import { useEventTracking } from '@/hooks';
import { createAccount } from 'genlayer-js';
import { computed } from 'vue';

const store = useAccountsStore();
const { trackEvent } = useEventTracking();

const hasMetaMaskAccount = computed(() =>
store.accounts.some((account) => account.type === 'metamask'),
);

const handleCreateNewAccount = async () => {
const privateKey = store.generateNewAccount();

Expand All @@ -27,6 +32,10 @@ const handleCreateNewAccount = async () => {
});
}
};

const connectMetaMask = async () => {
await store.fetchMetaMaskAccount();
};
</script>

<template>
Expand All @@ -39,12 +48,11 @@ const handleCreateNewAccount = async () => {
<template #popper>
<div class="divide-y divide-gray-200 dark:divide-gray-800">
<AccountItem
v-for="privateKey in store.privateKeys"
:key="privateKey"
:privateKey="privateKey"
:account="createAccount(privateKey)"
:active="privateKey === store.currentPrivateKey"
:canDelete="true"
v-for="account in store.accounts"
:key="account.privateKey"
:account="account"
:active="account.address === store.currentUserAccount?.address"
:canDelete="account.type === 'local'"
v-close-popper
/>
</div>
Expand All @@ -57,8 +65,17 @@ const handleCreateNewAccount = async () => {
secondary
class="w-full"
:icon="PlusIcon"
>New account</Btn
>
New account
</Btn>
<Btn
v-if="!hasMetaMaskAccount"
@click="connectMetaMask"
secondary
class="w-full"
>
Connect MetaMask
</Btn>
</div>
</template>
</Dropdown>
Expand Down
Loading
Loading