Skip to content

Instantly share code, notes, and snippets.

@DeRain
Created July 29, 2020 21:53
Show Gist options
  • Save DeRain/39fae070c7b5edfd21efd2cb7a50b68c to your computer and use it in GitHub Desktop.
Save DeRain/39fae070c7b5edfd21efd2cb7a50b68c to your computer and use it in GitHub Desktop.

Revisions

  1. DeRain created this gist Jul 29, 2020.
    70 changes: 70 additions & 0 deletions sign-tx.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    <!doctype html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Metamask sign tx poc</title>
    </head>
    <body>
    <button class="enableEthereumButton btn" type="button">Enable Ethereum</button>
    <button class="sendEthButton btn" type="button">Sign Transaction</button>
    <p>Signed transaction:</p>
    <pre class="txResult"></pre>
    <p>Transaction details</p>
    <pre class="txDetails"></pre>
    <script charset="utf-8"
    src="https://cdn.ethers.io/scripts/ethers-v4.min.js"
    type="text/javascript">
    </script>
    <script>
    const ethereumButton = document.querySelector('.enableEthereumButton');
    const sendEthButton = document.querySelector('.sendEthButton');
    const txResult = document.querySelector('.txResult');
    const txDetails = document.querySelector('.txDetails');
    const utils = ethers.utils;

    function connect() {
    if (typeof ethereum !== 'undefined') {
    ethereum.enable().catch(console.error)
    }
    }

    sendEthButton.addEventListener('click', (e) => {
    e.preventDefault();
    const from = web3.eth.accounts[0]
    if (!from) return connect()

    web3.currentProvider.sendAsync({
    method: 'eth_getTransactionCount',
    params: [from],
    }, function (err, result) {
    const txsCount = utils.bigNumberify(result.result);
    const tx = {
    to: '0x0174965F7ad2442bd158408749138b037A1B98F9',
    nonce: txsCount.toNumber(),
    gasLimit: utils.bigNumberify('60000'),
    gasPrice: utils.bigNumberify('45000000000'),
    value: utils.bigNumberify(0),
    chainId: 1,
    }
    const serializedTxHash = utils.keccak256(utils.serializeTransaction(tx));
    web3.currentProvider.sendAsync({
    method: 'eth_sign',
    params: [from, serializedTxHash],
    }, function (err, result) {
    if (err) return console.error(err);
    const signature = result.result;
    const signedTransaction = utils.serializeTransaction(tx, signature);
    txResult.innerHTML = signedTransaction;
    txDetails.innerHTML = JSON.stringify(utils.parseTransaction(signedTransaction));
    })
    })
    });

    ethereumButton.addEventListener('click', (e) => {
    e.preventDefault();
    connect();
    });
    </script>
    </body>
    </html>