Skip to content

Commit

Permalink
add toSolidityBytes32
Browse files Browse the repository at this point in the history
  • Loading branch information
vrolland committed Sep 15, 2017
1 parent 5acbaf1 commit c5d4746
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,52 @@ ABI.stringify = function (types, values) {
return ret
}

ABI.toSolidityBytes32 = function(type, value) {
type = elementaryName(type);
var ret = []
if (type === 'bytes') {
ret.push(utils.setLengthRight(value, 32))
} else if (type === 'bool') {
ret.push(utils.setLengthLeft(value ? 1 : 0, 32));
} else if (type === 'address') {
ret.push(utils.setLengthLeft(value, 32))
} else if (type.startsWith('bytes')) {
size = parseTypeN(type)
if (size < 1 || size > 32) {
throw new Error('Invalid bytes<N> width: ' + size)
}
ret.push(utils.setLengthRight(value, 32))
} else if (type.startsWith('uint')) {
size = parseTypeN(type)
if ((size % 8) || (size < 8) || (size > 256)) {
throw new Error('Invalid uint<N> width: ' + size)
}

num = parseNumber(value)
if (num.bitLength() > size) {
throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength())
}

ret.push(num.toArrayLike(Buffer, 'be', 32))
} else if (type.startsWith('int')) {
size = parseTypeN(type)
if ((size % 8) || (size < 8) || (size > 256)) {
throw new Error('Invalid int<N> width: ' + size)
}

num = parseNumber(value)
if (num.bitLength() > size) {
throw new Error('Supplied int exceeds width: ' + size + ' vs ' + num.bitLength())
}

ret.push(num.toTwos(size).toArrayLike(Buffer, 'be', 32))
} else {
// FIXME: support all other types : like string
throw new Error('Unsupported or invalid type: ' + type)
}
return ret;
}

ABI.solidityPack = function (types, values) {
if (types.length !== values.length) {
throw new Error('Number of types are not matching the values')
Expand Down

0 comments on commit c5d4746

Please sign in to comment.