Skip to content

Commit

Permalink
fix(ts): patches DecCoin.encode to input a float (#184)
Browse files Browse the repository at this point in the history
  • Loading branch information
ygrishajev committed Apr 12, 2024
1 parent 458c733 commit 61d2d0c
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
1 change: 0 additions & 1 deletion make/release-ts.mk
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
.PHONY: release-ts

release-ts: $(AKASH_TS_NODE_MODULES) $(AKASH_TS_ROOT)/dist
if [ -z "$$CI" ]; then \
cd $(AKASH_TS_ROOT) && npx semantic-release --no-ci; \
Expand Down
18 changes: 15 additions & 3 deletions ts/src/patch/cosmos/base/v1beta1/coin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,28 @@ import * as coin from './coin';

describe('DecCoin', () => {
describe('prototype.decode', () => {
it('should decode amount with a floating point', () => {
it('should properly decode whole amount', () => {
const encodedCoin = coin.DecCoin.encode({
$type: 'cosmos.base.v1beta1.DecCoin',
denom: '',
amount: '1000000000000000000',
amount: '1000',
}).finish();
const reader = new Reader(encodedCoin);
const result = coin.DecCoin.decode(reader);

expect(result.amount).toEqual('1.00000000000000000');
expect(result.amount).toEqual('1000.00000000000000');
});

it('should properly decode amount with a floating point', () => {
const encodedCoin = coin.DecCoin.encode({
$type: 'cosmos.base.v1beta1.DecCoin',
denom: '',
amount: '1000.5',
}).finish();
const reader = new Reader(encodedCoin);
const result = coin.DecCoin.decode(reader);

expect(result.amount).toEqual('1000.50000000000000');
});
});
});
18 changes: 17 additions & 1 deletion ts/src/patch/cosmos/base/v1beta1/coin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
import { Reader } from 'protobufjs/minimal';
import * as minimal from 'protobufjs/minimal';

import * as coin from '../../../../generated/cosmos/base/v1beta1/coin.original';
import { DecCoin } from '../../../../generated/cosmos/base/v1beta1/coin.original';

const originalEncode = coin.DecCoin.encode;

coin.DecCoin.encode = function encode(
message: DecCoin,
writer: minimal.Writer = minimal.Writer.create(),
): minimal.Writer {
const { amount } = message;
const parts = amount.includes('.')
? message.amount.split('.')
: [message.amount, ''];
message.amount = `${parts[0]}${parts[1].padEnd(18, '0')}`;

return originalEncode.apply(this, [message, writer]);
};

const originalDecode = coin.DecCoin.decode;

Expand All @@ -9,7 +26,6 @@ coin.DecCoin.decode = function decode(
length?: number,
): coin.DecCoin {
const message = originalDecode.apply(this, [input, length]);

message.amount = (parseInt(message.amount) / 10 ** 18).toPrecision(18);

return message;
Expand Down

0 comments on commit 61d2d0c

Please sign in to comment.