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

Integrate multichain-tools library with Ethereum example #54

Open
wants to merge 2 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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"hash.js": "^1.1.7",
"js-sha3": "^0.9.3",
"keccak": "^3.0.4",
"multichain-tools": "4.0.0",
"near-api-js": "^5.0.0",
"prop-types": "^15.8.1",
"react": "^18.2.0",
Expand All @@ -52,4 +53,4 @@
"eslint-plugin-react-refresh": "^0.4.5",
"vite": "^5.1.6"
}
}
}
81 changes: 53 additions & 28 deletions src/components/Ethereum/Ethereum.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,31 @@ import { useDebounce } from "../../hooks/debounce";
import { getTransactionHashes } from "../../services/utils";
import { TransferForm } from "./Transfer";
import { FunctionCallForm } from "./FunctionCall";
import { MPC_CONTRACT } from "../../services/kdf/mpc";
import { EVM } from "multichain-tools";
import { JsonRpcProvider } from "ethers";
import Web3 from "web3";

const Sepolia = 11155111;
const Eth = new Ethereum("https://sepolia.drpc.org", Sepolia);

const Evm = new EVM({
providerUrl: "https://sepolia.drpc.org",
nearNetworkId: "testnet",
contract: MPC_CONTRACT,
});

const provider = new JsonRpcProvider("https://sepolia.drpc.org");

const transactions = getTransactionHashes();

