This repository has been archived by the owner on Apr 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 54
feat: asset-value #1206
Open
pastaghost
wants to merge
5
commits into
main
Choose a base branch
from
asset-value
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat: asset-value #1206
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
# @shapeshiftoss/asset-value | ||
|
||
This package provides an arithmetic and formatting class used to store the numerical value of an [Asset](https://github.com/shapeshift/lib/blob/9286cf2c27835d766719298ae688e0805448b00f/packages/asset-service/src/service/AssetService.ts#L10). | ||
|
||
## Getting Started | ||
|
||
```shell | ||
yarn add @shapeshiftoss/asset-value | ||
``` | ||
|
||
## Usage | ||
|
||
### Format Conversion | ||
|
||
Initialize an `AssetValue` instance with an `Asset` or `AssetId` and value, and specify the initial representation of the value. | ||
|
||
```typescript | ||
// Initialization using Asset | ||
const asset: Asset = { | ||
assetId: 'cosmos:osmosis-1/ibc:gamm/pool/1', | ||
chainId: 'cosmos:osmosis-1', | ||
symbol: 'gamm/pool/1', | ||
name: 'Osmosis OSMO/ATOM LP Token', | ||
precision: 6, | ||
color: '#750BBB', | ||
icon: 'https://rawcdn.githack.com/cosmos/chain-registry/master/osmosis/images/osmo.png', | ||
explorer: 'https://www.mintscan.io/osmosis', | ||
explorerAddressLink: 'https://www.mintscan.io/osmosis/account/', | ||
explorerTxLink: 'https://www.mintscan.io/osmosis/txs/', | ||
} | ||
const av1 = new AssetValue({ value: '42', asset: asset, format: AssetValueFormat.BASE_UNIT }) | ||
|
||
// Initialization using AssetId | ||
const av2 = new AssetValue({ | ||
value: '420', | ||
assetId: 'cosmos:osmosis-1/ibc:118', | ||
precision: 6, | ||
format: AssetValueFormat.PRECISION, | ||
}) | ||
``` | ||
|
||
</br> | ||
Converting a string containing numerical value in baseunit representation to precision representation is cumbersome and error-prone. | ||
|
||
```typescript | ||
import { AssetValue } from '@shapeshiftoss/asset-value' | ||
|
||
// Converting a string in baseunit representation to precision representation | ||
const underlyingAsset0AmountPrecision = bnOrZero(asset0AmountBaseUnit) | ||
.dividedBy(bn(10).pow(lpAsset.precision ?? '0')) | ||
.toString() | ||
``` | ||
|
||
With AssetValue instances, this is much simpler. Just call the `toPrecision()` formatting method of the AssetValue. | ||
|
||
```typescript | ||
import { AssetValue } from '@shapeshiftoss/asset-value' | ||
|
||
// Return a string formatted to the native asset precision or DEFAULT_FORMAT_DECIMALS, whichever is lower. | ||
const underlyingAsset0Amount: string = asset0Amount.toPrecision() | ||
|
||
// Return a string formatted to six decimal places or DEFAULT_FORMAT_DECIMALS, whichever is lower. | ||
const underlyingAsset0Amount: string = asset0Amount.toPrecision(6) | ||
``` | ||
|
||
Likewise, for a string contining the numerical value in baseunit representation, call the `toBaseUnit()` formatting method of the AssetValue. | ||
|
||
```typescript | ||
import { AssetValue } from '@shapeshiftoss/asset-value' | ||
|
||
const underlyingAsset0Amount: string = asset0Amount.toBaseUnit() | ||
``` | ||
|
||
In cases where some formatting other than what is available through either `toPrecision()` or `toBaseUnit()` is needed, `toFixed()` is available and functions exactly like the [corresponding method](https://mikemcl.github.io/bignumber.js/#toFix) from [bignumber.js](https://mikemcl.github.io/bignumber.js). | ||
|
||
```typescript | ||
import { AssetValue } from '@shapeshiftoss/asset-value' | ||
import BigNumber from 'bignumber.js' | ||
|
||
const amountTo18DecimalPlaces: string = asset0Amount.toFixed(18, BigNumber.ROUND_DOWN) | ||
``` | ||
|
||
</br> | ||
### Math | ||
|
||
The AssetValue class keeps track of the appropriate precision for the value based on the asset used to initialize the instance. This way, you don't need to keep track of which set of units the value is in or what the correct precision for the asset is. In fact, there is no longer any concept of precision or baseunit representations for values. You can perform arbitrary arithmetic operations on AssetValues as needed and then call whichever formatting method is appropriate when you need a string representation of the value. | ||
|
||
</br> | ||
|
||
Math operations are performed on AssetValue instances as if they were [bignumbers](https://mikemcl.github.io/bignumber.js/). | ||
|
||
```typescript | ||
import { AssetValue } from '@shapeshiftoss/asset-value' | ||
|
||
// Arithmetic operations return a new AssetValue instance | ||
const result: AssetValue = av1.plus(av2) | ||
const negativeValue: AssetValue = av1.negated() | ||
|
||
// Scalar operations like multiplication and division take a string or number as the argument | ||
const product: AssetValue = av1.multipliedBy('100') | ||
const percent: AssetValue = av1.dividedBy(100) | ||
``` | ||
|
||
</br> | ||
### Redux | ||
|
||
For Redux-compatibility, AssetValues are serializable. | ||
Call the `toSerialized()` method of any `AssetValue` to get a `SerializedAssetValue` containing the state of the `AssetValue` | ||
|
||
```typescript | ||
import { AssetValue, SerializedAssetValue } from '@shapeshiftoss/asset-value' | ||
|
||
const state: SerializedAssetValue = av.toSerialized() | ||
``` | ||
|
||
</br> | ||
|
||
The `SerializedAssetValue` objects can be directly inserted into a Redux store, or used as an intermediate representation to be passed between React components and Redux via selectors and reducers. | ||
|
||
```typescript | ||
// selector.ts | ||
export const selectAccountBalancesByAccountId(state, id: AccountId){ | ||
const balances = state.portfolio.accountBalances.ById[id] | ||
return Object.entries(balances).map((assetId: AssetId, balance: string) => { | ||
const asset = state.assets[id] | ||
return (new AssetValue(asset, value: balance, format: AssetValueFormat.BASE_UNIT)).toSerialized() | ||
}) | ||
} | ||
|
||
// Component.tsx | ||
const serializedBalanceData = useAppSelector(state => selectAccountBalancesByAccountId(state, accountId)) | ||
const doubledBalances: AssetValue[] = serializedBalanceData.map((data: SerializedAssetValue) => { | ||
return (new AssetValue(data)).multipliedBy(2) | ||
}) | ||
|
||
const serializedDoubledBalanceData: SerializedAssetValue[] = doubledBalances.map(balance => balance.toSerialized()) | ||
|
||
dispatch({ | ||
type: ComponentActionType.SET_BALANCES_FOR_ACCOUNT_ID, | ||
payload: { | ||
accountId, | ||
balances: serializedDoubledBalanceData | ||
} | ||
}) | ||
|
||
// reducer.ts | ||
const reducer = { | ||
state: ComponentState, | ||
action: ComponentActionType | ||
}: ComponentState => { | ||
switch(action.type){ | ||
case SET_BALANCES_FOR_ACCOUNT_ID: | ||
const accountBalances = {[action.payload.id]: action.payload.balances} | ||
return {...state, balances: {...state.balances, accountBalances}} | ||
break; | ||
default: | ||
return state | ||
} | ||
} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
{ | ||
"name": "@shapeshiftoss/asset-value", | ||
"version": "1.0.0", | ||
"description": "Math and formatting utility class for asset data", | ||
"homepage": "https://github.com/shapeshift/lib/tree/main/packages/asset-value", | ||
"license": "MIT", | ||
"main": "./dist/index.js", | ||
"types": "./dist/index.d.ts", | ||
"files": [ | ||
"dist/*.js", | ||
"dist/*.d.ts", | ||
"dist/service" | ||
], | ||
"publishConfig": { | ||
"access": "public" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/pastaghost/asset-value" | ||
}, | ||
"scripts": { | ||
"build": "yarn clean && yarn compile", | ||
"clean": "rm -rf dist && rm -rf tsconfig.build.tsbuildinfo", | ||
"compile": "tsc -p tsconfig.build.json", | ||
"dev": "tsc --watch", | ||
"prepare": "yarn build", | ||
"test": "jest test", | ||
"type-check": "tsc --project ./tsconfig.build.json --noEmit" | ||
}, | ||
"dependencies": { | ||
"@shapeshiftoss/asset-service": "^8.8.1", | ||
"@shapeshiftoss/caip": "^8.13.0", | ||
"bignumber.js": "^9.1.1", | ||
"ts-md5": "^1.3.1" | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
update with shapeshift repo