File tree Expand file tree Collapse file tree 2 files changed +44
-2
lines changed
packages/jellyfish-address Expand file tree Collapse file tree 2 files changed +44
-2
lines changed Original file line number Diff line number Diff line change 1
- import { OP_CODES } from '@defichain/jellyfish-transaction'
1
+ import { OP_CODES , Script } from '@defichain/jellyfish-transaction'
2
2
import { Eth } from '../src'
3
3
4
4
const keypair = {
@@ -21,3 +21,25 @@ it('should return undefined script for invalid eth address', () => {
21
21
const evmScript = Eth . fromAddress ( '0xabc123' )
22
22
expect ( evmScript ) . toStrictEqual ( undefined )
23
23
} )
24
+
25
+ it ( 'should convert evm script to address' , ( ) => {
26
+ const script : Script = {
27
+ stack : [
28
+ OP_CODES . OP_16 ,
29
+ OP_CODES . OP_PUSHDATA_HEX_BE ( keypair . evmAddr . substring ( 2 ) )
30
+ ]
31
+ }
32
+ const evmAddress = Eth . fromScript ( script )
33
+ expect ( evmAddress ) . toStrictEqual ( keypair . evmAddr . substring ( 2 ) )
34
+ } )
35
+
36
+ it ( 'should return undefined address for invalid evm script' , ( ) => {
37
+ const script : Script = {
38
+ stack : [
39
+ OP_CODES . OP_0 ,
40
+ OP_CODES . OP_PUSHDATA_HEX_BE ( keypair . evmAddr . substring ( 2 ) )
41
+ ]
42
+ }
43
+ const evmAddress = Eth . fromScript ( script )
44
+ expect ( evmAddress ) . toStrictEqual ( undefined )
45
+ } )
Original file line number Diff line number Diff line change 1
- import { OP_CODES , Script } from '@defichain/jellyfish-transaction'
1
+ import { OP_CODES , OP_PUSHDATA , Script } from '@defichain/jellyfish-transaction'
2
2
3
3
function validateAddress ( address : string ) : boolean {
4
4
// https://github.com/ethers-io/ethers.js/blob/5210b68a7837654c6b84207a45e1e573d9472d1a/src.ts/address/address.ts#L123
5
5
const regex : RegExp = / ^ 0 x [ a - f A - F 0 - 9 ] { 40 } $ / gm
6
6
return regex . test ( address )
7
7
}
8
8
9
+ function validateScript ( script : Script ) : boolean {
10
+ return script . stack . length === 2 &&
11
+ script . stack [ 0 ] . type === OP_CODES . OP_16 . type &&
12
+ script . stack [ 1 ] . type === 'OP_PUSHDATA' && ( script . stack [ 1 ] as OP_PUSHDATA ) . length ( ) === 20
13
+ }
14
+
9
15
export const Eth = {
10
16
/**
11
17
* @param {string } address to convert into Script
@@ -21,5 +27,19 @@ export const Eth = {
21
27
OP_CODES . OP_PUSHDATA_HEX_BE ( address . substring ( 2 ) )
22
28
]
23
29
}
30
+ } ,
31
+
32
+ /**
33
+ * EVM Script is LE in DVM, revert back to BE as what Ethereum behave
34
+ *
35
+ * @param {Script } script to convert into address
36
+ * @returns {string } address parsed from script
37
+ */
38
+ fromScript ( script : Script ) : string | undefined {
39
+ if ( ! validateScript ( script ) ) {
40
+ return undefined
41
+ }
42
+ const { hex } = ( script . stack [ 1 ] as OP_PUSHDATA )
43
+ return Buffer . from ( hex , 'hex' ) . reverse ( ) . toString ( 'hex' )
24
44
}
25
45
}
You can’t perform that action at this time.
0 commit comments