Skip to content

Commit ab195a0

Browse files
committed
fix(core): negative number for numToBytes
1 parent 2a77f9b commit ab195a0

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

.changeset/wicked-pets-learn.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@ckb-ccc/core": patch
3+
---
4+
5+
fix(core): negative number for numToByte

packages/core/src/num/index.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,11 +154,31 @@ export function numLeToBytes(val: NumLike, bytes?: number): Bytes {
154154
* ```
155155
*/
156156
export function numBeToBytes(val: NumLike, bytes?: number): Bytes {
157-
const rawBytes = bytesFrom(numFrom(val).toString(16));
157+
let num = numFrom(val);
158+
if (num < numFrom(0)) {
159+
if (bytes == null) {
160+
throw Error(
161+
"negative number can not be serialized without knowing bytes length",
162+
);
163+
}
164+
165+
// 0x100............00 - abs(num)
166+
// | . bytes * 8 .|
167+
// 2's complement for negative number
168+
num = (numFrom(1) << (numFrom(8) * numFrom(bytes))) + num;
169+
if (num < 0) {
170+
throw Error("negative number underflow");
171+
}
172+
}
173+
174+
const rawBytes = bytesFrom(num.toString(16));
158175
if (bytes == null) {
159176
return rawBytes;
160177
}
161178

179+
if (rawBytes.length > bytes) {
180+
throw Error("number overflow");
181+
}
162182
return bytesConcat("00".repeat(bytes - rawBytes.length), rawBytes);
163183
}
164184

0 commit comments

Comments
 (0)