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

Luke/big num to precision improvement #1364

Merged
merged 14 commits into from
Dec 20, 2024
79 changes: 51 additions & 28 deletions sdk/scripts/postbuild.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,52 +20,75 @@ environments.forEach((environment) => {
console.log(``);

isomorphicPackages.forEach((package) => {
const isomorphPath = path.join(

// We want to overwrite the base isomorphic files (the "target" files) with the concrete implementation code and definition files (the "source" files).

const isomorphicFolderPath = path.join(
__dirname,
'..',
'lib',
environment,
'isomorphic',
package + '.js'
'isomorphic'
);

const targetEnv = forceEnv ? forceEnv : environment;

const targetPath = path.join(
__dirname,
'..',
'lib',
environment,
'isomorphic',
`${package}.${targetEnv}.js`
);
const filesToSwap = [
{
source: `${package}.${targetEnv}.js`,
target: `${package}.js`,
},
{
source: `${package}.${targetEnv}.d.ts`,
target: `${package}.d.ts`,
},
];

try {
const content = fs.readFileSync(targetPath, 'utf8');
fs.writeFileSync(isomorphPath, content);
} catch (error) {
console.error(
`Error processing isomophic package : ${package} :: ${error.message}`
for (const file of filesToSwap) {
const sourcePath = path.join(
isomorphicFolderPath,
file.source
);

const targetPath = path.join(
isomorphicFolderPath,
file.target
);

try {
const sourceContent = fs.readFileSync(sourcePath, 'utf8');
fs.writeFileSync(targetPath, sourceContent);
} catch (error) {
console.error(
`Error processing isomophic package : ${package} :: ${error.message}`
);
}
}

// Delete other environment files for safety
environments.forEach((otherEnvironment) => {
if (otherEnvironment === environment) {
if (otherEnvironment === targetEnv) {
return;
}

const otherTargetPath = path.join(
__dirname,
'..',
'lib',
environment,
'isomorphic',
`${package}.${otherEnvironment}.js`
);
const otherTargetFiles = [
`${package}.${otherEnvironment}.js`,
`${package}.${otherEnvironment}.d.ts`,
];

for (const otherTargetFile of otherTargetFiles) {
const otherTargetPath = path.join(
__dirname,
'..',
'lib',
environment,
'isomorphic',
otherTargetFile
);

if (fs.existsSync(otherTargetPath)) {
fs.unlinkSync(otherTargetPath);
if (fs.existsSync(otherTargetPath)) {
fs.unlinkSync(otherTargetPath);
}
}
});
});
Expand Down
4 changes: 2 additions & 2 deletions sdk/src/driftClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4166,7 +4166,7 @@ export class DriftClient {
public async fillSpotOrder(
userAccountPublicKey: PublicKey,
user: UserAccount,
order?: Order,
order?: Pick<Order, 'marketIndex' | 'orderId'>,
fulfillmentConfig?:
| SerumV3FulfillmentConfigAccount
| PhoenixV1FulfillmentConfigAccount
Expand Down Expand Up @@ -4196,7 +4196,7 @@ export class DriftClient {
public async getFillSpotOrderIx(
userAccountPublicKey: PublicKey,
userAccount: UserAccount,
order?: Order,
order?: Pick<Order, 'marketIndex' | 'orderId'>,
fulfillmentConfig?:
| SerumV3FulfillmentConfigAccount
| PhoenixV1FulfillmentConfigAccount
Expand Down
34 changes: 33 additions & 1 deletion sdk/src/factory/bigNum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,10 +386,42 @@ export class BigNum {
}

const isNeg = this.isNeg();

const printString = this.abs().print();
const thisString = this.abs().toString();

// Handle small numbers (those with leading zeros after decimal)
if (printString.includes(BigNum.delim)) {
const [leftSide, rightSide] = printString.split(BigNum.delim);
if (leftSide === '0' && rightSide) {
// Count leading zeros
let leadingZeros = 0;
for (let i = 0; i < rightSide.length; i++) {
if (rightSide[i] === '0') {
leadingZeros++;
} else {
break;
}
}
// Get significant digits starting after leading zeros
const significantPart = rightSide.slice(leadingZeros);
let significantDigits = significantPart.slice(0, fixedPrecision);

// Remove trailing zeros if not requested
if (!trailingZeroes) {
significantDigits = significantDigits.replace(/0+$/, '');
}

// Only return result if we have significant digits
if (significantDigits.length > 0) {
const result = `${isNeg ? '-' : ''}0${BigNum.delim}${rightSide.slice(
0,
leadingZeros
)}${significantDigits}`;
return result;
}
}
}

let precisionPrintString = printString.slice(0, fixedPrecision + 1);

if (
Expand Down
13 changes: 13 additions & 0 deletions sdk/tests/bn/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ import {
// if you used the '@types/mocha' method to install mocha type definitions, uncomment the following line
// import 'mocha';

const bn = (value: number, precision: number) =>
new BigNum(Math.round(value * 10 ** precision), precision);
const _bnPrice = (value: number) => bn(value, 6); // Price precision (6 decimals)
const _bnNotional = (value: number) => bn(value, 6); // USDC precision (6 decimals)
const _bnPercentage = (value: number) => bn(value, 4); // Percentage precision (4 decimals)
const bnBaseAmount = (value: number) => bn(value, 8); // BTC-like precision (8 decimals)

describe('BigNum Tests', () => {
it('basic string representations are correct', () => {
const bn = BigNum.from(TEN_THOUSAND);
Expand Down Expand Up @@ -108,6 +115,12 @@ describe('BigNum Tests', () => {
expect(val4.toNum().toFixed(3)).to.equal('0.025');
expect(val4.toPrecision(4)).to.equal('0.025');

expect(bnBaseAmount(0.001234).toPrecision(4)).to.equal('0.001234');

expect(bnBaseAmount(0.001004).toPrecision(4)).to.equal('0.001004');

expect(bnBaseAmount(0.001).toPrecision(4)).to.equal('0.001');
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these the super small number cases? I was assuming it would be more a number like .000004 or something like that. Just curious to understand.


// Case 5
expect(BigNum.fromPrint('1').toMillified()).to.equal('1.00');
expect(BigNum.fromPrint('12').toMillified()).to.equal('12.0');
Expand Down
Loading