-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
889 lines (744 loc) · 24.7 KB
/
index.js
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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
import MyAlgo from "@randlabs/myalgo-connect";
//import WalletConnect from "@walletconnect/client";
//import { WalletConnectModalSign } from "@walletconnect/modal-sign-html";
//import QRCodeModal from "algorand-walletconnect-qrcode-modal";
import { formatJsonRpcRequest } from "@json-rpc-tools/utils";
import createAsaTxn from "./createAsaTxn.js";
import {
getAppIndex,
getAsaIndex,
readGlobalState,
u8array,
} from "./teal_utils.js";
import algosdk from "algosdk";
import {
configAlgosdk,
configClient,
configIndexer,
sendTxns,
} from "./utils.js";
import "regenerator-runtime";
//import PipeWallet from "./pwallet.js";
import Escrow from "./escrow.js"
//in order to solve undiagnosed "missing parenthetical" error, PeraWallet cannot be installed via there instructions. In order to integrate PeraWallet, prior to building Pipeline, in terminal run: cd connect && npm install
import { PeraWalletConnect } from '@perawallet/connect'
import encodeUint64 from "./encode64.js";
export { sendTxns, Escrow, /*PipeWallet*/}
//Note: this class is a work in progress. May be unstable. Roll back to version 1.2.7 if issues encountered
export default class Pipeline {
static alerts = true;
static EnableDeveloperAPI = false;
static indexer = "http://localhost:8980";
static algod = "http://localhost:4001";
static token =
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
static devGenHash = "sC3P7e2SdbqKJK0tbiCdK9tdSpbe6XeCGKdoNzmlj0E=";
static devGenId = "devnet-v1.0";
static index = 0;
static pipeConnector = "myAlgoWallet";
static chainId = 0;
static main = true;
static address = "";
static txID = "";
static myBalance = 0;
/* static connector = new WalletConnect({
bridge: "https://bridge.walletconnect.org", // Required
qrcodeModal: QRCodeModal,
}); */
static wcId = "85663294acf9ea5f7b367dbf260038bc"
static connector = {}
/*
static connector = new WalletConnectModalSign({
projectId: Pipeline.wcId,
metadata: {
name: "My Dapp",
description: "My Dapp description",
url: "https://my-dapp.com",
icons: ["https://my-dapp.com/logo.png"],
},
});
*/
static init = () => { return new MyAlgo } //backwards compatibility
static wallet = new MyAlgo();
static PeraWallet = new PeraWalletConnect()
static async balance(address) {
let indexerURL = configIndexer(this.main, this.EnableDeveloperAPI, this);
let url2 = indexerURL + "/v2/accounts/" + address;
try {
let data = await fetch(url2);
let data2 = await data.json();
let data3 = JSON.stringify(data2.account.amount / 1000000);
this.myBalance = data3;
return data3;
} catch (error) {
console.log(error);
return 0;
}
}
static async readAccount(address) {
let indexerURL = configIndexer(this.main, this.EnableDeveloperAPI, this);
let url2 = indexerURL + "/v2/accounts/" + address;
try {
let data = await fetch(url2);
let data2 = await data.json();
return data2
} catch (error) {
console.log(error);
return error;
}
}
static async connect(wallet) {
switch (this.pipeConnector) {
case "myAlgoWallet":
try {
const accounts = await this.wallet.connect();
let item1 = accounts[0];
item1 = item1["address"];
this.address = item1;
} catch (err) {
console.error(err);
}
break;
case "PeraWallet":
let newAccounts = await this.PeraWallet.connect()
this.address = newAccounts[0];
/* try {
const peraAccounts = await this.PeraWallet.reconnectSession()
if (peraAccounts.length > 0) {
this.PeraWallet.connector?.on("disconnect", function () {
Pipeline.PeraWallet.disconnect()
Pipeline.address = ""
})
this.address = peraAccounts[0]
}
else { }
}
catch (error) {
let newAccounts = await this.PeraWallet.connect()
// Setup the disconnect event listener
this.PeraWallet.connector?.on("disconnect", function () {
Pipeline.PeraWallet.disconnect()
Pipeline.address = ""
})
this.address = newAccounts[0];
}*/
break;
case "WalletConnect":
try {
alert("Wallet Connect no longer supported due to mind-blowing stupidity")
} catch (err) {
alert(err);
}
break;
case "AlgoSigner":
if (typeof AlgoSigner !== "undefined") {
await AlgoSigner.connect();
let data = await AlgoSigner.accounts({
ledger: this.main === true ? "MainNet" : "TestNet",
});
this.address = data[0].address;
} else {
alert("AlgoSigner is NOT installed.");
}
break;
/*case "PipeWallet":
PipeWallet.openWallet();
break;
*/
case "escrow":
Pipeline.address = Escrow.address
break;
default:
break;
}
return this.address;
}
static async sign(mytxnb, group = false, signed = []) {
console.log(mytxnb);
let signedTxn = "";
if (this.pipeConnector === "myAlgoWallet") {
if (!group) {
signedTxn = await this.wallet.signTransaction(mytxnb.toByte());
signedTxn = signedTxn.blob;
return signedTxn;
} else {
signedTxn = await this.wallet.signTransaction(
mytxnb.map((txn) => txn.toByte())
);
let txnsb = [];
signedTxn.forEach((item) => {
txnsb.push(item.blob);
});
return txnsb;
}
}
else {
if (this.pipeConnector === "PeraWallet") {
try {
if (!group) {
signedTxn = await this.PeraWallet.signTransaction([[{ txn: mytxnb, signers: [Pipeline.address] }]]);
return signedTxn[0];
}
else {
let index = 0
let groupToSign = []
mytxnb.forEach((txn) => {
groupToSign.push([{ txn: txn, signers: [signed[index] || Pipeline.address] }])
index++
})
signedTxn = await this.PeraWallet.signTransaction(groupToSign)
let txnsb = [];
signedTxn.forEach((item) => {
txnsb.push(item)
})
return txnsb
}
}
catch (e) {
window.pipelineErrors.push(e)
}
}
else {
if (this.pipeConnector === "PipeWallet") {
/*
PipeWallet.openWallet();
PipeWallet.previewTxn(mytxnb);
let approved = await PipeWallet.waitForApproval();
if (approved) {
if (!group) {
let signedTxn = PipeWallet.sign(mytxnb);
PipeWallet.clearPreviewTxn();
PipeWallet.close();
return signedTxn.blob;
} else {
let signedGroup = [];
mytxnb.forEach((transaction) => {
let signed = PipeWallet.sign(transaction);
signedGroup.push(signed.blob);
});
console.log("Signed Group:");
console.log(signedGroup);
return signedGroup;
}
} else {
return {};
}*/
}
else {
if (this.pipeConnector === "escrow") {
if (!group) {
let signedTxn = Escrow.sign(mytxnb);
return signedTxn;
} else {
let signedGroup = [];
mytxnb.forEach((transaction) => {
let signed = Escrow.sign(transaction);
signedGroup.push(signed);
});
console.log("Signed Group:");
console.log(signedGroup);
return signedGroup;
}
}
else {
let txns = [];
if (!group) {
txns[0] = mytxnb;
} else {
txns = mytxnb;
}
console.log("Unencoded txns:");
console.log(txns);
/*
let prototxn = {
"amt": mytxnb.amount,
"fee": 1000,
"fv": mytxnb.lastRound - 1000,
"gen": mytxnb.genesisID,
"gh": new Uint8Array(Buffer.from(mytxnb.genesisHash, 'base64')),
"lv": mytxnb.lastRound,
"note": mytxnb.note,
"rcv": new Uint8Array(base32.decode.asBytes(mytxnb.to).slice(0, 32)),
"snd": new Uint8Array(base32.decode.asBytes(this.address).slice(0, 32)),
"type": "pay"
}
let prototxnASA = {};
let prototxnb = encode(prototxn);
let txns = [];
txns[0] = prototxnb;
if (this.index !== 0) {
prototxnASA = {
"aamt": mytxnb.amount,
"arcv": new Uint8Array(base32.decode.asBytes(mytxnb.to).slice(0, 32)),
"fee": 1000,
"fv": mytxnb.lastRound - 1000,
"gen": mytxnb.genesisID,
"gh": new Uint8Array(Buffer.from(mytxnb.genesisHash, 'base64')),
"lv": mytxnb.lastRound,
"note": mytxnb.note,
"snd": new Uint8Array(base32.decode.asBytes(this.address).slice(0, 32)),
"type": "axfer",
"xaid": parseInt(mytxnb.assetIndex)
}
prototxnb = encode(prototxnASA);
txns[0] = prototxnb;
}
console.log(prototxnb)
console.log(new TextDecoder().decode(prototxnb))
console.log(JSON.stringify(decode(prototxnb)))
*/
// Sign transaction
let txnsToSign = txns.map((txnb) => {
let packed = algosdk.encodeUnsignedTransaction(txnb);
let encodedTxn = Buffer.from(packed).toString("base64");
if (this.pipeConnector === "WalletConnect") {
return {
txn: encodedTxn,
message: "",
// Note: if the transaction does not need to be signed (because it's part of an atomic group
// that will be signed by another party), specify an empty singers array like so:
// signers: [],
};
} else {
return { txn: encodedTxn };
}
});
let nestedArray = []
if (group && signed.length !== 0) {
for (let i = 0; i < signed.length; i++) {
if (signed[i] !== Pipeline.address) {
txnsToSign[i].signers = [];
}
}
}
let requestParams = [txnsToSign]
console.log("TXNs to Sign:");
console.log(requestParams);
if (this.pipeConnector === "WalletConnect") {
alert("Wallet Connect no longer supported due to mind-blowing stupidity")
/*
let request = formatJsonRpcRequest("algo_signTxn", requestParams);
//request.id = this.chainId
console.log(request);
try {
let result = await this.connector.sendCustomRequest(request);
console.log("Response from walletconnect: ", result)
let binarySignedTxs = await result.map((tx) => {
if (tx !== null) {
return new Uint8Array(Buffer.from(tx, "base64"));
}
else { return tx }
});
return !group ? binarySignedTxs[0] : binarySignedTxs;
} catch (error) {
console.log(error);
}
*/} else {
try {
let result = await AlgoSigner.signTxn(requestParams);
console.log("Response from AlgoSigner: ", result)
let binarySignedTxs = await result.map((tx) => {
if (tx !== null) {
return new Uint8Array(Buffer.from(tx.blob, "base64"));
}
else { return tx }
});
return !group ? binarySignedTxs[0] : binarySignedTxs;
} catch (error) {
console.log(error);
}
}
}
}
}
}
}
static makeAppCall(appId, appArgs, params, accounts, assets, applications, boxes) {
let id = parseInt(appId);
let converted = [];
appArgs.forEach((arg) => {
converted.push(
typeof arg === "number" ? encodeUint64(arg) : u8array(arg)
);
});
appArgs = converted;
let txn = algosdk.makeApplicationNoOpTxn(
this.address,
params,
id,
appArgs,
accounts,
applications,
assets,
undefined,
undefined,
undefined,
boxes
);
return txn;
}
static makeTransfer(address, amt, myNote, index = 0, params = {}) {
const buf = new Array(myNote.length);
const encodedNote = new Uint8Array(buf);
for (let i = 0, strLen = myNote.length; i < strLen; i++) {
encodedNote[i] = myNote.charCodeAt(i);
}
console.log("My encoded note: " + encodedNote);
let txn = {
from: this.address,
to: address,
amount: parseInt(amt),
note: encodedNote,
genesisId: params.genesisID,
genesisHash: params.genesisHash,
type: "pay",
flatFee: true,
fee: 1000,
firstRound: parseInt(params["last-round"]),
lastRound: parseInt(params["last-round"] + 1000),
};
if (index !== 0) {
this.index = index;
txn.type = "axfer";
txn.assetIndex = parseInt(index);
txn = algosdk.makeAssetTransferTxnWithSuggestedParams(
txn.from,
txn.to,
undefined,
undefined,
txn.amount,
txn.note,
txn.assetIndex,
params,
undefined
);
} else {
txn = algosdk.makePaymentTxnWithSuggestedParams(
txn.from,
txn.to,
txn.amount,
undefined,
txn.note,
params,
undefined
);
}
txn.fee = 1000;
console.log(txn);
return txn;
}
static async send(address, amt, myNote, _sendingAddress, _wallet, index = 0) {
let client = await configClient(this.main, this.EnableDeveloperAPI, this);
let transServer = client.tranServer;
let params = client.params;
try {
let txn = this.makeTransfer(address, amt, myNote, index, params);
let signedTxn = {};
signedTxn = await this.sign(txn);
console.log(signedTxn);
let transactionID = await sendTxns(
signedTxn,
transServer,
this.EnableDeveloperAPI,
this.token,
this.alerts
);
this.txID = transactionID;
if (transactionID === undefined) {
transactionID = "Transaction failed";
}
return transactionID;
} catch (err) {
console.error(err);
}
}
static async createAsa(asaObject = {}) {
let txn = {};
let client = await configClient(this.main, this.EnableDeveloperAPI, this);
let transServer = client.tranServer;
let params = client.params;
let myNote = asaObject.note || "New Asa";
let buf = new Array(myNote.length);
let encodedNote = new Uint8Array(buf);
for (let i = 0, strLen = myNote.length; i < strLen; i++) {
encodedNote[i] = myNote.charCodeAt(i);
}
asaObject.note = encodedNote;
console.log("My encoded note: " + encodedNote);
txn = createAsaTxn(params, asaObject);
txn.fee = 1000;
console.log(txn);
let signedTxn = {};
signedTxn = await this.sign(txn, false);
console.log(signedTxn);
try {
let transactionID = await sendTxns(
signedTxn,
transServer,
this.EnableDeveloperAPI,
this.token,
this.alerts
);
this.txID = transactionID;
if (transactionID === undefined) {
return "Transaction failed";
} else {
let assetID = await getAsaIndex(transactionID, this.main, this);
console.log(assetID);
return assetID;
}
} catch (err) {
console.error(err);
}
}
static async compileProgram(client, teal) {
let encoder = new TextEncoder();
let programBytes = encoder.encode(teal);
try {
let compileResponse = await client.compile(programBytes).do();
return compileResponse;
} catch (error) {
console.log(error);
}
}
static async deployTeal(
teal = "",
teal2 = "",
bytesInts = [],
appArgs = [],
onComplete = 0
) {
if (teal !== "") {
let algodClient = configAlgosdk(this);
let clientb = await configClient(this.main, this.EnableDeveloperAPI,this);
let transServer = clientb.tranServer;
let compiled = "";
compiled = await this.compileProgram(algodClient, teal);
let compiledClear = await this.compileProgram(algodClient, teal2);
let params = {};
params = await algodClient.getTransactionParams().do();
let converted = [];
appArgs.forEach((arg) => {
converted.push(
typeof arg === "number" ? encodeUint64(arg) : u8array(arg)
);
});
appArgs = converted;
console.log(appArgs);
let lbytes = bytesInts[0];
let gbytes = bytesInts[1];
let lints = bytesInts[2];
let gints = bytesInts[3];
let txn = algosdk.makeApplicationCreateTxnFromObject({
suggestedParams: params,
from: this.address,
numLocalByteSlices: lbytes,
numGlobalByteSlices: gbytes,
numLocalInts: lints,
numGlobalInts: gints,
appArgs: appArgs,
approvalProgram: new Uint8Array(Buffer.from(compiled.result, "base64")),
clearProgram: new Uint8Array(
Buffer.from(compiledClear.result, "base64")
),
onComplete: onComplete,
});
try {
let signedTxn = await this.sign(txn);
console.log(signedTxn);
let response = await sendTxns(
signedTxn,
transServer,
this.EnableDeveloperAPI,
this.token,
this.alerts
);
console.log(response);
this.txID = response;
let appId = await getAppIndex(response, this.main, this);
console.log(appId);
if (appId === undefined) {
appId = "Transaction failed";
}
return appId;
} catch (error) {
console.log(error);
}
} else {
console.log("Teal program or clear program empty");
}
}
static async optIn(appId = 0, appArgs = []) {
let algodClient = configAlgosdk(this);
let clientb = await configClient(this.main, this.EnableDeveloperAPI, this);
let transServer = clientb.tranServer;
let params = await algodClient.getTransactionParams().do();
let converted = [];
appArgs.forEach((arg) => {
converted.push(
typeof arg === "number" ? algosdk.encodeUint64(arg) : u8array(arg)
);
});
appArgs = converted;
let txn = "";
txn = algosdk.makeApplicationOptInTxnFromObject({
suggestedParams: params,
from: this.address,
appIndex: parseInt(appId),
appArgs: appArgs,
});
try {
let signedTxn = await this.sign(txn);
console.log(signedTxn);
let response = await sendTxns(
signedTxn,
transServer,
this.EnableDeveloperAPI,
this.token,
this.alerts
);
console.log(response);
return response;
} catch (error) {
console.log(error);
}
}
static async appCall(
appId,
appArgs,
accounts = undefined,
assets = undefined,
applications = undefined,
boxes = undefined
) {
let clientb = await configClient(this.main, this.EnableDeveloperAPI,this);
let transServer = clientb.tranServer;
let params = clientb.params;
let txn = this.makeAppCall(
appId,
appArgs,
params,
accounts,
assets,
applications,
boxes
);
try {
let signedTxn = await this.sign(txn);
console.log(signedTxn);
let response = await sendTxns(
signedTxn,
transServer,
this.EnableDeveloperAPI,
this.token,
this.alerts
);
console.log(response);
return response;
} catch (error) {
console.log(error);
}
}
static async getParams() {
let client = await configClient(this.main, this.EnableDeveloperAPI, this);
return client.params;
}
static async deleteApp(appId = 0) {
let algodClient = configAlgosdk(this);
let params = await algodClient.getTransactionParams().do();
let txn = algosdk.makeApplicationDeleteTxnFromObject({
suggestedParams: params,
from: this.address,
appIndex: parseInt(appId),
});
let signedTxn = await this.sign(txn);
let clientb = await configClient(this.main, this.EnableDeveloperAPI, this);
let transServer = clientb.tranServer;
try {
let response = await sendTxns(
signedTxn,
transServer,
this.EnableDeveloperAPI,
this.token,
this.alerts
);
console.log(response);
return response;
} catch (error) {
console.log(error);
}
}
static async appCallWithTxn(
appId = 0,
appArgs = [],
reciever = "",
amount = 0,
note = "",
index = 0,
accounts = undefined,
assets = undefined
) {
let id = parseInt(appId);
let algodClient = configAlgosdk(this);
let clientb = await configClient(this.main, this.EnableDeveloperAPI, this);
let params = clientb.params;
let txns = [
this.makeAppCall(id, appArgs, params, accounts, assets),
this.makeTransfer(reciever, amount, note, index, params),
];
txns = algosdk.assignGroupID(txns);
console.log(txns);
let signedTxn = await this.sign(txns, true);
console.log(signedTxn);
try {
let response = await algodClient.sendRawTransaction(signedTxn).do();
if (response.txId !== undefined) {
return response.txId;
} else {
if (this.alerts) {
alert(response.message);
}
}
} catch (error) {
console.log(error);
}
}
static async getAppCreator(appid) {
let data = undefined;
let dataObj = undefined;
let id = undefined;
let url = "";
url = configIndexer(this.main, this.EnableDeveloperAPI, this);
data = await fetch(url + "/v2/applications/" + parseInt(appid));
dataObj = await data.json();
id = await dataObj.application.params.creator;
return id;
}
static async readGlobalState(appId) {
let data = await readGlobalState(this.main, appId, this);
return data;
}
}
window.pipeline = Pipeline
//window.PipeWallet = PipeWallet
window.pipeEscrow = Escrow
window.pipelineErrors = []
/* usage
update balance at intervals:
componentDidMount() {
this.interval = setInterval(() => this.setState({balance: Pipeline.myBalance}), 1000);
}
var balance = 0;
Pipeline.balance(address).then(data => balance = data);
const myAlgoWallet = Pipeline.init();
//useTestNet
Pipeline.main = false;
Pipeline.connect(myAlgoWallet)
.then(data => {
console.log(data);
});
Pipeline.send(address, amount, note, sendingAddress, myAlgowallet, index)
.then(data => {
console.log(data);
});
*/