-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
264 lines (249 loc) · 13.2 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<!DOCTYPE html>
<html>
<head>
<title>Web3 Transaction Builder Tool</title>
<script src="https://cdn.jsdelivr.net/npm/web3/dist/web3.min.js"></script>
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; }
.container { max-width: 600px; margin: auto; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }
#input-section-wrapper {margin-bottom: 20px; }
#input-section { border: 1px solid #ccc; padding: .5em; /*padding-right: 1.5em;*/ margin-bottom: 0;}
.input-group { margin-bottom: 15px; }
.input-group input { margin-bottom: 0px; box-sizing: border-box; width: 100%; }
.input-group:last-child { margin-bottom: 5px; }
.input-label { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0; }
.input-group input { width: 100%; padding: .5em; border: 1px solid #ccc; border-radius: 4px; }
.copy-link-container {text-align: right; margin-top: 0; padding-top: 0; vertical-align: top; }
.link-small-text {display: block; font-size: 12px; line-height: 1; }
button { width: 100%; padding: 10px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
button:hover { background-color: #45a049; }
.section-label { margin-bottom: .25em; }
#transactionResult { margin-top: 20px; padding: 10px; border: 1px solid #ddd; }
textarea { box-sizing: border-box; width: 100%; border: 1px solid #ccc; border-radius: 4px; resize: vertical; margin-bottom: 20px; }
.top-links {display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.top-links a:last-child {margin-left: auto; }
.small-text { font-size: 12px; color: #666; margin-left: auto; }
</style>
</head>
<body>
<div class="container">
<div style="padding: 1em">Caution: If you received a link directing you to this tool with pre-filled fields, please ensure the source is trustworthy. Always verify the details before proceeding with any transactions to safeguard against potential misuse.</div>
<div class="top-links">
<a target="_self" href="?to=0x0000000000000000000000000000000000000000&data=0x4445585420746F20746865206D6F6F6E21&chain=5">Example TX</a>
<a target="_self" href="?">[clear all]</a>
</div>
<div id="walletAddress" style="padding: 1em">Enter transaction details then 'Connect Wallet' below</div>
<div id="input-section-wrapper">
<p class="section-label">Transaction Inputs:</p>
<div id="input-section">
<div class="input-group">
<div class="input-label">
<label for="to">To Address:</label>
<span class="small-text">(Recipient address/smart contract)</span>
</div>
<input type="text" id="to" />
</div>
<div class="input-group">
<div class="input-label">
<label for="value">Value (in wei):</label>
<span class="small-text">(E.g. 1 ETH = 1000000000000000000)</span>
</div>
<input type="text" id="value" />
</div>
<div class="input-group">
<div class="input-label">
<label for="data">Data:</label>
<span class="small-text">(Must be in 0x... form)</span>
</div>
<input type="text" id="data" />
</div>
<div class="input-group">
<div class="input-label">
<label for="gas">Gas (optional):</label>
<span class="small-text">(Leave blank to auto-calculate)</span>
</div>
<input type="text" id="gas" />
</div>
<div class="input-group">
<div class="input-label">
<label for="chain">Chain #:</label>
<span class="small-text">(Must be an integer, or blank to use your wallet's current selected chain)</span>
</div>
<input type="text" id="chain" />
</div>
</div>
<div class="copy-link-container">
<a href="#" class="link-small-text" id="copyLink">[Copy a link to this transaction]</a>
</div>
</div>
<button id="connectWallet">Connect Wallet / Build TX</button>
<div id="txnDetailsDiv" style="display:none;">
<p class="section-label">Transaction Payload:</p>
<textarea id="txnDetailsText" rows="14"></textarea>
</div>
<button id="signTransaction" style="display:none;">Sign Transaction</button>
<div id="transactionResult"></div>
</div>
<script>
if (window.ethereum) {
let web3 = new Web3(window.ethereum);
} else {
console.log("Ethereum provider not found. Install MetaMask/Rabby.");
}
let connectedAccount = null;
let explorerURL = null;
// Transaction Parameters init
let transactionParameters = {
from: '',
to: '',
value: '',
data: '',
gasPrice: '',
gas: '',
nonce: '',
chainId: '',
};
function updateTxnDetailsText(txDetails) {
const txDetailsString = JSON.stringify(txDetails, bigIntReplacer, 2);
const formattedTxDetails = txDetailsString.substring(1, txDetailsString.length - 1)
.replace(/,\n\s*/g, '\n').trim(); // Remove braces and replace commas
document.getElementById('txnDetailsText').value = formattedTxDetails;
}
function bigIntReplacer(key, value) {
if (typeof value === 'bigint') {
return value.toString();
}
return value;
}
// Get chainName and explorerURL from chainId
async function getChainInfo(chainId) {
const response = await fetch('https://chainid.network/chains.json');
const chains = await response.json();
const chain = chains.find(c => c.chainId === chainId);
if (chain) {
return { chainName: chain.name, explorerURL: chain.explorers?.[0].url || 'No explorer available' };
} else {
return { chainName: 'Unknown', explorerURL: 'No explorer available' };
}
}
async function switchChain(chainId) {
try {
await ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: `0x${chainId.toString(16)}` }], // Convert chainId to hexadecimal
});
} catch (addError) {
console.error('Error adding chain:', addError);
}
}
// Pre-fill url parameters
document.addEventListener('DOMContentLoaded', () => {
const urlParams = new URLSearchParams(window.location.search);
document.getElementById('to').value = urlParams.get('to') || '';
document.getElementById('value').value = urlParams.get('value') || '';
document.getElementById('data').value = urlParams.get('data') || '';
document.getElementById('gas').value = urlParams.get('gas') || '';
document.getElementById('chain').value = urlParams.get('chain') || '';
});
document.getElementById('copyLink').addEventListener('click', function(e) {
e.preventDefault();
const toValue = document.getElementById('to').value;
const valueValue = document.getElementById('value').value;
const dataValue = document.getElementById('data').value;
const gasValue = document.getElementById('gas').value;
const chainValue = document.getElementById('chain').value;
const url = new URL(window.location.href);
url.searchParams.set('to', toValue);
url.searchParams.set('value', valueValue);
url.searchParams.set('data', dataValue);
url.searchParams.set('gas', gasValue);
url.searchParams.set('chain', chainValue);
navigator.clipboard.writeText(url).then(() => {
alert('Link copied to clipboard!');
}).catch(err => {
console.error('Error copying link:', err);
});
});
// Connect Wallet Button
document.getElementById('connectWallet').addEventListener('click', async function() {
if (window.ethereum) {
try {
document.getElementById('transactionResult').innerHTML = '';
document.getElementById('txnDetailsDiv').style.display = 'block';
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
connectedAccount = Web3.utils.toChecksumAddress(accounts[0]);
// Get the chain that the wallet is currently connected to
const browserConnectedChain = await window.ethereum.request({ method: 'eth_chainId' });
const chainInput = document.getElementById('chain').value;
let inputChainValue;
if (chainInput === '') {
inputChainValue = parseInt(browserConnectedChain, 16); // Use the connected wallet's chain ID
} else {
inputChainValue = parseInt(chainInput, 10); // Convert input value to integer
}
if (!isNaN(inputChainValue)) {
const hexChainValue = `0x${inputChainValue.toString(16)}`;
// Compare and switch chains if the chain input is different
if (browserConnectedChain !== hexChainValue) {
switchChain(inputChainValue);
}
} else {
console.error("Invalid chain input");
}
transactionParameters.chainId = await window.ethereum.request({ method: 'eth_chainId' });
transactionParameters.from = connectedAccount;
updateTxnDetailsText(transactionParameters);
const chainIdInt = parseInt(transactionParameters.chainId, 16);
const { chainName, explorerURL } = await getChainInfo(chainIdInt);
document.getElementById('walletAddress').innerText = 'Connected: ' + connectedAccount + ' on ' + chainName + ' (' + chainIdInt + ')';
try {
transactionParameters.to = Web3.utils.toChecksumAddress(document.getElementById('to').value);
} catch (error) {console.error('Invalid "to" address:', error);} // Set value, convert to hex if not blank
const valueInput = document.getElementById('value').value;
transactionParameters.value = valueInput ? '0x' + BigInt(valueInput).toString(16) : '0x0';
transactionParameters.gasPrice = await window.ethereum.request({ method: 'eth_gasPrice' });
updateTxnDetailsText(transactionParameters);
transactionParameters.nonce = await window.ethereum.request({
method: 'eth_getTransactionCount',
params: [connectedAccount, 'latest']
});
const dataInput = document.getElementById('data').value;
const dataRegex = /^0x[A-Fa-f0-9]*$/; // Looser pattern, just checks for a valid hex string
transactionParameters.data = dataRegex.test(dataInput) ? dataInput : '0x';
updateTxnDetailsText(transactionParameters);
// Check for gas input, calculate if empty
const gasValue = document.getElementById('gas').value;
if (gasValue) {
transactionParameters.gas = Web3.utils.toHex(parseInt(gasValue, 10));
} else {
transactionParameters.gas = await window.ethereum.request({ method: 'eth_estimateGas', params: [transactionParameters] });
}
updateTxnDetailsText(transactionParameters);
document.getElementById('signTransaction').style.display = 'block';
} catch (error) {
console.error('Error connecting to wallet:', error);
}
} else {
console.log('Please install MetaMask!');
}
});
// Sign and Send Transaction Button
document.getElementById('signTransaction').addEventListener('click', async function() {
try {
const txHash = await window.ethereum.request({
method: 'eth_sendTransaction',
params: [transactionParameters],
});
console.log('Transaction Hash:', txHash);
// Display Transaction Hash and Link to Explorer
const chainIdInt = parseInt(transactionParameters.chainId, 16);
const { chainName, explorerURL } = await getChainInfo(chainIdInt);
const explorerLink = explorerURL + '/tx/' + txHash;
document.getElementById('transactionResult').innerHTML = 'Transaction Hash: <a href="' + explorerLink + '" target="_blank">' + txHash + '</a>';
} catch (error) {
console.error('Error in transaction:', error);
}
});
</script>
</body>
</html>