Skip to content

Commit

Permalink
added recreate method to Uint256Struct to create class from its parts…
Browse files Browse the repository at this point in the history
… coming from chain as simple numbers
  • Loading branch information
joshglogau committed Jan 9, 2025
1 parent 5012a73 commit 0e26acd
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@wireio/core",
"description": "Library for working with Wire powered blockchains.",
"version": "0.0.5-4",
"version": "0.0.5-5",
"homepage": "https://github.com/Wire-Network/sdk-core",
"license": "FSL-1.1-Apache-2.0",
"main": "lib/core.js",
Expand Down
10 changes: 9 additions & 1 deletion src/chain/integer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,14 @@ export class Uint256Struct {
);
}

/**
* Rereate a Uint256Struct class from its low and high parts as numbers
* Useful when creating Uint256Struct from the value stored in a smart contract
*/
static recreate(low: number, high: number){
return new Uint256Struct(UInt128.from(low), UInt128.from(high));
}

/**
* Construct a Uint256Struct from a raw 256-bit BN (no scaling).
* Internal helper for add/sub/mul/div.
Expand Down Expand Up @@ -629,7 +637,7 @@ export class Uint256Struct {
// 5) Combine integer + fraction. If that sum is still <= 2^53,
// we return it; otherwise, return BN.
const result = intNum + fracNum;

if (!Number.isFinite(result) || result > Number.MAX_SAFE_INTEGER) {
return new BN(this.toString());
}
Expand Down
18 changes: 18 additions & 0 deletions test/integer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,24 @@ suite('Uint256Struct', function () {
assertUint256(Uint256Struct.from('0.000000000000000001'), '0.000000000000000001');
});

test('recreate', function () {
// Simple test values for low and high
const low = 123;
const high = 456;

// Recreate struct from low, high
const recreated = Uint256Struct.recreate(low, high);

// Check that the internal UInt128 values match what we passed in
// (Number(...) uses your UInt128.toNumber() or BN logic)
assert.equal(Number(recreated.low), low, 'Low part should match');
assert.equal(Number(recreated.high), high, 'High part should match');

// Confirm the full 256-bit value (raw) matches expected:
const expectedBN = new BN(high).shln(128).add(new BN(low));
assert.equal(recreated.raw().toString(), expectedBN.toString());
});

test('toString', function () {
const uint256 = Uint256Struct.from('1234567890123456789.987654321');
assert.equal(uint256.toString(), '1234567890123456789.987654321');
Expand Down

0 comments on commit 0e26acd

Please sign in to comment.