export function EthereumView({ props: { setStatus, MPC_CONTRACT } }) {
const { wallet, signedAccountId } = useContext(NearContext);

const [loading, setLoading] = useState(false);
const [step, setStep] = useState(transactions ? "relay" : "request");
const [signedTransaction, setSignedTransaction] = useState(null);
const [unsignedTransaction, setUnsignedTransaction] = useState(null);
const [signature, setSignature] = useState(null);
const [senderLabel, setSenderLabel] = useState("");
const [senderAddress, setSenderAddress] = useState("");
const [balance, setBalance] = useState(""); // Add balance state
Expand Down Expand Up @@ -75,16 +88,15 @@ export function EthereumView({ props: { setStatus, MPC_CONTRACT } }) {
}

async function signTransaction() {
const { big_r, s, recovery_id } = await wallet.getTransactionResult(
transactions[0]
);
const signedTransaction = await Eth.reconstructSignedTXFromLocalSession(
big_r,
s,
recovery_id,
senderAddress
);
setSignedTransaction(signedTransaction);
const transaction = Evm.getTransaction("evm_transaction");

if (!transaction) return;

setUnsignedTransaction(transaction);

const signature = await wallet.getTransactionResult(transactions[0]);
setSignature(signature);

setStatus(
"✅ Signed payload ready to be relayed to the Ethereum network"
);
Expand All @@ -110,23 +122,28 @@ export function EthereumView({ props: { setStatus, MPC_CONTRACT } }) {
};

const fetchEthereumAddress = async () => {
const { address } = await Eth.deriveAddress(
const { address } = await Evm.deriveAddressAndPublicKey(
signedAccountId,
derivationPath
);
setSenderAddress(address);
setSenderLabel(address);

if (!reloaded) {
const balance = await Eth.getBalance(address);
const balanceInWei = await provider.getBalance(address)
const balance = Web3.utils.fromWei(balanceInWei, 'ether');
setBalance(balance); // Update balance state
}
};

async function chainSignature() {
setStatus("🏗️ Creating transaction");

const { transaction } = await childRef.current.createTransaction();
const { transaction, mpcPayloads } =
await childRef.current.createTransaction();

Evm.setTransaction(transaction, "evm_transaction");
setUnsignedTransaction(transaction);

setStatus(
`🕒 Asking ${MPC_CONTRACT} to sign the transaction, this might take a while`
Expand All @@ -135,19 +152,24 @@ export function EthereumView({ props: { setStatus, MPC_CONTRACT } }) {
// to reconstruct on reload
sessionStorage.setItem("derivation", derivationPath);

const { big_r, s, recovery_id } = await Eth.requestSignatureToMPC({
wallet,
path: derivationPath,
transaction,
// even tough ChainSignaturesContract.sign() is out there
// we can't use it here because FullAcess key pair can't be retrieved directly from WalletSelector
const signature = await wallet.callMethod({
contractId: MPC_CONTRACT,
method: "sign",
args: {
request: {
payload: Array.from(mpcPayloads[0].payload),
path: derivationPath,
key_version: 0,
},
},
gas: "250000000000000", // 250 Tgas
deposit: 1,
});
const signedTransaction = await Eth.reconstructSignedTransaction(
big_r,
s,
recovery_id,
transaction
);

setSignedTransaction(signedTransaction);
setSignature(signature);

setStatus(
`✅ Signed payload ready to be relayed to the Ethereum network`
);
Expand All @@ -165,7 +187,10 @@ export function EthereumView({ props: { setStatus, MPC_CONTRACT } }) {
);

try {
const txHash = await Eth.broadcastTX(signedTransaction);
const txHash = await Evm.addSignatureAndBroadcast({
transaction: unsignedTransaction,
mpcSignatures: [signature],
});
setStatus(
<>
<a href={`https://sepolia.etherscan.io/tx/${txHash}`} target="_blank">
Expand Down Expand Up @@ -256,11 +281,11 @@ export function EthereumView({ props: { setStatus, MPC_CONTRACT } }) {
</div>

{action === "transfer" ? (
<TransferForm ref={childRef} props={{ Eth, senderAddress, loading }} />
<TransferForm ref={childRef} props={{ Evm, senderAddress, loading }} />
) : (
<FunctionCallForm
ref={childRef}
props={{ Eth, senderAddress, loading }}
props={{ Evm, senderAddress, loading }}
/>
)}

Expand Down
173 changes: 97 additions & 76 deletions src/components/Ethereum/FunctionCall.jsx
Original file line number Diff line number Diff line change
@@ -1,118 +1,139 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useMemo } from "react";

import PropTypes from 'prop-types';
import { forwardRef } from 'react';
import { useImperativeHandle } from 'react';
import PropTypes from "prop-types";
import { forwardRef } from "react";
import { useImperativeHandle } from "react";
import Web3 from "web3";
import { Contract, JsonRpcProvider } from "ethers";

const abi = [
{
inputs: [
{
internalType: 'uint256',
name: '_num',
type: 'uint256',
internalType: "uint256",
name: "_num",
type: "uint256",
},
],
name: 'set',
name: "set",
outputs: [],
stateMutability: 'nonpayable',
type: 'function',
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [],
name: 'get',
name: "get",
outputs: [
{
internalType: 'uint256',
name: '',
type: 'uint256',
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: 'view',
type: 'function',
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: 'num',
name: "num",
outputs: [
{
internalType: 'uint256',
name: '',
type: 'uint256',
internalType: "uint256",
name: "",
type: "uint256",
},
],
stateMutability: 'view',
type: 'function',
stateMutability: "view",
type: "function",
},
];

const contract = '0xe2a01146FFfC8432497ae49A7a6cBa5B9Abd71A3';
const contractAddress = "0xe2a01146FFfC8432497ae49A7a6cBa5B9Abd71A3";

export const FunctionCallForm = forwardRef(({ props: { Eth, senderAddress, loading } }, ref) => {
const [number, setNumber] = useState(1000);
const [currentNumber, setCurrentNumber] = useState('');
export const FunctionCallForm = forwardRef(
({ props: { Evm, senderAddress, loading } }, ref) => {
const [number, setNumber] = useState(1000);
const [currentNumber, setCurrentNumber] = useState("");
const contract = useMemo(() => {
const provider = new JsonRpcProvider("https://sepolia.drpc.org", 11155111);

async function getNumber() {
const result = await Eth.getContractViewFunction(contract, abi, 'get');
setCurrentNumber(String(result));
}
return new Contract(contractAddress, abi, provider);
}, []);

async function getNumber() {
const result = await contract["get"]();
setCurrentNumber(String(result));
}

useEffect(() => {
getNumber();
}, []);

useEffect(() => { getNumber() }, []);
useImperativeHandle(ref, () => ({
async createTransaction() {
const data = contract.interface.encodeFunctionData("set", [number]);

useImperativeHandle(ref, () => ({
async createTransaction() {
const data = Eth.createTransactionData(contract, abi, 'set', [number]);
const { transaction } = await Eth.createTransaction({ sender: senderAddress, receiver: contract, amount: 0, data });
return { transaction };
},
return await Evm.getMPCPayloadAndTransaction({
from: senderAddress,
to: contractAddress,
data: data,
value: Web3.utils.toWei(0, "ether"),
});
},

async afterRelay() { getNumber(); }
}));
async afterRelay() {
getNumber();
},
}));

return (
<>
<div className="row mb-3">
<label className="col-sm-2 col-form-label col-form-label-sm">Counter:</label>
<div className="col-sm-10">
<input
type="text"
className="form-control form-control-sm"
value={contract}
disabled
/>
<div className="form-text">Contract address</div>
return (
<>
<div className="row mb-3">
<label className="col-sm-2 col-form-label col-form-label-sm">
Counter:
</label>
<div className="col-sm-10">
<input
type="text"
className="form-control form-control-sm"
value={contractAddress}
disabled
/>
<div className="form-text">Contract address</div>
</div>
</div>
</div>
<div className="row mb-3">
<label className="col-sm-2 col-form-label col-form-label-sm">
Number:
</label>
<div className="col-sm-10">
<input
type="number"
className="form-control form-control-sm"
value={number}
onChange={(e) => setNumber(e.target.value)}
step="1"
disabled={loading}
/>
<div className="form-text"> The number to save, current value: <b> {currentNumber} </b> </div>
<div className="row mb-3">
<label className="col-sm-2 col-form-label col-form-label-sm">
Number:
</label>
<div className="col-sm-10">
<input
type="number"
className="form-control form-control-sm"
value={number}
onChange={(e) => setNumber(e.target.value)}
step="1"
disabled={loading}
/>
<div className="form-text">
{" "}
The number to save, current value: <b> {currentNumber} </b>{" "}
</div>
</div>
</div>
</div>
</>
);
});
</>
);
}
);

FunctionCallForm.propTypes = {
props: PropTypes.shape({
senderAddress: PropTypes.string.isRequired,
loading: PropTypes.bool.isRequired,
Eth: PropTypes.shape({
createTransaction: PropTypes.func.isRequired,
createTransactionData: PropTypes.func.isRequired,
getContractViewFunction: PropTypes.func.isRequired,
Evm: PropTypes.shape({
getMPCPayloadAndTransaction: PropTypes.func.isRequired,
}).isRequired,
}).isRequired
}).isRequired,
};

FunctionCallForm.displayName = 'EthereumContractView';
FunctionCallForm.displayName = "EthereumContractView";
Loading