-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathindex.js
More file actions
99 lines (92 loc) · 2.55 KB
/
Copy pathindex.js
File metadata and controls
99 lines (92 loc) · 2.55 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
const unMarshalBinaryLengthPrefixed = require('./utils/amino')
const addressUtil = require('./utils/bnb_addr_util')
const TYPE = require('./utils/types')
function decode(hex, testnet=false){
try{
return decodeTransfer(hex, testnet)
} catch (error){
try{
return decodePlaceOrder(hex, testnet)
} catch (error){
try{
return decodeCancelOrder(hex, testnet)
} catch(error){
throw new Error('Transaction Type not supported')
}
}
}
}
/**
* Decode standard transfer transaction.
* @param {string} hex
* @param {boolean} testnet default = false
**/
function decodeTransfer(hex, testnet=false) {
let clonedType = clone(TYPE.Transfer)
let tx = unMarshalBinaryLengthPrefixed(Buffer.from(hex, 'hex'), clonedType).val
tx.msg.map(item => {
item.inputs.map(input => {
input.address = addressUtil.encodeAddress(input.address, testnet)
})
item.outputs.map(output => {
output.address = addressUtil.encodeAddress(output.address, testnet)
})
})
return tx
}
/**
* Decode bnb Place Order transaction
* @param {string} hex
* @param {boolean} testnet default = false
*/
function decodePlaceOrder(hex, testnet=false){
let clonedType = clone(TYPE.PlaceOrder)
let tx = unMarshalBinaryLengthPrefixed(Buffer.from(hex, 'hex'), clonedType).val
tx.msg.map(item => {
item.sender = addressUtil.encodeAddress(item.sender, testnet)
})
return tx
}
/**
* Decode bnb Cancel Order transaction
* @param {string} hex
* @param {boolean} testnet default = false
*/
function decodeCancelOrder(hex, testnet=false){
let clonedType = clone(TYPE.CancelOrder)
let tx = unMarshalBinaryLengthPrefixed(Buffer.from(hex, 'hex'), clonedType).val
tx.msg.map(item => {
item.sender = addressUtil.encodeAddress(item.sender, testnet)
})
return tx
}
/**
* @param {string} hex
* @param {class} type
*/
function decodeCustomType(hex, type) {
if (typeof type === 'object') return unMarshalBinaryLengthPrefixed(Buffer.from(hex, 'hex'), type).val
else throw 'type should be an object'
}
/**
* clone obj
* @author @YordanPavlov
*/
function clone(obj) {
if (obj == null || typeof obj != 'object') {
return obj
}
if (Buffer.isBuffer(obj)) {
return Buffer.from([])
}
var temp = new obj.constructor()
for (var key in obj) {
temp[key] = clone(obj[key])
}
return temp
}
module.exports.decode = decode
module.exports.decodeCustomType = decodeCustomType
module.exports.decodeTransfer = decodeTransfer
module.exports.decodePlaceOrder = decodePlaceOrder
module.exports.decodeCancelOrder = decodeCancelOrder