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 13 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.nonce

def get_transactions_for_block(
self, block_number: int, include_full_tx: bool
) -> dict:
transactions = (
self.session.query(Transactions)
.filter(Transactions.nonce == block_number)
Copy link
Contributor

Choose a reason for hiding this comment

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

we should explain somehow that block_number === nonce

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I changed from nonce to timestamp here: 20b83f0

timestamp is the only unique key on transactions table

.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
133 changes: 132 additions & 1 deletion backend/protocol_rpc/endpoints.py
Original file line number Diff line number Diff line change
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(61_999)


def get_net_version() -> str:
return "61999"
AgustinRamiroDiaz marked this conversation as resolved.
Show resolved Hide resolved


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
21 changes: 19 additions & 2 deletions frontend/src/components/Simulator/AccountSelect.vue
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
});
}
};

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

Check warning on line 33 in frontend/src/components/Simulator/AccountSelect.vue

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/Simulator/AccountSelect.vue#L30-L33

Added lines #L30 - L33 were not covered by tests
</script>

<template>
Expand All @@ -38,12 +42,21 @@

<template #popper>
<div class="divide-y divide-gray-200 dark:divide-gray-800">
<AccountItem
v-if="store.walletAddress"
:account="{ address: store.walletAddress }"
:active="store.isWalletSelected"
:canDelete="false"
v-close-popper
/>

Check warning on line 51 in frontend/src/components/Simulator/AccountSelect.vue

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/Simulator/AccountSelect.vue#L45-L51

Added lines #L45 - L51 were not covered by tests
<AccountItem
v-for="privateKey in store.privateKeys"
:key="privateKey"
:privateKey="privateKey"
:account="createAccount(privateKey)"
:active="privateKey === store.currentPrivateKey"
:active="
privateKey === store.currentPrivateKey && !store.isWalletSelected
"

Check warning on line 59 in frontend/src/components/Simulator/AccountSelect.vue

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/Simulator/AccountSelect.vue#L57-L59

Added lines #L57 - L59 were not covered by tests
:canDelete="true"
v-close-popper
/>
Expand All @@ -57,8 +70,12 @@
secondary
class="w-full"
:icon="PlusIcon"
>New account</Btn
>
New account
</Btn>
<Btn @click="connectMetaMask" secondary class="w-full">
Connect MetaMask
</Btn>

Check warning on line 78 in frontend/src/components/Simulator/AccountSelect.vue

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/Simulator/AccountSelect.vue#L74-L78

Added lines #L74 - L78 were not covered by tests
</div>
</template>
</Dropdown>
Expand Down
13 changes: 2 additions & 11 deletions frontend/src/components/Simulator/ContractMethodItem.vue
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,22 @@

const isExpanded = ref(false);
const isCalling = ref(false);
const responseMessage = ref('');
const responseMessage = ref();

Check warning on line 24 in frontend/src/components/Simulator/ContractMethodItem.vue

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/Simulator/ContractMethodItem.vue#L24

Added line #L24 was not covered by tests

const calldataArguments = ref<ArgData>({ args: [], kwargs: {} });

const handleCallReadMethod = async () => {
responseMessage.value = '';
isCalling.value = true;

try {
const result = await callReadMethod(
responseMessage.value = await callReadMethod(

Check warning on line 32 in frontend/src/components/Simulator/ContractMethodItem.vue

View check run for this annotation

Codecov / codecov/patch

frontend/src/components/Simulator/ContractMethodItem.vue#L32

Added line #L32 was not covered by tests
props.name,
unfoldArgsData({
args: calldataArguments.value.args,
kwargs: calldataArguments.value.kwargs,
}),
);

let repr: string;
if (typeof result === 'string') {
const val = Uint8Array.from(atob(result), (c) => c.charCodeAt(0));
responseMessage.value = calldata.toString(calldata.decode(val));
} else {
responseMessage.value = '<unknown>';
}

trackEvent('called_read_method', {
contract_name: contract.value?.name || '',
method_name: props.name,
Expand Down
8 changes: 8 additions & 0 deletions frontend/src/global.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// global.d.ts
interface Window {
ethereum?: {
isMetaMask?: boolean;
request: (args: { method: string; params?: unknown[] }) => Promise<Array>;
on: (method: string, callback: Function) => {};
};
}
10 changes: 8 additions & 2 deletions frontend/src/hooks/useGenlayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@
}

watch(
() => accountsStore.currentUserAddress,
[
() => accountsStore.currentUserAddress,
() => accountsStore.isWalletSelected,
() => accountsStore.walletAddress,
],

Check warning on line 21 in frontend/src/hooks/useGenlayer.ts

View check run for this annotation

Codecov / codecov/patch

frontend/src/hooks/useGenlayer.ts#L17-L21

Added lines #L17 - L21 were not covered by tests
() => {
initClient();
},
Expand All @@ -24,7 +28,9 @@
client = createClient({
chain: simulator,
endpoint: import.meta.env.VITE_JSON_RPC_SERVER_URL,
account: createAccount(accountsStore.currentPrivateKey || undefined),
account: accountsStore.isWalletSelected
? accountsStore.walletAddress
: createAccount(accountsStore.currentPrivateKey || undefined),

Check warning on line 33 in frontend/src/hooks/useGenlayer.ts

View check run for this annotation

Codecov / codecov/patch

frontend/src/hooks/useGenlayer.ts#L31-L33

Added lines #L31 - L33 were not covered by tests
});
}

Expand Down
Loading
Loading