-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathconstruction.ts
More file actions
1061 lines (954 loc) · 37.5 KB
/
construction.ts
File metadata and controls
1061 lines (954 loc) · 37.5 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 { has0xPrefix, hexToBuffer } from '@hirosystems/api-toolkit';
import { hexToBytes } from '@stacks/common';
import { StacksMainnet, StacksTestnet } from '@stacks/network';
import { StackingClient, decodeBtcAddress, poxAddressToTuple } from '@stacks/stacking';
import {
NetworkIdentifier,
RosettaAccountIdentifier,
RosettaAmount,
RosettaConstructionCombineRequest,
RosettaConstructionCombineResponse,
RosettaConstructionDeriveResponse,
RosettaConstructionHashRequest,
RosettaConstructionHashResponse,
RosettaConstructionMetadataRequest,
RosettaConstructionMetadataResponse,
RosettaConstructionParseResponse,
RosettaConstructionPayloadResponse,
RosettaConstructionPreprocessResponse,
RosettaConstructionSubmitResponse,
RosettaCurrency,
RosettaError,
RosettaMaxFeeAmount,
RosettaOperation,
RosettaOptions,
RosettaPublicKey,
} from '../../../rosetta/types';
import {
AnchorMode,
AuthType,
BytesReader,
MessageSignature,
OptionalCV,
StacksTransaction,
TransactionSigner,
UnsignedContractCallOptions,
UnsignedTokenTransferOptions,
bufferCV,
createMessageSignature,
createStacksPrivateKey,
deserializeTransaction,
emptyMessageSignature,
isSingleSig,
makeRandomPrivKey,
makeSigHashPreSign,
makeUnsignedContractCall,
makeUnsignedSTXTokenTransfer,
noneCV,
principalCV,
someCV,
standardPrincipalCV,
tupleCV,
uintCV,
} from '@stacks/transactions';
import * as express from 'express';
import { bitcoinToStacksAddress } from '@stacks/codec';
import { StacksCoreRpcClient, getCoreNodeEndpoint } from '../../../core-rpc/client';
import { DbBlock } from '../../../datastore/common';
import { PgStore } from '../../../datastore/pg-store';
import {
BigIntMath,
ChainID,
FoundOrNot,
doesThrow,
getChainIDNetwork,
isValidC32Address,
} from '../../../helpers';
import {
getOperations,
getOptionsFromOperations,
getSigners,
getStacksNetwork,
isDecimalsSupported,
isSignedTransaction,
isSymbolSupported,
makePresignHash,
parseTransactionMemo,
publicKeyToBitcoinAddress,
rawTxToBaseTx,
rawTxToStacksTransaction,
verifySignature,
} from '../../../rosetta/rosetta-helpers';
import { asyncHandler } from '../../async-handler';
import {
RosettaConstants,
RosettaErrors,
RosettaErrorsTypes,
RosettaOperationType,
} from '../../rosetta-constants';
import { ValidSchema, makeRosettaError, rosettaValidateRequest } from './../../rosetta-validate';
import { randomBytes } from 'node:crypto';
export function createRosettaConstructionRouter(db: PgStore, chainId: ChainID): express.Router {
const router = express.Router();
router.use(express.json());
const stackingOpts = { url: `http://${getCoreNodeEndpoint()}` };
const stackingRpc = new StackingClient(
'', // anonymous
getChainIDNetwork(chainId) == 'mainnet'
? new StacksMainnet(stackingOpts)
: new StacksTestnet(stackingOpts)
);
//construction/derive endpoint
router.post(
'/derive',
asyncHandler(async (req, res) => {
const valid: ValidSchema = await rosettaValidateRequest(req.originalUrl, req.body, chainId);
if (!valid.valid) {
//TODO have to fix this and make error generic
if (valid.error?.includes('must be equal to one of the allowed values')) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidCurveType]);
return;
}
res.status(400).json(makeRosettaError(valid));
return;
}
const publicKey: RosettaPublicKey = req.body.public_key;
const network: NetworkIdentifier = req.body.network_identifier;
if (has0xPrefix(publicKey.hex_bytes)) {
publicKey.hex_bytes = publicKey.hex_bytes.replace('0x', '');
}
try {
const btcAddress = publicKeyToBitcoinAddress(publicKey.hex_bytes, network.network);
if (btcAddress === undefined) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidPublicKey]);
return;
}
const stxAddress = bitcoinToStacksAddress(btcAddress);
const accountIdentifier: RosettaAccountIdentifier = {
address: stxAddress,
};
const response: RosettaConstructionDeriveResponse = {
account_identifier: accountIdentifier,
};
res.json(response);
} catch (e) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidPublicKey]);
}
})
);
//construction/preprocess endpoint
router.post(
'/preprocess',
makeValidationMiddleware(chainId),
asyncHandler(async (req, res) => {
const operations: RosettaOperation[] = req.body.operations;
// Max operations should be 3 for one transaction
if (operations.length > 3) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
if (!isSymbolSupported(operations)) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidCurrencySymbol]);
return;
}
if (!isDecimalsSupported(operations)) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidCurrencyDecimals]);
return;
}
const options = getOptionsFromOperations(operations);
if (options == null) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
if (req.body.metadata) {
if (req.body.metadata.gas_limit) {
options.gas_limit = req.body.metadata.gas_limit;
}
if (req.body.metadata.gas_price) {
options.gas_price = req.body.metadata.gas_price;
}
if (req.body.suggested_fee_multiplier) {
// todo: should this only be done if we have `metadata`?
options.suggested_fee_multiplier = req.body.suggested_fee_multiplier;
}
}
if (req.body.max_fee) {
const max_fee: RosettaMaxFeeAmount = req.body.max_fee[0];
if (
max_fee.currency.symbol === RosettaConstants.symbol &&
max_fee.currency.decimals === RosettaConstants.decimals
) {
options.max_fee = max_fee.value;
} else {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidFee]);
return;
}
}
let transaction: StacksTransaction;
switch (options.type as RosettaOperationType) {
case RosettaOperationType.TokenTransfer:
// dummy transaction to calculate size
const dummyTokenTransferTx: UnsignedTokenTransferOptions = {
recipient: options.token_transfer_recipient_address as string,
amount: BigInt(options.amount as string),
fee: 0, // placeholder
publicKey: '000000000000000000000000000000000000000000000000000000000000000000', // placeholder
network: getStacksNetwork(),
nonce: 0, // placeholder
memo: req.body.metadata?.memo,
anchorMode: AnchorMode.Any,
};
transaction = await makeUnsignedSTXTokenTransfer(dummyTokenTransferTx);
break;
case RosettaOperationType.StackStx: {
const poxContract = await stackingRpc.getStackingContract();
const [contractAddress, contractName] = poxContract.split('.');
const isPox4 = contractName === 'pox-4';
const poxAddr = options.pox_addr;
if (!options.number_of_cycles || !poxAddr) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
if (isPox4 && !options.signer_key) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
if (doesThrow(() => decodeBtcAddress(poxAddr))) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
if (!options.amount) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
// dummy transaction to calculate size
let dummyStackingTx: UnsignedContractCallOptions;
if (isPox4) {
const signerPrivKey = makeRandomPrivKey();
const signerSig = hexToBytes(
stackingRpc.signPoxSignature({
topic: 'stack-stx',
poxAddress: poxAddr,
rewardCycle: 0,
period: options.number_of_cycles ?? 1,
signerPrivateKey: signerPrivKey,
maxAmount: options.pox_max_amount ?? options.amount ?? 1,
authId: options.pox_auth_id ?? 0,
})
);
dummyStackingTx = {
publicKey: '000000000000000000000000000000000000000000000000000000000000000000',
contractAddress: contractAddress,
contractName: contractName,
functionName: 'stack-stx',
functionArgs: [
uintCV(options.amount), // amount-ustx
poxAddressToTuple(poxAddr), // pox-addr
uintCV(0), // start-burn-ht
uintCV(options.number_of_cycles ?? 1), // lock-period
someCV(bufferCV(signerSig)), // signer-sig
bufferCV(hexToBytes(options.signer_key as string)), // signer-key
uintCV(options.pox_max_amount ?? options.amount ?? 1), // max-amount
uintCV(options.pox_auth_id ?? 0), // auth-id
],
validateWithAbi: false,
network: getStacksNetwork(),
fee: 0,
nonce: 0,
anchorMode: AnchorMode.Any,
};
} else {
dummyStackingTx = {
publicKey: '000000000000000000000000000000000000000000000000000000000000000000',
contractAddress: contractAddress,
contractName: contractName,
functionName: 'stack-stx',
functionArgs: [
uintCV(options.amount), // amount-ustx
poxAddressToTuple(poxAddr), // pox-addr
uintCV(0), // start-burn-ht
uintCV(options.number_of_cycles), // lock-period
],
validateWithAbi: false,
network: getStacksNetwork(),
fee: 0,
nonce: 0,
anchorMode: AnchorMode.Any,
};
}
transaction = await makeUnsignedContractCall(dummyStackingTx);
break;
}
case RosettaOperationType.DelegateStx: {
if (!options.amount || !options.delegate_to) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
const poxAddrOptionalCV = options.pox_addr
? someCV(poxAddressToTuple(options.pox_addr))
: noneCV();
// dummy transaction to calculate size
const dummyDelegateStxTx: UnsignedContractCallOptions = {
publicKey: '000000000000000000000000000000000000000000000000000000000000000000',
contractAddress: 'ST000000000000000000002AMW42H',
contractName: 'pox',
functionName: 'delegate-stx',
functionArgs: [
uintCV(options.amount),
standardPrincipalCV(options.delegate_to),
noneCV(),
poxAddrOptionalCV,
],
validateWithAbi: false,
network: getStacksNetwork(),
fee: 0,
nonce: 0,
anchorMode: AnchorMode.Any,
};
transaction = await makeUnsignedContractCall(dummyDelegateStxTx);
break;
}
default:
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
options.size = transaction.serialize().byteLength;
options.memo = req.body.metadata?.memo;
const rosettaPreprocessResponse: RosettaConstructionPreprocessResponse = {
options,
required_public_keys: [{ address: options.sender_address as string }],
};
res.json(rosettaPreprocessResponse);
})
);
//construction/metadata endpoint
router.post(
'/metadata',
makeValidationMiddleware(chainId),
asyncHandler(async (req, res) => {
const request: RosettaConstructionMetadataRequest = req.body;
const options: RosettaOptions | undefined = request.options;
let dummyTransaction: StacksTransaction;
if (options?.sender_address && !isValidC32Address(options.sender_address)) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidSender]);
return;
}
if (options?.symbol !== RosettaConstants.symbol) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidCurrencySymbol]);
return;
}
if (!options?.fee && options?.size === undefined) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.missingTransactionSize]);
return;
}
let response = {} as RosettaConstructionMetadataResponse;
switch (options.type as RosettaOperationType) {
case RosettaOperationType.TokenTransfer:
const recipientAddress = options.token_transfer_recipient_address;
if (options?.decimals !== RosettaConstants.decimals) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidCurrencyDecimals]);
return;
}
if (recipientAddress == null || !isValidC32Address(recipientAddress)) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidRecipient]);
return;
}
// dummy transaction to calculate fee
const dummyTokenTransferTx: UnsignedTokenTransferOptions = {
recipient: recipientAddress,
amount: 1n, // placeholder
publicKey: '000000000000000000000000000000000000000000000000000000000000000000', // placeholder
network: getStacksNetwork(),
nonce: 0, // placeholder
memo: '123456', // placeholder
anchorMode: AnchorMode.Any,
};
// Do not set fee so that the fee is calculated
dummyTransaction = await makeUnsignedSTXTokenTransfer(dummyTokenTransferTx);
break;
case RosettaOperationType.StackStx: {
// Getting PoX info
const poxInfo = await stackingRpc.getPoxInfo();
const [contractAddress, contractName] = poxInfo.contract_id.split('.');
if (!options.number_of_cycles || !options.pox_addr) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
let burnBlockHeight =
options?.burn_block_height ?? poxInfo.current_burnchain_block_height;
// In Stacks 2.1, the burn block height is included in `/v2/pox` so we can skip the extra network request
burnBlockHeight ??= (await new StacksCoreRpcClient().getInfo()).burn_block_height;
options.contract_address = contractAddress;
options.contract_name = contractName;
options.burn_block_height = burnBlockHeight;
options.reward_cycle_id ??= poxInfo.current_cycle.id;
// dummy transaction to calculate fee
let dummyStackingTx: UnsignedContractCallOptions;
const poxAddr = options?.pox_addr;
if (contractName === 'pox-4') {
// fields required for pox4
if (!options.signer_key) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
options.pox_auth_id ??= BigInt(`0x${randomBytes(16).toString('hex')}`).toString();
let signerSigCV: OptionalCV = noneCV();
if (options.signer_signature) {
signerSigCV = someCV(bufferCV(hexToBytes(options.signer_signature)));
} else if (options.signer_private_key) {
const signerSig = stackingRpc.signPoxSignature({
topic: 'stack-stx',
poxAddress: poxAddr,
rewardCycle: options.reward_cycle_id,
period: options.number_of_cycles,
signerPrivateKey: createStacksPrivateKey(options.signer_private_key),
maxAmount: (options.pox_max_amount ?? options.amount) as string,
authId: options.pox_auth_id,
});
options.signer_signature = signerSig;
signerSigCV = someCV(bufferCV(hexToBytes(signerSig)));
}
dummyStackingTx = {
publicKey: '000000000000000000000000000000000000000000000000000000000000000000',
contractAddress: contractAddress,
contractName: contractName,
functionName: 'stack-stx',
functionArgs: [
uintCV(0), // amount-ustx
poxAddressToTuple(poxAddr), // pox-addr
uintCV(options?.burn_block_height ?? 0), // start-burn-ht
uintCV(options?.number_of_cycles ?? 0), // lock-period
signerSigCV, // signer-sig
bufferCV(hexToBytes(options.signer_key)), // signer-key
uintCV(options?.pox_max_amount ?? options?.amount ?? 1), // max-amount
uintCV(options?.pox_auth_id ?? 0), // auth-id
],
validateWithAbi: false,
network: getStacksNetwork(),
nonce: 0,
anchorMode: AnchorMode.Any,
};
} else {
dummyStackingTx = {
publicKey: '000000000000000000000000000000000000000000000000000000000000000000',
contractAddress: contractAddress,
contractName: contractName,
functionName: 'stack-stx',
functionArgs: [
uintCV(0),
poxAddressToTuple(poxAddr), // placeholder
uintCV(0),
uintCV(1),
],
validateWithAbi: false,
network: getStacksNetwork(),
nonce: 0,
anchorMode: AnchorMode.Any,
};
}
// Do not set fee so that the fee is calculated
dummyTransaction = await makeUnsignedContractCall(dummyStackingTx);
break;
}
case RosettaOperationType.DelegateStx: {
// Delegate stacking
const contract = await stackingRpc.getStackingContract();
const [contractAddress, contractName] = contract.split('.');
options.contract_address = contractAddress;
options.contract_name = contractName;
// dummy transaction to calculate fee
const dummyDelegateStxTx: UnsignedContractCallOptions = {
publicKey: '000000000000000000000000000000000000000000000000000000000000000000',
contractAddress: 'ST000000000000000000002AMW42H',
contractName: 'pox',
functionName: 'delegate-stx',
functionArgs: [
uintCV(1), // placeholder
principalCV('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159.some-contract-name-v1-2-3-4'), // placeholder,
someCV(uintCV(1)), // placeholder
someCV(poxAddressToTuple('bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4')), // placeholder
],
validateWithAbi: false,
network: getStacksNetwork(),
nonce: 0,
anchorMode: AnchorMode.Any,
};
// Do not set fee so that the fee is calculated
dummyTransaction = await makeUnsignedContractCall(dummyDelegateStxTx);
break;
}
default:
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidTransactionType]);
return;
}
if (typeof options.sender_address === 'undefined') {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.missingSenderAddress]);
return;
}
const stxAddress = options.sender_address;
// Getting nonce info
const accountInfo = await new StacksCoreRpcClient().getAccount(stxAddress);
let recentBlockHash = undefined;
const blockQuery: FoundOrNot<DbBlock> = await db.getCurrentBlock();
if (blockQuery.found) {
recentBlockHash = blockQuery.result.block_hash;
}
response = {
metadata: {
...options,
account_sequence: accountInfo.nonce,
recent_block_hash: recentBlockHash,
},
};
// Getting fee info if not operation fee was given in /preprocess
const feeValue = dummyTransaction.auth.spendingCondition.fee.toString();
if (feeValue === undefined || feeValue === '0') {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidFee]);
return;
}
if (!options.size) {
res.status(400).json(RosettaErrorsTypes.missingTransactionSize);
return;
}
const currency: RosettaCurrency = {
symbol: RosettaConstants.symbol,
decimals: RosettaConstants.decimals,
};
const fee: RosettaAmount = {
value: feeValue,
currency,
};
response.suggested_fee = [fee];
res.json(response);
})
);
//construction/hash endpoint
router.post('/hash', makeValidationMiddleware(chainId), (req, res) => {
const request: RosettaConstructionHashRequest = req.body;
if (!has0xPrefix(request.signed_transaction)) {
request.signed_transaction = '0x' + request.signed_transaction;
}
let buffer: Buffer;
try {
buffer = hexToBuffer(request.signed_transaction);
} catch (error) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidTransactionString]);
return;
}
const transaction = deserializeTransaction(new BytesReader(buffer));
const hash = transaction.txid();
if (!transaction.auth.spendingCondition) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.transactionNotSigned]);
return;
}
if (isSingleSig(transaction.auth.spendingCondition)) {
/**Single signature Transaction has an empty signature, so the transaction is not signed */
if (
!transaction.auth.spendingCondition.signature.data ||
emptyMessageSignature().data === transaction.auth.spendingCondition.signature.data
) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.transactionNotSigned]);
return;
}
} else {
/**Multi-signature transaction does not have signature fields thus the transaction not signed */
if (transaction.auth.spendingCondition.fields.length === 0) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.transactionNotSigned]);
return;
}
}
const hashResponse: RosettaConstructionHashResponse = {
transaction_identifier: {
hash: '0x' + hash,
},
};
res.status(200).json(hashResponse);
});
//construction/parse endpoint
router.post(
'/parse',
makeValidationMiddleware(chainId),
asyncHandler(async (req, res) => {
let inputTx = req.body.transaction;
const signed = req.body.signed;
if (!has0xPrefix(inputTx)) {
inputTx = '0x' + inputTx;
}
const transaction = rawTxToStacksTransaction(inputTx);
const checkSigned = isSignedTransaction(transaction);
if (signed != checkSigned) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidParams]);
return;
}
try {
const baseTx = rawTxToBaseTx(inputTx);
const operations = await getOperations(baseTx, db, chainId);
const txMemo = parseTransactionMemo(baseTx.token_transfer_memo);
let response: RosettaConstructionParseResponse;
if (signed) {
response = {
operations: operations,
account_identifier_signers: getSigners(transaction),
};
} else {
response = {
operations: operations,
};
}
if (txMemo) {
response.metadata = {
memo: txMemo,
};
}
res.json(response);
} catch (error) {
console.error(error);
res.status(400).json(RosettaErrors[RosettaErrorsTypes.unknownError]);
}
})
);
//construction/submit endpoint
router.post(
'/submit',
makeValidationMiddleware(chainId),
asyncHandler(async (req, res) => {
let transaction = req.body.signed_transaction;
let buffer: Buffer;
if (!has0xPrefix(transaction)) {
transaction = '0x' + transaction;
}
try {
buffer = hexToBuffer(transaction);
} catch (error) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidTransactionString]);
return;
}
try {
const submitResult = await new StacksCoreRpcClient().sendTransaction(buffer);
const response: RosettaConstructionSubmitResponse = {
transaction_identifier: {
hash: submitResult.txId,
},
};
res.status(200).json(response);
} catch (e: any) {
const err: RosettaError = {
...RosettaErrors[RosettaErrorsTypes.invalidTransactionString],
details: { message: e.message },
};
res.status(400).json(err);
}
})
);
//construction/payloads endpoint
router.post(
'/payloads',
makeValidationMiddleware(chainId),
asyncHandler(async (req, res) => {
const options = getOptionsFromOperations(req.body.operations);
if (options == null) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
if (!options.amount) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidAmount]);
return;
}
if (!options.fee || typeof options.fee !== 'string') {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidFees]);
return;
}
const txFee = BigIntMath.abs(BigInt(options.fee));
const publicKeys: RosettaPublicKey[] = req.body.public_keys;
if (!publicKeys) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.emptyPublicKey]);
return;
}
const senderAddress = options.sender_address;
if (!senderAddress) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidSender]);
return;
}
if (!('metadata' in req.body) || !('account_sequence' in req.body.metadata)) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.missingNonce]);
return;
}
const nonce = BigInt(req.body.metadata.account_sequence);
if (publicKeys.length !== 1) {
//TODO support multi-sig in the future.
res.status(400).json(RosettaErrors[RosettaErrorsTypes.needOnePublicKey]);
return;
}
if (publicKeys[0].curve_type !== 'secp256k1') {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidCurveType]);
return;
}
if (has0xPrefix(publicKeys[0].hex_bytes)) {
publicKeys[0].hex_bytes = publicKeys[0].hex_bytes.slice(2);
}
let transaction: StacksTransaction;
switch (options.type as RosettaOperationType) {
case RosettaOperationType.TokenTransfer: {
const recipientAddress = options.token_transfer_recipient_address;
if (!recipientAddress) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidRecipient]);
return;
}
// signel signature
const tokenTransferOptions: UnsignedTokenTransferOptions = {
recipient: recipientAddress,
amount: BigInt(options.amount),
fee: txFee,
publicKey: publicKeys[0].hex_bytes,
network: getStacksNetwork(),
nonce: nonce,
memo: req.body.metadata?.memo,
anchorMode: AnchorMode.Any,
};
transaction = await makeUnsignedSTXTokenTransfer(tokenTransferOptions);
break;
}
case RosettaOperationType.StackStx: {
const contractAddress = options.contract_address ?? req.body.metadata.contract_address;
const contractName = options.contract_name ?? req.body.metadata.contract_name;
const poxAddr = options.pox_addr ?? req.body.metadata.pox_addr;
const burnBlockHeight = options.burn_block_height ?? req.body.metadata.burn_block_height;
const numberOfCycles = options.number_of_cycles ?? req.body.metadata.number_of_cycles;
// pox4 fields
const authID = options.pox_auth_id ?? req.body.metadata.pox_auth_id;
const signerKey = options.signer_key ?? req.body.metadata.signer_key;
const rewardCycleID = options.reward_cycle_id ?? req.body.metadata.reward_cycle_id;
const poxMaxAmount =
options.pox_max_amount ?? req.body.metadata.pox_max_amount ?? options.amount;
const signerSignature = options.signer_signature ?? req.body.metadata.signer_signature;
if (!poxAddr) {
res.status(400).json(RosettaErrorsTypes.invalidOperation);
return;
}
if (!contractAddress) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.missingContractAddress]);
return;
}
if (!contractName) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.missingContractName]);
return;
}
if (!burnBlockHeight) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
if (!numberOfCycles || !options.amount) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
const isPox4 = contractName === 'pox-4';
// fields required for pox4
if (isPox4 && (!signerKey || !poxMaxAmount || !rewardCycleID || !authID)) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
let stackingTx: UnsignedContractCallOptions;
if (isPox4) {
stackingTx = {
contractAddress: contractAddress,
contractName: contractName,
functionName: 'stack-stx',
publicKey: publicKeys[0].hex_bytes,
functionArgs: [
uintCV(options.amount), // amount-ustx
poxAddressToTuple(poxAddr), // pox-addr
uintCV(burnBlockHeight), // start-burn-ht
uintCV(numberOfCycles), // lock-period
signerSignature ? someCV(bufferCV(hexToBytes(signerSignature))) : noneCV(), // signer-sig
bufferCV(hexToBytes(signerKey)), // signer-key
uintCV(poxMaxAmount), // max-amount
uintCV(authID), // auth-id
],
fee: txFee,
nonce: nonce,
validateWithAbi: false,
network: getStacksNetwork(),
anchorMode: AnchorMode.Any,
};
} else {
stackingTx = {
contractAddress: req.body.metadata.contract_address,
contractName: req.body.metadata.contract_name,
functionName: 'stack-stx',
publicKey: publicKeys[0].hex_bytes,
functionArgs: [
uintCV(options.amount),
poxAddressToTuple(poxAddr),
uintCV(burnBlockHeight),
uintCV(numberOfCycles),
],
fee: txFee,
nonce: nonce,
validateWithAbi: false,
network: getStacksNetwork(),
anchorMode: AnchorMode.Any,
};
}
transaction = await makeUnsignedContractCall(stackingTx);
break;
}
case RosettaOperationType.DelegateStx: {
let poxAddressCV: OptionalCV = noneCV();
if (options.pox_addr) {
const poxBTCAddress = options.pox_addr;
const { version: hashMode, data } = decodeBtcAddress(poxBTCAddress);
const hashModeBuffer = bufferCV(Buffer.from([hashMode]));
const hashbytes = bufferCV(data);
poxAddressCV = someCV(
tupleCV({
hashbytes,
version: hashModeBuffer,
})
);
}
if (!req.body.metadata.contract_address) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.missingContractAddress]);
return;
}
if (!req.body.metadata.contract_name) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.missingContractName]);
return;
}
let expire_burn_block_heightCV: OptionalCV = noneCV();
if (req.body.metadata.burn_block_height) {
const burn_block_height = req.body.metadata.burn_block_height;
if (typeof burn_block_height !== 'number' || typeof burn_block_height !== 'string')
expire_burn_block_heightCV = someCV(uintCV(burn_block_height));
}
if (!options.delegate_to || !options.amount) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
const stackingTx: UnsignedContractCallOptions = {
contractAddress: req.body.metadata.contract_address,
contractName: req.body.metadata.contract_name,
functionName: 'delegate-stx',
publicKey: publicKeys[0].hex_bytes,
functionArgs: [
uintCV(options.amount),
standardPrincipalCV(options.delegate_to),
expire_burn_block_heightCV,
poxAddressCV,
],
fee: txFee,
nonce: nonce,
validateWithAbi: false,
network: getStacksNetwork(),
anchorMode: AnchorMode.Any,
};
transaction = await makeUnsignedContractCall(stackingTx);
break;
}
default:
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidOperation]);
return;
}
const unsignedTransaction = Buffer.from(transaction.serialize());
const signer = new TransactionSigner(transaction);
const prehash = makeSigHashPreSign(signer.sigHash, AuthType.Standard, txFee, nonce);
const accountIdentifier: RosettaAccountIdentifier = {
address: senderAddress,
};
const response: RosettaConstructionPayloadResponse = {
unsigned_transaction: '0x' + unsignedTransaction.toString('hex'),
payloads: [
{
address: senderAddress,
account_identifier: accountIdentifier,
hex_bytes: prehash,
signature_type: 'ecdsa_recovery',
},
],
};
res.json(response);
})
);
//construction/combine endpoint
router.post('/combine', makeValidationMiddleware(chainId), (req, res) => {
const combineRequest: RosettaConstructionCombineRequest = req.body;
const signatures = combineRequest.signatures;
if (!has0xPrefix(combineRequest.unsigned_transaction)) {
combineRequest.unsigned_transaction = '0x' + combineRequest.unsigned_transaction;
}
if (signatures.length === 0) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.noSignatures]);
return;
}
let unsigned_transaction_buffer: Buffer;
let transaction: StacksTransaction;
try {
unsigned_transaction_buffer = hexToBuffer(combineRequest.unsigned_transaction);
transaction = deserializeTransaction(new BytesReader(unsigned_transaction_buffer));
} catch (e) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidTransactionString]);
return;
}
if (signatures.length !== 1) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.needOnlyOneSignature]);
return;
}
if (signatures[0].public_key.curve_type !== 'secp256k1') {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidCurveType]);
return;
}
const preSignHash = makePresignHash(transaction);
if (!preSignHash) {
res.status(400).json(RosettaErrors[RosettaErrorsTypes.invalidTransactionString]);
return;
}