-
Notifications
You must be signed in to change notification settings - Fork 0
/
ibc.html
699 lines (628 loc) · 31.8 KB
/
ibc.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IBC Reference UI</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/[email protected]/lib/anchor-link.bundle.js"></script>
<script src="https://unpkg.com/[email protected]/lib/anchor-link-browser-transport.bundle.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body style="max-width:640px;margin:40px auto;">
<div class="container" style="border:1px solid #64646d;padding:24px;">
<h3 class="text-center">IBC DEMO</h3>
<div class="flexRow" style="margin-top:24px;">
<select onchange="chainChanged()" class="form-select chainSelect" id="sourceChain">
<option value="" disabled selected>Select Source Chain</option>
</select>
<select onchange="chainChanged()" class="form-select chainSelect" id="destinationChain">
<option value="" disabled selected>Select Destination Chain</option>
</select>
</div>
<div class="flexRow" style="margin-top:24px;">
<button style="display:none;" id="sourceLogin" onclick="login('source')" type="button" class="btn btn-success">Login</button>
<button style="display:none;" id="sourceLogout" onclick="logout('source')" type="button" class="btn btn-danger">Logout</button>
<button style="display:none;" id="destinationLogin" onclick="login('destination')" type="button" class="btn btn-success">Login</button>
<button style="display:none;" id="destinationLogout" onclick="logout('destination')" type="button" class="btn btn-danger">Logout</button>
</div>
<hr>
<div class="flexRow" style="margin-top:48px;">
<div class="input-group" style="width:260px;">
<input id="amount" placeholder="Amount" min="0.0001" step="0.0001" type="number"class="form-control"></input>
<div class="input-group-prepend">
<select style="width:120px;" class="form-select tokenSelect" id="sourceAsset">
<option value="" disabled selected>Token</option>
</select>
</div>
</div>
<button id="transferBtn" onclick="transfer()" disabled type="button" class="btn btn-primary">Transfer and Prove</button>
</div>
<div class="box"><section id="status">
<div><div>Fetching tokens available for IBC</div><div class="progressDiv">0%</div></div>
</section></div>
<div style="text-align:center;margin-top:24px;"><button id="resetBtn" onclick="reset()" style="display:none;" type="button" class="btn btn-primary">New Transfer</button></div>
</div>
</body>
<script>
/*
Chain settings (change to connect to different infrastructure)
- nodeUrl: Nodeos API
- txExplorer: TX Explorer prefix
- proofSocket: IBC Proof WS Server
- bridgeContract: Name of account where IBC contract is deployed
- wrapLockContractsArray: Array of the account names of desired wrap lock contracts
*/
const chains = [{
chainId: 'f16b1833c747c43682f4386fca9cbb327929334a762755ebec17f6f23c9b8a12',
nodeUrl: 'https://test.wax.eosusa.io',
name: "waxtestnet",
label: "WAX Testnet",
txExplorer: "https://wax-test.bloks.io/transaction",
proofSocket: "wss://wax-testnet-ibc.goldenplatform.com",
bridgeContract:"antelopeibc2",
wrapLockContractsArray: ["antelopewlk1", "antelopewlk2", "antelopewlk3", "antelopewlk4"],
},{
chainId: '1eaa0824707c8c16bd25145493bf062aecddfeb56c736f6ba6397f3195f33c9f',
nodeUrl: 'https://test.telos.eosusa.io',
txExplorer: "https://explorer-test.telos.net/transaction",
name: "telostestnet",
label: "Telos Testnet",
proofSocket: "wss://telos-testnet-ibc.goldenplatform.com",
bridgeContract:"antelopeibc2",
wrapLockContractsArray: ["antelopewlk1", "antelopewlk2", "antelopewlk3", "antelopewlk4"],
},{
chainId: '5002d6813ffe275d9471a7e3a301eab91c36e8017f9664b8431fbf0e812a0b04',
nodeUrl: 'https://test.ux.eosusa.io',
txExplorer: 'https://testnet.uxnetwork.io/tx',
name: "uxpubtestnet",
label: "UX Public Testnet",
proofSocket: "wss://testnet-ibc.uxnetwork.io",
bridgeContract:"antelopeibc2",
wrapLockContractsArray: ["antelopewlk1", "antelopewlk2", "antelopewlk3", "antelopewlk4"]
},{
chainId: '73e4385a2708e6d7048834fbc1079f2fabb17b3c125b146af438971e90716c4d',
nodeUrl: 'https://jungle4.api.eosnation.io', //api supporting send_transaction2
txExplorer: 'https://jungle4.eosq.eosnation.io/tx',
name: "jungle4",
label: "Jungle 4 Testnet",
proofSocket: "wss://jungle4-ibc.goldenplatform.com",
bridgeContract:"antelopeibc2",
wrapLockContractsArray: ["antelopewlk1", "antelopewlk2", "antelopewlk3", "antelopewlk4"],
version:3.1 //Can fetch from get_info
},{
chainId: '5fff1dae8dc8e2fc4d5b23b2c7665c97f9e9d8edf2b6485a86ba311c25639191',
nodeUrl: 'https://kylin.api.eosnation.io', //api supporting send_transaction2
txExplorer: 'https://kylin.eosq.eosnation.io/tx',
name: "kylin",
label: "Kylin Testnet",
proofSocket: "wss://kylin-ibc.goldenplatform.com",
bridgeContract:"antelopeibc2",
wrapLockContractsArray: ["antelopewlk1", "antelopewlk2", "antelopewlk3", "antelopewlk4"],
version:3.1 //Can fetch from get_info
}];
for (var chain of chains){
chain.session = null;
chain.symbols = null;
chain.auth = null;
chain.wrapLockContracts = [];
}
let sourceChain, destinationChain, tokenRow, fetchProgress=0,progressInterval;
fetchTokens();
async function fetchTokens(){
//fetch wraplock contracts tokens & details
let promises = [];
let allWraplockContracts = []
//get global and contractmap rows from each chain
for (var chain of chains) for (var wrapLockContract of chain.wrapLockContractsArray) {
allWraplockContracts.push(wrapLockContract);
promises.push(
$.post(`${chain.nodeUrl}/v1/chain/get_table_rows`, JSON.stringify({ json: true, code: wrapLockContract, scope: wrapLockContract, table: 'global'})),
$.post(`${chain.nodeUrl}/v1/chain/get_table_rows`, JSON.stringify({ json: true, code: wrapLockContract, scope: wrapLockContract, table: 'contractmap'}))
)
}
const initialResults = (await Promise.all(promises)).map(r=>r.rows);
fetchProgress+=50;
$('.progressDiv').last().html(fetchProgress+"%");
let groupedResults = [];
while(initialResults.length > 2) groupedResults.push(initialResults.splice(0, 2));
let tokenPromises = []
for (var result of groupedResults){
const global = result[0][0];
const contractMaps = result[1];
for (var map of contractMaps){
const chain = chains.find(c=>c.chainId === global.chain_id);
if (!chain) continue;
tokenPromises.push($.post(`${chain.nodeUrl}/v1/chain/get_table_by_scope`, JSON.stringify({ code: map.native_token_contract, table: 'stat'})))
}
}
const tokenResults = await Promise.all(tokenPromises);
let tokenResultsIndex = 0;
for (var result of groupedResults){
const global = result[0][0];
const contractMaps = result[1];
for (var map of contractMaps){
const chain = chains.find(c=>c.chainId === global.chain_id);
const pairedChain = chains.find(c=>c.chainId === global.paired_chain_id);
if (!chain) continue;
let symbolsres = tokenResults[tokenResultsIndex];
let symbols = symbolsres.rows.map(r => toName(nameToUint64(r.scope)));
console.log(`${chain.name} -> ${pairedChain.name} tokens: ${symbols}`)
chain.wrapLockContracts.push({
chain_id: global.chain_id,
wrapLockContract: allWraplockContracts[tokenResultsIndex],
nativeTokenContract: map.native_token_contract,
pairedChainId: global.paired_chain_id,
pairedWrapTokenContract: map.paired_wraptoken_contract,
symbols
});
tokenResultsIndex++;
}
}
console.log("chains",chains)
$('.progressDiv').last().html("100%");
//on DOM ready
$(async function() {
//add chain options to chain select elements
for (var chain of chains) {
$('#sourceChain').append(new Option(chain.label, chain.name));
$('#destinationChain').append(new Option(chain.label, chain.name));
}
});
}
//handler for source chain change
const chainChanged = () =>{
//clear Token select options
$('#sourceAsset').find('option').remove().end();
$('#sourceAsset').find('optgroup').remove().end();
let sourceName = $('#sourceChain').val();
let destinationName = $('#destinationChain').val();
sourceChain = chains.find(c=>c.name == sourceName);
destinationChain = chains.find(c=>c.name == destinationName);
if (sourceName === destinationName || !destinationName){
destinationChain = chains.find(c=>c.name !== sourceName);
$("#destinationChain").val(destinationChain.name);
}
$('#status').html("<div><div>Fetching tokens available for IBC</div><div class='progressDiv'>100%</div></div>");
logout("source");
logout("destination");
// $('#sourceLogin').show();
// $('#destinationLogin').show();
let id = 1, nativeList = [], wrappedList = [];
for (var row of sourceChain.wrapLockContracts.filter(r=>r.pairedChainId ==destinationChain.chainId)) for (var symbol of row.symbols) {
nativeList.push({ ...row, id, symbol, sourceTokenContract: row.nativeTokenContract, destinationTokenContract: row.pairedWrapTokenContract, native: true });
id++;
}
nativeList = nativeList.sort((a, b) => (a.symbol > b.symbol ? 1 : -1));
id = 1000;
for (var row of destinationChain.wrapLockContracts.filter(r=>r.pairedChainId ==sourceChain.chainId)) for (var symbol of row.symbols) {
wrappedList.push({ ...row, id, symbol, sourceTokenContract: row.pairedWrapTokenContract, destinationTokenContract: row.nativeTokenContract, native: false });
id++;
}
wrappedList = wrappedList.sort((a, b) => (a.symbol > b.symbol ? 1 : -1));
sourceChain.symbols = [...nativeList, ...wrappedList];
//set Token select options
let optionsHtml = `<optgroup label="Native">`
for (var r of sourceChain.symbols.filter(r=>r.native)) optionsHtml+=`<option value=${r.id}>${r.symbol}</option>`;
optionsHtml+=`</optgroup><optgroup label="Wrapped">`;
for (var r of sourceChain.symbols.filter(r=>!r.native)) optionsHtml+=`<option value=${r.id}>${r.symbol}</option>`;
optionsHtml+=`</optgroup>`;
$('#sourceAsset').append(optionsHtml);
}
//UI functions
const login = type => {
const chain = chains.find(c=>c.name===$(`#${type}Chain`).val());
const link = new AnchorLink({
transport: new AnchorLinkBrowserTransport(),
chains: [{ chainId: chain.chainId, nodeUrl: chain.nodeUrl}]
})
link.login("IBC")
.then((result) => {
chain.session = result.session;
chain.auth = { actor:chain.session.auth.actor.toString(), permission: chain.session.auth.permission.toString()}
$(`#${type}Login`).hide();
$(`#${type}Logout`).text(`Logout ${chain.auth.actor}@${chain.auth.permission}`);
$(`#${type}Logout`).show();
$(`#${type}Chain`).prop('disabled', true);
$(`#transferBtn`).prop('disabled', chains.filter(r=>[sourceChain.name, destinationChain.name].includes(r.name)).map(r=>r.session).includes(null));
})
.catch(ex=> alert(ex));
}
const logout = type => {
const chain = chains.find(c=>c.name===$(`#${type}Chain`).val());
$(`#${type}Logout`).hide();
$(`#${type}Login`).show();
$(`#${type}Chain`).prop('disabled', false);
$(`#transferBtn`).prop('disabled', true);
if (!chain || !chain.session) return;
chain.session?.remove();
chain.session = null;
chain.auth = null;
}
const lock = () => {
$(`#transferBtn`).prop('disabled', true);
$(`#sourceLogout`).prop('disabled', true);
$(`#destinationLogout`).prop('disabled', true);
$(`#sourceAsset`).prop('disabled', true);
$(`#amount`).prop('disabled', true);
}
const reset = () =>{
$('#resetBtn').hide();
$('#status').html("<div><div>Fetching tokens available for IBC</div><div class='progressDiv'>100%</div></div>");
$(`#transferBtn`).prop('disabled', false);
$(`#sourceLogout`).prop('disabled', false);
$(`#destinationLogout`).prop('disabled', false);
$(`#sourceAsset`).prop('disabled', false);
$(`#amount`).prop('disabled', false);
// logout('destination');
// logout('source');
}
//transfer function to lock or retire tokens
const transfer = async () => {
//get values form UI
tokenRow = sourceChain.symbols.find(r=>r.id===parseInt($('#sourceAsset').val()));
let amount = parseFloat($("#amount").val());
//fetch token decimal places from native chain
const statChain = chains.find(r=>r.chainId===tokenRow.chain_id);
const statResult = await $.post(`${statChain.nodeUrl}/v1/chain/get_table_rows`, JSON.stringify({
json: true,
code: tokenRow.nativeTokenContract,
scope: tokenRow.symbol,
table: 'stat',
limit:1
}))
const decimals = statResult.rows[0].supply.split('.')[1].split(' ')[0].length;
console.log("decimals",decimals)
const quantity = `${amount.toFixed(decimals)} ${tokenRow.symbol}`;
let sourceActions;
if (tokenRow.native) sourceActions = [ transferToken({ tokenRow, sourceChain, destinationChain, quantity })]; //transfer token to the wraplock token
else sourceActions = [ retireWrappedToken({ tokenRow, sourceChain, destinationChain, quantity }) ]; //retire tokens from a non-native chain
console.log("sourceActions",sourceActions)
lock();
//sign tx w/o broadcasting
let signedTx;
try{
console.log("sourceActions",sourceActions)
signedTx = await sourceChain.session.transact({actions: sourceActions}, {broadcast:false, expireSeconds:360, blocksBehind:3});
console.log("signedTx",signedTx)
}catch(ex){
$('#resetBtn').show();
console.log("ex", ex)
$('#status').append("<br>");
$('#status').append(ex);
return
}
$('#status').append(`<div><div>Waiting for TX irreversibility <span id="lockTx" style="margin-left:12px"></span></div><div class="progressDiv">0%</div></div>`);
let prog = 0;
progressInterval = setInterval(()=>{
prog = Math.min(prog +1, 100);
$('.progressDiv').last().html(prog +"%");
}, 1700);
submitTx(signedTx, sourceChain ).then( async result => {
clearInterval(progressInterval); //clear progress interval
$('.progressDiv').last().html("100%");
$('#lockTx').html(`<a target="_blank" style="color:#1a8754" href="${sourceChain.txExplorer}/${result.processed.id}">${tokenRow.native?'Lock TX':'Retire TX'}<a>`)
console.log(result) // processed tx of transfer/retire
let emitxferAction = result.processed.action_traces.find(r=>r.act.name==='emitxfer'); //if flattened traces (using send_transaction)
if (!emitxferAction){ //if api returns inline traces within action_trace (using push_transaction) shouldnt be used now
const lockActionTrace = result.processed.action_traces.find(r=>r.act.name==='transfer' || r.act.name==='retire');
emitxferAction = lockActionTrace.inline_traces.find(r=>r.act.name==='emitxfer');
console.log("!!!!!!!!!!!!!!!Shouldn't happen!!!!!!!!!!!!!!!!")
}
console.log("emitxferAction to prove", emitxferAction);
//Get schedule proofs;
const scheduleProofs = await getScheduleProofs(result.processed.block_num);
console.log("scheduleProofs",scheduleProofs)
if (!scheduleProofs) {
$('#resetBtn').show();
return $('#status').append(`<div><div>Error, no schedule proofs</div><div class="progressDiv"></div></div>`);
}
$('#status').append(`<div><div>Fetching proof for interchain transfer</div><div class="progressDiv">0%</div></div>`);
const emitxferProof = await getProof({
type: "heavyProof",
action: emitxferAction,
block_to_prove: result.processed.block_num //block that includes the emitxfer action we want to prove
});
console.log("emitxferProof",emitxferProof)
//submit proof to destination chain's bridge contract
let destinationActions = [...scheduleProofs, emitxferProof];
console.log("destinationActions",destinationActions)
$('#status').append(`<div><div>Submitting proof(s)<span id="proofTx" style="margin-left:12px"></span></div> <div class="progressDiv">0%</div></div>`);
const signedDestinationTx = await destinationChain.session.transact({actions: destinationActions}, {broadcast:false, expireSeconds:360, blocksBehind:3});
$('.progressDiv').last().html("50%");
if (!signedDestinationTx || !signedDestinationTx.signatures) return $('#status').append(`<div>Error signing TX</div>`);
submitTx(signedDestinationTx, destinationChain, 6 ).then( async result => {
$('.progressDiv').last().html("100%");
console.log("result", result);
$('#proofTx').html(`<a target="_blank" style="color:#1a8754" href="${destinationChain.txExplorer}/${result.processed.id}">Proof TX<a>`)
$('#resetBtn').show();
}).catch(async err=>{
$('.progressDiv').last().html("Error");
console.log("Error pushing proof", err);
if(progressInterval) clearInterval(progressInterval);
$('#status').append(`<br><div>Error submitting proof(s): </div>`);
$('#status').append(`${err.responseJSON.error.details[0].message}</div>`);
$('#resetBtn').show();
})
})
.catch(err2=>{
console.log("Error submitting TX", err2);
if(progressInterval) clearInterval(progressInterval);
$('#status').append(`<br><div>Error submitting TX: </div>`);
$('#status').append(`${err2.responseJSON.error.details[0].message}</div>`);
$('#resetBtn').show();
})
}
const getScheduleProofs = async (transferBlock) => {
async function getProducerScheduleBlock(blocknum) {
try{
const sourceAPIURL = sourceChain.nodeUrl+"/v1/chain";
var header = await $.post(sourceAPIURL + "/get_block", JSON.stringify({"block_num_or_id":blocknum,"json": true}));
let target_schedule = header.schedule_version;
let min_block = 2;
//fetch last proved block to use as min block for schedule change search
const lastBlockProved = await $.post(destinationChain.nodeUrl+ '/v1/chain/get_table_rows', JSON.stringify({
code: destinationChain.bridgeContract,
table: "lastproofs",
scope: sourceChain.name,
limit: 1, reverse: true, show_payer: false, json: true
}));
if (lastBlockProved && lastBlockProved.rows[0]) min_block = lastBlockProved.rows[0].block_height;
let max_block = blocknum;
//detect active schedule change
while (max_block - min_block > 1) {
blocknum = Math.round((max_block + min_block) / 2);
try{
header = await $.post(sourceAPIURL + "/get_block", JSON.stringify({"block_num_or_id":blocknum,"json": true}));
if (header.schedule_version < target_schedule) min_block = blocknum;
else max_block = blocknum;
}catch(ex){console.log("Internet connection lost, retrying")}
}
if (blocknum > 337) blocknum -= 337;
//search before active schedule change for new_producer_schedule
let bCount = 0; //since header already checked once above
while (blocknum < max_block && (!("new_producer_schedule" in header) && !header.new_producers)) {
try{
header = await $.post(sourceAPIURL + "/get_block", JSON.stringify({"block_num_or_id":blocknum,"json": true}));
bCount++;
blocknum++;
}catch(ex){console.log("Internet connection lost, retrying")}
}
blocknum = header.block_num;
return blocknum;
}catch(ex){ console.log("getProducerScheduleBlock ex",ex); return null;}
}
const proofs = [];
const bridgeScheduleData = await $.post(destinationChain.nodeUrl+ '/v1/chain/get_table_rows', JSON.stringify({
code: destinationChain.bridgeContract,
table: "schedules",
scope: sourceChain.name,
limit: 1, reverse: true, show_payer: false, json: true
}));
console.log("bridgeScheduleData",bridgeScheduleData)
var last_proven_schedule_version = 0;
// if (bridgeScheduleData.rows.length > 0) last_proven_schedule_version = bridgeScheduleData.rows[0].producer_schedule.version;
if (bridgeScheduleData.rows.length > 0) last_proven_schedule_version = bridgeScheduleData.rows[0].version;
if (!last_proven_schedule_version) return console.log('No Schedule Found in Contract!');
console.log("Last proved source schedule:",last_proven_schedule_version);
let schedule = (await $.get(sourceChain.nodeUrl+ '/v1/chain/get_producer_schedule'));
var schedule_version = parseInt(schedule.active.version);
console.log("Source active schedule:",schedule_version);
console.log("Pending schedule:", schedule.pending?'True':'False')
let head = (await $.get(sourceChain.nodeUrl+ '/v1/chain/get_info')).head_block_num;
let schedule_block = head + 0;
console.log("head",head)
while (schedule_version > last_proven_schedule_version) {
$('#status').append(`<div><div>Locating block header with producer schedule (v${schedule_version})</div><div class="progressDiv">0%</div></div>`);
let block_num = await getProducerScheduleBlock(schedule_block);
if (!block_num) return; //should never occur
$('.progressDiv').last().html("100%");
$('#status').append(`<div><div>Fetching proof for active schedule (v${schedule_version})</div><div class="progressDiv">0%</div></div>`);
var proof = await getProof({block_to_prove: block_num});
schedule_version = proof.data.blockproof.blocktoprove.block.header.schedule_version;
schedule_block = block_num;
proofs.unshift(proof);
};
// check for pending schedule and prove pending schedule if found;
if (schedule.pending) {
$('#status').append(`<div><div>Fetching proof for pending schedule</div><div class="progressDiv">0%</div>`);
let newPendingBlockHeader=null;
let currentBlock = transferBlock + 0;
while(!newPendingBlockHeader){
let bHeader = (await $.post(`${sourceChain.nodeUrl}/v1/chain/get_block`, JSON.stringify({ block_num_or_id: currentBlock })));
if (bHeader['new_producer_schedule']) newPendingBlockHeader = bHeader;
else currentBlock--;
}
var pendingProof = await getProof({block_to_prove: newPendingBlockHeader.block_num});
proofs.push(pendingProof); //push pending after proving active
}
return proofs;
};
const getProof = ({type="heavyProof", block_to_prove, action}) => {
return new Promise(resolve=>{
//initialize socket to proof server
const ws = new WebSocket(sourceChain.proofSocket);
ws.addEventListener('open', (event) => {
// connected to websocket server
const query = { type, block_to_prove };
if (action) query.action_receipt = action.receipt;
ws.send(JSON.stringify(query));
});
//messages from websocket server
ws.addEventListener('message', (event) => {
const res = JSON.parse(event.data);
//log non-progress messages from ibc server
if (res.type !=='progress') console.log("Received message from ibc proof server", res);
if (res.type =='progress') $('.progressDiv').last().html(res.progress +"%");
if (res.type !=='proof') return;
ws.close();
$('.progressDiv').last().html("100%");
//handle issue/withdraw if proving transfer/retire 's emitxfer action, else submit block proof to bridge directly (for schedules)
const actionToSubmit = {
authorization: [destinationChain.auth],
name: !action ? "checkproofd" : tokenRow.native ? "issuea" : "withdrawa",
account: !action ? destinationChain.bridgeContract : tokenRow.native ? tokenRow.pairedWrapTokenContract : tokenRow.wrapLockContract,
data: { ...res.proof, prover: destinationChain.auth.actor }
};
//if proving an action, add action and formatted receipt to actionproof object
if (action) {
let auth_sequence = [];
for (var authSequence of action.receipt.auth_sequence) auth_sequence.push({ account: authSequence[0], sequence: authSequence[1] });
actionToSubmit.data.actionproof = {
...res.proof.actionproof,
action: {
account: action.act.account,
name: action.act.name,
authorization: action.act.authorization,
data: action.act.hex_data
},
receipt: { ...action.receipt, auth_sequence }
}
}
resolve(actionToSubmit);
});
});
}
const submitTx = (signedTx, chain, retry_trx_num_blocks=null) => {
let leap = chain.version && chain.version >=3;
let url = `${chain.nodeUrl}/v1/chain/send_transaction`;
let obj = {
signatures: signedTx.signatures,
compression: signedTx.compression || false,
packed_trx: arrayToHex(signedTx.resolved.serializedTransaction),
packed_context_free_data: null
}
if (leap){
url+='2'; //use send transaction2 if available
obj = {
transaction: obj,
return_failure_trace: false,
retry_trx: true,
retry_trx_num_blocks, //if not specified, it defaults to LIB
}
return $.post(url, JSON.stringify(obj));
}
return pushGurantee(chain, obj, retry_trx_num_blocks); //if waiting for lib
}
//Add retry logic and waiting for blocks to send_transaction, to emulate send_transaction2 retry_trx_num_blocks
const pushGurantee = async (chain, packedTx, retry_trx_num_blocks ) => new Promise(async resolve=>{
let tx;
try{
tx = await $.post(`${chain.nodeUrl}/v1/chain/send_transaction`, JSON.stringify(packedTx));
console.log("tx",JSON.parse(JSON.stringify(tx)));
}catch(ex){
if(progressInterval) clearInterval(progressInterval);
$('#resetBtn').show();
$('.progressDiv').last().html("0%");
console.log("Exception submitting tx", ex);
$('#status').append(`<br><div>Error submitting TX: </div>`);
$('#status').append(`<div>${ex.responseJSON.error.details[0].message}</div>`);
if (ex.responseJSON.error.details[1]) $('#status').append(`<div>${ex.responseJSON.error.details[1].message}</div>`)
return
}
const transaction_id = tx.processed.id;
let finished = false;
let delay = 500;
while (!finished){
await sleep(delay);
delay*=1.1;
delay=Math.min(delay, 5000)
try{
const block = await $.post(`${chain.nodeUrl}/v1/chain/get_block`, JSON.stringify({block_num_or_id: tx.processed.block_num }));
const txFound = block.transactions.find(r=>r.trx.id === transaction_id);
if (txFound) { //if tx is in block, check relation to retry_trx_num_blocks
const headInfo = await $.get(`${chain.nodeUrl}/v1/chain/get_info`);
// console.log("Blocks passed: ~" + (headInfo.head_block_num - tx.processed.block_num) + "/330", "LIB: " + headInfo.last_irreversible_block_num)
if (
(!retry_trx_num_blocks && headInfo.last_irreversible_block_num >= tx.processed.block_num) || // passed lib
(retry_trx_num_blocks && headInfo.head_block_num - tx.processed.block_num >= retry_trx_num_blocks) // passed blocks specified
) finished = true;
}
else if(!txFound){ //if tx is not in block, resubmit packed tx
try{
tx = await $.post(`${chain.nodeUrl}/v1/chain/send_transaction`, JSON.stringify(packedTx));
console.log("tx not found in block (fork/stale block), resubmitted tx",tx);
}
catch(ex){//handle duplicate tx error, in case it auto got included in next block than reported, check next block and so on
console.log(ex)
//TODO verify exception is duplicate tx error
tx.processed.block_num++;
console.log("exception resubmitting duplicate tx, incremented block number to find tx", tx.processed.block_num)
}
}
}catch(ex){console.log("lost internet, retrying")}
}// end of while
if (retry_trx_num_blocks) return resolve(tx); //return tx if we dont need to worry about correct global action
//fetch from firehose to set correct global sequence (from produced block) in action_receipt
const ws = new WebSocket(sourceChain.proofSocket);
ws.addEventListener('open', (event) => ws.send(JSON.stringify({ type: "getBlockActions", block_to_prove: tx.processed.block_num })));
ws.addEventListener('message', (event) => {
const res = JSON.parse(event.data);
console.log("res",res)
const firhoseTx = res.txs.find(r=>r.find(s=>s.transactionId === transaction_id));
console.log("firhoseTx",firhoseTx)
const firehoseEmitxfer = firhoseTx.find(r=>r.action.name==='emitxfer');
console.log("firehoseEmitxfer",firehoseEmitxfer)
let emitxferAction = tx.processed.action_traces.find(r=>r.act.name==='emitxfer');
console.log("api emitxferAction receipt", JSON.parse(JSON.stringify(emitxferAction.receipt)))
emitxferAction.receipt = firehoseEmitxfer.receipt;
//convert firehose authSequence to expected format for ibc-proof server
let auth_sequence = [];
for (var auth of emitxferAction.receipt.auth_sequence) auth_sequence.push([auth.account, auth.sequence]);
emitxferAction.receipt.auth_sequence = auth_sequence;
console.log("bp emitxferAction receipt",firehoseEmitxfer.receipt)
resolve(tx);
});
})
const sleep = ms => new Promise(resolve=>setTimeout(resolve,ms));
//action creation functions
const transferToken = ({tokenRow, sourceChain, destinationChain, quantity} ) => ({
account: tokenRow.nativeTokenContract,
name: "transfer",
authorization: [sourceChain.auth],
data: { from: sourceChain.auth.actor, to: tokenRow.wrapLockContract, quantity, memo: destinationChain.auth.actor }
});
const retireWrappedToken = ({ tokenRow, sourceChain, destinationChain, quantity }) => ({
account: tokenRow.sourceTokenContract,
name: "retire",
authorization: [sourceChain.auth],
data: { owner: sourceChain.auth.actor, quantity, beneficiary: destinationChain.auth.actor }
});
//eosio name helper functions
const char_to_symbol = c => {
if (typeof c == 'string') c = c.charCodeAt(0);
if (c >= 'a'.charCodeAt(0) && c <= 'z'.charCodeAt(0)) return c - 'a'.charCodeAt(0) + 6;
if (c >= '1'.charCodeAt(0) && c <= '5'.charCodeAt(0)) return c - '1'.charCodeAt(0) + 1;
return 0;
};
const toName = value => {
let v = BigInt.asUintN(64, value), result = '';
while (v > 0) {
const c = v & BigInt(0xff);
result += String.fromCharCode(Number(c.toString()));
v >>= 8n;
}
return result;
};
const nameToUint64 = s => {
let n = 0n, i = 0;
for (; i < 12 && s[i]; i++) n |= BigInt(char_to_symbol(s.charCodeAt(i)) & 0x1f) << BigInt(64 - 5 * (i + 1));
if (i == 12) n |= BigInt(char_to_symbol(s.charCodeAt(i)) & 0x0f);
return n.toString();
};
const arrayToHex = data => {
let result = '';
for (const x of data) result += ('00' + x.toString(16)).slice(-2);
return result.toUpperCase();
};
</script>
<style>
html,body{ background-color: #31313d; color:white; font-family: Verdana, Geneva, Tahoma, sans-serif; }
.flexRow{ display: flex; align-items: center; justify-content: space-between;}
label{ width:70px; text-align: left;color:white; }
.form-select, .form-control, button{ width:272px; }
.form-select:disabled { background-color: #adafb2; }
.box{ padding:16px; border:1px solid #64646d;margin-top:44px; }
.box > div, #status > div{ display:flex; justify-content: space-between; }
</style>
</html>