Skip to content

Commit 35aa1e5

Browse files
committed
add eth.fromScript
1 parent 291fd1f commit 35aa1e5

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

packages/jellyfish-address/__tests__/eth.test.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { OP_CODES } from '@defichain/jellyfish-transaction'
1+
import { OP_CODES, Script } from '@defichain/jellyfish-transaction'
22
import { Eth } from '../src'
33

44
const keypair = {
@@ -21,3 +21,25 @@ it('should return undefined script for invalid eth address', () => {
2121
const evmScript = Eth.fromAddress('0xabc123')
2222
expect(evmScript).toStrictEqual(undefined)
2323
})
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+
})

packages/jellyfish-address/src/eth.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
1-
import { OP_CODES, Script } from '@defichain/jellyfish-transaction'
1+
import { OP_CODES, OP_PUSHDATA, Script } from '@defichain/jellyfish-transaction'
22

33
function validateAddress (address: string): boolean {
44
// https://github.com/ethers-io/ethers.js/blob/5210b68a7837654c6b84207a45e1e573d9472d1a/src.ts/address/address.ts#L123
55
const regex: RegExp = /^0x[a-fA-F0-9]{40}$/gm
66
return regex.test(address)
77
}
88

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+
915
export const Eth = {
1016
/**
1117
* @param {string} address to convert into Script
@@ -21,5 +27,19 @@ export const Eth = {
2127
OP_CODES.OP_PUSHDATA_HEX_BE(address.substring(2))
2228
]
2329
}
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')
2444
}
2545
}

0 commit comments

Comments
 (0)