-
Notifications
You must be signed in to change notification settings - Fork 1
/
avatar-uploader.html
245 lines (204 loc) · 8.72 KB
/
avatar-uploader.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Avatar uploader</title>
<style type="text/css">
label { display: block; }
fieldset { border: 0; }
label.radio { display: inline-block; }
textarea { display: inline-block; background-color: #f3f2f2; }
input { background-color: #f3f2f2; }
</style>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/json-bigint-browser.min.js"></script>
</head>
<body style='background-color: #f3efe6'>
<form>
<div class='section'>
<h2>avatar uploader (works with SSS extension)</h2>
<h3>🟢 updating should also wor🎉</h3>
<h3>Currently selected (SSS) account <span id="sss-address"></span></h3>
<div style='display: inline-block; vertical-align: top;'>
<p>
<label for="fee-multiplier">Fee multiplier:</label>
<input type="number" name="fee-multiplier" id="fee-multiplier" size="10" value="1000"/>
</p>
<p>
<label for="image-upload">Select image (max 1024 bytes)</label>
<input type='file' id="image-upload" accept=".png, .jpg, .jpeg" />
</p>
</div>
<div style='display: inline-block; border: 1px solid black; width: 50%;'>
<pre id="console-box"></pre>
<figure>
<div id="b32-image"> </div>
<figcaption>avatar preview</figcaption>
</figure>
</div>
<div style="clear:both"></div>
</div>
</form>
<script type="module">
import symbolSdk from './devtools-bundle/bundle.web.js';
const domFeeMultiplier = document.getElementById('fee-multiplier');
const domImageUpload = document.getElementById('image-upload');
const domConsoleBox = document.getElementById('console-box');
const domAppendText = (domElem, textContent) => {
domElem.appendChild(document.createTextNode(textContent));
};
const base64_arraybuffer = (data) => {
// Use a FileReader to generate a base64 data URI
const base64promise = new Promise(resolve => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(new Blob([data]));
});
return base64promise.then(result => result.split(",", 2)[1]);
};
const byteToHex = [];
for (let n = 0; n <= 0xff; ++n) byteToHex.push(n.toString(16).padStart(2, "0"));
const toHex = buffer => {
const hexOctets = new Array(buffer.length)
for (let i = 0; i < buffer.length; ++i)
hexOctets[i] = byteToHex[buffer[i]];
return hexOctets.join("");
};
const hexToUint8 = str => {
var bytes = new Uint8Array(Math.floor(str.length / 2));
for (let i = 0; i < bytes.length; i++)
bytes[i] = parseInt(str.substr(i * 2, 2), 16);
return bytes;
};
const wait = delay => new Promise(resolve => setTimeout(resolve, delay));
const fetchRetry = (url, delay, tries, fetchOptions = {}) =>
fetch(url, fetchOptions)
.then(response => {
if (!response.ok) {
domAppendText(domConsoleBox, '.');
console.log('fetch http error', response.status);
if (!--tries) {
return new Promise((resolve, reject) => reject('exceeded max tries'));
}
return wait(delay).then(() => fetchRetry(url, delay, tries, fetchOptions));
} else {
return response;
}
});
const pickNode = () => {
return fetch('https://symbol.services/nodes?filter=suggested&limit=10&ssl=true')
.then(response => response.json())
.then(data => data[0].apiStatus.restGatewayUrl);
}
if (typeof isAllowedSSS != 'undefined' && isAllowedSSS()) {
const signerPublicKey = window.SSS.activePublicKey;
const targetAddress = window.SSS.activeAddress;
const facade = new symbolSdk.facade.SymbolFacade('mainnet');
document.getElementById('sss-address').innerText = targetAddress;
const createImageChangeHandler = reader => () => {
if (reader.result.byteLength > 1024) {
domAppendText(domConsoleBox, 'selected image is too large\n');
return;
}
// convert image to base64 and display image
base64_arraybuffer(reader.result)
.then(imageData => {
const timg = new Image();
timg.src = `data:image/jpg;base64,${imageData}`;
const imgElem = document.getElementById('b32-image');
imgElem.replaceChild(timg, imgElem.childNodes[0]);
});
const avatarValue = new Uint8Array(reader.result);
pickNode()
.then(restGateway => {
domAppendText(domConsoleBox, `picked node: ${restGateway}\n`)
domAppendText(domConsoleBox, `retrieving existing metadata\n`)
fetch(`${restGateway}/metadata?targetAddress=${targetAddress}&scopedMetadataKey=0000524154416541`)
.then(response => response.json())
.then(metadata_response => metadata_response.data[0] ? hexToUint8(metadata_response.data[0].metadataEntry.value) : null)
.then(existingEntry => ({ oldValue: existingEntry, newValue: symbolSdk.symbol.metadataUpdateValue(existingEntry, avatarValue) }))
.then(oldNewObj => {
let valueSizeDelta = oldNewObj.newValue.length - (oldNewObj.oldValue ? oldNewObj.oldValue.length : 0);
// create transaction
domAppendText(domConsoleBox, 'all ok, preparing transaction\n');
const embeddedDescriptor = {
'type': 'account_metadata_transaction_v1',
'signerPublicKey': signerPublicKey,
'scopedMetadataKey': 0x524154416541n,
'targetAddress': targetAddress,
'value': oldNewObj.newValue,
'valueSizeDelta': valueSizeDelta
};
const embeddedMetadataTransaction = facade.transactionFactory.createEmbedded(embeddedDescriptor);
const transaction = facade.transactionFactory.create({
'type': 'aggregate_complete_transaction_v2',
'signerPublicKey': signerPublicKey,
'transactionsHash': symbolSdk.facade.SymbolFacade.hashEmbeddedTransactions([embeddedMetadataTransaction]),
'transactions': [embeddedMetadataTransaction]
});
// set transaction fee
const feeMultiplier = BigInt(parseInt(domFeeMultiplier.value, 10));
transaction.fee = new symbolSdk.symbol.Amount(feeMultiplier * BigInt(transaction.size))
domAppendText(domConsoleBox, `maximal transaction fee ${transaction.fee.value} (hex ${transaction.fee})\n`);
return transaction;
})
.then(transaction => {
// get timestamp and prepare deadline 1h in future
return fetch(`${restGateway}/node/time`)
.then(response => response.json())
.then(timestamps => {
const timestamp = new facade.network.NetworkTimestampClass(timestamps.communicationTimestamps.sendTimestamp);
const deadline = timestamp.addHours(1);
const displayedDeadline = facade.network.toDatetime(deadline);
domAppendText(domConsoleBox, `current timestamp ${timestamp}, setting deadline: ${displayedDeadline}\n`);
transaction.deadline = new symbolSdk.symbol.Timestamp(deadline.timestamp);
return transaction;
});
}).then(transaction => {
const serializedTransaction = transaction.serialize();
// old js api is dumb and needs serialized tx in hex
const hexed = toHex(serializedTransaction);
window.SSS.setTransactionByPayload(hexed);
return window.SSS.requestSign();
}).then(signedTransaction => {
domAppendText(domConsoleBox, `transaction hash: ${signedTransaction.hash}\n`);
domAppendText(domConsoleBox, `got signed payload, announcing to the network 🤞\n`);
return fetch(`${restGateway}/transactions`, {
method: "PUT",
cache: "no-cache",
credentials: "same-origin",
headers: { "Content-Type": "application/json", },
redirect: "follow",
referrerPolicy: "no-referrer",
body: JSON.stringify({ payload: signedTransaction.payload }),
})
.then(response => response.json())
.then(announcement_response => {
console.log(announcement_response);
domAppendText(domConsoleBox, `got response: ${announcement_response.message}\n`)
return wait(100)
.then(() => fetchRetry(`${restGateway}/transactionStatus/${signedTransaction.hash}`, 150, 10))
.then(response => response.json())
.then(transactionStatus_response => {
domAppendText(domConsoleBox, `transaction group: ${transactionStatus_response.group}\n`)
})
})
});
});
};
domImageUpload.addEventListener('change', () => {
const file = domImageUpload.files[0];
const reader = new FileReader();
reader.onloadend = createImageChangeHandler(reader);
// trigger read
if (file) {
reader.readAsArrayBuffer(file);
} else {
domAppendText(domConsoleBox, 'no file provided\n');
}
}, true);
} else {
domAppendText(domConsoleBox, 'SSS extension needs to be allowed on this page\n');
}
</script>
</body>
</html>