-
-
Save AliWisam/2c966840f789e4a7d0f268e555159218 to your computer and use it in GitHub Desktop.
Sign transaction without sending via Metamask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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