-
Notifications
You must be signed in to change notification settings - Fork 350
/
Eth.ts
1318 lines (1220 loc) · 40.5 KB
/
Eth.ts
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
/********************************************************************************
* Ledger Node JS API
* (c) 2016-2017 Ledger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
// FIXME drop:
import type Transport from "@ledgerhq/hw-transport";
import { BigNumber } from "bignumber.js";
import { decodeTxInfo, hexBuffer, maybeHexBuffer, splitPath } from "./utils";
// NB: these are temporary import for the deprecated fallback mechanism
import { LedgerEthTransactionResolution, LoadConfig } from "./services/types";
import ledgerService from "./services/ledger";
import {
EthAppNftNotSupported,
EthAppPleaseEnableContractData,
} from "./errors";
import {
signEIP712HashedMessage,
signEIP712Message,
EIP712Message,
isEIP712Message,
getFiltersForMessage,
} from "./modules/EIP712";
export { ledgerService, isEIP712Message, getFiltersForMessage };
export type StarkQuantizationType =
| "eth"
| "erc20"
| "erc721"
| "erc20mintable"
| "erc721mintable";
const starkQuantizationTypeMap = {
eth: 1,
erc20: 2,
erc721: 3,
erc20mintable: 4,
erc721mintable: 5,
};
const remapTransactionRelatedErrors = (e) => {
if (e && e.statusCode === 0x6a80) {
return new EthAppPleaseEnableContractData(
"Please enable Blind signing or Contract data in the Ethereum app Settings"
);
}
return e;
};
/**
* Ethereum API
*
* @example
* import Eth from "@ledgerhq/hw-app-eth";
* const eth = new Eth(transport)
*/
export default class Eth {
transport: Transport;
loadConfig: LoadConfig;
setLoadConfig(loadConfig: LoadConfig): void {
this.loadConfig = loadConfig;
}
constructor(
transport: Transport,
scrambleKey = "w0w",
loadConfig: LoadConfig = {}
) {
this.transport = transport;
this.loadConfig = loadConfig;
transport.decorateAppAPIMethods(
this,
[
"getAddress",
"provideERC20TokenInformation",
"signTransaction",
"signPersonalMessage",
"getAppConfiguration",
"signEIP712Message",
"signEIP712HashedMessage",
"starkGetPublicKey",
"starkSignOrder",
"starkSignOrder_v2",
"starkSignTransfer",
"starkSignTransfer_v2",
"starkProvideQuantum",
"starkProvideQuantum_v2",
"starkUnsafeSign",
"eth2GetPublicKey",
"eth2SetWithdrawalIndex",
"setExternalPlugin",
"setPlugin",
"getEIP1024PublicEncryptionKey",
"getEIP1024SharedSecret",
],
scrambleKey
);
}
/**
* get Ethereum address for a given BIP 32 path.
* @param path a path in BIP 32 format
* @option boolDisplay optionally enable or not the display
* @option boolChaincode optionally enable or not the chaincode request
* @return an object with a publicKey, address and (optionally) chainCode
* @example
* eth.getAddress("44'/60'/0'/0/0").then(o => o.address)
*/
getAddress(
path: string,
boolDisplay?: boolean,
boolChaincode?: boolean
): Promise<{
publicKey: string;
address: string;
chainCode?: string;
}> {
const paths = splitPath(path);
const buffer = Buffer.alloc(1 + paths.length * 4);
buffer[0] = paths.length;
paths.forEach((element, index) => {
buffer.writeUInt32BE(element, 1 + 4 * index);
});
return this.transport
.send(
0xe0,
0x02,
boolDisplay ? 0x01 : 0x00,
boolChaincode ? 0x01 : 0x00,
buffer
)
.then((response) => {
const publicKeyLength = response[0];
const addressLength = response[1 + publicKeyLength];
return {
publicKey: response.slice(1, 1 + publicKeyLength).toString("hex"),
address:
"0x" +
response
.slice(
1 + publicKeyLength + 1,
1 + publicKeyLength + 1 + addressLength
)
.toString("ascii"),
chainCode: boolChaincode
? response
.slice(
1 + publicKeyLength + 1 + addressLength,
1 + publicKeyLength + 1 + addressLength + 32
)
.toString("hex")
: undefined,
};
});
}
/**
* You can sign a transaction and retrieve v, r, s given the raw transaction and the BIP 32 path of the account to sign.
*
* @param path: the BIP32 path to sign the transaction on
* @param rawTxHex: the raw ethereum transaction in hexadecimal to sign
* @param resolution: resolution is an object with all "resolved" metadata necessary to allow the device to clear sign information. This includes: ERC20 token information, plugins, contracts, NFT signatures,... You must explicitly provide something to avoid having a warning. By default, you can use Ledger's service or your own resolution service. See services/types.js for the contract. Setting the value to "null" will fallback everything to blind signing but will still allow the device to sign the transaction.
* @example
import { ledgerService } from "@ledgerhq/hw-app-eth"
const tx = "e8018504e3b292008252089428ee52a8f3d6e5d15f8b131996950d7f296c7952872bd72a2487400080"; // raw tx to sign
const resolution = await ledgerService.resolveTransaction(tx);
const result = eth.signTransaction("44'/60'/0'/0/0", tx, resolution);
console.log(result);
*/
async signTransaction(
path: string,
rawTxHex: string,
resolution?: LedgerEthTransactionResolution | null
): Promise<{
s: string;
v: string;
r: string;
}> {
if (resolution === undefined) {
console.warn(
"hw-app-eth: signTransaction(path, rawTxHex, resolution): " +
"please provide the 'resolution' parameter. " +
"See https://github.com/LedgerHQ/ledgerjs/blob/master/packages/hw-app-eth/README.md " +
"– the previous signature is deprecated and providing the 3rd 'resolution' parameter explicitly will become mandatory so you have the control on the resolution and the fallback mecanism (e.g. fallback to blind signing or not)." +
"// Possible solution:\n" +
" + import { ledgerService } from '@ledgerhq/hw-app-eth';\n" +
" + const resolution = await ledgerService.resolveTransaction(rawTxHex);"
);
resolution = await ledgerService
.resolveTransaction(rawTxHex, this.loadConfig, {
externalPlugins: true,
erc20: true,
})
.catch((e) => {
console.warn(
"an error occurred in resolveTransaction => fallback to blind signing: " +
String(e)
);
return null;
});
}
// provide to the device resolved information to make it clear sign the signature
if (resolution) {
for (const plugin of resolution.plugin) {
await setPlugin(this.transport, plugin);
}
for (const { payload, signature } of resolution.externalPlugin) {
await setExternalPlugin(this.transport, payload, signature);
}
for (const nft of resolution.nfts) {
await provideNFTInformation(this.transport, Buffer.from(nft, "hex"));
}
for (const data of resolution.erc20Tokens) {
await provideERC20TokenInformation(
this.transport,
Buffer.from(data, "hex")
);
}
}
const rawTx = Buffer.from(rawTxHex, "hex");
const { vrsOffset, txType, chainId, chainIdTruncated } =
decodeTxInfo(rawTx);
const paths = splitPath(path);
let response;
let offset = 0;
while (offset !== rawTx.length) {
const first = offset === 0;
const maxChunkSize = first ? 150 - 1 - paths.length * 4 : 150;
let chunkSize =
offset + maxChunkSize > rawTx.length
? rawTx.length - offset
: maxChunkSize;
if (vrsOffset != 0 && offset + chunkSize >= vrsOffset) {
// Make sure that the chunk doesn't end right on the EIP 155 marker if set
chunkSize = rawTx.length - offset;
}
const buffer = Buffer.alloc(
first ? 1 + paths.length * 4 + chunkSize : chunkSize
);
if (first) {
buffer[0] = paths.length;
paths.forEach((element, index) => {
buffer.writeUInt32BE(element, 1 + 4 * index);
});
rawTx.copy(buffer, 1 + 4 * paths.length, offset, offset + chunkSize);
} else {
rawTx.copy(buffer, 0, offset, offset + chunkSize);
}
response = await this.transport
.send(0xe0, 0x04, first ? 0x00 : 0x80, 0x00, buffer)
.catch((e) => {
throw remapTransactionRelatedErrors(e);
});
offset += chunkSize;
}
const response_byte: number = response[0];
let v = "";
if (chainId.times(2).plus(35).plus(1).isGreaterThan(255)) {
const oneByteChainId = (chainIdTruncated * 2 + 35) % 256;
const ecc_parity = Math.abs(response_byte - oneByteChainId);
if (txType != null) {
// For EIP2930 and EIP1559 tx, v is simply the parity.
v = ecc_parity % 2 == 1 ? "00" : "01";
} else {
// Legacy type transaction with a big chain ID
v = chainId.times(2).plus(35).plus(ecc_parity).toString(16);
}
} else {
v = response_byte.toString(16);
}
// Make sure v has is prefixed with a 0 if its length is odd ("1" -> "01").
if (v.length % 2 == 1) {
v = "0" + v;
}
const r = response.slice(1, 1 + 32).toString("hex");
const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex");
return { v, r, s };
}
/**
*/
getAppConfiguration(): Promise<{
arbitraryDataEnabled: number;
erc20ProvisioningNecessary: number;
starkEnabled: number;
starkv2Supported: number;
version: string;
}> {
return this.transport.send(0xe0, 0x06, 0x00, 0x00).then((response) => {
return {
arbitraryDataEnabled: response[0] & 0x01,
erc20ProvisioningNecessary: response[0] & 0x02,
starkEnabled: response[0] & 0x04,
starkv2Supported: response[0] & 0x08,
version: "" + response[1] + "." + response[2] + "." + response[3],
};
});
}
/**
* You can sign a message according to eth_sign RPC call and retrieve v, r, s given the message and the BIP 32 path of the account to sign.
* @example
eth.signPersonalMessage("44'/60'/0'/0/0", Buffer.from("test").toString("hex")).then(result => {
var v = result['v'] - 27;
v = v.toString(16);
if (v.length < 2) {
v = "0" + v;
}
console.log("Signature 0x" + result['r'] + result['s'] + v);
})
*/
async signPersonalMessage(
path: string,
messageHex: string
): Promise<{
v: number;
s: string;
r: string;
}> {
const paths = splitPath(path);
let offset = 0;
const message = Buffer.from(messageHex, "hex");
let response;
while (offset !== message.length) {
const maxChunkSize = offset === 0 ? 150 - 1 - paths.length * 4 - 4 : 150;
const chunkSize =
offset + maxChunkSize > message.length
? message.length - offset
: maxChunkSize;
const buffer = Buffer.alloc(
offset === 0 ? 1 + paths.length * 4 + 4 + chunkSize : chunkSize
);
if (offset === 0) {
buffer[0] = paths.length;
paths.forEach((element, index) => {
buffer.writeUInt32BE(element, 1 + 4 * index);
});
buffer.writeUInt32BE(message.length, 1 + 4 * paths.length);
message.copy(
buffer,
1 + 4 * paths.length + 4,
offset,
offset + chunkSize
);
} else {
message.copy(buffer, 0, offset, offset + chunkSize);
}
response = await this.transport.send(
0xe0,
0x08,
offset === 0 ? 0x00 : 0x80,
0x00,
buffer
);
offset += chunkSize;
}
const v = response[0];
const r = response.slice(1, 1 + 32).toString("hex");
const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex");
return { v, r, s };
}
/**
* Sign a prepared message following web3.eth.signTypedData specification. The host computes the domain separator and hashStruct(message)
* @example
eth.signEIP712HashedMessage("44'/60'/0'/0/0", Buffer.from("0101010101010101010101010101010101010101010101010101010101010101").toString("hex"), Buffer.from("0202020202020202020202020202020202020202020202020202020202020202").toString("hex")).then(result => {
var v = result['v'] - 27;
v = v.toString(16);
if (v.length < 2) {
v = "0" + v;
}
console.log("Signature 0x" + result['r'] + result['s'] + v);
})
*/
signEIP712HashedMessage(
path: string,
domainSeparatorHex: string,
hashStructMessageHex: string
): Promise<{
v: number;
s: string;
r: string;
}> {
return signEIP712HashedMessage(
this.transport,
path,
domainSeparatorHex,
hashStructMessageHex
);
}
/**
* Sign an EIP-721 formatted message following the specification here:
* https://github.com/LedgerHQ/app-ethereum/blob/develop/doc/ethapp.asc#sign-eth-eip-712
* ⚠️ This method is not compatible with nano S (LNS). Make sure to use a try/catch to fallback on the signEIP712HashedMessage method ⚠️
@example
eth.signEIP721Message("44'/60'/0'/0/0", {
domain: {
chainId: 69,
name: "Da Domain",
verifyingContract: "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC",
version: "1"
},
types: {
"EIP712Domain": [
{ name: "name", type: "string" },
{ name: "version", type: "string" },
{ name: "chainId", type: "uint256" },
{ name: "verifyingContract", type: "address" }
],
"Test": [
{ name: "contents", type: "string" }
]
},
primaryType: "Test",
message: {contents: "Hello, Bob!"},
})
*
* @param {String} path derivationPath
* @param {Object} jsonMessage message to sign
* @param {Boolean} fullImplem use the legacy implementation
* @returns {Promise}
*/
async signEIP712Message(
path: string,
jsonMessage: EIP712Message,
fullImplem = false
): Promise<{
v: number;
s: string;
r: string;
}> {
return signEIP712Message(
this.transport,
path,
jsonMessage,
fullImplem,
this.loadConfig
);
}
/**
* get Stark public key for a given BIP 32 path.
* @param path a path in BIP 32 format
* @option boolDisplay optionally enable or not the display
* @return the Stark public key
*/
starkGetPublicKey(path: string, boolDisplay?: boolean): Promise<Buffer> {
const paths = splitPath(path);
const buffer = Buffer.alloc(1 + paths.length * 4);
buffer[0] = paths.length;
paths.forEach((element, index) => {
buffer.writeUInt32BE(element, 1 + 4 * index);
});
return this.transport
.send(0xf0, 0x02, boolDisplay ? 0x01 : 0x00, 0x00, buffer)
.then((response) => {
return response.slice(0, response.length - 2);
});
}
/**
* sign a Stark order
* @param path a path in BIP 32 format
* @option sourceTokenAddress contract address of the source token (not present for ETH)
* @param sourceQuantization quantization used for the source token
* @option destinationTokenAddress contract address of the destination token (not present for ETH)
* @param destinationQuantization quantization used for the destination token
* @param sourceVault ID of the source vault
* @param destinationVault ID of the destination vault
* @param amountSell amount to sell
* @param amountBuy amount to buy
* @param nonce transaction nonce
* @param timestamp transaction validity timestamp
* @return the signature
*/
starkSignOrder(
path: string,
sourceTokenAddress: string | undefined,
sourceQuantization: BigNumber,
destinationTokenAddress: string | undefined,
destinationQuantization: BigNumber,
sourceVault: number,
destinationVault: number,
amountSell: BigNumber,
amountBuy: BigNumber,
nonce: number,
timestamp: number
): Promise<Buffer | { r: string; s: string }> {
const sourceTokenAddressHex = maybeHexBuffer(sourceTokenAddress);
const destinationTokenAddressHex = maybeHexBuffer(destinationTokenAddress);
const paths = splitPath(path);
const buffer = Buffer.alloc(
1 + paths.length * 4 + 20 + 32 + 20 + 32 + 4 + 4 + 8 + 8 + 4 + 4,
0
);
let offset = 0;
buffer[0] = paths.length;
paths.forEach((element, index) => {
buffer.writeUInt32BE(element, 1 + 4 * index);
});
offset = 1 + 4 * paths.length;
if (sourceTokenAddressHex) {
sourceTokenAddressHex.copy(buffer, offset);
}
offset += 20;
Buffer.from(sourceQuantization.toString(16).padStart(64, "0"), "hex").copy(
buffer,
offset
);
offset += 32;
if (destinationTokenAddressHex) {
destinationTokenAddressHex.copy(buffer, offset);
}
offset += 20;
Buffer.from(
destinationQuantization.toString(16).padStart(64, "0"),
"hex"
).copy(buffer, offset);
offset += 32;
buffer.writeUInt32BE(sourceVault, offset);
offset += 4;
buffer.writeUInt32BE(destinationVault, offset);
offset += 4;
Buffer.from(amountSell.toString(16).padStart(16, "0"), "hex").copy(
buffer,
offset
);
offset += 8;
Buffer.from(amountBuy.toString(16).padStart(16, "0"), "hex").copy(
buffer,
offset
);
offset += 8;
buffer.writeUInt32BE(nonce, offset);
offset += 4;
buffer.writeUInt32BE(timestamp, offset);
return this.transport
.send(0xf0, 0x04, 0x01, 0x00, buffer)
.then((response) => {
const r = response.slice(1, 1 + 32).toString("hex");
const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex");
return {
r,
s,
};
});
}
/**
* sign a Stark order using the Starkex V2 protocol
* @param path a path in BIP 32 format
* @option sourceTokenAddress contract address of the source token (not present for ETH)
* @param sourceQuantizationType quantization type used for the source token
* @option sourceQuantization quantization used for the source token (not present for erc 721 or mintable erc 721)
* @option sourceMintableBlobOrTokenId mintable blob (mintable erc 20 / mintable erc 721) or token id (erc 721) associated to the source token
* @option destinationTokenAddress contract address of the destination token (not present for ETH)
* @param destinationQuantizationType quantization type used for the destination token
* @option destinationQuantization quantization used for the destination token (not present for erc 721 or mintable erc 721)
* @option destinationMintableBlobOrTokenId mintable blob (mintable erc 20 / mintable erc 721) or token id (erc 721) associated to the destination token
* @param sourceVault ID of the source vault
* @param destinationVault ID of the destination vault
* @param amountSell amount to sell
* @param amountBuy amount to buy
* @param nonce transaction nonce
* @param timestamp transaction validity timestamp
* @return the signature
*/
starkSignOrder_v2(
path: string,
sourceTokenAddress: string | undefined,
sourceQuantizationType: StarkQuantizationType,
sourceQuantization: BigNumber | undefined,
sourceMintableBlobOrTokenId: BigNumber | undefined,
destinationTokenAddress: string | undefined,
destinationQuantizationType: StarkQuantizationType,
destinationQuantization: BigNumber | undefined,
destinationMintableBlobOrTokenId: BigNumber | undefined,
sourceVault: number,
destinationVault: number,
amountSell: BigNumber,
amountBuy: BigNumber,
nonce: number,
timestamp: number
): Promise<Buffer | { r: string; s: string }> {
const sourceTokenAddressHex = maybeHexBuffer(sourceTokenAddress);
const destinationTokenAddressHex = maybeHexBuffer(destinationTokenAddress);
if (!(sourceQuantizationType in starkQuantizationTypeMap)) {
throw new Error(
"eth.starkSignOrderv2 invalid source quantization type=" +
sourceQuantizationType
);
}
if (!(destinationQuantizationType in starkQuantizationTypeMap)) {
throw new Error(
"eth.starkSignOrderv2 invalid destination quantization type=" +
destinationQuantizationType
);
}
const paths = splitPath(path);
const buffer = Buffer.alloc(
1 +
paths.length * 4 +
1 +
20 +
32 +
32 +
1 +
20 +
32 +
32 +
4 +
4 +
8 +
8 +
4 +
4,
0
);
let offset = 0;
buffer[0] = paths.length;
paths.forEach((element, index) => {
buffer.writeUInt32BE(element, 1 + 4 * index);
});
offset = 1 + 4 * paths.length;
buffer[offset] = starkQuantizationTypeMap[sourceQuantizationType];
offset++;
if (sourceTokenAddressHex) {
sourceTokenAddressHex.copy(buffer, offset);
}
offset += 20;
if (sourceQuantization) {
Buffer.from(
sourceQuantization.toString(16).padStart(64, "0"),
"hex"
).copy(buffer, offset);
}
offset += 32;
if (sourceMintableBlobOrTokenId) {
Buffer.from(
sourceMintableBlobOrTokenId.toString(16).padStart(64, "0"),
"hex"
).copy(buffer, offset);
}
offset += 32;
buffer[offset] = starkQuantizationTypeMap[destinationQuantizationType];
offset++;
if (destinationTokenAddressHex) {
destinationTokenAddressHex.copy(buffer, offset);
}
offset += 20;
if (destinationQuantization) {
Buffer.from(
destinationQuantization.toString(16).padStart(64, "0"),
"hex"
).copy(buffer, offset);
}
offset += 32;
if (destinationMintableBlobOrTokenId) {
Buffer.from(
destinationMintableBlobOrTokenId.toString(16).padStart(64, "0"),
"hex"
).copy(buffer, offset);
}
offset += 32;
buffer.writeUInt32BE(sourceVault, offset);
offset += 4;
buffer.writeUInt32BE(destinationVault, offset);
offset += 4;
Buffer.from(amountSell.toString(16).padStart(16, "0"), "hex").copy(
buffer,
offset
);
offset += 8;
Buffer.from(amountBuy.toString(16).padStart(16, "0"), "hex").copy(
buffer,
offset
);
offset += 8;
buffer.writeUInt32BE(nonce, offset);
offset += 4;
buffer.writeUInt32BE(timestamp, offset);
return this.transport
.send(0xf0, 0x04, 0x03, 0x00, buffer)
.then((response) => {
const r = response.slice(1, 1 + 32).toString("hex");
const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex");
return {
r,
s,
};
});
}
/**
* sign a Stark transfer
* @param path a path in BIP 32 format
* @option transferTokenAddress contract address of the token to be transferred (not present for ETH)
* @param transferQuantization quantization used for the token to be transferred
* @param targetPublicKey target Stark public key
* @param sourceVault ID of the source vault
* @param destinationVault ID of the destination vault
* @param amountTransfer amount to transfer
* @param nonce transaction nonce
* @param timestamp transaction validity timestamp
* @return the signature
*/
starkSignTransfer(
path: string,
transferTokenAddress: string | undefined,
transferQuantization: BigNumber,
targetPublicKey: string,
sourceVault: number,
destinationVault: number,
amountTransfer: BigNumber,
nonce: number,
timestamp: number
): Promise<Buffer | { r: string; s: string }> {
const transferTokenAddressHex = maybeHexBuffer(transferTokenAddress);
const targetPublicKeyHex = hexBuffer(targetPublicKey);
const paths = splitPath(path);
const buffer = Buffer.alloc(
1 + paths.length * 4 + 20 + 32 + 32 + 4 + 4 + 8 + 4 + 4,
0
);
let offset = 0;
buffer[0] = paths.length;
paths.forEach((element, index) => {
buffer.writeUInt32BE(element, 1 + 4 * index);
});
offset = 1 + 4 * paths.length;
if (transferTokenAddressHex) {
transferTokenAddressHex.copy(buffer, offset);
}
offset += 20;
Buffer.from(
transferQuantization.toString(16).padStart(64, "0"),
"hex"
).copy(buffer, offset);
offset += 32;
targetPublicKeyHex.copy(buffer, offset);
offset += 32;
buffer.writeUInt32BE(sourceVault, offset);
offset += 4;
buffer.writeUInt32BE(destinationVault, offset);
offset += 4;
Buffer.from(amountTransfer.toString(16).padStart(16, "0"), "hex").copy(
buffer,
offset
);
offset += 8;
buffer.writeUInt32BE(nonce, offset);
offset += 4;
buffer.writeUInt32BE(timestamp, offset);
return this.transport
.send(0xf0, 0x04, 0x02, 0x00, buffer)
.then((response) => {
const r = response.slice(1, 1 + 32).toString("hex");
const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex");
return {
r,
s,
};
});
}
/**
* sign a Stark transfer or conditional transfer using the Starkex V2 protocol
* @param path a path in BIP 32 format
* @option transferTokenAddress contract address of the token to be transferred (not present for ETH)
* @param transferQuantizationType quantization type used for the token to be transferred
* @option transferQuantization quantization used for the token to be transferred (not present for erc 721 or mintable erc 721)
* @option transferMintableBlobOrTokenId mintable blob (mintable erc 20 / mintable erc 721) or token id (erc 721) associated to the token to be transferred
* @param targetPublicKey target Stark public key
* @param sourceVault ID of the source vault
* @param destinationVault ID of the destination vault
* @param amountTransfer amount to transfer
* @param nonce transaction nonce
* @param timestamp transaction validity timestamp
* @option conditionalTransferAddress onchain address of the condition for a conditional transfer
* @option conditionalTransferFact fact associated to the condition for a conditional transfer
* @return the signature
*/
starkSignTransfer_v2(
path: string,
transferTokenAddress: string | undefined,
transferQuantizationType: StarkQuantizationType,
transferQuantization: BigNumber | undefined,
transferMintableBlobOrTokenId: BigNumber | undefined,
targetPublicKey: string,
sourceVault: number,
destinationVault: number,
amountTransfer: BigNumber,
nonce: number,
timestamp: number,
conditionalTransferAddress?: string,
conditionalTransferFact?: BigNumber
): Promise<Buffer | { r: string; s: string }> {
const transferTokenAddressHex = maybeHexBuffer(transferTokenAddress);
const targetPublicKeyHex = hexBuffer(targetPublicKey);
const conditionalTransferAddressHex = maybeHexBuffer(
conditionalTransferAddress
);
if (!(transferQuantizationType in starkQuantizationTypeMap)) {
throw new Error(
"eth.starkSignTransferv2 invalid quantization type=" +
transferQuantizationType
);
}
const paths = splitPath(path);
const buffer = Buffer.alloc(
1 +
paths.length * 4 +
1 +
20 +
32 +
32 +
32 +
4 +
4 +
8 +
4 +
4 +
(conditionalTransferAddressHex ? 32 + 20 : 0),
0
);
let offset = 0;
buffer[0] = paths.length;
paths.forEach((element, index) => {
buffer.writeUInt32BE(element, 1 + 4 * index);
});
offset = 1 + 4 * paths.length;
buffer[offset] = starkQuantizationTypeMap[transferQuantizationType];
offset++;
if (transferTokenAddressHex) {
transferTokenAddressHex.copy(buffer, offset);
}
offset += 20;
if (transferQuantization) {
Buffer.from(
transferQuantization.toString(16).padStart(64, "0"),
"hex"
).copy(buffer, offset);
}
offset += 32;
if (transferMintableBlobOrTokenId) {
Buffer.from(
transferMintableBlobOrTokenId.toString(16).padStart(64, "0"),
"hex"
).copy(buffer, offset);
}
offset += 32;
targetPublicKeyHex.copy(buffer, offset);
offset += 32;
buffer.writeUInt32BE(sourceVault, offset);
offset += 4;
buffer.writeUInt32BE(destinationVault, offset);
offset += 4;
Buffer.from(amountTransfer.toString(16).padStart(16, "0"), "hex").copy(
buffer,
offset
);
offset += 8;
buffer.writeUInt32BE(nonce, offset);
offset += 4;
buffer.writeUInt32BE(timestamp, offset);
if (conditionalTransferAddressHex && conditionalTransferFact) {
offset += 4;
Buffer.from(
conditionalTransferFact.toString(16).padStart(64, "0"),
"hex"
).copy(buffer, offset);
offset += 32;
conditionalTransferAddressHex.copy(buffer, offset);
}
return this.transport
.send(
0xf0,
0x04,
conditionalTransferAddressHex ? 0x05 : 0x04,
0x00,
buffer
)
.then((response) => {
const r = response.slice(1, 1 + 32).toString("hex");
const s = response.slice(1 + 32, 1 + 32 + 32).toString("hex");
return {
r,
s,
};
});
}
/**
* provide quantization information before singing a deposit or withdrawal Stark powered contract call
*
* It shall be run following a provideERC20TokenInformation call for the given contract
*
* @param operationContract contract address of the token to be transferred (not present for ETH)
* @param operationQuantization quantization used for the token to be transferred
*/
starkProvideQuantum(
operationContract: string | undefined,
operationQuantization: BigNumber
): Promise<boolean> {
const operationContractHex = maybeHexBuffer(operationContract);
const buffer = Buffer.alloc(20 + 32, 0);
if (operationContractHex) {
operationContractHex.copy(buffer, 0);
}
Buffer.from(
operationQuantization.toString(16).padStart(64, "0"),
"hex"
).copy(buffer, 20);
return this.transport.send(0xf0, 0x08, 0x00, 0x00, buffer).then(
() => true,
(e) => {
if (e && e.statusCode === 0x6d00) {
// this case happen for ETH application versions not supporting Stark extensions
return false;
}
throw e;
}
);
}
/**
* provide quantization information before singing a deposit or withdrawal Stark powered contract call using the Starkex V2 protocol
*
* It shall be run following a provideERC20TokenInformation call for the given contract
*
* @param operationContract contract address of the token to be transferred (not present for ETH)