-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.src.js
More file actions
1910 lines (1726 loc) · 51.1 KB
/
main.src.js
File metadata and controls
1910 lines (1726 loc) · 51.1 KB
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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { connect, disconnect, isConnected, request } from "https://esm.sh/@stacks/connect?bundle&target=es2020";
import {
Cl,
Pc,
principalCV,
serializeCV,
} from "https://esm.sh/@stacks/transactions@7.2.0?bundle&target=es2020";
const CHAIN_IDS = {
mainnet: 1n,
testnet: 2147483648n,
devnet: 2147483648n,
mocknet: 2147483648n,
};
const PEER_PROTOCOL_VERSION = "1";
const STORAGE_KEY = "stackflow-console-config-v1";
let connectedAddress = null;
let stackflowNodeCounterpartyEnabled = false;
let stackflowNodeCounterpartyPrincipal = null;
let peerRequestCounter = 0;
const ids = {
serverUrl: "stackflow-node-url",
contractId: "contract-id",
network: "network",
contractVersion: "contract-version",
walletStatus: "wallet-status",
pipesBody: "pipes-body",
sigWith: "sig-with",
sigActor: "sig-actor",
sigToken: "sig-token",
sigTokenAssetName: "sig-token-asset-name",
sigAction: "sig-action",
sigMyBalance: "sig-my-balance",
sigTheirBalance: "sig-their-balance",
sigNonce: "sig-nonce",
sigValidAfter: "sig-valid-after",
sigSecret: "sig-secret",
sigMySignature: "sig-my-signature",
sigTheirSignature: "sig-their-signature",
signaturePayload: "signature-payload",
txResult: "tx-result",
actionHelp: "action-help",
actionSelect: "action-select",
actionSubmitBtn: "action-submit-btn",
callFundAmount: "call-fund-amount",
callAmountLabel: "call-amount-label",
sigMySignatureLabel: "sig-my-signature-label",
sigMySignatureHelp: "sig-my-signature-help",
};
const ACTION_FIELD_IDS = [
"field-sig-with",
"field-sig-token",
"field-sig-token-asset-name",
"field-call-fund-amount",
"field-sig-nonce",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-action",
"field-sig-actor",
"field-sig-valid-after",
"field-sig-secret",
"field-sig-my-signature",
"field-sig-their-signature",
];
const ACTION_DEFS = {
"fund-pipe": {
submitLabel: "Submit fund-pipe",
help: "Create or add initial liquidity to a pipe on-chain.",
amountLabel: "fund-pipe Amount",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-token-asset-name",
"field-call-fund-amount",
"field-sig-nonce",
],
},
deposit: {
submitLabel: "Submit deposit",
help: "Add funds on-chain using signatures from both parties.",
amountLabel: "deposit Amount",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-token-asset-name",
"field-call-fund-amount",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-my-signature",
"field-sig-their-signature",
],
},
withdraw: {
submitLabel: "Submit withdraw",
help: "Withdraw funds on-chain using signatures from both parties.",
amountLabel: "withdraw Amount",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-token-asset-name",
"field-call-fund-amount",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-my-signature",
"field-sig-their-signature",
],
},
"force-cancel": {
submitLabel: "Submit force-cancel",
help: "Start an on-chain cancellation waiting period for this pipe.",
fields: ["field-sig-with", "field-sig-token"],
},
"close-pipe": {
submitLabel: "Submit close-pipe",
help: "Cooperatively close a pipe with both signatures.",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-token-asset-name",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-my-signature",
"field-sig-their-signature",
],
},
"force-close": {
submitLabel: "Submit force-close",
help: "Start a forced closure with signed balances.",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-action",
"field-sig-actor",
"field-sig-secret",
"field-sig-valid-after",
"field-sig-my-signature",
"field-sig-their-signature",
],
},
"finalize": {
submitLabel: "Submit finalize",
help: "Finalize a previously forced closure after the waiting period.",
fields: ["field-sig-with", "field-sig-token", "field-sig-token-asset-name"],
},
"sign-transfer": {
submitLabel: "Sign transfer state",
help: "Generate your signature for an off-chain transfer state.",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-actor",
"field-sig-secret",
"field-sig-valid-after",
"field-sig-my-signature",
],
},
"sign-deposit": {
submitLabel: "Sign deposit state",
help: "Generate your signature for an off-chain deposit state.",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-actor",
"field-sig-secret",
"field-sig-valid-after",
"field-sig-my-signature",
],
},
"sign-withdrawal": {
submitLabel: "Sign withdrawal state",
help: "Generate your signature for an off-chain withdrawal state.",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-actor",
"field-sig-secret",
"field-sig-valid-after",
"field-sig-my-signature",
],
},
"sign-close": {
submitLabel: "Sign close state",
help: "Generate your signature for an off-chain close state.",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-actor",
"field-sig-my-signature",
],
},
"request-counterparty-transfer": {
submitLabel: "Request counterparty transfer signature",
help: "Send your transfer signature to the counterparty and receive their signature.",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-actor",
"field-sig-secret",
"field-sig-valid-after",
"field-sig-my-signature",
"field-sig-their-signature",
],
},
"request-counterparty-deposit": {
submitLabel: "Request counterparty deposit signature",
help: "Send your deposit signature to the counterparty and receive their signature.",
amountLabel: "deposit Amount",
fields: [
"field-sig-with",
"field-sig-token",
"field-call-fund-amount",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-actor",
"field-sig-secret",
"field-sig-valid-after",
"field-sig-my-signature",
"field-sig-their-signature",
],
},
"request-counterparty-withdrawal": {
submitLabel: "Request counterparty withdrawal signature",
help: "Send your withdrawal signature to the counterparty and receive their signature.",
amountLabel: "withdraw Amount",
fields: [
"field-sig-with",
"field-sig-token",
"field-call-fund-amount",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-actor",
"field-sig-secret",
"field-sig-valid-after",
"field-sig-my-signature",
"field-sig-their-signature",
],
},
"request-counterparty-close": {
submitLabel: "Request counterparty close signature",
help: "Send your close signature to the counterparty and receive their signature.",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-actor",
"field-sig-my-signature",
"field-sig-their-signature",
],
},
"submit-signature-state": {
submitLabel: "Submit signature state",
help: "Send the latest signed state to the server.",
fields: [
"field-sig-with",
"field-sig-token",
"field-sig-my-balance",
"field-sig-their-balance",
"field-sig-nonce",
"field-sig-action",
"field-sig-actor",
"field-sig-secret",
"field-sig-valid-after",
"field-sig-my-signature",
"field-sig-their-signature",
],
},
};
const PRODUCER_ACTION_CONFIG = {
"request-counterparty-transfer": {
endpoint: "/counterparty/transfer",
action: "1",
},
"request-counterparty-close": {
endpoint: "/counterparty/signature-request",
action: "0",
},
"request-counterparty-deposit": {
endpoint: "/counterparty/signature-request",
action: "2",
},
"request-counterparty-withdrawal": {
endpoint: "/counterparty/signature-request",
action: "3",
},
};
function $(id) {
const node = document.getElementById(id);
if (!node) {
throw new Error(`Missing node: ${id}`);
}
return node;
}
function setStatus(id, message, isError = false) {
const node = $(id);
node.textContent = message;
node.classList.toggle("error", isError);
}
function getInput(id) {
return /** @type {HTMLInputElement | HTMLSelectElement} */ ($(id));
}
function getSelectedAction() {
const selected = normalizedText(getInput(ids.actionSelect).value);
return ACTION_DEFS[selected] ? selected : "fund-pipe";
}
function setSignedActionForSelection(action) {
const mapping = {
"sign-close": "0",
"sign-transfer": "1",
"sign-deposit": "2",
"sign-withdrawal": "3",
"request-counterparty-close": "0",
"request-counterparty-transfer": "1",
"request-counterparty-deposit": "2",
"request-counterparty-withdrawal": "3",
};
const value = mapping[action];
if (value !== undefined) {
getInput(ids.sigAction).value = value;
}
}
function getCounterpartyActionConfig(action) {
return PRODUCER_ACTION_CONFIG[action] || null;
}
function isCounterpartyRequestAction(action) {
return Boolean(getCounterpartyActionConfig(action));
}
function updateActionUi() {
const action = getSelectedAction();
const def = ACTION_DEFS[action];
for (const fieldId of ACTION_FIELD_IDS) {
const field = document.getElementById(fieldId);
if (!field) {
continue;
}
const shouldShow = def.fields.includes(fieldId);
field.classList.toggle("hidden", !shouldShow);
field.hidden = !shouldShow;
field.style.display = shouldShow ? "" : "none";
}
$(ids.actionSubmitBtn).textContent = def.submitLabel;
const amountLabel = document.getElementById(ids.callAmountLabel);
if (amountLabel) {
amountLabel.textContent = def.amountLabel || "Amount";
}
const signAction = action.startsWith("sign-");
const mySigInput = getInput(ids.sigMySignature);
const mySigLabel = document.getElementById(ids.sigMySignatureLabel);
const mySigHelp = document.getElementById(ids.sigMySignatureHelp);
mySigInput.readOnly = signAction;
mySigInput.classList.toggle("generated-output", signAction);
mySigInput.placeholder = signAction ? "Auto-generated after signing" : "0x...";
if (mySigLabel) {
mySigLabel.textContent = signAction
? "My Signature (Generated Output)"
: "My Signature (RSV hex)";
}
if (mySigHelp) {
mySigHelp.textContent = signAction
? "Click the submit button to generate this signature. It will auto-fill here."
: "Paste your signature, or switch to a sign-* action to generate it here.";
}
if (
isCounterpartyRequestAction(action) &&
!normalizedText(getInput(ids.sigWith).value) &&
stackflowNodeCounterpartyPrincipal
) {
getInput(ids.sigWith).value = stackflowNodeCounterpartyPrincipal;
}
let counterpartyHint = "";
if (isCounterpartyRequestAction(action)) {
if (stackflowNodeCounterpartyEnabled && stackflowNodeCounterpartyPrincipal) {
counterpartyHint = ` Counterparty principal: ${stackflowNodeCounterpartyPrincipal}.`;
} else {
counterpartyHint =
" Counterparty signing is not reported as enabled by the server.";
}
}
setStatus(ids.actionHelp, `Action: ${action}. ${def.help}${counterpartyHint}`, false);
setSignedActionForSelection(action);
}
function normalizedText(value) {
return String(value || "").trim();
}
function createPeerProtocolHeaders() {
peerRequestCounter += 1;
const seed = `${Date.now().toString(36)}-${peerRequestCounter.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
return {
"content-type": "application/json",
"x-stackflow-protocol-version": PEER_PROTOCOL_VERSION,
"x-stackflow-request-id": `req-${seed}`,
"idempotency-key": `idem-${seed}`,
};
}
function splitContractPrincipal(contractId) {
const value = normalizedText(contractId);
const parts = value.split(".");
if (parts.length !== 2 || !parts[0] || !parts[1]) {
throw new Error(`Invalid contract id: ${contractId}`);
}
return {
address: parts[0],
name: parts[1],
};
}
function parseClarityName(value, fieldName) {
const text = normalizedText(value);
if (!text) {
throw new Error(`${fieldName} is required`);
}
if (!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(text)) {
throw new Error(`${fieldName} must be a valid Clarity name`);
}
return text;
}
function inferTokenAssetName(tokenContractId) {
try {
const { name } = splitContractPrincipal(tokenContractId);
if (/^[a-zA-Z][a-zA-Z0-9-]*$/.test(name)) {
return name;
}
} catch {
// Ignore and require explicit name when needed.
}
return null;
}
function getTokenAssetName(tokenContractId) {
if (!tokenContractId) {
return null;
}
const explicit = normalizedText(getInput(ids.sigTokenAssetName).value);
if (explicit) {
return parseClarityName(explicit, "Token asset name");
}
const inferred = inferTokenAssetName(tokenContractId);
if (inferred) {
return inferred;
}
throw new Error("Token asset name is required for FT post-conditions");
}
function makePostConditionForTransfer(principal, tokenContractId, amount) {
const builder = Pc.principal(principal).willSendEq(amount);
if (!tokenContractId) {
return builder.ustx();
}
return builder.ft(tokenContractId, getTokenAssetName(tokenContractId));
}
function saveConfig() {
const data = {
serverUrl: getInput(ids.serverUrl).value.trim(),
contractId: getInput(ids.contractId).value.trim(),
network: getInput(ids.network).value.trim(),
contractVersion: getInput(ids.contractVersion).value.trim(),
};
localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
}
function loadConfig() {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) {
return;
}
try {
const parsed = JSON.parse(raw);
if (typeof parsed.serverUrl === "string") {
getInput(ids.serverUrl).value = parsed.serverUrl;
}
if (typeof parsed.contractId === "string") {
getInput(ids.contractId).value = parsed.contractId;
}
if (typeof parsed.network === "string") {
getInput(ids.network).value = parsed.network;
}
if (typeof parsed.contractVersion === "string") {
getInput(ids.contractVersion).value = parsed.contractVersion;
}
} catch {
// Ignore invalid cached data.
}
}
function defaultConfig() {
getInput(ids.serverUrl).value = window.location.origin;
getInput(ids.contractVersion).value = "0.6.0";
}
function toBigInt(value, field) {
const text = normalizedText(value);
if (!text) {
throw new Error(`${field} is required`);
}
if (!/^\d+$/.test(text)) {
throw new Error(`${field} must be an unsigned integer`);
}
return BigInt(text);
}
function optionalBigInt(value, field) {
const text = normalizedText(value);
if (!text) {
return null;
}
if (!/^\d+$/.test(text)) {
throw new Error(`${field} must be an unsigned integer`);
}
return BigInt(text);
}
function normalizeHex(value, field, expectedBytes = null) {
const raw = normalizedText(value).toLowerCase();
if (!raw) {
throw new Error(`${field} is required`);
}
const text = raw.startsWith("0x") ? raw.slice(2) : raw;
if (!/^[0-9a-f]+$/.test(text)) {
throw new Error(`${field} must be hex`);
}
if (expectedBytes !== null && text.length !== expectedBytes * 2) {
throw new Error(`${field} must be ${expectedBytes} bytes`);
}
return `0x${text}`;
}
function optionalHex(value, field, expectedBytes = null) {
const text = normalizedText(value);
if (!text) {
return null;
}
return normalizeHex(text, field, expectedBytes);
}
function hexToBytes(hex) {
const normalized = normalizeHex(hex, "hex");
const raw = normalized.slice(2);
const output = new Uint8Array(raw.length / 2);
for (let i = 0; i < raw.length; i += 2) {
output[i / 2] = Number.parseInt(raw.slice(i, i + 2), 16);
}
return output;
}
async function sha256(bytes) {
const digest = await crypto.subtle.digest("SHA-256", bytes);
return new Uint8Array(digest);
}
function compareBytes(left, right) {
const len = Math.min(left.length, right.length);
for (let i = 0; i < len; i += 1) {
if (left[i] < right[i]) {
return -1;
}
if (left[i] > right[i]) {
return 1;
}
}
if (left.length < right.length) {
return -1;
}
if (left.length > right.length) {
return 1;
}
return 0;
}
function canonicalPrincipals(a, b) {
const aBytes = serializeCV(principalCV(a));
const bBytes = serializeCV(principalCV(b));
if (compareBytes(aBytes, bBytes) <= 0) {
return { principal1: a, principal2: b };
}
return { principal1: b, principal2: a };
}
function optionalPrincipalCv(value) {
const text = normalizedText(value);
return text ? Cl.some(Cl.principal(text)) : Cl.none();
}
function optionalUIntCv(value) {
return value === null ? Cl.none() : Cl.some(Cl.uint(value));
}
function optionalSecretCv(secretHex) {
if (!secretHex) {
return Cl.none();
}
return Cl.some(Cl.buffer(hexToBytes(secretHex)));
}
function signatureToBufferCv(signature) {
return Cl.buffer(hexToBytes(normalizeHex(signature, "signature", 65)));
}
function parseContractId() {
const raw = normalizedText(getInput(ids.contractId).value);
let contractId = raw;
if (contractId.startsWith("'")) {
contractId = contractId.slice(1);
}
if (!contractId.includes(".") && contractId.includes("/")) {
contractId = contractId.replace("/", ".");
}
const parts = contractId.split(".");
if (parts.length !== 2 || !parts[0] || !parts[1]) {
throw new Error("Stackflow contract must be a contract principal");
}
try {
principalCV(parts[0]);
} catch {
throw new Error("Invalid contract address in contract principal");
}
getInput(ids.contractId).value = contractId;
return contractId;
}
function parseSignerInputs() {
if (!connectedAddress) {
throw new Error("Connect wallet first");
}
const withPrincipal = normalizedText(getInput(ids.sigWith).value);
if (!withPrincipal) {
throw new Error("Counterparty principal is required");
}
const actorInput = normalizedText(getInput(ids.sigActor).value);
const actor = actorInput || connectedAddress;
const token = normalizedText(getInput(ids.sigToken).value) || null;
const myBalance = toBigInt(getInput(ids.sigMyBalance).value, "My balance");
const theirBalance = toBigInt(
getInput(ids.sigTheirBalance).value,
"Their balance",
);
const nonce = toBigInt(getInput(ids.sigNonce).value, "Nonce");
const action = toBigInt(getInput(ids.sigAction).value, "Action");
const validAfter = optionalBigInt(
getInput(ids.sigValidAfter).value,
"Valid-after",
);
const secret = optionalHex(
getInput(ids.sigSecret).value,
"Secret preimage",
32,
);
return {
withPrincipal,
actor,
token,
myBalance,
theirBalance,
nonce,
action,
validAfter,
secret,
};
}
function parseActionContext({ requireNonce = false } = {}) {
if (!connectedAddress) {
throw new Error("Connect wallet first");
}
const withPrincipal = normalizedText(getInput(ids.sigWith).value);
if (!withPrincipal) {
throw new Error("Counterparty principal is required");
}
const token = normalizedText(getInput(ids.sigToken).value) || null;
const nonce = requireNonce
? toBigInt(getInput(ids.sigNonce).value, "Nonce")
: null;
return {
withPrincipal,
token,
nonce,
};
}
async function getHashedSecretCv(secret) {
if (!secret) {
return Cl.none();
}
const digest = await sha256(hexToBytes(secret));
return Cl.some(Cl.buffer(digest));
}
async function buildStructuredState() {
const contractId = parseContractId();
const signer = parseSignerInputs();
const pair = canonicalPrincipals(connectedAddress, signer.withPrincipal);
const balance1 =
pair.principal1 === connectedAddress ? signer.myBalance : signer.theirBalance;
const balance2 =
pair.principal1 === connectedAddress ? signer.theirBalance : signer.myBalance;
const hashedSecret = await getHashedSecretCv(signer.secret);
const message = Cl.tuple({
token: optionalPrincipalCv(signer.token),
"principal-1": Cl.principal(pair.principal1),
"principal-2": Cl.principal(pair.principal2),
"balance-1": Cl.uint(balance1),
"balance-2": Cl.uint(balance2),
nonce: Cl.uint(signer.nonce),
action: Cl.uint(signer.action),
actor: Cl.principal(signer.actor),
"hashed-secret": hashedSecret,
"valid-after": optionalUIntCv(signer.validAfter),
});
const network = normalizedText(getInput(ids.network).value);
const chainId = CHAIN_IDS[network] || CHAIN_IDS.testnet;
const version = normalizedText(getInput(ids.contractVersion).value) || "0.6.0";
const domain = Cl.tuple({
name: Cl.stringAscii(contractId),
version: Cl.stringAscii(version),
"chain-id": Cl.uint(chainId),
});
return {
contractId,
signer,
message,
domain,
};
}
function extractAddress(response) {
const isStacksAddress = (value) =>
typeof value === "string" && /^S[PMT][A-Z0-9]{38,42}$/i.test(value);
const seen = new Set();
const findAddress = (value) => {
if (value === null || value === undefined) {
return null;
}
if (isStacksAddress(value)) {
return value;
}
if (typeof value !== "object") {
return null;
}
if (seen.has(value)) {
return null;
}
seen.add(value);
if (Array.isArray(value)) {
// Prefer explicit STX-marked entries first.
for (const item of value) {
if (
item &&
typeof item === "object" &&
String(item.symbol || item.chain || "").toUpperCase().includes("STX") &&
isStacksAddress(item.address)
) {
return item.address;
}
}
for (const item of value) {
const nested = findAddress(item);
if (nested) {
return nested;
}
}
return null;
}
if (isStacksAddress(value.address)) {
return value.address;
}
if (isStacksAddress(value.stxAddress)) {
return value.stxAddress;
}
if (isStacksAddress(value.stacksAddress)) {
return value.stacksAddress;
}
const priorityKeys = [
"result",
"addresses",
"account",
"accounts",
"stx",
"stacks",
"wallet",
];
for (const key of priorityKeys) {
if (key in value) {
const nested = findAddress(value[key]);
if (nested) {
return nested;
}
}
}
for (const nestedValue of Object.values(value)) {
const nested = findAddress(nestedValue);
if (nested) {
return nested;
}
}
return null;
};
return findAddress(response);
}
async function resolveConnectedAddress(connectResponse = null) {
const initialAddress = extractAddress(connectResponse);
if (initialAddress) {
return initialAddress;
}
const response = await request("getAddresses");
const address = extractAddress(response);
if (!address) {
const details = JSON.stringify(response);
throw new Error(
`Wallet connected, but no valid STX address found. getAddresses response: ${details.slice(0, 300)}`,
);
}
return address;
}
function extractSignature(response) {
if (!response || typeof response !== "object") {
return null;
}
if (typeof response.signature === "string") {
return response.signature;
}
if (response.result && typeof response.result === "object") {
if (typeof response.result.signature === "string") {
return response.result.signature;
}
}
return null;
}
function extractTxid(response) {
if (!response || typeof response !== "object") {
return null;
}
if (typeof response.txid === "string") {
return response.txid;
}
if (response.result && typeof response.result === "object") {
if (typeof response.result.txid === "string") {
return response.result.txid;
}
}
return null;
}
function buildStackflowNodePayload() {
const parsed = parseSignerInputs();
const contractId = parseContractId();
const mySignature = normalizeHex(
getInput(ids.sigMySignature).value,
"My signature",
65,
);
const theirSignature = normalizeHex(
getInput(ids.sigTheirSignature).value,
"Counterparty signature",
65,
);
const amount =
parsed.action === 2n || parsed.action === 3n
? toBigInt(getInput(ids.callFundAmount).value, "Amount").toString(10)
: "0";
return {
contractId,
forPrincipal: connectedAddress,
withPrincipal: parsed.withPrincipal,
token: parsed.token,
amount,
myBalance: parsed.myBalance.toString(10),
theirBalance: parsed.theirBalance.toString(10),
mySignature,
theirSignature,
nonce: parsed.nonce.toString(10),
action: parsed.action.toString(10),
actor: parsed.actor,
secret: parsed.secret,
validAfter: parsed.validAfter ? parsed.validAfter.toString(10) : null,
beneficialOnly: false,
};
}
function buildCounterpartyRequestPayload(action) {
const config = getCounterpartyActionConfig(action);
if (!config) {
throw new Error(`Unsupported counterparty action: ${action}`);
}
if (!connectedAddress) {
throw new Error("Connect wallet first");
}
const parsed = parseSignerInputs();
const contractId = parseContractId();
const mySignature = normalizeHex(
getInput(ids.sigMySignature).value,
"My signature",
65,
);
const amount =
config.action === "2" || config.action === "3"
? toBigInt(getInput(ids.callFundAmount).value, "Amount").toString(10)
: "0";
return {
endpoint: config.endpoint,
payload: {
contractId,
forPrincipal: parsed.withPrincipal,
withPrincipal: connectedAddress,
token: parsed.token,
amount,
myBalance: parsed.theirBalance.toString(10),
theirBalance: parsed.myBalance.toString(10),