Skip to content

Instantly share code, notes, and snippets.

@DeRain
Created July 29, 2020 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DeRain/39fae070c7b5edfd21efd2cb7a50b68c to your computer and use it in GitHub Desktop.
Save DeRain/39fae070c7b5edfd21efd2cb7a50b68c to your computer and use it in GitHub Desktop.
Sign transaction without sending via Metamask
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment