-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit cac0b9d
Showing
9 changed files
with
7,205 additions
and
0 deletions.
There are no files selected for viewing
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,2 @@ | ||
node_modules/ | ||
.husky/ |
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,26 @@ | ||
# Contributing to `erc-token-js` | ||
|
||
Thank you for your interest in improving `erc-token-js`! We welcome contributions of all kinds: from discussions and documentation to bug fixes and feature enhancements. | ||
|
||
Please review this document to help streamline the process and save everyone's precious time. | ||
|
||
## Issues | ||
|
||
No software is bug-free. If you encounter an issue, follow these steps: | ||
|
||
1. Search the [issue list](https://github.com/clbrge/erc-token-js/issues) for current and old issues. | ||
- If you find an existing issue, please UPVOTE the issue by adding a "thumbs-up reaction". We use this to help prioritize issues! | ||
2. If none of that is helping, create an issue with the following information: | ||
- Clear title (shorter is better). | ||
- Describe the issue in clear language. | ||
- Share error logs, screenshots, etc. | ||
- To speed up the issue fixing process, send us a sample repo with the issue you faced. | ||
|
||
## Pull Requests (PRs) | ||
|
||
We welcome all contributions. Before submitting a pull request, please ensure you have followed these guidelines: | ||
|
||
1. Make sure your code follows the [Standard JavaScript style](https://standardjs.com/). | ||
2. Provide a clear and concise description of the changes in the PR title and description. | ||
3. Ensure that your changes do not introduce new linting or test errors. | ||
4. Update any relevant documentation or tests as necessary. |
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,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2020-2022 Christophe Le Bars <[email protected]> | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
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,201 @@ | ||
# `erc-token-js` | ||
|
||
erc-token-js is a versatile JavaScript library tailored for handling Ethereum blockchain ERC20 tokens and native tokens, emphasizing serialization, deserialization, and display capabilities. This easy-to-use library streamlines the process of interacting with tokens by offering a user-friendly interface for creating, formatting, and performing arithmetic operations on token amounts. | ||
|
||
Features: | ||
|
||
- Create Token and TokenAmount instances from various sources, including objects and ethers.js contracts class | ||
- Effortlessly perform arithmetic operations (addition, subtraction, multiplication, and division) on token amounts | ||
- Intuitive formatting of token amounts for display purposes | ||
- Easily serialize and deserialize Token and TokenAmount classes in JSON format, ideal for storing data in databases or IPFS | ||
- Automatic unserialization when recreating classes from objects | ||
- Support for native tokens (e.g., Ether) | ||
- Seamless integration with and extension of the popular [ethers.js library](https://docs.ethers.io/) | ||
|
||
## Installation | ||
|
||
This package is [ESM only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c): | ||
Node 12+ is needed to use it and it must be `import`ed instead of `require`d. | ||
|
||
Install the package using npm: | ||
|
||
```bash | ||
npm install erc-token-js | ||
``` | ||
|
||
## Usage | ||
|
||
### Importing the Library | ||
|
||
```javascript | ||
import { Token, TokenAmount, expandToNDecimals } from 'erc-token-js' | ||
``` | ||
|
||
### Creating Tokens | ||
|
||
Create a new token from an object: | ||
|
||
```javascript | ||
const token = Token.from({ | ||
chainId, | ||
address: '0x...', | ||
name: 'Token Name', | ||
symbol: 'TKN', | ||
decimals: 18 | ||
}) | ||
``` | ||
|
||
Create a new token from an ethers.js contract: | ||
|
||
```javascript | ||
const token = await Token.from(contractInstance) | ||
``` | ||
|
||
Create a native token (e.g., Ether): | ||
|
||
```javascript | ||
const nativeToken = Token.native({ | ||
decimals: 18, | ||
name: 'Ether', | ||
symbol: 'ETH', | ||
formatSymbol: 'Ξ' | ||
}) | ||
``` | ||
|
||
## Working with `TokenAmount` | ||
|
||
### Create a new token amount | ||
|
||
```javascript | ||
const amount = TokenAmount.from(token, 123) | ||
``` | ||
|
||
In `erc-token-js`, when you create a `TokenAmount` with a decimal number, the library will automatically expand it to its corresponding value with the token's full decimals. For instance, if your token has 18 decimals and you provide 1 as the amount, it will be internally represented as 1 \* 10^18. However, if you prefer to avoid this automatic decimals expansion, you can directly provide a BigInt number as the amount. In this case, the library will use the provided BigInt value without any further modification, allowing for more precise control over the internal representation of token amounts. | ||
|
||
```javascript | ||
import { Token, TokenAmount } from 'erc-token-js' | ||
|
||
// Assuming you have a token instance, for example, USDC with 6 decimals | ||
const usdc = Token.from({ | ||
chainId: 1, | ||
address: '0xUSDC_ADDRESS', | ||
decimals: 6, | ||
symbol: 'USDC' | ||
}) | ||
|
||
// Automatic decimals expansion | ||
const amountA = TokenAmount.from(usdc, 1) // 1 USDC will be represented as 1 * 10^6 internally | ||
console.log(amountA.toString()) // "USDC 1.00" | ||
|
||
// Using BigInt to avoid decimals expansion | ||
const amountB = TokenAmount.from(usdc, 10000n) // 1 * 10^4 USDC | ||
console.log(amountB.toString()) // "USDC 0.01" | ||
``` | ||
|
||
In the previous example, both amountA and amountB represent the same value of 1 USDC, but they are created using different approaches. amountA demonstrates the automatic decimals expansion, while amountB shows how to avoid it by providing a BigInt value. | ||
|
||
### Perform arithmetic operations on token amounts | ||
|
||
```javascript | ||
const amountA = TokenAmount.from(token, 3) | ||
const amountB = TokenAmount.from(token, 2) | ||
|
||
const sum = amountA.add(amountB) // '5.00 TKN' | ||
const difference = amountA.sub(amountB) // '1.00 TKN' | ||
const product = amountA.mul(amountB) // '6,000,000.00 TKN' | ||
const product = amountA.mul(2n) // '6.00 TKN' | ||
const quotient = amountA.div(3n) // '1.00 TKN' | ||
``` | ||
|
||
In `erc-token-js`, arithmetic operations work on the full expanded amount. This means that when performing operations like multiplication or division, the internal representation with all decimal places is used. For example, when you multiply a token with 6 decimals by 6, it actually multiplies the internal value by 6,000,000. If you're looking to multiply the token amount by just 6, you should use "6n" or BigInt(6) as the argument. This ensures that the operation is performed with the intended value, avoiding unexpected results due to the internal representation. | ||
|
||
```javascript | ||
const amount = TokenAmount.from(usdc, 1) // 1 USDC with 6 decimals | ||
|
||
const multipliedBySixMillion = amount.mul(6) // Multiplies by 6,000,000 | ||
console.log(multipliedBySixMillion.toString()) // "USDC 6,000,000.00" | ||
|
||
const multipliedBySix = amount.mul(6n) // Multiplies by 6 | ||
console.log(multipliedBySix.toString()) // "USDC 6.00" | ||
|
||
// Alternatively, you can use BigInt(6) | ||
const multipliedBySixAlt = amount.mul(BigInt(6)) | ||
console.log(multipliedBySixAlt.toString()) // "USDC 6.00" | ||
``` | ||
|
||
In the previous example, we demonstrate how using 6n or BigInt(6) provides the expected result, while using 6 as the argument would lead to an unintended outcome due to the internal representation of the token amount. | ||
|
||
### Format token amounts for display | ||
|
||
```javascript | ||
const formattedAmount = amount.toString() // '123.00 TKN' | ||
``` | ||
|
||
## Serialization and Deserialization | ||
|
||
erc-token-js is designed with easy serialization and deserialization of `Token` and `TokenAmount` instances in mind, making it perfect for storing and retrieving data from databases or IPFS. | ||
|
||
Both `Token` and `TokenAmount` classes can be serialized into JSON and deserialized back into their respective classes effortlessly. This enables you to store token-related data as JSON and recreate the classes with all their functionalities when needed. | ||
|
||
Here's an example demonstrating the serialization and deserialization process: | ||
|
||
```javascript | ||
import { Token, TokenAmount } from 'erc-token-js' | ||
|
||
// Create a Token instance | ||
const usdc = Token.from({ | ||
chainId: 1, | ||
address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', | ||
decimals: 6, | ||
symbol: 'USDC' | ||
}) | ||
|
||
// Serialize the Token instance into JSON | ||
const serializedToken = JSON.stringify(usdc) | ||
|
||
// Deserialize the JSON back into a Token instance | ||
const deserializedToken = Token.from(JSON.parse(serializedToken)) | ||
|
||
// Create a TokenAmount instance | ||
const tokenAmount = await TokenAmount.from(usdc, 42) | ||
|
||
// Serialize the TokenAmount instance into JSON | ||
const serializedTokenAmount = JSON.stringify(tokenAmount) | ||
|
||
// Deserialize the JSON back into a TokenAmount instance | ||
const deserializedTokenAmount = TokenAmount.from( | ||
JSON.parse(serializedTokenAmount) | ||
) | ||
``` | ||
|
||
You can also serialize and deserialize objects containing `TokenAmount` instances: | ||
|
||
```javascript | ||
// Create an object containing a TokenAmount instance | ||
const complexObject = { | ||
id: 1, | ||
name: 'Test Object', | ||
amount: tokenAmount | ||
} | ||
|
||
// Serialize the object into JSON | ||
const serializedComplexObject = JSON.stringify(complexObject) | ||
|
||
// Deserialize the JSON back into an object | ||
const deserializedComplexObject = JSON.parse(serializedComplexObject) | ||
|
||
// Convert the deserialized amount back into a TokenAmount instance | ||
deserializedComplexObject.amount = TokenAmount.from( | ||
deserializedComplexObject.amount | ||
) | ||
``` | ||
|
||
This feature allows you to easily work with token data, no matter how you choose to store or transfer it. | ||
|
||
## Utility Functions | ||
|
||
Expand a number to N decimals: | ||
|
||
```javascript | ||
const expanded = expandToNDecimals(18)(1) // Returns a BigInt with 18 decimals | ||
``` |
Oops, something went wrong.