Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Conversions.motesToCSPR #490

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/types/Conversions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { expect } from 'chai';

import { Conversions } from "./Conversions";

describe('Conversions', () => {
it('should convert motes to CSPR correctly', function() {
const bal1 = Conversions.motesToCSPR('1');
const bal2 = Conversions.motesToCSPR('123400047000');
const bal3 = Conversions.motesToCSPR('1000000040234023040234023040234023042040230420402000000');
const bal4 = Conversions.motesToCSPR('0');
const bal5 = Conversions.motesToCSPR('100000000000');

expect(bal1).to.deep.equal('0.000000001');
expect(bal2).to.deep.equal('123.400047');
expect(bal3).to.deep.equal('1000000040234023040234023040234023042040230420.402');
expect(bal4).to.deep.equal('0');
expect(bal5).to.deep.equal('100');
expect(() => Conversions.motesToCSPR('-100')).to.throw('Motes cannot be negative number');
});
});
16 changes: 14 additions & 2 deletions src/types/Conversions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,19 @@ export class Conversions {
* const cspr = Conversions.motesToCSPR(motes);
* console.log(cspr.toString()); // Outputs: "1"
*/
static motesToCSPR(motes: BigNumberish): BigNumber {
return BigNumber.from(motes).div('1000000000');
static motesToCSPR(motes: BigNumberish): string {
const motesBigNumber = BigNumber.from(motes);

if (motesBigNumber.lt(0)) {
throw new Error('Motes cannot be negative number');
}

const result = motesBigNumber.toBigInt() * BigInt(10 ** 9) / BigInt(10 ** 9);
const resultStr = result.toString();

const integerPart = resultStr.slice(0, -9) || "0";
const decimalPart = resultStr.slice(-9).padStart(9, '0');

return `${integerPart}.${decimalPart}`.replace(/\.?0+$/, '');
}
}
Loading