Showing preview only (1,177K chars total). Download the full file or copy to clipboard to get everything.
Repository: Loopring/loopring_sdk
Branch: master
Commit: 852e9f6a127e
Files: 165
Total size: 1.1 MB
Directory structure:
gitextract_m37m1v1z/
├── .babelrc
├── .eslintignore
├── .eslintrc
├── .gitignore
├── .gitpod.yml
├── .prettierignore
├── .prettierrc.json
├── Changelog.md
├── LICENSE
├── README.md
├── book.json
├── docs/
│ ├── .bookignore
│ ├── Changelog.md
│ ├── README.md
│ ├── SUMMARY.md
│ ├── about_us.md
│ └── js_sdk/
│ ├── Deposit.md
│ ├── NFTAction/
│ │ ├── collectionNFT.md
│ │ ├── deployNFT.md
│ │ ├── metaNFT.md
│ │ ├── mintNFT.md
│ │ ├── tradeNFT.md
│ │ └── validateNFTOrder.md
│ ├── README.md
│ ├── account/
│ │ ├── activeAccount.md
│ │ ├── fee.md
│ │ ├── historyRecord.md
│ │ ├── signature.md
│ │ ├── wallet_api.md
│ │ └── whitelisted_user_api.md
│ ├── deposit/
│ │ ├── depositERC20.md
│ │ └── depositNFT.md
│ ├── erc20Trade/
│ │ └── orderERC20.md
│ ├── exchange/
│ │ ├── ammpool_api.md
│ │ ├── exchange.md
│ │ └── webSocket.md
│ ├── transfer/
│ │ ├── transferERC20.md
│ │ └── transferNFT.md
│ └── withdraw/
│ ├── withdrawERC20.md
│ └── withdrawNFT.md
├── jest.config.cjs
├── package.json
├── rollup.config.mjs
├── src/
│ ├── api/
│ │ ├── ammpool_api.ts
│ │ ├── base_api.ts
│ │ ├── config/
│ │ │ ├── abis/
│ │ │ │ ├── contractWallet.ts
│ │ │ │ ├── erc1155.ts
│ │ │ │ ├── erc20.ts
│ │ │ │ ├── erc721.ts
│ │ │ │ ├── exchange_3_6.ts
│ │ │ │ ├── hebao.ts
│ │ │ │ ├── index.ts
│ │ │ │ └── smartWallet.ts
│ │ │ ├── guardianTypeData.ts
│ │ │ └── index.ts
│ │ ├── contacts_api.ts
│ │ ├── contract_api.ts
│ │ ├── defi_api.ts
│ │ ├── delegate_api.ts
│ │ ├── ethereum/
│ │ │ └── contracts/
│ │ │ ├── AbiFunction.ts
│ │ │ ├── Contract.ts
│ │ │ ├── Contracts.ts
│ │ │ └── index.ts
│ │ ├── exchange_api.ts
│ │ ├── global_api.ts
│ │ ├── index.ts
│ │ ├── luckToken_api.ts
│ │ ├── nft_api.ts
│ │ ├── rabbitWithdraw_api.ts
│ │ ├── request.ts
│ │ ├── sign/
│ │ │ ├── poseidon/
│ │ │ │ ├── EDDSAUtil.ts
│ │ │ │ ├── TestsEDDSAUtil_test.ts
│ │ │ │ ├── babyJub.ts
│ │ │ │ ├── eddsa.ts
│ │ │ │ ├── eddsa_test.ts
│ │ │ │ ├── field.ts
│ │ │ │ ├── field_test.ts
│ │ │ │ ├── jubjub.ts
│ │ │ │ ├── jubjub_test.ts
│ │ │ │ ├── permutation.ts
│ │ │ │ └── permutation_test.ts
│ │ │ └── sign_tools.ts
│ │ ├── user_api.ts
│ │ ├── vault_api.ts
│ │ ├── wallet_api.ts
│ │ ├── whitelisted_user_api.ts
│ │ └── ws_api.ts
│ ├── defs/
│ │ ├── account_defs.ts
│ │ ├── error_codes.ts
│ │ ├── index.ts
│ │ ├── loopring_constants.ts
│ │ ├── loopring_defs.ts
│ │ ├── loopring_enums.ts
│ │ ├── nft_defs.ts
│ │ ├── url_defs.ts
│ │ ├── web3_defs.ts
│ │ └── ws_defs.ts
│ ├── index.ts
│ ├── tests/
│ │ ├── .eslintrc
│ │ ├── .gitignore
│ │ ├── MockData.ts
│ │ ├── MockSwapData.ts
│ │ ├── README.md
│ │ ├── UTC--2021-02-04T02-55-36.490219109Z--ef439044717c3af35f4f46e52aa99280217a7114
│ │ ├── demo/
│ │ │ ├── NFTAction/
│ │ │ │ ├── collectionNFT.md
│ │ │ │ ├── collectionNFT.test.ts
│ │ │ │ ├── deployNFT.md
│ │ │ │ ├── deployNFT.test.ts
│ │ │ │ ├── metaNFT.md
│ │ │ │ ├── metaNFT.test.ts
│ │ │ │ ├── mintNFT.md
│ │ │ │ ├── mintNFT.test.ts
│ │ │ │ ├── tradeNFT.md
│ │ │ │ ├── tradeNFT.test.ts
│ │ │ │ ├── validateNFTOrder.md
│ │ │ │ └── validateNFTOrder.test.ts
│ │ │ ├── account/
│ │ │ │ ├── account.test.ts
│ │ │ │ ├── activeAccount.md
│ │ │ │ ├── activeAccount.test.ts
│ │ │ │ ├── fee.md
│ │ │ │ ├── fee.test.ts
│ │ │ │ ├── historyRecord.md
│ │ │ │ ├── historyRecord.test.ts
│ │ │ │ ├── signature.md
│ │ │ │ └── signature.test.ts
│ │ │ ├── deposit/
│ │ │ │ ├── deposit.md
│ │ │ │ ├── deposit.test.ts
│ │ │ │ ├── depositNFT.md
│ │ │ │ └── depositNFT.test.ts
│ │ │ ├── erc20Trade/
│ │ │ │ ├── orderERC20.md
│ │ │ │ └── orderERC20.test.ts
│ │ │ ├── exchange/
│ │ │ │ ├── exchange.md
│ │ │ │ ├── exchange.test.ts
│ │ │ │ ├── webSocket.md
│ │ │ │ └── webSocket.test.ts
│ │ │ ├── transfer/
│ │ │ │ ├── transferERC20.md
│ │ │ │ ├── transferERC20.test.ts
│ │ │ │ ├── transferNFT.md
│ │ │ │ └── transferNFT.test.ts
│ │ │ └── withdraw/
│ │ │ ├── withdrawERC20.md
│ │ │ ├── withdrawERC20.test.ts
│ │ │ ├── withdrawNFT.md
│ │ │ └── withdrawNFT.test.ts
│ │ ├── formatter.test.ts
│ │ └── unitTest/
│ │ ├── account/
│ │ │ ├── account.test.ts
│ │ │ └── sign_tools.test.ts
│ │ ├── appWallet/
│ │ │ └── wallet.test.ts
│ │ ├── erc20Trade/
│ │ │ ├── amm.test.ts
│ │ │ ├── amm_calc.test.ts
│ │ │ └── defi.test.ts
│ │ ├── exchange/
│ │ │ └── exchange.test.ts
│ │ ├── transfer/
│ │ │ └── transferUT.test.ts
│ │ └── withdraw/
│ │ ├── forceWithdrawls.test.ts
│ │ └── withdrawUT.test.ts
│ ├── types/
│ │ └── eddsa.d.ts
│ ├── types.d.ts
│ └── utils/
│ ├── formatter.ts
│ ├── index.ts
│ ├── log_tools.ts
│ ├── network_tools.ts
│ ├── obj_tools.ts
│ ├── swap_calc_utils.ts
│ ├── symbol_tools.ts
│ └── window_utils.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .babelrc
================================================
{
"env": {
"esmBundled": {
"presets": [
["@babel/env", {
"targets": "> 0.25%, not dead"
}], "@babel/typescript"]
},
"cjs": {
"presets": [
["@babel/env", {
"modules":"commonjs"
}], "@babel/typescript"]
},
"prod": {
"presets": [
[
"@babel/env",
{
"targets": { "node": "18" },
"useBuiltIns": "usage",
"corejs": 3
}
],
"@babel/typescript"
]
}
},
"plugins": [
"@babel/plugin-transform-optional-chaining",
"@babel/plugin-transform-typescript",
"transform-class-properties"
]
}
================================================
FILE: .eslintignore
================================================
# Ignore artifacts:
build
coverage
_book
dist
node_modules
dist
================================================
FILE: .eslintrc
================================================
{
"root": true,
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"no-console": 2 ,
// Remember, this means error!
"camelcase": ["warn"]
}
}
================================================
FILE: .gitignore
================================================
yarn-error.log
*.tgz
*testfile*
.idea
_book
dist
node_modules
coverage
./docs
.DS_Store
================================================
FILE: .gitpod.yml
================================================
# This configuration file was automatically generated by Gitpod.
# Please adjust to your needs (see https://www.gitpod.io/docs/config-gitpod-file)
# and commit this file to your remote git repository to share the goodness with others.
tasks:
- init: yarn install && yarn run build
command: yarn run start
================================================
FILE: .prettierignore
================================================
# Ignore artifacts:
build
coverage
_book
dist
node_modules
================================================
FILE: .prettierrc.json
================================================
{}
================================================
FILE: Changelog.md
================================================
# CHANGELOG
## JS SDK Version ChangeLog
#### 3.6.14
1) Guardian approve
#### v3.5.0
1)ecdsaSignature update to `eth_signTypedData_v4` use method `sendAsync`
#### v3.4.15
1)Internal browser contract signarue support
2)referral signature at active account
3)referral reword
4)Explorer Collection related Entry and feature optimization
5)insufficient quota reminder for Dual Invest
6)Add tutorial on Block trade
#### v3.3.16
1)Change Ecrecove function
2)Stop limit
3) Red Packet
4) Block trade
#### v3.3.0
1) GLOBAL information update
#### v3.2.6
1) BlindBox Redpacket
#### v3.2.1
1) LRC staking
2) signature bug fix
#### v3.1.5
1) hardware wallet last digital match / hard-code
generateKeyPair(_, publicKey: { x: string; y: string } | undefined = undefined)
#### v3.1.0
1) dual API update (support for Partial order)
2) red Packet feature
3) amm redeem mini order
#### v3.0.1 - v3.0.8
1) reformate Error throw code states
2) new feature for collection group
3) method split for localStorage
#### v2.0.24
1)collection feature
2)investment feature
#### v2.0.17
1) submitForceWithdrawals
2) return a result hash
3) order/swap demo
#### v2.0.12
1) ipfs cid to nftId startWith 0
2) server-side retturn nftId startWith 0
#### v2.0.11
1) add deposit to
2) get Account by account id
3) add HEBAO_META_TYPE deposit_wallet
#### v2.0.7
1) Fix isMobile
#### v2.0.6
1) mintNFT nftData
#### v2.0.5 (If you use v2 please move to >= v2.0.4 )
1) payPayeeUpdateAccount
2) fix generateApiKey error
#### v2.0.0
1) update poseidon
***
#### v1.10.3
1) Demo update
#### v1.10.1
1) getAllowances formatter update
2) getTokenBalances formatter update
3) unit test update
#### v1.9.6
1) add is Mobile in personalSign
#### v1.9.4
1) remove Authereum & walletLink
2) DEPLOYMENT_STATUS
#### v1.8.13
1)Update web3_defs.ts CREATION_CODE
2)submitDeployNFT transfer.maxFee tokenId: transfer.token.tokenId,
#### v1.8.7
1)getAmmPoolTxs V3
#### v1.8.5
1)validateNftOrder
#### v1.8.1
1)validateNftOrder
2)NFTCounterFactualInfo
#### v1.7.9
1) nftMint NFTCounterFactualInfo
####v1.7.6
1) Doc update,UT update
####v1.7.2
1) NFT ACTION
2) AMM Bug
####v1.6.6
1) NFT MINT IPFS
####v1.6.5
1) The eddsaKey is generated by a keyseed, default format is 'Sign this message to access Loopring
####v1.6.3
1) Error format bug fix {code:number,message:string}
####v1.6.0
1) Error format `{code:number, msg|message: string}`
####v1.5.7
1) 721 NFT URI function
#### v1.5.6
1) submitDeployNFT
#### v1.5.2
1) NFT deposit
#### v1.4.9
1) Counter Factual check
2) updateAccount
#### v1.4.7
1) NFT META
2) HEBAO
#### v1.4.5
1) CF wallet action sign update
#### v1.4.4 (alpha)
1) fix unlock FC wallet
#### v1.4.3 (alpha)
1) bug fix for NFT get contractMeta
2) FC wallet connect signature
3) Error code
#### v1.4.2
1) update activity
#### v1.3.10
1) Add recognizing header for web
#### v1.3.9
1) Update getLatestTokenPrice url
#### v1.3.8
1) SDK update for error type
#### v1.3.4 - v1.3.7 destroy
#### v1.3.3
1) add computeNFTAddress
2) add eslint and prettie for the code format
#### v1.3.2
1) Fix some bug
2) Update withdraw NFT unit test
#### v1.3.0 && v1.3.1 -- !!! revert
formatter Uint8Array support
# !!! revert
================================================
FILE: LICENSE
================================================
Licensor: Loopring Technology Limited
Licensed Work: Loopring-web/loopring-sdk
The Licensed Work is (c) 2022 Loopring Technology Limited
-----------------------------------------------------------------------------
Terms
The Licensor hereby grants you the right to copy, modify, create derivative
works, redistribute, and make limited-production use of the Licensed Work, on condition that Loopring L2 protocol/technology is supported on your platform that this Licensed Work is being used.
If your use of the Licensed Work does not comply with the requirements
currently in effect as described in this License, you must acquire a
full licensing agreement from the Licensor, or its affiliated entities,
or you must refrain from using the Licensed Work.
All copies of the original and modified Licensed Work, and derivative works
of the Licensed Work, are subject to this License. This License applies
separately for each version of the Licensed Work.
You must conspicuously display this License on each original or modified copy
of the Licensed Work. If you receive the Licensed Work in original or
modified form from a third party, the terms and conditions set forth in this
License apply to your use of that work.
Any use of the Licensed Work in violation of this License will automatically
terminate your rights under this License for the current and all other
versions of the Licensed Work.
This License does not grant you any right in any trademark or logo of
Licensor or its affiliates (provided that you may use a trademark or logo of
Licensor as expressly required by this License).
TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
TITLE.
-----------------------------------------------------------------------------
================================================
FILE: README.md
================================================
# Loopring SDK
[](https://raw.githubusercontent.com/Loopring/loopring_sdk/master/LICENSE)
[](https://www.npmjs.com/package/react-data-grid)
[](https://discord.com/invite/KkYccYp)
## 🚀 Quick Start
```shell
# Using npm
npm i @loopring-web/loopring-sdk --save
# Using yarn
yarn add @loopring-web/loopring-sdk
```
when using for browser make sure set up `NODE_ENV=production|development`
> Make sure you are using the original npm registry.
> `npm config set registry http://registry.npmjs.org`
## 📒 Documentation
Please see the [documentation page](https://loopring.github.io/loopring_sdk/) for information about getting started and developing with the Loopring SDK.
- [JS SDK](https://loopring.github.io/loopring_sdk)
- [APIs](https://docs-protocol.loopring.io)
## ✨ Changelog
- [Changelog](https://loopring.github.io/loopring_sdk/ChangeLog.html)
## 🫂 Community
- [Loopring Website](https://loopring.org/)
- [Loopring Exchange](https://loopring.io/#/layer2)
- [Loopring Reddit](https://www.reddit.com/r/loopringorg/)
- [Loopring Medium](https://medium.com/loopring-protocol)
- [Loopring Twitter](https://twitter.com/loopringorg)
- [Loopring Telegram](https://t.me/loopring_en)
## 🎒 Getting Started
Please see our [introduction page](https://loopring.github.io/loopring_sdk/) for details on integrating the SDK into your application.
## 🙋 Protocol & Architecture
- [Whitepaper](https://loopring.org/resources/en_whitepaper.pdf)
- [Design Docs](https://github.com/LoopringSecondary/docs/wiki/Loopring3_Design)
## ❓[Help](https://desk.zoho.com/portal/loopring/en/home)
## 👉 [What is Loopring?](https://loopring.org/#/)
## 🔑 Security
- [Wallet](https://security.loopring.io/)
- [Protocol Audit](https://loopring.org/resources/loopring1.0_audit.pdf)
================================================
FILE: book.json
================================================
{
"root": "./docs",
"description": "loopring sdk",
"author": "Loopring Dev Team",
"title": "Loopring SDK",
"gitbook": ">=3.0.0",
"links": {
"sidebar": {
"Home": "https://loopring.io"
}
}
}
================================================
FILE: docs/.bookignore
================================================
docs/detail
docs/README.md
docs/Changelog.mdv
================================================
FILE: docs/Changelog.md
================================================
# CHANGELOG
## JS SDK Version ChangeLog
#### v3.6.0
1) dual Invest autoReinvest
2) guardina singature typeData
3) remove signature 02/03 ended
#### v3.2.1
1) LRC staking
2) signature bug fix
#### v3.1.5
1) hardware wallet last digital match / hard-code
generateKeyPair(_, publicKey: { x: string; y: string } | undefined = undefined)
#### v3.1.0
1) dual API update (support for Partial order)
2) red Packet feature
3) amm redeem mini order
#### v3.0.1 - v3.0.8
1) reformate Error throw code states
2) new feature for collection group
3) method split for localStorage
#### v2.0.24
1)collection feature
2)investment feature
#### v2.0.17
1) submitForceWithdrawals
2) return a result hash
3) order/swap demo
#### v2.0.12
1) ipfs cid to nftId startWith 0
2) server-side retturn nftId startWith 0
#### v2.0.11
1) add deposit to
2) get Account by account id
3) add HEBAO_META_TYPE deposit_wallet
#### v2.0.7
1) Fix isMobile
#### v2.0.6
1) mintNFT nftData
#### v2.0.5 (If you use v2 please move to >= v2.0.4 )
1) payPayeeUpdateAccount
2) fix generateApiKey error
#### v2.0.0
1) update poseidon
***
#### v1.10.3
1) Demo update
#### v1.10.1
1) getAllowances formatter update
2) getTokenBalances formatter update
3) unit test update
#### v1.9.6
1) add is Mobile in personalSign
#### v1.9.4
1) remove Authereum & walletLink
2) DEPLOYMENT_STATUS
#### v1.8.13
1)Update web3_defs.ts CREATION_CODE
2)submitDeployNFT transfer.maxFee tokenId: transfer.token.tokenId,
#### v1.8.7
1)getAmmPoolTxs V3
#### v1.8.5
1)validateNftOrder
#### v1.8.1
1)validateNftOrder
2)NFTCounterFactualInfo
#### v1.7.9
1) nftMint NFTCounterFactualInfo
####v1.7.6
1) Doc update,UT update
####v1.7.2
1) NFT ACTION
2) AMM Bug
####v1.6.6
1) NFT MINT IPFS
####v1.6.5
1) The eddsaKey is generated by a keyseed, default format is 'Sign this message to access Loopring
####v1.6.3
1) Error format bug fix {code:number,message:string}
####v1.6.0
1) Error format `{code:number, msg|message: string}`
####v1.5.7
1) 721 NFT URI function
#### v1.5.6
1) submitDeployNFT
#### v1.5.2
1) NFT deposit
#### v1.4.9
1) Counter Factual check
2) updateAccount
#### v1.4.7
1) NFT META
2) HEBAO
#### v1.4.5
1) CF wallet action sign update
#### v1.4.4 (alpha)
1) fix unlock FC wallet
#### v1.4.3 (alpha)
1) bug fix for NFT get contractMeta
2) FC wallet connect signature
3) Error code
#### v1.4.2
1) update activity
#### v1.3.10
1) Add recognizing header for web
#### v1.3.9
1) Update getLatestTokenPrice url
#### v1.3.8
1) SDK update for error type
#### v1.3.4 - v1.3.7 destroy
#### v1.3.3
1) add computeNFTAddress
2) add eslint and prettie for the code format
#### v1.3.2
1) Fix some bug
2) Update withdraw NFT unit test
#### v1.3.0 && v1.3.1 -- !!! revert
formatter Uint8Array support
# !!! revert
================================================
FILE: docs/README.md
================================================
# Loopring SDK
[](https://raw.githubusercontent.com/Loopring/loopring_sdk/master/LICENSE)
[](https://www.npmjs.com/package/react-data-grid)
[](https://discord.com/invite/KkYccYp)
## 🚀 Quick Start
```shell
# Using npm
npm i @loopring-web/loopring-sdk --save
# Using yarn
yarn add @loopring-web/loopring-sdk
```
> Make sure you are using the original npm registry.
> `npm config set registry http://registry.npmjs.org`
## 📒 Documentation
Please see the [documentation page](https://loopring.github.io/loopring_sdk/) for information about getting started and developing with the Loopring SDK.
- [JS SDK](https://loopring.github.io/loopring_sdk)
- [Python](https://github.com/Loopring/hello_loopring)
- [APIs](https://docs.loopring.io/en/)
## ✨ Changelog
- [Changelog](https://loopring.github.io/loopring_sdk/ChangeLog.html)
## 🫂 Community
- [Loopring Website](https://loopring.org/)
- [Loopring Exchange](https://loopring.io/#/layer2)
- [Loopring Reddit](https://www.reddit.com/r/loopringorg/)
- [Loopring Medium](https://medium.com/loopring-protocol)
- [Loopring Twitter](https://twitter.com/loopringorg)
- [Loopring Telegram](https://t.me/loopring_en)
## 🎒 Getting Started
Please see our [introduction page](https://loopring.github.io/loopring_sdk/) for details on integrating the SDK into your application.
## 🙋 Protocol & Architecture
- [Whitepaper](https://loopring.org/resources/en_whitepaper.pdf)
- [Design Docs](https://github.com/LoopringSecondary/docs/wiki/Loopring3_Design)
## ❓[Help](https://desk.zoho.com/portal/loopring/en/home)
## 👉 [What is Loopring?](https://loopring.org/#/)
## 🔑 Security
- [Wallet](https://security.loopring.io/)
- [Protocol Audit](https://loopring.org/resources/loopring1.0_audit.pdf)
================================================
FILE: docs/SUMMARY.md
================================================
# Summary
### Overview
- [Introduction](README.md)
- [Changelog](Changelog.md)
- [GitHub](https://github.com/Loopring/loopring_sdk)
### SDKs demo
- [JS SDK](./js_sdk/README.md)
- [Exchange](./js_sdk/exchange/exchange.md)
- [Web Socket](./js_sdk/exchange/webSocket.md)
- [Amm](./js_sdk/exchange/ammpool_api.md)
- [Account](./js_sdk/README.md#mock-account)
- [Active Account](./js_sdk/account/activeAccount.md)
- [Fees](./js_sdk/account/fee.md)
- [Signature](./js_sdk/account/signature.md)
- [Transaction Recorder](./js_sdk/account/historyRecord.md)
- [ERC20](./js_sdk/README.md#mock-erc20-token-map)
- [Deposit](./js_sdk/deposit/depositERC20.md)
- [Transfer](./js_sdk/transfer/transferERC20.md)
- [Withdraw](./js_sdk/withdraw/withdrawERC20.md)
- [Order](./js_sdk/erc20Trade/orderERC20.md)
- [NFT](./js_sdk/README.md#mock-account)
- [Deposit](./js_sdk/deposit/depositNFT.md)
- [Transfer](./js_sdk/transfer/transferNFT.md)
- [Withdraw](./js_sdk/withdraw/withdrawNFT.md)
- [Mint](./js_sdk/NFTAction/mintNFT.md)
- [MetaData](./js_sdk/NFTAction/metaNFT.md)
- [Collection](./js_sdk/NFTAction/collectionNFT.md)
- [Deploy](./js_sdk/NFTAction/deployNFT.md)
- [Trade](./js_sdk/NFTAction/tradeNFT.md)
- [Validate Order](./js_sdk/NFTAction/validateNFTOrder.md)
### Links
- [Python](https://github.com/Loopring/hello_loopring)
- [APIs](https://docs.loopring.io/en/)
- [About us](https://loopring.org/#/)
- [Submit a Request](https://desk.zoho.com/portal/loopring/en/newticket)
================================================
FILE: docs/about_us.md
================================================
##### written by loopring dev team.
================================================
FILE: docs/js_sdk/Deposit.md
================================================
# Deposit from Ethereum L1 to Loopring, First Step for Start L2
- [Step1: getUser Layer1 ETH balance](#step1️⃣-getuser-layer1-eth-balance)
- [ETH](#1-let-start-from-eth)
- [ERC20](#2-erc20-token-such-as-lrc)
- [NFT](#3-nft)
- [Step2: Allow and Approve Loopring to get transaction those Token access](#step2️⃣-allow-and-approve-loopring-to-get-transaction-those-token-access)
- [ETH](#1-eth-skip-this-step)
- [ERC20](#2-erc20-token-such-as-lrc-1)
- [NFT](#3-nft-1)
- [Step3: Deposit](#step3️⃣-deposit)
- [ETH](#1-eth-same-as-erc20-only-can-not-deposit-all-for-gas-cost)
- [ERC20](#2-erc20-token-such-as-lrc-2)
- [NFT](#3-nft-2)
- [Additional & Reference](#additional--reference)
- [Approve Simple Signature Demo](#approve-simple-signature-demo)
- [Deposit Signature Demo](#deposit-signature-demo-fee-is-pay-by-eth-only-current-fee-is-0)
>**All Deposit Method, User should have enough `ETH` pay for the >Ethereum Gas (Loopring have no charge, no fee for Deposit).**
Before start read this Doc, make sure you understand how to create an We3 with an Ethereum provider
Let's start step by step how to Deposit from Ethereum L1 to Loopring ( Demo as [Loopring JS SDK](https://loopring.github.io/loopring_sdk) ):
Connect Wallet processing...
When you connect with Wallet (EOA or Loopring Wallet), you will know your `accAddress = ${Account_Address}` and have a `web3` instance
User has Three chooses Deposit `ETH`; `ERC20 Token (Such as LRC )`; `NFT (ERC721 & ERC1155)`;
***
### Step1️⃣: getUser Layer1 ETH balance
#### 1. Let start from ETH
```ts
const { ethBalance } = await LoopringAPI.exchangeAPI.getEthBalances({owner: accAddress});
```
SDK: [getEthBalances](https://github.com/Loopring/loopring_sdk/blob/master/src/api/exchange_api.ts#L514)
API: [/api/v3/eth/balances](https://uat2.loopring.io/api/v3/eth/balances?owner=0xfF7d59D9316EBA168837E3eF924BCDFd64b237D8)
Choose deposit amount from UI
>tips: user should keep some ETH pay for Ethereum Gas
#### 2. ERC20 Token (Such as LRC)
```ts
const { ethBalance } = await LoopringAPI.exchangeAPI.getEthBalances({owner: accAddress});
//tokenArr is Loopring supprot ERC20 TokenId Array.jion(',')
const { tokenBalances } = await LoopringAPI.exchangeAPI.getTokenBalances({owner: accAddress, token: tokenArr.join()})
```
API: [/api/v3/eth/tokenBalances](https://uat2.loopring.io/api/v3/eth/tokenBalances?owner=0xfF7d59D9316EBA168837E3eF924BCDFd64b237D8&token=0xfc28028d9b1f6966fe74710653232972f50673be%2C0x0000000000000000000000000000000000000000%2C0xd4e71c4bb48850f5971ce40aa428b09f242d3e8a%2C0xcd2c81b322a5b530b5fa3432e57da6803b0317f7%2C0x47525e6a5def04c9a56706e93f54cc70c2e8f165)
> {tokenArr} = getMixMarkets()
> SDK:[getMixMarkets](https://github.com/Loopring/loopring_sdk/blob/master/src/api/exchange_api.ts#L409)
> API:[/api/v3/mix/markets](https://api.loopring.network/api/v3/mix/markets) Market pair reduce to Unique Token Name ['ETH','LRC','USDT',...]
#### 3. NFT
- Prepare Token Address `nftTokenAddress`
- NFT ID `nftId`
- Know NFT Type `ERC721` or `ERC1155`
```ts
const response = await nft.getNFTBalance({
web3,
account: accAddress,
tokenAddress: nftTokenAddress,
nftId: nftId,
nftType: NFTType.ERC1155,
});
```
SDK: [getNFTBalance](https://github.com/Loopring/loopring_sdk/blob/master/src/api/nft_api.ts#L100)
***
### Step2️⃣: Allow and Approve Loopring to get transaction those Token access
#### 1. ETH Skip this step
#### 2. ERC20 Token (Such as LRC )
- check Allowances
- getNonce web3.eth.getTransactionCount
- contract.approveMax
```ts
import {getTradeArg} from "./ws_defs";
const {tokenAllowances} = await exchangeAPI.getAllowances({
owner: accAddress,
token: "LRC",
})
if (tokenAllowances["LRC"] === undefined || tokenAllowances["LRC"] < getTradeArgValue){
const nonce = await web3.eth.getTransactionCount(accAddress);
const response = await contract.approveMax(
web3,
accAddress,
tokenAddress, // LRC address {tokenIdMap} = getTokens(); tokenIdMap['LRC']
depositAddress, //{exchangeInfo} = getExchangeInfo() exchangeInfo.depositAddress
gasPrice,
gasLimit,
ChainId.GOERLI,
nonce,
true
);
}
```
SDK:[getAllowances](https://github.com/Loopring/loopring_sdk/blob/master/src/api/exchange_api.ts#L583)
API:[/api/v3/eth/allowances](https://uat2.loopring.io/api/v3/eth/allowances?owner=0xfF7d59D9316EBA168837E3eF924BCDFd64b237D8&token=0xfc28028d9b1f6966fe74710653232972f50673be)
SDK:[getExchangeInfo](https://github.com/Loopring/loopring_sdk/blob/master/src/api/exchange_api.ts#L624)
API:[/api/v3/exchange/info](https://uat2.loopring.io/api/v3/exchange/info)
SDK:[getTokens](https://github.com/Loopring/loopring_sdk/blob/master/src/api/exchange_api.ts#L416)
API:[/apiv3/exchange/tokens](https://uat2.loopring.io/api/v3/exchange/tokens)
SDK:[approveMax](https://github.com/Loopring/loopring_sdk/blob/master/src/api/contract_api.ts#L271)
[Approve Signature Demo](#approve-simple-signature-demo)
#### 3. NFT
- check nft isApprovedForAll
- getNonce web3.eth.getTransactionCount
- contract.approveNFT (ALL) by nftTokenAddress
```ts
const isApproved = await nft.isApprovedForAll({
web3,
from: accAddress,
exchangeAddress: exchangeAddr, //{exchangeInfo} = getExchangeInfo() exchangeInfo.exchangeAddr
nftType: NFTType.ERC1155,
tokenAddress: nftTokenAddress,
});
if(!isApproved){
const nonce = await web3.eth.getTransactionCount(accAddress);
const response = await nft.approveNFT({
web3,
from: accAddress,
depositAddress,
tokenAddress: nftTokenAddress,
tokenId: nftId,
nftType: NFTType.ERC1155,
gasPrice,
gasLimit,
chainId: ChainId.GOERLI,
nonce,
approved: true,
sendByMetaMask: true,
});
}
```
SDK:[isApprovedForAll](https://github.com/Loopring/loopring_sdk/blob/master/src/api/nft_api.ts#L312)
SDK:[approveNFT](https://github.com/Loopring/loopring_sdk/blob/master/src/api/nft_api.ts#L235)
[Approve Signature Demo](#approve-simple-signature-demo)
***
### Step3️⃣: Deposit
#### 1. ETH (Same as ERC20, only can not deposit all for Gas cost)
#### 2. ERC20 Token (Such as LRC )
```ts
const nonce = await web3.eth.getTransactionCount(accAddress);
const response = await contract.deposit(
web3,
accAddress,
exchangeAddr, // {exchangeInfo} = getExchangeInfo() exchangeInfo.exchangeAddr
tokenInfo,
10, // tradeValue
0, // fee 0
gasPrice,
gasLimit,
ChainId.GOERLI,
nonce,
true
);
```
SDK:[deposit](https://github.com/Loopring/loopring_sdk/blob/master/src/api/contract.ts#L300)
[Deposit Signature Demo](#deposit-signature-demo-fee-is-pay-by-eth-only-current-fee-is-0)
#### 3. NFT
```ts
const nonce = await web3.eth.getTransactionCount(accAddress);
const response = await nft.depositNFT({
web3,
from:accAddress,
exchangeAddress::exchangeAddr, //{exchangeInfo} = getExchangeInfo() exchangeInfo.exchangeAddr
nftType: NFTType.ERC1155,
tokenAddress: nftTokenAddress,
amount: 1,
gasPrice,
gasLimit,
chainId: ChainId.GOERLI,
nonce,
sendByMetaMask:true}
);
```
SDK:[depositNFT](https://github.com/Loopring/loopring_sdk/blob/master/src/api/nft_api.ts#L354)
[Deposit Signature Demo](#deposit-signature-demo-fee-is-pay-by-eth-only-current-fee-is-0)
***
### Additional & Reference
#### Approve Simple Signature Demo
For more detail about genERC{XXX}Data please read [Contract ABI Specification](//https://docs.soliditylang.org/en/develop/abi-spec.html#)
```ts
/* ERC20 Approve Data structure */
const data = genERC20Data(ERC20Method.Approve, {
_spender: depositAddress,
_value:"0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
});
/* NFT setApprovalForAll Data structure */
// if (nftType === NFTType.ERC1155) {
// data = this._genERC1155Data(NFTMethod.setApprovalForAll, {
// operator: depositAddress,
// approved,
// });
// } else if (nftType === NFTType.ERC721) {
// //TODO list not support now
// data = this._genERC721Data(NFTMethod.setApprovalForAll, {
// operator: depositAddress,
// approved,
// });
// }
const gasPrice = fm.fromGWEI(gasPrice).toNumber();
web3.eth.sendTransaction({
from:accAddress,
to: depositAddress, //{exchangeInfo} = getExchangeInfo() exchangeInfo.depositAddress
value:"0",
data,
chainId,
nonce,
gasPrice,
gasLimit,
}).then((_error,transactionHash: string) =>{
if (!err) {
resolve({ result: transactionHash });
} else {
resolve({ error: { message: err.message } });
}
});
```
### Deposit Signature Demo (fee is pay by ETH only current fee is 0)
- tokenSymbol is ETH, sendTransaction value should be `amount + fee`
- Other tokenSymbol as LRC sendTransaction value is `fee`
- `fee` is pay by ETH only (current fee is 0)
```ts
const tokenAddress = "0x?????????";
const tokenSymbol = "LRC";
const fee = 0;
/* tokenSymbol is ETH, sendTransaction value should be `amount + fee` (current fee is 0)
* other tokenSymbol as LRC addresss valueC is fee (current fee is 0)
*/
const value = tokenSymbol === "ETH"? amount + fee : fee;
const data = genExchangeData(ERC20Method.Deposit, {
tokenAddress,
amount,
from,
to: from,
extraData: "",
});
/* NFT deposit Data structure */
// const data = genExchangeData(NFTMethod.depositNFT, {
// from,
// to: from,
// nftType,
// tokenAddress,
// nftId,
// amount,
// extraData: extraData ? extraData : "",
// });
web3.eth.sendTransaction({
from:accAddress,
to:exchangeAddress, //{exchangeInfo} = getExchangeInfo() exchangeInfo.depositAddress
value,
data,
chainId,
nonce,
gasPrice,
gasLimit,
}).then((_error,transactionHash: string) =>{
if (!err) {
resolve({ result: transactionHash });
} else {
resolve({ error: { message: err.message } });
}
});
return await sendRawTx(
web3,
from,
exchangeAddress,
valueC.toFixed(),
data,
chainId,
nonce,
gasPrice,
gasLimit,
sendByMetaMask
);
```
last but not least, waiting and check your layer 2 account Balance... start Layer2
#### Reference
- @Loopring-web/web3-provider Package & [DEMO](https://github.com/Loopring/web3-provider)
- Loopring allow you directory dev with our [APIs](https://docs.loopring.io/en/)
- For your Web-app & Dapp welcome use our [JS SDK](https://loopring.github.io/loopring_sdk)
================================================
FILE: docs/js_sdk/NFTAction/collectionNFT.md
================================================
# Collection NFT
Definition: allow user create a NFT Collection with different Contract(token) address.
- allow user mint the NFTs with collection
- when collection deployed, NFTs will have different Contract(token) address in layer1
- Loopring own collection on L2, allow user to view/edit their Collection information.
- will soon enable the "Import Collection" to manage legacy NFTs
***
## Step 1. get Account
```ts
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
```
***
## Step 2. get eddsaKey
```ts
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
```
***
## Step 3. get apiKey
```ts
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
```
***
## Step 4. get storageId
```ts
const storageId = await LoopringAPI.userAPI.getNextStorageId(
{
accountId: accInfo.accountId,
sellTokenId: TOKEN_INFO.tokenMap[ "LRC" ].tokenId, // same as maxFee tokenId
},
apiKey
);
```
***
## Step 5. get collection Information(tokenAddress)
```ts
const collectionRes = await LoopringAPI.userAPI
.getUserOwenCollection({
owner: accInfo.owner,
tokenAddress: mockData.nftTokenAddress,
isMintable: true
},
apiKey
)
if ((collectionRes &&
((collectionRes as sdk.RESULT_INFO).code ||
(collectionRes as sdk.RESULT_INFO).message)) || !collectionRes.collections.length
) {
console.log("Collection is disable to mint ");
throw "Collection is disable to mint ";
}
const collectionMeta = (collectionRes as any).collections[ 0 ] as CollectionMeta;
const counterFactualNftInfo: NFTCounterFactualInfo = {
nftOwner: accInfo.owner,
nftFactory: collectionMeta.nftFactory ?? sdk.NFTFactory_Collection[ sdk.ChainId.GOERLI ],
nftBaseUri: collectionMeta.baseUri,
};
```
***
## Step 6. fee
```ts
const fee = await LoopringAPI.userAPI.getNFTOffchainFeeAmt(
{
accountId: accInfo.accountId,
tokenAddress: collectionMeta.contractAddress,
requestType: sdk.OffchainNFTFeeReqType.NFT_MINT,
},
apiKey
);
```
***
## Step7. Mint
```ts
const response = await LoopringAPI.userAPI.submitNFTMint({
request: {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
minterId: accInfo.accountId,
minterAddress: accInfo.owner,
toAccountId: accInfo.accountId,
toAddress: accInfo.owner,
nftType: 0,
tokenAddress: collectionMeta.contractAddress,
nftId: LOOPRING_EXPORTED_ACCOUNT.nftId, //nftId.toString(16),
amount: "1",
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
storageId: storageId.offchainId ?? 9,
maxFee: {
tokenId: TOKEN_INFO.tokenMap[ "LRC" ].tokenId,
amount: fee.fees[ "LRC" ].fee ?? "9400000000000000000",
},
counterFactualNftInfo,
royaltyPercentage: 5,
forceToMint: true, // suggest use as false, for here is just for run test
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.Unknown,
eddsaKey: eddsaKey.sk,
apiKey: apiKey,
});
```
____
### ps: Mint with legacy nftFactory
<font color='red'>! Mint NFT from this way has no collection information at deploy contract(tokenAdress is
unique)</font>
***
#### Step 1,2,3,4 is same logic
#### Step 5. get tokenAddress
```ts
const counterFactualNftInfo = {
nftOwner: accInfo.owner,
nftFactory: sdk.NFTFactory[ sdk.ChainId.GOERLI ],
nftBaseUri: "",
};
const nftTokenAddress =
LoopringAPI.nftAPI.computeNFTAddress(counterFactualNftInfo)
.tokenAddress || "";
console.log("nftTokenAddress", nftTokenAddress);
```
***
#### Step 6. get fee
```ts
const fee = await LoopringAPI.userAPI.getNFTOffchainFeeAmt(
{
accountId: accInfo.accountId,
tokenAddress: nftTokenAddress,
requestType: sdk.OffchainNFTFeeReqType.NFT_MINT,
},
apiKey
);
```
#### Step 7. Mint
```ts
const response = await LoopringAPI.userAPI.submitNFTMint({
request: {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
minterId: accInfo.accountId,
minterAddress: accInfo.owner,
toAccountId: accInfo.accountId,
toAddress: accInfo.owner,
nftType: 0,
tokenAddress: nftTokenAddress,
nftId: LOOPRING_EXPORTED_ACCOUNT.nftId, //nftId.toString(16),
amount: "1",
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
storageId: storageId.offchainId ?? 9,
maxFee: {
tokenId: TOKEN_INFO.tokenMap[ "LRC" ].tokenId,
amount: fee.fees[ "LRC" ].fee ?? "9400000000000000000",
},
royaltyPercentage: 5,
counterFactualNftInfo,
forceToMint: true, // suggest use as false, for here is just for run test
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.Unknown,
eddsaKey: eddsaKey.sk,
apiKey: apiKey,
});
```
================================================
FILE: docs/js_sdk/NFTAction/deployNFT.md
================================================
# Deploy NFT
Definition: Only nft minter can deploy NFT
***
## Step 1. get Account
```ts
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
```
***
## Step 2. get eddsaKey
```ts
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
```
***
## Step 3. get apiKey
```ts
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
```
***
## Step 4. get fee
```ts
const fee = await LoopringAPI.userAPI.getNFTOffchainFeeAmt(
{
accountId: accInfo.accountId,
requestType: sdk.OffchainNFTFeeReqType.NFT_DEPLOY,
amount: "0",
},
apiKey
);
console.log(fee);
```
***
## Step 5. get storageId
```ts
const storageId = await LoopringAPI.userAPI.getNextStorageId(
{
accountId: accInfo.accountId,
sellTokenId: TOKEN_INFO.tokenMap["LRC"].tokenId, // same as Step 7. transfer->token->tokenId
},
apiKey
);
```
***
## Step 6. broker
```ts
const {broker} = await LoopringAPI.exchangeAPI.getAvailableBroker();
```
***
## Step 7. Build transfer & Deploy
```ts
const transfer = {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
payerAddr: LOOPRING_EXPORTED_ACCOUNT.address,
payerId: LOOPRING_EXPORTED_ACCOUNT.accountId,
payeeAddr: broker,
// payeeAddr: LOOPRING_EXPORTED_ACCOUNT.address2,
storageId: storageId.offchainId,
token: {
tokenId: TOKEN_INFO.tokenMap["LRC"].tokenId,
volume: fee.fees["LRC"].fee ?? "9400000000000000000",
},
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
};
const response = await LoopringAPI.userAPI.submitDeployNFT({
request: {
transfer,
tokenAddress: LOOPRING_EXPORTED_ACCOUNT.nftTokenAddress,
nftData: LOOPRING_EXPORTED_ACCOUNT.nftData,
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.Unknown,
eddsaKey: eddsaKey.sk,
apiKey: apiKey,
});
console.log(response);
```
================================================
FILE: docs/js_sdk/NFTAction/metaNFT.md
================================================
# NFT META METHODS
***
## getContractNFTMeta
```ts
const result = await LoopringAPI.nftAPI.getContractNFTMeta({
web3,
tokenAddress: LOOPRING_EXPORTED_ACCOUNT.nftTokenAddress,
nftId: LOOPRING_EXPORTED_ACCOUNT.nftId,
nftType: sdk.NFTType.ERC1155,
});
console.log(result);
```
***
## getInfoForNFTTokens
```ts
const response = await LoopringAPI.nftAPI.getInfoForNFTTokens({
nftDatas: [LOOPRING_EXPORTED_ACCOUNT.nftData],
});
console.log(`getInfoForNFTTokens: response: `, JSON.stringify(response));
```
***
## computeNFTAddress
```ts
const response = LoopringAPI.nftAPI.computeNFTAddress({
nftOwner: "0xE20cF871f1646d8651ee9dC95AAB1d93160b3467",
nftFactory: "0x40F2C1770E11c5bbA3A26aEeF89616D209705C5D",
});
console.log(
`computeNFTAddress:`,
response,
"0xee354d81778a4c5a08fd9dbeb5cfd01a840a746d"
);
```
***
## ipfsCid0ToNftID
```ts
const ipfs = "QmNuqdeWUJ9iEiw5qZfJ2pJ9onqAS45ZffvV8JQSUzp7DQ";
const nftID =
"0x0880847b7587968f32ba6c741f9d797d9dc64971979922a80c4e590453b8dc2f";
console.log(
`ipfsCid0ToNftID: ipfs: `,
ipfs,
LoopringAPI.nftAPI.ipfsCid0ToNftID(ipfs)
);
```
***
## ipfsNftIDToCid
```ts
const ipfs = "QmNuqdeWUJ9iEiw5qZfJ2pJ9onqAS45ZffvV8JQSUzp7DQ";
const nftID =
"0x0880847b7587968f32ba6c741f9d797d9dc64971979922a80c4e590453b8dc2f";
console.log(
`ipfsCid0ToNftID: nftID: `,
nftID,
LoopringAPI.nftAPI.ipfsNftIDToCid(nftID)
);
```
================================================
FILE: docs/js_sdk/NFTAction/mintNFT.md
================================================
# Mint NFT
Definition: Mint Layer2 NFT, Loopring follow the ipfs NFT format, IPFS CID will convert to nftId, please view MetaNFT.md
> <p style={color:"red"}>!!! important describe<p>
> <p>Follow mehod is the simple way for mint NTF, but this kind of NFT will using the same contact & with no Contract metadata forever on L1</p>
> <p>New Version of NFT will has it isolate Contract/colletion with metadata inforamtion</p>
> <P>From Step 3. nftTokenAddress please follow create `collectionNFT` step create collection(contract), the api will return follow info for mint NFT</p>
>
```ts
tokenAddress: collectionMeta.contractAddress
counterFactualNftInfo: {
nftOwner: ccInfo.owner,
nftFactory: collectionMeta.nftFactory ?? sdk.NFTFactory_Collection[chainId],
nftBaseUri: collectionMeta?.baseUri ?? "",
},
```
## Step 1. get Account
```ts
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
```
***
## Step 2. get eddsaKey
```ts
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
```
***
## Step 3. get apiKey
```ts
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey({
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
```
***
## Step 4. get storageId
```ts
const storageId = await LoopringAPI.userAPI.getNextStorageId(
{
accountId: accInfo.accountId,
sellTokenId: TOKEN_INFO.tokenMap[ "LRC" ].tokenId, // same as maxFee tokenId
},
apiKey
);
```
***
## Step 5. get collection Information(tokenAddress)
```ts
const collectionRes = await LoopringAPI.userAPI
.getUserOwenCollection({
owner: accInfo.owner,
tokenAddress: mockData.nftTokenAddress,
isMintable: true
},
apiKey
)
if ((collectionRes &&
((collectionRes as sdk.RESULT_INFO).code ||
(collectionRes as sdk.RESULT_INFO).message)) || !collectionRes.collections.length
) {
console.log("Collection is disable to mint ");
throw "Collection is disable to mint ";
}
const collectionMeta = (collectionRes as any).collections[ 0 ] as CollectionMeta;
const counterFactualNftInfo: NFTCounterFactualInfo = {
nftOwner: accInfo.owner,
nftFactory: collectionMeta.nftFactory ?? sdk.NFTFactory_Collection[ sdk.ChainId.GOERLI ],
nftBaseUri: collectionMeta.baseUri,
};
```
***
## Step 6. fee
```ts
const fee = await LoopringAPI.userAPI.getNFTOffchainFeeAmt(
{
accountId: accInfo.accountId,
tokenAddress: collectionMeta.contractAddress,
requestType: sdk.OffchainNFTFeeReqType.NFT_MINT,
},
apiKey
);
```
***
## Step7. Mint
```ts
const response = await LoopringAPI.userAPI.submitNFTMint({
request: {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
minterId: accInfo.accountId,
minterAddress: accInfo.owner,
toAccountId: accInfo.accountId,
toAddress: accInfo.owner,
nftType: 0,
tokenAddress: nftTokenAddress, // please read the description -> tokenAddress: collectionMeta.contractAddress,
nftId: LOOPRING_EXPORTED_ACCOUNT.nftId, //nftId.toString(16),
amount: "1",
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
storageId: storageId.offchainId ?? 9,
maxFee: {
tokenId: TOKEN_INFO.tokenMap[ "LRC" ].tokenId,
amount: fee.fees[ "LRC" ].fee ?? "9400000000000000000",
},
counterFactualNftInfo,
royaltyPercentage: 5,
forceToMint: true, // suggest use as false, for here is just for run test
// please read the description
// counterFactualNftInfo: {
// nftOwner: ccInfo.owner,
// nftFactory: collectionMeta.nftFactory ?? sdk.NFTFactory_Collection[chainId],
// nftBaseUri: collectionMeta?.baseUri ?? "",
// },
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.Unknown,
eddsaKey: eddsaKey.sk,
apiKey: apiKey,
});
```
____
### ps: Mint with legacy nftFactory
<font color='red'>! Mint NFT from this way has no collection information at deploy contract(tokenAdress is
unique)</font>
***
#### Step 1,2,3,4 is same logic
#### Step 5. get tokenAddress
```ts
const counterFactualNftInfo = {
nftOwner: accInfo.owner,
nftFactory: sdk.NFTFactory[ sdk.ChainId.GOERLI ],
nftBaseUri: "",
};
const nftTokenAddress =
LoopringAPI.nftAPI.computeNFTAddress(counterFactualNftInfo)
.tokenAddress || "";
console.log("nftTokenAddress", nftTokenAddress);
```
***
#### Step 6. get fee
```ts
const fee = await LoopringAPI.userAPI.getNFTOffchainFeeAmt(
{
accountId: accInfo.accountId,
tokenAddress: nftTokenAddress,
requestType: sdk.OffchainNFTFeeReqType.NFT_MINT,
},
apiKey
);
```
#### Step 7. Mint
```ts
const response = await LoopringAPI.userAPI.submitNFTMint({
request: {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
minterId: accInfo.accountId,
minterAddress: accInfo.owner,
toAccountId: accInfo.accountId,
toAddress: accInfo.owner,
nftType: 0,
tokenAddress: nftTokenAddress,
nftId: LOOPRING_EXPORTED_ACCOUNT.nftId, //nftId.toString(16),
amount: "1",
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
storageId: storageId.offchainId ?? 9,
maxFee: {
tokenId: TOKEN_INFO.tokenMap[ "LRC" ].tokenId,
amount: fee.fees[ "LRC" ].fee ?? "9400000000000000000",
},
royaltyPercentage: 5,
counterFactualNftInfo,
forceToMint: true, // suggest use as false, for here is just for run test
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.Unknown,
eddsaKey: eddsaKey.sk,
apiKey: apiKey,
});
```
================================================
FILE: docs/js_sdk/NFTAction/tradeNFT.md
================================================
# Trade NFT
Definition: This method is help for understand how to match a maker with a taker order
***
## tradeNFT
> Private or third account can signature and approve this order
[mock order](#MockOrder)
```ts
// Step 1. getAccount
const accInfoC = (
await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
})
).accInfo;
// Step 1. eddsaKeyC
const eddsaKeyC = await signatureKeyPairMock(accInfoC);
// Step 3. apiKey
const apiKeyC = (
await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfoC.accountId,
},
eddsaKeyC.sk
)
).apiKey;
// NFT Trade
const response = await LoopringAPI.userAPI.submitNFTTrade({
request: {
maker: {
...mockData.makerOrder,
eddsaSignature: mockData.makerOrderEddsaSignature,
},
makerFeeBips: 1000,
taker: {
...mockData.takerOrder,
eddsaSignature: mockData.takerOrderEddsaSignature,
},
takerFeeBips: 100,
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.Unknown,
apiKey: apiKeyC,
eddsaKey: eddsaKeyC.sk,
});
console.log(response);
```
***
## MockOrder
> Validate NFT Order please reader @Validate NFT Order
```ts
// Step 1. getAccount
const accInfo = (
await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
})
).accInfo;
const accInfo2 = (
await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address2,
})
).accInfo;
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
const eddsaKey2 = await signatureKeyPairMock(accInfo2, web3_2);
// Step 3. apiKey
const apiKey = (
await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
)
).apiKey;
const apiKey2 = (
await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo2.accountId,
},
eddsaKey2.sk
)
).apiKey;
// Step 4. storageId
const storageId = await LoopringAPI.userAPI.getNextStorageId(
{
accountId: accInfo.accountId,
sellTokenId: LOOPRING_EXPORTED_ACCOUNT.nftTokenId,
},
apiKey
);
const storageId2 = await LoopringAPI.userAPI.getNextStorageId(
{
accountId: accInfo2.accountId,
sellTokenId: TOKEN_INFO.tokenMap["LRC"].tokenId,
},
apiKey2
);
// Step 5. generate Order, please read validateNFTOrder
const makerOrder: sdk.NFTOrderRequestV3 = {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
accountId: accInfo.accountId,
storageId: storageId.orderId,
sellToken: {
tokenId: LOOPRING_EXPORTED_ACCOUNT.nftTokenId,
nftData: LOOPRING_EXPORTED_ACCOUNT.nftData,
amount: "1",
},
buyToken: {
tokenId: TOKEN_INFO.tokenMap["LRC"].tokenId,
amount: LOOPRING_EXPORTED_ACCOUNT.tradeLRCValue.toString(),
},
allOrNone: false,
fillAmountBOrS: false,
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
maxFeeBips: 1000,
};
const makerOrderEddsaSignature = sdk.get_EddsaSig_NFT_Order(
makerOrder,
eddsaKey.sk
);
const takerOrder: sdk.NFTOrderRequestV3 = {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
accountId: accInfo2.accountId,
storageId: storageId2.orderId,
sellToken: {
tokenId: TOKEN_INFO.tokenMap["LRC"].tokenId,
amount: LOOPRING_EXPORTED_ACCOUNT.tradeLRCValue.toString(),
},
buyToken: {
tokenId: LOOPRING_EXPORTED_ACCOUNT.nftTokenId,
nftData: LOOPRING_EXPORTED_ACCOUNT.nftData,
amount: "1",
},
allOrNone: false,
fillAmountBOrS: true,
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
maxFeeBips: 100,
};
const takerOrderEddsaSignature = sdk.get_EddsaSig_NFT_Order(
takerOrder,
eddsaKey2.sk
);
mockData = {
takerOrder,
takerOrderEddsaSignature,
makerOrder,
makerOrderEddsaSignature,
makerFeeBips: 1000,
maxFeeBips: 100,
};
```
================================================
FILE: docs/js_sdk/NFTAction/validateNFTOrder.md
================================================
# Validate NFT Order
Definition: Loopring L2 support a method help for Validate NFT one side Order, validate NFT Order is not required for
Loopring, but when make NFT Trade, it should pass this validation
## SellNFTByERC20
```ts
// Step 1. getAccount
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. apiKey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
// Step 4. storageId
const storageId = await LoopringAPI.userAPI.getNextStorageId(
{
accountId: accInfo.accountId,
sellTokenId: LOOPRING_EXPORTED_ACCOUNT.nftTokenId,
},
apiKey
);
console.log("storageId:", storageId);
// let hash: any = new BN(nftId,'hex')
// hash = toHex(hash);//new BigInteger(sha256(nftId.toString()).toString(), 16)
// Step 5. submitNFTValidateOrder
const response = await LoopringAPI.userAPI.submitNFTValidateOrder({
request: {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
accountId: accInfo.accountId,
storageId: storageId.orderId,
sellToken: {
tokenId: LOOPRING_EXPORTED_ACCOUNT.nftTokenId,
nftData: LOOPRING_EXPORTED_ACCOUNT.nftData,
amount: "1",
},
buyToken: {
tokenId: 1,
amount: "10000000000000",
},
allOrNone: false,
fillAmountBOrS: false,
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
maxFeeBips: 1000,
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.Unknown,
eddsaKey: eddsaKey.sk,
apiKey: apiKey,
});
console.log("sellNFT NFTOrderRequestV3:", response);
```
***
## BuyNFTByERC20
```ts
// Step 1. getAccount
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. apiKey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
// Step 5. submitNFTValidateOrder
const storageId = await LoopringAPI.userAPI.getNextStorageId(
{
accountId: accInfo.accountId,
sellTokenId: LOOPRING_EXPORTED_ACCOUNT.nftTokenId,
},
apiKey
);
console.log("storageId:", storageId);
const response = await LoopringAPI.userAPI.submitNFTValidateOrder({
request: {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
accountId: accInfo.accountId,
storageId: storageId.orderId,
sellToken: {
tokenId: 1,
amount: "10000000000000",
},
buyToken: {
tokenId: LOOPRING_EXPORTED_ACCOUNT.nftTokenId,
nftData: LOOPRING_EXPORTED_ACCOUNT.nftData,
amount: "1",
},
fillAmountBOrS: true,
allOrNone: false,
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
maxFeeBips: 100,
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.Unknown,
eddsaKey: eddsaKey.sk,
apiKey: apiKey,
});
```
================================================
FILE: docs/js_sdk/README.md
================================================
# Loopring SDK
Loopring SDK Initialize and Mock Data structure
***
## SDK Initialize
```ts
import * as sdk from "../index";
export class LoopringAPIClass {
public static userAPI: UserAPI;
public static exchangeAPI: ExchangeAPI;
public static ammpoolAPI: AmmpoolAPI;
public static walletAPI: WalletAPI;
public static wsAPI: WsAPI;
public static nftAPI: NFTAPI;
public static delegate: DelegateAPI;
public static globalAPI: GlobalAPI;
public static contractAPI: typeof ContractAPI;
public static __chainId__: sdk.ChainId;
public static InitApi = (chainId: sdk.ChainId) => {
LoopringAPI.userAPI = new UserAPI({ chainId });
LoopringAPI.exchangeAPI = new ExchangeAPI({ chainId });
LoopringAPI.globalAPI = new GlobalAPI({ chainId });
LoopringAPI.ammpoolAPI = new AmmpoolAPI({ chainId });
LoopringAPI.walletAPI = new WalletAPI({ chainId });
LoopringAPI.wsAPI = new WsAPI({ chainId });
LoopringAPI.nftAPI = new NFTAPI({ chainId });
LoopringAPI.delegate = new DelegateAPI({ chainId });
LoopringAPI.__chainId__ = chainId;
LoopringAPI.contractAPI = ContractAPI;
};
}
/* env:
* test: sdk.ChainId.GOERLI
* eth: sdk.ChainId.MAINNET
*/
LoopringAPIClass.InitApi({sdk.ChainId.MAINNET});
```
***
## Connect Wallet
Suggestion web3 provider
```shell
# Using npm
npm i @loopring-web/web3-provider --save
# Using yarn
yarn add @loopring-web/web3-provider
```
- [Demo Vue](https://codesandbox.io/s/vue-8nco78)
- [Demo React](https://codesandbox.io/s/react-4v50ft)
[Mock Provider](#mock-provider)
***
## Loopring ERC20 Data Structure
```ts
const {tokensMap, idIndex, addressIndex} = LoopringAPI.exchangeAPI.getTokens();
```
[Mock ERC20](#mock-erc20-token-map)
***
## Token Decimal
```ts
const uiValue = 100;
const tradeValue = sdk.toBig(uiValue).times("1e" + TOKEN_INFO.tokenMap.LRC.decimals);
```
***
## Test Mock Data
##### Mock Account
```ts
export const LOOPRING_EXPORTED_ACCOUNT = {
address: "0x727e0fa09389156fc803eaf9c7017338efd76e7f",
privateKey:
"491aecdb1d5f6400a6b62fd12a41a86715bbab675c37a4060ba115fecf94083c",
accountId: 12454,
address2: "0xb6d8c39D5528357dBCe6BEd82aC71c74e9D19079",
privateKey2:
"e020ed769032ba95d9a5207687a663d6198fe2f5cedf28a250f7cbd8c81a5263",
accountId2: 10488,
addressCF: "0x23dE4Da688c94a66E8bbE9BCc95CB03b4e209C15",
accountIdCF: 11632,
addressContractWallet: "0xD4BD7c71B6d4A09217ccc713f740d6ed8f4EA0cd",
depositAddress: "0xb684B265f650a77afd27Ce0D95252a7329B5bD72",
exchangeAddress: "0x2e76EBd1c7c0C8e7c2B875b6d505a260C525d25e",
whitelistedAddress: "0x35405E1349658BcA12810d0f879Bf6c5d89B512C",
whitelistedEddkey:
"0x27a5b716c7309a30703ede3f1a218cdec857e424a31543f8a658e7d2208db33",
// const eddkeyWhitelisted =
// "0x27a5b716c7309a30703ede3f1a218cdec857e424a31543f8a658e7d2208db33";
// apiKey: "2PYgTOZwXHkPXtJMlOMG06ZX1QKJInpoky6iYIbtMgmkbfdL4PvxyEOj0LPOfgYX",
chainId: 5,
nftTokenAddress: "0x8394cB7e768070217592572582228f62CdDE4FCE",
nftTokenId: 32768,
nftId: "0xa0ce8990402955e559799af24ea765b14ffecc32dfa1cce2dadaf20016b074e6",
nftData: "0x1a2001aac7a1fd00cef07889cdb67b1355f86e5bc9df71cfa44fa1c7b49f598f",
testNotOx: "727e0fa09389156fc803eaf9c7017338efd76e7f",
tradeLRCValue: 1000000000000000000,
tradeETHValue: 0.0001, //same as UI
gasPrice: 20, // for test
gasLimit: 200000, // for test
validUntil: Math.round(Date.now() / 1000) + 30 * 86400,
};
export const CUSTOMER_KEY_SEED = "XXXXXX" + " with key nonce: " + "${nonce}";
```
##### Mock provider
```ts
const provider = new PrivateKeyProvider(
LOOPRING_EXPORTED_ACCOUNT.privateKey,
"https://goerli.infura.io/v3/a06ed9c6b5424b61beafff27ecc3abf3"
);
const provider2 = new PrivateKeyProvider(
LOOPRING_EXPORTED_ACCOUNT.privateKey2,
"https://goerli.infura.io/v3/a06ed9c6b5424b61beafff27ecc3abf3"
);
export const web3 = new Web3(provider);
export const web3_2 = new Web3(provider2);
```
##### Mock ERC20 Token Map
```ts
export let TOKEN_INFO = {
addressIndex: {
"0x0000000000000000000000000000000000000000": "ETH",
"0xfc28028d9b1f6966fe74710653232972f50673be": "LRC",
"0xd4e71c4bb48850f5971ce40aa428b09f242d3e8a": "USDT",
"0xfeb069407df0e1e4b365c10992f1bc16c078e34b": "LP-LRC-ETH",
"0x049a02fa9bc6bd54a2937e67d174cc69a9194f8e": "LP-ETH-USDT",
"0xcd2c81b322a5b530b5fa3432e57da6803b0317f7": "DAI",
"0x47525e6a5def04c9a56706e93f54cc70c2e8f165": "USDC",
"0xf37cf4ced77b985708d591acc6bfd08586ab3409": "LP-USDC-ETH",
},
tokenMap: {
ETH: {
type: "ETH",
tokenId: 0,
symbol: "ETH",
name: "Ethereum",
address: "0x0000000000000000000000000000000000000000",
decimals: 18,
precision: 7,
precisionForOrder: 3,
orderAmounts: {
minimum: "5000000000000000",
maximum: "1000000000000000000000",
dust: "200000000000000",
},
luckyTokenAmounts: {
minimum: "50000000000000",
maximum: "1000000000000000000000",
dust: "50000000000000",
},
fastWithdrawLimit: "100000000000000000000",
gasAmounts: {
distribution: "85000",
deposit: "100000",
},
enabled: true,
isLpToken: false,
tradePairs: ["LRC", "USDT", "USDC"],
},
LRC: {
type: "erc20Trade",
tokenId: 1,
symbol: "LRC",
name: "Loopring",
address: "0xfc28028d9b1f6966fe74710653232972f50673be",
decimals: 18,
precision: 3,
precisionForOrder: 3,
orderAmounts: {
minimum: "5000000000000000000",
maximum: "5000000000000000000000000",
dust: "5000000000000000000",
},
luckyTokenAmounts: {
minimum: "50000000000000000",
maximum: "5000000000000000000000000",
dust: "50000000000000000",
},
fastWithdrawLimit: "750000000000000000000000",
gasAmounts: {
distribution: "101827",
deposit: "200000",
},
enabled: true,
isLpToken: false,
tradePairs: ["ETH"],
},
USDT: {
type: "erc20Trade",
tokenId: 2,
symbol: "USDT",
name: "USDT",
address: "0xd4e71c4bb48850f5971ce40aa428b09f242d3e8a",
decimals: 6,
precision: 2,
precisionForOrder: 3,
orderAmounts: {
minimum: "5000000",
maximum: "2000000000000",
dust: "250000",
},
luckyTokenAmounts: {
minimum: "50000",
maximum: "200000000000",
dust: "50000",
},
fastWithdrawLimit: "250000000000",
gasAmounts: {
distribution: "106233",
deposit: "200000",
},
enabled: true,
isLpToken: false,
tradePairs: ["ETH", "DAI"],
},
"LP-LRC-ETH": {
type: "erc20Trade",
tokenId: 4,
symbol: "LP-LRC-ETH",
name: "AMM-LRC-ETH",
address: "0xfeb069407df0e1e4b365c10992f1bc16c078e34b",
decimals: 8,
precision: 6,
precisionForOrder: 3,
orderAmounts: {
minimum: "100000000",
maximum: "10000000000000000000",
dust: "100000000",
},
luckyTokenAmounts: {
minimum: "100000000",
maximum: "10000000000000000000",
dust: "100000000",
},
fastWithdrawLimit: "20000000000",
gasAmounts: {
distribution: "150000",
deposit: "200000",
},
enabled: true,
isLpToken: true,
},
"LP-ETH-USDT": {
type: "erc20Trade",
tokenId: 7,
symbol: "LP-ETH-USDT",
name: "LP-ETH-USDT",
address: "0x049a02fa9bc6bd54a2937e67d174cc69a9194f8e",
decimals: 8,
precision: 6,
precisionForOrder: 3,
orderAmounts: {
minimum: "100000000",
maximum: "10000000000000",
dust: "100000000",
},
luckyTokenAmounts: {
minimum: "100000000",
maximum: "10000000000000",
dust: "100000000",
},
fastWithdrawLimit: "20000000000",
gasAmounts: {
distribution: "150000",
deposit: "200000",
},
enabled: true,
isLpToken: true,
},
DAI: {
type: "erc20Trade",
tokenId: 6,
symbol: "DAI",
name: "dai",
address: "0xcd2c81b322a5b530b5fa3432e57da6803b0317f7",
decimals: 18,
precision: 6,
precisionForOrder: 3,
orderAmounts: {
minimum: "10000000000000000000",
maximum: "100000000000000000000000",
dust: "10000000000000000",
},
luckyTokenAmounts: {
minimum: "10000000000000000000",
maximum: "100000000000000000000000",
dust: "10000000000000000000",
},
fastWithdrawLimit: "10000000000000000000000",
gasAmounts: {
distribution: "150000",
deposit: "200000",
},
enabled: true,
isLpToken: false,
tradePairs: ["USDT"],
},
USDC: {
type: "USDC",
tokenId: 8,
symbol: "USDC",
name: "USDC",
address: "0x47525e6a5def04c9a56706e93f54cc70c2e8f165",
decimals: 6,
precision: 6,
precisionForOrder: 3,
orderAmounts: {
minimum: "1000",
maximum: "10000000000000000000",
dust: "100",
},
luckyTokenAmounts: {
minimum: "1000000",
maximum: "10000000000",
dust: "1000000",
},
fastWithdrawLimit: "20000000000000000000",
gasAmounts: {
distribution: "150000",
deposit: "200000",
},
enabled: true,
isLpToken: false,
tradePairs: ["ETH"],
},
"LP-USDC-ETH": {
type: "LP-USDC-ETH",
tokenId: 9,
symbol: "LP-USDC-ETH",
name: "LP-USDC-ETH",
address: "0xf37cf4ced77b985708d591acc6bfd08586ab3409",
decimals: 8,
precision: 7,
precisionForOrder: 3,
orderAmounts: {
minimum: "100000",
maximum: "1000000000000000000000000000000000000000",
dust: "10000",
},
luckyTokenAmounts: {
minimum: "1000000000000000",
maximum: "10000000000000000000",
dust: "1000000000000000",
},
fastWithdrawLimit: "20000000000000000000",
gasAmounts: {
distribution: "150000",
deposit: "200000",
},
enabled: true,
isLpToken: true,
},
},
idIndex: {
"0": "ETH",
"1": "LRC",
"2": "USDT",
"4": "LP-LRC-ETH",
"6": "DAI",
"7": "LP-ETH-USDT",
"8": "USDC",
"9": "LP-USDC-ETH",
},
marketMap: {
"LRC-ETH": {
baseTokenId: 1,
enabled: true,
market: "LRC-ETH",
orderbookAggLevels: 5,
precisionForPrice: 6,
quoteTokenId: 0,
status: 3,
isSwapEnabled: true,
createdAt: 1617967800000,
},
"ETH-USDT": {
baseTokenId: 0,
enabled: true,
market: "ETH-USDT",
orderbookAggLevels: 3,
precisionForPrice: 3,
quoteTokenId: 2,
status: 3,
isSwapEnabled: true,
createdAt: 1617972300000,
},
"DAI-USDT": {
baseTokenId: 6,
enabled: true,
market: "DAI-USDT",
orderbookAggLevels: 2,
precisionForPrice: 4,
quoteTokenId: 2,
status: 3,
isSwapEnabled: true,
createdAt: 0,
},
"USDC-ETH": {
baseTokenId: 8,
enabled: true,
market: "USDC-ETH",
orderbookAggLevels: 3,
precisionForPrice: 3,
quoteTokenId: 0,
status: 3,
isSwapEnabled: true,
createdAt: 1636974420000,
},
},
};
```
##### Mock AMM MAP
```ts
export let AMM_MAP = {
"AMM-LRC-ETH": {
name: "LRCETH-Pool",
market: "AMM-LRC-ETH",
address: "0xfEB069407df0e1e4B365C10992F1bc16c078E34b",
version: "1.0.0",
tokens: { pooled: [1, 0], lp: 4 },
feeBips: 20,
precisions: { price: 6, amount: 5 },
createdAt: "1617967800000",
status: 31,
},
"AMM-ETH-USDT": {
name: "AMM-ETH-USDT",
market: "AMM-ETH-USDT",
address: "0x049a02FA9bc6bd54a2937E67D174cc69a9194f8e",
version: "1.0.0",
tokens: { pooled: [0, 2], lp: 7 },
feeBips: 20,
precisions: { price: 3, amount: 3 },
createdAt: "1617972300000",
status: 31,
},
"AMM-USDC-ETH": {
name: "AMM-USDC-ETH",
market: "AMM-USDC-ETH",
address: "0xf37cf4CEd77b985708D591AcC6BfD08586Ab3409",
version: "1.0.0",
tokens: {
pooled: [8, 0],
lp: 9,
},
feeBips: 20,
precisions: {
price: 3,
amount: 4,
},
createdAt: "1636974420000",
status: 0,
},
};
```
##### Mock EIP712 Typed Data
```ts
export const testTypedData: EIP712TypedData = {
types: {
EIP712Domain: [
{ name: "name", type: "string" },
{ name: "version", type: "string" },
{ name: "chainId", type: "uint256" },
{ name: "verifyingContract", type: "address" },
],
TestTypedData: [
{ name: "from", type: "address" },
{ name: "to", type: "address" },
{ name: "tokenID", type: "uint16" },
],
},
primaryType: "TestTypedData",
domain: {
name: "Loopring Protocol",
version: "3.6.0",
chainId: sdk.ChainId.GOERLI,
verifyingContract: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
},
message: {
from: LOOPRING_EXPORTED_ACCOUNT.address,
to: LOOPRING_EXPORTED_ACCOUNT.address2,
tokenID: TOKEN_INFO.tokenMap.LRC.tokenId,
},
};
```
##### Mock generate eddsaKey
```ts
export async function signatureKeyPairMock(
accInfo: sdk.AccountInfo,
_web3: Web3 = web3
) {
const eddsaKey = await sdk.generateKeyPair({
web3: _web3,
address: accInfo.owner,
keySeed:
accInfo.keySeed ??
sdk.GlobalAPI.KEY_MESSAGE.replace(
"${exchangeAddress}",
LOOPRING_EXPORTED_ACCOUNT.exchangeAddress
).replace("${nonce}", (accInfo.nonce - 1).toString()),
walletType: sdk.ConnectorNames.MetaMask,
chainId: sdk.ChainId.GOERLI,
});
return eddsaKey;
}
```
================================================
FILE: docs/js_sdk/account/activeAccount.md
================================================
# Active Account
Definition: After user Deposit or (Third-Part Transfer), how to active Loopring L2 account.
***
## Step 1. get account info
```ts
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
```
***
## Step 2. use keySeed or CUSTOMER_KEY_SEED generateKeyPair
```ts
const keySeed = sdk.BaseAPI.KEY_MESSAGE.replace(
"${exchangeAddress}",
LOOPRING_EXPORTED_ACCOUNT.exchangeAddress
).replace("${nonce}", accInfo.nonce.toString());
const eddsaKey = await sdk.generateKeyPair({
web3,
address: accInfo.owner,
keySeed,
walletType: sdk.ConnectorNames.MetaMask,
chainId: sdk.ChainId.GOERLI,
});
console.log("eddsakey:", eddsaKey.sk);
```
Or
```ts
// CUSTOMER_KEY_SEED = "XXXXXX" + " with key nonce: " + "${nonce}";
const keySeed = CUSTOMER_KEY_SEED.replace(
"${nonce}",
accInfo.nonce.toString()
const eddsaKey = await sdk.generateKeyPair({
web3,
address: accInfo.owner,
keySeed,
walletType: sdk.ConnectorNames.MetaMask,
chainId: sdk.ChainId.GOERLI,
});
console.log("eddsakey:", eddsaKey.sk);
```
***
## Step 3. get fee
```ts
const fee = await LoopringAPI.globalAPI.getActiveFeeInfo({
accountId: accInfo.accountId,
});
console.log("fee:", fee);
```
***
## Step 4. updateAccount (active or rest)
```ts
const result = await LoopringAPI.userAPI.updateAccount({
request: {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
owner: accInfo.owner,
accountId: accInfo.accountId,
publicKey: {x: eddsaKey.formatedPx, y: eddsaKey.formatedPy},
maxFee: {
tokenId: TOKEN_INFO.tokenMap["LRC"].tokenId,
volume: fee.fees["LRC"].fee ?? "9400000000000000000",
},
keySeed,
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
nonce: accInfo.nonce as number,
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.Unknown,
isHWAddr: false,
});
const {accInfo: updateAccountInfo} =
await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log(
"updateAccount Result: ",
result,
"updateAccountInfo:",
updateAccountInfo
);
```
================================================
FILE: docs/js_sdk/account/fee.md
================================================
# Fee
Loopring have 2 get Fee api:
- getOffchainFeeAmt:
- `ORDER`,
- `FFCHAIN_WITHDRAWAL`,
- `UPDATE_ACCOUNT`,
- `TRANSFER`,
- `FAST_OFFCHAIN_WITHDRAWAL`,
- `OPEN_ACCOUNT`,
- `AMM_EXIT`,
- `DEPOSIT`,
- `AMM_JOIN`,
- getNFTOffchainFeeAmt:
- `NFT_MINT`,
- `NFT_WITHDRAWAL`,
- `NFT_TRANSFER`,
- `NFT_DEPLOY`,
***
## Fee: updateAccount
```ts
// Step 1. get account info
console.log(LoopringAPI.exchangeAPI.getAccount);
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. get apikey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
return {accInfo, eddsaKey, apiKey};
const response = await LoopringAPI.userAPI.getOffchainFeeAmt(
{
accountId: accInfo.accountId,
requestType: sdk.OffchainFeeReqType.UPDATE_ACCOUNT,
},
apiKey
);
console.log("updateAccount:", response);
```
***
## Fee: transfer
```ts
// Step 1. get account info
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. get apikey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
return {accInfo, eddsaKey, apiKey};
const response = await LoopringAPI.userAPI.getOffchainFeeAmt(
{
accountId: accInfo.accountId,
requestType: sdk.OffchainFeeReqType.TRANSFER,
},
apiKey
);
console.log("transfer:", response);
```
***
## Fee: withdraw
```ts
// Step 1. get account info
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. get apikey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
return {accInfo, eddsaKey, apiKey};
const response = await LoopringAPI.userAPI.getOffchainFeeAmt(
{
accountId: accInfo.accountId,
tokenSymbol: TOKEN_INFO.tokenMap.LRC.symbol,
requestType: sdk.OffchainFeeReqType.OFFCHAIN_WITHDRAWAL,
},
apiKey
);
console.log("withdraw:", response);
```
***
## Fee: fastWithdraw
```ts
// Step 1. get account info
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. get apikey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
return {accInfo, eddsaKey, apiKey};
const response = await LoopringAPI.userAPI.getOffchainFeeAmt(
{
accountId: accInfo.accountId,
requestType: sdk.OffchainFeeReqType.FAST_OFFCHAIN_WITHDRAWAL,
tokenSymbol: TOKEN_INFO.tokenMap.LRC.symbol,
},
apiKey
);
console.log("fastWithdraw:", response);
```
***
## Fee: order
```ts
// Step 1. get account info
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. get apikey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
return {accInfo, eddsaKey, apiKey};
const response = await LoopringAPI.userAPI.getOffchainFeeAmt(
{
accountId: accInfo.accountId,
requestType: sdk.OffchainFeeReqType.ORDER,
tokenSymbol: TOKEN_INFO.tokenMap.LRC.symbol,
},
apiKey
);
console.log("order:", response);
```
***
## Fee: amm_exit
```ts
// Step 1. get account info
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. get apikey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
return {accInfo, eddsaKey, apiKey};
const response = await LoopringAPI.userAPI.getOffchainFeeAmt(
{
accountId: accInfo.accountId,
requestType: sdk.OffchainFeeReqType.AMM_EXIT,
},
apiKey
);
console.log("amm_exit:", response);
```
***
## Fee: amm_join
```ts
// Step 1. get account info
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. get apikey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
return {accInfo, eddsaKey, apiKey};
const response = await LoopringAPI.userAPI.getOffchainFeeAmt(
{
accountId: accInfo.accountId,
requestType: sdk.OffchainFeeReqType.AMM_JOIN,
},
apiKey
);
console.log("amm_join:", response);
```
***
## Fee: NFT Transfer
```ts
// Step 1. get account info
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. get apikey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
return {accInfo, eddsaKey, apiKey};
const response = await LoopringAPI.userAPI.getNFTOffchainFeeAmt(
{
accountId: accInfo.accountId,
requestType: sdk.OffchainNFTFeeReqType.NFT_TRANSFER,
tokenAddress: LOOPRING_EXPORTED_ACCOUNT.nftTokenAddress,
},
apiKey
);
console.log("NFTTransfer:", response);
```
***
## Fee: NFT Withdrawal
```ts
// Step 1. get account info
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. get apikey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
return {accInfo, eddsaKey, apiKey};
const response = await LoopringAPI.userAPI.getNFTOffchainFeeAmt(
{
accountId: accInfo.accountId,
tokenAddress: LOOPRING_EXPORTED_ACCOUNT.nftTokenAddress,
requestType: sdk.OffchainNFTFeeReqType.NFT_WITHDRAWAL,
},
apiKey
);
console.log("NFTWithdrawal:", response);
```
## Fee: NFT Mint
```ts
// Step 1. get account info
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. get apikey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
const response = await LoopringAPI.userAPI.getNFTOffchainFeeAmt(
{
accountId: accInfo.accountId,
requestType: sdk.OffchainNFTFeeReqType.NFT_MINT,
tokenAddress: LOOPRING_EXPORTED_ACCOUNT.nftTokenAddress
},
apiKey
);
console.log("NFTWithdrawal:", response);
```
## Fee: NFT Deploy
```ts
// Step 1. get account info
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount(
{owner: LOOPRING_EXPORTED_ACCOUNT.address,});
console.log("accInfo:", accInfo);
// Step 2. eddsaKey
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
// Step 3. get apikey
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
const response = await LoopringAPI.userAPI.getNFTOffchainFeeAmt(
{
accountId: accInfo.accountId,
requestType: sdk.OffchainNFTFeeReqType.NFT_DEPLOY,
},
apiKey
);
console.log("NFTWithdrawal:", response);
```
***
## getActiveFeeInfo without apikey & accountId
```ts
const response = await LoopringAPI.globalAPI.getActiveFeeInfo({});
```
***
## getActiveFeeInfo without apikey with accountId
```ts
const response = await
LoopringAPI.globalAPI.getActiveFeeInfo({accountId: LOOPRING_EXPORTED_ACCOUNT.accountId});
```
================================================
FILE: docs/js_sdk/account/historyRecord.md
================================================
# User Actions History
For check account Actions, more detail such as filters please read SDK interface or API .
***
## getUserTrades
```ts
async () => {
const result = await LoopringAPI.userAPI.getUserTrades(
{
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
offset: 0,
limit: 20,
fillTypes: sdk.TradesFillTypes.dex,
},
apiKey
);
console.log("getUserTrades:", result);
```
***
## getUserTxs
```ts
async () => {
const result = await LoopringAPI.userAPI.getUserTxs(
{
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
types: [
sdk.UserTxTypes.DEPOSIT,
sdk.UserTxTypes.TRANSFER,
sdk.UserTxTypes.ONCHAIN_WITHDRAWAL,
],
},
apiKey
);
console.log("getUserTxs:", result);
```
***
## getUserNFTTransactionHistory
```ts
async () => {
const result = await LoopringAPI.userAPI.getUserNFTTransactionHistory(
{
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
types: [
sdk.UserNFTTxTypes.DEPOSIT,
sdk.UserNFTTxTypes.TRANSFER,
sdk.UserNFTTxTypes.WITHDRAW,
sdk.UserNFTTxTypes.MINT,
],
},
apiKey
);
console.log("getUserNFTTransactionHistory:", result);
```
***
## getOrders
```ts
async () => {
const result = await LoopringAPI.userAPI.getOrders(
{
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
orderTypes: sdk.OrderType.LimitOrder,
},
apiKey
);
console.log("getOrders:", result);
```
================================================
FILE: docs/js_sdk/account/signature.md
================================================
# Signature
Loopring SDK support EOA (EOA hardware wallet) & Loopring Smart wallet Signature
- For Browser extension, Dapp, Hardware wallet we only support for EOA
- For Loopring Smart wallet (App), Provider gateway only can be walletConnect
## Follow is the provider gateway we inject & test:
- MetaMask (Ledger, Trezor)
- WalletConnect (Authereum, Loopring Smart wallet )
- Coinbase
- [Coming soon...](https://desk.zoho.com/portal/loopring/en/newticket)
## For signature:
For eth_sign signing types (eth_sign, personal_sign, v1, v3, v4)
### EOA:
- For Browser
extension ([More information: signing-data](https://docs.metamask.io/guide/signing-data.html#a-brief-history))
+ common EOA we use the `v4` signature and `web3.eth.personal.ecRecover` validate signature
+ when `v4` signature is failed for any step, we will try `personal_sign` and `web3.eth.personal.ecRecover` validate
signature
- For Dapp
+ when loopring Dex is inside Dapp Webview & connect by `window.ethereum`, we remove the `web3.eth.personal.ecRecover`
validate
### Loopring Smart wallet:
- For Smart wallet we send `eth_signTypedData` by walletConnect & validate
ABI.Contracts.ContractWallet.encodeInputs `isValidSignature(bytes32,bytes)`
### Loopring Counterfactual wallet:
- signature is same as Smart wallet
- But ecRecover is by
walletOwner, `const {walletOwner} = await LoopringAPI.exchangeAPI.getCounterFactualInfo({ accountId: LOOPRING_EXPORTED_ACCOUNT.accountIdCF, });`
> ❗ when add `SigSuffix` `02|03` ( follow EIP712 + `02`, personal_sign + `03`)
>- for `v4` ecdsaSignature the result signature should + `SigSuffix.Suffix02`;
>- for `personal_sign` ecdsaSignature the result signature should + `SigSuffix.Suffix03`;
***
## generateKeyPair
```ts
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
const result = await signatureKeyPairMock(accInfo);
console.log(result.sk);
```
***
## getEcDSASig: eth_signTypedData_v4
```ts
// test case is not allow brock by Mock provider
const result = await sdk.getEcDSASig(
web3,
testTypedData,
LOOPRING_EXPORTED_ACCOUNT.address,
sdk.GetEcDSASigType.HasDataStruct,
sdk.ChainId.GOERLI,
LOOPRING_EXPORTED_ACCOUNT.accountId,
"",
sdk.ConnectorNames.Unknown
);
console.log("getEcDSASig:eth_signTypedData_v4",
result,
"ecdsaSig+sdk.SigSuffix.Suffix02",
result.ecdsaSig + sdk.SigSuffix.Suffix02
);
```
***
## getEcDSASig: personalSign(WithoutDataStruct--Hardware wallet)
```ts
const result = await sdk.getEcDSASig(
web3,
testTypedData,
LOOPRING_EXPORTED_ACCOUNT.address,
sdk.GetEcDSASigType.WithoutDataStruct,
sdk.ChainId.GOERLI,
LOOPRING_EXPORTED_ACCOUNT.accountId,
"",
sdk.ConnectorNames.Unknown
);
console.log(
"getEcDSASig:WithoutDataStruct(personalSign)",
result,
"ecdsaSig+sdk.SigSuffix.Suffix03",
result.ecdsaSig + sdk.SigSuffix.Suffix03
);
```
***
## getEcDSASig: personalSign(Contract)
```ts
// test case is not allow brock by Mock provider
const result = await sdk.getEcDSASig(
web3,
testTypedData,
LOOPRING_EXPORTED_ACCOUNT.address,
sdk.GetEcDSASigType.Contract,
sdk.ChainId.GOERLI,
LOOPRING_EXPORTED_ACCOUNT.accountId,
"",
sdk.ConnectorNames.Unknown
);
console.log(
"getEcDSASig:personalSign(Contract)",
result
);
```
## Validate signature
[github: src/api/base_api.ts#personalSign](https://github.com/Loopring/loopring_sdk/blob/2c79c1837114f4f383e2d292de3da4b2dac02252/src/api/base_api.ts#L549)
```
export async function personalSign(
web3: any,
account: string | undefined,
pwd: string,
msg: string,
walletType: ConnectorNames,
chainId: ChainId,
accountId?: number,
counterFactualInfo?: CounterFactualInfo,
isMobile?: boolean
) {
if (!account) {
return { error: "personalSign got no account" };
}
return new Promise((resolve) => {
try {
web3.eth.personal.sign(
msg,
account,
pwd,
async function (err: any, result: any) {
if (!err) {
// Valid:1. counter Factual signature Valid
if (counterFactualInfo && accountId) {
myLog("fcWalletValid counterFactualInfo accountId:");
const fcValid = await fcWalletValid(
web3,
account,
msg,
result,
accountId,
chainId,
counterFactualInfo
);
if (fcValid.result) {
resolve({
sig: result,
counterFactualInfo: fcValid.counterFactualInfo,
});
return;
}
}
// Valid: 2. webview directory signature Valid
if (
(window?.ethereum?.isImToken || window?.ethereum?.isMetaMask) &&
isMobile &&
// Mobile directory connect will sign ConnectorNames as MetaMask only
walletType === ConnectorNames.MetaMask
) {
const address: string[] = await window.ethereum?.request({
method: "eth_requestAccounts",
});
if (
address?.find(
(item) => item.toLowerCase() === account.toLowerCase()
)
) {
return resolve({ sig: result });
}
}
// Valid: 3. EOA signature Valid by ecRecover
const valid: any = await ecRecover(web3, account, msg, result);
if (valid.result) {
return resolve({ sig: result });
}
// Valid: 4. contractWallet signature Valid `isValidSignature(bytes32,bytes)`
const walletValid2: any = await contractWalletValidate32(
web3,
account,
msg,
result
);
if (walletValid2.result) {
return resolve({ sig: result });
}
// Valid: 5. counter Factual signature Valid when no counterFactualInfo
if (accountId) {
const fcValid = await fcWalletValid(
web3,
account,
msg,
result,
accountId,
chainId
);
if (fcValid.result) {
return resolve({
sig: result,
counterFactualInfo: fcValid.counterFactualInfo,
});
}
}
// Valid: 6. myKeyValid Valid again
const myKeyValid: any = await mykeyWalletValid(
web3,
account,
msg,
result
);
if (myKeyValid.result) {
return resolve({ sig: result });
}
// Valid: Error cannot pass personalSign Valid
// eslint-disable-next-line no-console
console.log(
"web3.eth.personal.sign Valid, valid 5 ways, all failed!"
);
return resolve({
error: "web3.eth.personal.sign Valid, valid 5 ways, all failed!",
});
} else {
return resolve({
error: "personalSign err before Validate:" + err,
});
}
}
);
} catch (reason) {
resolve({ error: reason });
}
});
}
```
================================================
FILE: docs/js_sdk/account/wallet_api.md
================================================
# Whitelisted User Part
##### 1) getUserAssets
```javascript
// step 1. get account info
const request: GetUserAssetsRequest = {
wallet: "0xeF041462825bFdF79b2f1f02A70b2753cB5b1516",
offset: 10,
limit: 10,
};
const response = await api.getUserAssets(request);
```
##### 2) getTokenPrices
```javascript
// step 1. get account info
const request: GetTokenPricesRequest = {
token: "0xdac17f958d2ee523a2206206994597c13d831ec7",
};
const response = await api.getTokenPrices(request);
```
##### 3) getLatestTokenPrices
```javascript
// step 1. get account info
const response = await api.getLatestTokenPrices();
```
================================================
FILE: docs/js_sdk/account/whitelisted_user_api.md
================================================
# Whitelisted User Part
## submitInternalTransfer
```javascript
// step 1. get account info
let addressWhitlisted = "0x35405E1349658BcA12810d0f879Bf6c5d89B512C";
let eddkeyWhitelisted =
"0x27a5b716c7309a30703ede3f1a218cdec857e424a31543f8a658e7d2208db33";
const { accInfo } = await exchange.getAccount({ owner: addressWhitlisted });
console.log("accInfo:", accInfo);
const { exchangeInfo } = await exchange.getExchangeInfo();
// step 2 get apikey
const request: GetUserApiKeyRequest = {
accountId: accInfo.accountId,
};
const { apiKey } = await userApi.getUserApiKey(request, eddkeyWhitelisted);
console.log("apiKey:", apiKey);
// step 3 get storageId
const request2: GetNextStorageIdRequest = {
accountId: accInfo.accountId,
sellTokenId: 1,
};
const storageId = await userApi.getNextStorageId(request2, apiKey);
// step 4 transfer
const request3: OriginTransferRequestV3 = {
exchange: exchangeInfo.exchangeAddress,
payerAddr: addressWhitlisted,
payerId: accInfo.accountId,
payeeAddr: "0xb6AdaC3e924B4985Ad74646FEa3610f14cDFB79c",
payeeId: 0,
storageId: storageId.offchainId,
token: {
tokenId: 1,
volume: "100000000000000000000",
},
maxFee: {
tokenId: 1,
volume: "9400000000000000000",
},
validUntil: VALID_UNTIL,
};
console.log("request3:", request3);
const response = await whitelistedUserApi.submitInternalTransfer(
request3,
eddkeyWhitelisted,
apiKey
);
console.log(response);
```
## submitOffchainWithdraw is unavailable.
TODO: submitOffchainWithdraw example
================================================
FILE: docs/js_sdk/deposit/depositERC20.md
================================================
# Deposit ERC20
Definition: Move user L1 ERC20 assets to Loopring L2
> **All Deposit Method, User should have enough `ETH` pay for the Ethereum Gas (Loopring have no charge, no fee for Deposit).**
Provider will give the Gas Price & Limit, sdk also have a method get gasPrice:
`const gasPrice = (await LoopringAPI.exchangeAPI.getGasPrice() ).gasPrice;`
# ETH
***
## Step 1. getNonce
```ts
const nonce = await sdk.getNonce(web3, LOOPRING_EXPORTED_ACCOUNT.address);
console.log(
`deposit: ${TOKEN_INFO.tokenMap.ETH.symbol}-${LOOPRING_EXPORTED_ACCOUNT.tradeETHValue}, gasPrice: ${LOOPRING_EXPORTED_ACCOUNT.gasPrice}, `
);
```
***
## Step 2. deposit
```ts
const response = await sdk.deposit(
web3,
LOOPRING_EXPORTED_ACCOUNT.address,
LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
TOKEN_INFO.tokenMap.ETH,
LOOPRING_EXPORTED_ACCOUNT.tradeETHValue,
0,
LOOPRING_EXPORTED_ACCOUNT.gasPrice,
LOOPRING_EXPORTED_ACCOUNT.gasLimit,
sdk.ChainId.GOERLI,
nonce,
true
);
console.log(`nonce: ${nonce} deposit_ETH: `, response);
```
# ERC20
***
## Step 1. getAllowances
```ts
const {tokenAllowances} = await LoopringAPI.exchangeAPI.getAllowances({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
token: [TOKEN_INFO.tokenMap.LRC.address],
});
if (
tokenAllowances.has(TOKEN_INFO.tokenMap.LRC.address) &&
Number(tokenAllowances.get(TOKEN_INFO.tokenMap.LRC.address)) <
LOOPRING_EXPORTED_ACCOUNT.tradeLRCValue
) {
const nonce = await web3.eth.getTransactionCount(
LOOPRING_EXPORTED_ACCOUNT.address
);
await sdk.approveMax(
web3,
LOOPRING_EXPORTED_ACCOUNT.address,
TOKEN_INFO.tokenMap.LRC.address, // LRC address {tokenIdMap} = getTokens(); tokenIdMap['LRC']
LOOPRING_EXPORTED_ACCOUNT.depositAddress, //{exchangeInfo} = getExchangeInfo() exchangeInfo.depositAddress
LOOPRING_EXPORTED_ACCOUNT.gasPrice,
LOOPRING_EXPORTED_ACCOUNT.gasLimit,
sdk.ChainId.GOERLI,
nonce,
true
);
}
```
***
## Step 2. getNonce
```ts
const nonce = await sdk.getNonce(web3, LOOPRING_EXPORTED_ACCOUNT.address);
console.log(
`deposit: ${TOKEN_INFO.tokenMap.LRC.symbol}-${LOOPRING_EXPORTED_ACCOUNT.tradeLRCValue}, gasPrice: ${LOOPRING_EXPORTED_ACCOUNT.gasPrice}, `
);
```
***
## Step 3. deposit
```ts
const response = await sdk.deposit(
web3,
LOOPRING_EXPORTED_ACCOUNT.address,
LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
TOKEN_INFO.tokenMap.LRC,
sdk
.toBig(LOOPRING_EXPORTED_ACCOUNT.tradeLRCValue)
.div("1e" + TOKEN_INFO.tokenMap.LRC.decimals)
.toNumber(),
0,
LOOPRING_EXPORTED_ACCOUNT.gasPrice,
LOOPRING_EXPORTED_ACCOUNT.gasLimit,
sdk.ChainId.GOERLI,
nonce,
true
);
console.log(`nonce: ${nonce} deposit_LRC: `, response);
```
================================================
FILE: docs/js_sdk/deposit/depositNFT.md
================================================
# Deposit NFT
Definition: Move user L1 NFT assets to Loopring L2
> **All Deposit Method, User should have enough `ETH` pay for the Ethereum Gas (Loopring have no charge, no fee for Deposit).**
***
## Step 1. getNFTBalance & getEthBalances
```ts
const {ethBalance} = await LoopringAPI.exchangeAPI.getEthBalances({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
const nftBalance = await LoopringAPI.nftAPI.getNFTBalance({
web3,
account: LOOPRING_EXPORTED_ACCOUNT.address,
tokenAddress: LOOPRING_EXPORTED_ACCOUNT.nftTokenAddress,
nftId: LOOPRING_EXPORTED_ACCOUNT.nftId,
nftType: sdk.NFTType.ERC1155,
});
```
***
## Step 2. isApprovedForAll
```ts
const isApprovedForAll = await LoopringAPI.nftAPI.isApprovedForAll({
web3,
from: LOOPRING_EXPORTED_ACCOUNT.address,
exchangeAddress: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
nftType: sdk.NFTType.ERC1155, // todo: sdk.NFTType.ERC721
tokenAddress: LOOPRING_EXPORTED_ACCOUNT.nftTokenAddress,
});
console.log(`check is approveNFT`, isApprovedForAll);
```
***
## Step 3. approveNFT All
```ts
if (!isApprovedForAll) {
const nonce = await sdk.getNonce(
web3,
LOOPRING_EXPORTED_ACCOUNT.address
);
const approveNFT = await LoopringAPI.nftAPI.approveNFT({
web3,
from: LOOPRING_EXPORTED_ACCOUNT.address,
depositAddress: LOOPRING_EXPORTED_ACCOUNT.depositAddress,
tokenAddress: LOOPRING_EXPORTED_ACCOUNT.nftTokenAddress,
nftType: sdk.NFTType.ERC1155, // todo: sdk.NFTType.ERC721
gasPrice: LOOPRING_EXPORTED_ACCOUNT.gasPrice,
gasLimit: LOOPRING_EXPORTED_ACCOUNT.gasLimit,
chainId: sdk.ChainId.GOERLI,
nonce,
sendByMetaMask: true,
});
console.log(`nonce: ${nonce} approveNFT: ${approveNFT?.result}`);
}
```
***
## Step 3. nonce
```ts
const nonce = await sdk.getNonce(web3, LOOPRING_EXPORTED_ACCOUNT.address);
console.log(
`deposit: NFT, gasPrice: ${LOOPRING_EXPORTED_ACCOUNT.gasPrice}, `
);
```
***
## Step 4. depositNFT
```ts
const response = await LoopringAPI.nftAPI.depositNFT({
web3,
from: LOOPRING_EXPORTED_ACCOUNT.address,
exchangeAddress: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
nftType: sdk.NFTType.ERC1155, // todo: sdk.NFTType.ERC721
tokenAddress: LOOPRING_EXPORTED_ACCOUNT.nftTokenAddress,
nftId: LOOPRING_EXPORTED_ACCOUNT.nftId,
amount: 2, // todo:when sdk.NFTType.ERC721 amount: 1,
gasPrice: LOOPRING_EXPORTED_ACCOUNT.gasPrice,
gasLimit: LOOPRING_EXPORTED_ACCOUNT.gasLimit + 100000,
chainId: sdk.ChainId.GOERLI,
nonce,
sendByMetaMask: true,
});
console.log(`nonce: ${nonce} deposit NFT ERC1155: `, response);
```
================================================
FILE: docs/js_sdk/erc20Trade/orderERC20.md
================================================
# Order ERC20
***
> ### mini-order
To support small quantity trading, we introduce an additional concept "tradeCost", which is the minimum gas fee when a trade transaction is uplink to Ethereum.
Let's take LRC-ETH trading as an example.
Below are the steps -
**1) Query api/v3/exchange/tokens to get the dust value of orderAmounts for both LRC and ETH.**
The dust value is the minimum value to pass Relayer check. Any amount less than "dust" can't be traded. In this case, we will get both minTOkenLRC and minTokenETH after getting dust value. If user wants to convert LRC to ETH, the set LRC amount can't be less than minTokenLRC and the converted ETH amount can't be less than minTokenETH.
**2) Query api/v3/user/orderUserRateAmount to get the tradeCost value.**
The parameters to call this interface are "accountId" and "market=LRC-ETH". In this example, we will get two tradeCost values for LRC and ETH as tradeCostLRC and tradeCostETH.
**3) Set maxAllowBips = 50% as the maxFeeBips can't exceed 50%**
**4) Set slippage as the slippage value user configured in UI (for example 0.1%)**
**5)Caculate minCostLRC and minCostETH as below**
minCostLRC = max(minTokenLRC, tradeCostLRC/maxAllowBips)
minCostETH = max(minTokenETH, tradeCostETH/maxAllowBips)
**6) Caculate the cost by considering slippage**
minCostLRCSlip = minCostLRC/(1-slippage)
minCostETHSlip = minCostETH/(1-slippage)
**7) Cacluate the minimum quantity user has to set**
tradeCostSellLRC = max(tradeCostSellLRC, minTokenLRC) * 1.1
tradeCostSellETH = max(tradeCostSellETH, minTokenETH) * 1.1
Here we add additonally 10% tolerance.
**8) Caculate the previous minimum token amount per calling api/v3/user/orderUserRateAmount (existing logic)**
This is the threshold to distinguish small quantity trading and normal trading
We will get two values (configSellLRC and configSellETH) which are used for previous trading quantity limit (Per USD 100) caculation
**9)Caculate the new maxFeeBips and start trading**
Let's take LRC->ETH as the example
User inputs the amount of LRC to convert, amount = sellLRC
if sellLRC >= configSellLRC then
// Normal trading case, stay with previous logic
maxFeeBips=63 (the default value for maxFeeBips)
Trade
else if sellLRC < tradeCostSellLRC then
// Really too small to support
Prompt user the amount is too small to support
Exit
else
// This is what we call as small quantity
costRate = Ceil(tradeCostETH/minbuyETH)
maxFeeBips = max(costRate, takerRate)
Trade
End If
> ### price impact update
> 1. sellTokenMinAmount = baseOrderInfo.minAmount from LoopringAPI.userAPI.getMinimumTokenAmt({accountId,marke}, apiKey);
> 2. {output} from sdk.getOutputAmount(input: sellTokenMinAmount, isAtoB: isAtoB,…}).output
> 3. PriceBase = output / sellTokenMinAmount
> 4. tradePrice = calcTradeParams.minReceive / userInputSell
> 5. priceImpact = 1 - tradePrice/PriceBase - 0.005
> 6. If priceImpact < 0 priceImpact = 0
> Else priceImpact
## calculateSwap function
```ts
const calculateSwap = (
sellSymbol = "LRC",
buySymbol = "ETH",
isInputSellToBuy: boolean,
inputValue: number, // user Input value no decimal,
_slippage = 0.1,
// MOCK value
amountMap: { [key: string]: any } = userAmount,
market: string = deepMock.symbol,
// close = ticker.tickers[7],
depth: any = deepMock,
ammPoolSnapshot: sdk.AmmPoolSnapshot = ammPoolSnapshotMock,
tokenMap: sdk.LoopringMap<sdk.TokenInfo> = TokenMapMockSwap,
ammMap: { [key: string]: any } = AMM_MAP
) => {
let calcFor100USDAmount, calcForMinCost, calcForPriceImpact;
if (depth && market && tokenMap) {
const sellToken = tokenMap[sellSymbol];
const buyToken = tokenMap[buySymbol];
const isInputSellOutputBuy = isInputSellToBuy;
let input: any = inputValue;
console.log(
"sellToken: Symbol ",
sellSymbol,
"buyToken: Symbol",
buySymbol,
"is Input Sell Output Buy:",
isInputSellOutputBuy,
"input value",
input
);
input = input === undefined || isNaN(Number(input)) ? 0 : Number(input);
let slippage = sdk.toBig(_slippage).times(100).toString();
let totalFee = undefined;
let feeTakerRate = undefined;
let feeBips = undefined;
let takerRate = undefined;
let buyMinAmtInfo = undefined;
let sellMinAmtInfo = undefined;
let tradeCost = undefined;
let basePrice = undefined;
let maxFeeBips = MAPFEEBIPS;
let minAmt = undefined;
if (amountMap && amountMap[market] && ammMap) {
console.log(`amountMap[${market}]:`, amountMap[market]);
const ammMarket = `AMM-${market}`;
const amountMarket = amountMap[market]; // userAmount from LRC-ETH(Market)
buyMinAmtInfo = amountMarket[buySymbol];
sellMinAmtInfo = amountMarket[sellSymbol];
console.log(
`buyMinAmtInfo: ${market}, ${buySymbol}`,
buyMinAmtInfo,
`sellMinAmtInfo: ${market}, ${sellSymbol}`,
sellMinAmtInfo
);
feeBips = ammMap[ammMarket] ? ammMap[ammMarket].feeBips : 1;
feeTakerRate =
amountMarket[buySymbol] &&
amountMarket[buySymbol].userOrderInfo.takerRate;
tradeCost = amountMarket[buySymbol].tradeCost;
/** @description for charge fee calc, calcFor100USDAmount
* Loopring market consider buyToken value small then max(buyMinAmtInfo.userOrderInfo.minAmount,buyToken.orderAmounts.dust) is a small order,
* the fee will take the Max(tradeCost,userTakeRate)
* use the buyMinAmount Input calc the selltoken value,
* please read Line:321
* **/
const minAmountInput = BigNumber.max(
buyMinAmtInfo.userOrderInfo.minAmount,
buyToken.orderAmounts.dust
)
.div(sdk.toBig(1).minus(sdk.toBig(slippage).div(10000)))
.div("1e" + buyToken.decimals)
.toString();
calcFor100USDAmount = sdk.getOutputAmount({
input: minAmountInput,
sell: sellSymbol,
buy: buySymbol,
isAtoB: false,
marketArr: marketArray as string[],
tokenMap: tokenMap as any,
marketMap: marketMap as any,
depth,
ammPoolSnapshot: ammPoolSnapshot,
feeBips: feeBips ? feeBips.toString() : 1,
takerRate: "0",
slipBips: slippage,
});
console.log(
"buyMinAmtInfo.userOrderInfo.minAmount:",
buyMinAmtInfo.userOrderInfo.minAmount,
`buyMinAmtInfo.userOrderInfo.minAmount, with slippage:${slippage}`,
sdk
.toBig(buyMinAmtInfo.userOrderInfo.minAmount)
.div(sdk.toBig(1).minus(sdk.toBig(slippage).div(10000)))
.toString()
);
/*** calc for Price Impact ****/
const sellMinAmtInput = sdk
.toBig(sellMinAmtInfo.baseOrderInfo.minAmount)
.div("1e" + sellToken.decimals)
.toString();
calcForPriceImpact = sdk.getOutputAmount({
input: sellMinAmtInput,
sell: sellSymbol,
buy: buySymbol,
isAtoB: true,
marketArr: marketArray as string[],
tokenMap: tokenMap as any,
marketMap: marketMap as any,
depth,
ammPoolSnapshot: ammPoolSnapshot,
feeBips: feeBips ? feeBips.toString() : 1,
takerRate: "0",
slipBips: "10",
});
basePrice = sdk.toBig(calcForPriceImpact?.output).div(sellMinAmtInput);
console.log(
"calcForPriceImpact input: ",
sellMinAmtInput,
", output: ",
sdk.toBig(calcForPriceImpact?.output).div(sellMinAmtInput).toNumber(),
", calcForPriceImpact:",
calcForPriceImpact?.amountBOutSlip?.minReceivedVal,
", calcForPriceImpact basePrice: ",
basePrice.toNumber()
);
/**** calc for mini Cost ****/
//minCostBuyToken = max(dustBuyToken, tradeCostETH/maxAllowBips)
const dustToken = buyToken;
let minCostBuyTokenInput = BigNumber.max(
sdk.toBig(tradeCost).times(2), //maxAllowBips = 50% tradeCostETH/50%
dustToken.orderAmounts.dust
);
const tradeCostInput = sdk
.toBig(minCostBuyTokenInput)
.div(sdk.toBig(1).minus(sdk.toBig(slippage).div(10000)))
.div("1e" + dustToken.decimals)
.toString();
console.log(
`tradeCost: ${tradeCost}*2:`,
sdk.toBig(tradeCost).times(2).toString(),
"buyToken.orderAmounts.dust",
buyToken.orderAmounts.dust,
"minCostBuyToken:",
minCostBuyTokenInput.toString(),
`calcForMinCostInput, with slippage:${slippage}`,
sdk
.toBig(minCostBuyTokenInput ?? 0)
.div(sdk.toBig(1).minus(sdk.toBig(slippage).div(10000)))
.toString(),
"calcForMinCost, Input",
tradeCostInput
);
calcForMinCost = sdk.getOutputAmount({
input: tradeCostInput,
sell: sellSymbol,
buy: buySymbol,
isAtoB: false,
marketArr: marketArray as string[],
tokenMap: tokenMap as any,
marketMap: marketMap as any,
depth,
ammPoolSnapshot: ammPoolSnapshot,
feeBips: feeBips ? feeBips.toString() : 1,
takerRate: "0",
slipBips: slippage,
});
//add additionally 10% tolerance for minimum quantity user has to set on sell Token
/**
* @output: minAmt for UI
* this value mini-order Sell token amount (show on the UI for available order check)
* setSellMinAmt(minAmt.toString());
*/
minAmt = BigNumber.max(
sellToken.orderAmounts.dust,
calcForMinCost?.amountS ?? 0
).times(1.1);
console.log(
"UI show mini-order Sell token amount:",
minAmt.toString(),
sdk
.toBig(minAmt)
.div("1e" + sellToken.decimals)
.toString()
);
console.log(
`calcFor100USDAmount.amountS`,
sdk
.toBig(calcFor100USDAmount?.amountS ?? 0)
.div("1e" + sellToken.decimals)
.toString(),
"calcForMinCost.amountS",
sdk
.toBig(calcForMinCost?.amountS ?? 0)
.div("1e" + sellToken.decimals)
.toString()
);
}
const calcTradeParams = sdk.getOutputAmount({
input: input.toString(),
sell: sellSymbol,
buy: buySymbol,
isAtoB: isInputSellOutputBuy,
marketArr: marketArray as string[],
tokenMap: tokenMap as any,
marketMap: marketMap as any,
depth,
ammPoolSnapshot: ammPoolSnapshot,
feeBips: feeBips ? feeBips.toString() : 1,
takerRate: "0", // for new calc miniReceive will minus fee, so takeRate can fix as 0
slipBips: slippage,
});
const minSymbol = buySymbol;
const tradePrice = sdk
.toBig(calcTradeParams?.amountBOutSlip?.minReceivedVal ?? 0)
.div(isInputSellOutputBuy ? input.toString() : calcTradeParams?.output);
const priceImpact = sdk
.toBig(1)
.minus(sdk.toBig(tradePrice).div(basePrice ?? 1))
.minus(0.001);
if (calcTradeParams && priceImpact.gte(0)) {
calcTradeParams.priceImpact = priceImpact.toFixed(4, 1);
} else {
calcTradeParams && (calcTradeParams.priceImpact = "0");
}
console.log(
"calcTradeParams input:",
input.toString(),
", calcTradeParams Price: ",
sdk
.toBig(calcTradeParams?.amountBOutSlip?.minReceivedVal ?? 0)
.div(input.toString())
.toNumber(),
`isAtoB mean isInputSellOutputBuy:${isInputSellOutputBuy}, ${
isInputSellOutputBuy ? input.toString() : calcTradeParams?.output
} tradePrice: `,
tradePrice.toString(),
"basePrice: ",
basePrice?.toString(),
"toBig(tradePrice).div(basePrice)",
sdk
.toBig(tradePrice)
.div(basePrice ?? 1)
.toNumber(),
"priceImpact (1-tradePrice/basePrice) - 0.001",
priceImpact.toNumber(),
"priceImpact view",
calcTradeParams?.priceImpact
);
if (
tradeCost &&
calcTradeParams &&
calcTradeParams.amountBOutSlip?.minReceived &&
feeTakerRate
) {
let value = sdk
.toBig(calcTradeParams.amountBOutSlip?.minReceived)
.times(feeTakerRate)
.div(10000);
console.log(
"input Accounts",
calcTradeParams?.amountS,
"100 U Amount Sell:",
calcFor100USDAmount?.amountS
);
let validAmt = !!(
calcTradeParams?.amountS &&
calcFor100USDAmount?.amountS &&
sdk.toBig(calcTradeParams?.amountS).gte(calcFor100USDAmount.amountS)
);
let totalFeeRaw;
console.log(
`${minSymbol} tradeCost:`,
tradeCost,
"useTakeRate Fee:",
value.toString(),
"calcFor100USDAmount?.amountS:",
calcFor100USDAmount?.amountS,
`is setup minTrade amount, ${calcFor100USDAmount?.amountS}:`,
validAmt
);
if (!validAmt) {
if (sdk.toBig(tradeCost).gte(value)) {
totalFeeRaw = sdk.toBig(tradeCost);
} else {
totalFeeRaw = value;
}
console.log(
"maxFeeBips update for tradeCost before value:",
maxFeeBips,
"totalFeeRaw",
totalFeeRaw.toString()
);
maxFeeBips = Math.ceil(
totalFeeRaw
.times(10000)
.div(calcTradeParams.amountBOutSlip?.minReceived)
.toNumber()
);
console.log("maxFeeBips update for tradeCost after value:", maxFeeBips);
} else {
totalFeeRaw = sdk.toBig(value);
}
/**
* totalFee
*/
totalFee = totalFeeRaw
.div("1e" + tokenMap[minSymbol].decimals)
.toString();
/** @output: UI
* getValuePrecisionThousand(
* totalFeeRaw.div("1e" + tokenMap[minSymbol].decimals).toString(),
* tokenMap[minSymbol].precision,
* tokenMap[minSymbol].precision,
* tokenMap[minSymbol].precision,
* false,
* { floor: true }
* );
*/
tradeCost = sdk
.toBig(tradeCost)
// @ts-ignore
.div("1e" + tokenMap[minSymbol].decimals)
.toString();
/** @output: UI code with precision
* getValuePrecisionThousand(
* sdk
* .toBig(tradeCost)
* .div("1e" + tokenMap[minSymbol].decimals)
* .toString(),
* tokenMap[minSymbol].precision,
* tokenMap[minSymbol].precision,
* tokenMap[minSymbol].precision,
* false,
* { floor: true }
* );
*/
console.log("totalFee view value:", totalFee + " " + minSymbol);
console.log("tradeCost view value:", tradeCost + " " + minSymbol);
}
const minimumReceived = sdk
.toBig(calcTradeParams?.amountBOutSlip?.minReceivedVal ?? 0)
.minus(totalFee ?? 0)
.toString();
console.log("minimumReceived:", minimumReceived);
/** @output: UI code with precision
* getValuePrecisionThousand(
* toBig(calcTradeParams?.amountBOutSlip?.minReceivedVal ?? 0)
* .minus(totalFee)
* .toString(),
* tokenMap[minSymbol].precision,
* tokenMap[minSymbol].precision,
* tokenMap[minSymbol].precision,
* false,
* { floor: true }
* );
*/
let priceImpactView: any = calcTradeParams?.priceImpact
? parseFloat(calcTradeParams?.priceImpact) * 100
: undefined;
console.log("priceImpact view:", priceImpactView + "%");
// @output: UI code with color alert
// const priceImpactObj = getPriceImpactInfo(calcTradeParams);
// const _tradeCalcData: Partial<TradeCalcData<C>> = {
// priceImpact: priceImpactObj.value.toString(),
// priceImpactColor: priceImpactObj.priceImpactColor,
// minimumReceived: !minimumReceived?.toString().startsWith("-")
// ? minimumReceived
// : undefined,
// fee: totalFee,
// feeTakerRate,
// tradeCost,
// };
console.log(
`isInputSellOutputBuy:${isInputSellOutputBuy}`,
`output ${isInputSellOutputBuy ? "Buy" : "Sell"}`,
calcTradeParams?.output
);
return {
market,
feeBips,
takerRate,
sellMinAmtInfo: sellMinAmtInfo as any,
buyMinAmtInfo: buyMinAmtInfo as any,
totalFee,
maxFeeBips,
feeTakerRate,
tradeCost,
minimumReceived,
calcTradeParams,
minAmt,
};
}
};
```
### Step 1. get apikey & eddsaKey
```ts
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
const eddsaKey = await signatureKeyPairMock(accInfo);
apiKey = (
await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
)
).apiKey;
```
### Step Step 2 : storageId
```ts
const storageId = await LoopringAPI.userAPI.getNextStorageId(
{
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
sellTokenId: TOKEN_INFO.tokenMap[sell].tokenId,
},
apiKey
);
```
### Step 3. get user AmountMap, which decided user minimum order
```ts
const amountMap = {
[AMM_MARKET]: (
await LoopringAPI.userAPI.getMinimumTokenAmt(
{
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
market: AMM_MAP[AMM_MARKET].market,
},
apiKey
)
).amountMap,
[MARKET]: (
await LoopringAPI.userAPI.getMinimumTokenAmt(
{
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
market: MARKET,
},
apiKey
)
).amountMap,
};
```
### Step 4. depth, ammPoolSnapshot ,tickMap
```ts
const [{depth}, {ammPoolSnapshot}] = await Promise.all([
LoopringAPI.exchangeAPI.getMixDepth({
market: AMM_MAP["AMM-LRC-ETH"].market,
}),
LoopringAPI.ammpoolAPI.getAmmPoolSnapshot({
poolAddress: AMM_MAP["AMM-LRC-ETH"].address,
}),
]);
```
### Step 5. check MinAmt
```ts
let buyMinAmtInfo = (amountMap[AMM_MARKET] ?? amountMap[MARKET])[buy];
let takerRate = buyMinAmtInfo
? buyMinAmtInfo.userOrderInfo.takerRate
: 0;
const minAmountInput = buyMinAmtInfo.userOrderInfo.minAmount;
```
### Step 6. calcTradeParams
```ts
const calcTradeParams = sdk.getOutputAmount({
input: LOOPRING_EXPORTED_ACCOUNT.tradeLRCValue.toString(),
sell,
buy,
isAtoB,
marketArr: ["LRC-ETH", "ETH-USDT", "DAI-USDT", "USDC-ETH"],
tokenMap: TOKEN_INFO.tokenMap,
marketMap: TOKEN_INFO.marketMap,
depth,
ammPoolSnapshot: ammPoolSnapshot,
feeBips: AMM_MAP["AMM-LRC-ETH"].feeBips.toString(),
takerRate: takerRate ? takerRate.toString() : "0",
slipBips: slippage,
});
console.log(
"Buy",
",LRC:",
LOOPRING_EXPORTED_ACCOUNT.tradeLRCValue.toString(),
",minAmountInput LRC:",
minAmountInput,
",ETH:",
calcTradeParams?.amountBOutSlip?.minReceivedVal
);
const response: { hash: string } | any =
await LoopringAPI.userAPI.submitOrder(
{
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
storageId: storageId.orderId,
sellToken: {
tokenId: TOKEN_INFO.tokenMap[sell].tokenId,
volume: calcTradeParams?.amountS as string,
},
buyToken: {
tokenId: TOKEN_INFO.tokenMap[buy].tokenId,
volume: calcTradeParams?.amountBOutSlip.minReceived as string,
},
allOrNone: false,
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
maxFeeBips: 63,
fillAmountBOrS: false, // amm only false
tradeChannel: calcTradeParams?.exceedDepth
? sdk.TradeChannel.BLANK
: sdk.TradeChannel.MIXED,
orderType: calcTradeParams?.exceedDepth
? sdk.OrderType.ClassAmm
: sdk.OrderType.TakerOnly,
eddsaSignature: "",
},
eddsaKey.sk,
apiKey
);
console.log("submitOrder", response);
```
***
## ETH-LRC : for Quote to Base
### MOCK Data
> user should had apikey, please check get apikey
```ts
const buy = "ETH",
sell = "LRC",
MARKET = "LRC-ETH",
AMM_MARKET = "AMM-LRC-ETH",
slippage = "50";
const isAtoB = false;
```
### Step 1. get apikey & eddsaKey
```ts
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
const eddsaKey = await signatureKeyPairMock(accInfo);
apiKey = (
await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
)
).apiKey;
```
### Step 2. storageId
```ts
const storageId = await LoopringAPI.userAPI.getNextStorageId(
{
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
sellTokenId: TOKEN_INFO.tokenMap[sell].tokenId,
},
apiKey
);
```
### Step 3. get user AmountMap, which decided user minimum order
```ts
const amountMap = {
[AMM_MARKET]: (
await LoopringAPI.userAPI.getMinimumTokenAmt(
{
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
market: AMM_MAP[AMM_MARKET].market,
},
apiKey
)
).amountMap,
[MARKET]: (
await LoopringAPI.userAPI.getMinimumTokenAmt(
{
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
market: MARKET,
},
apiKey
)
).amountMap,
};
```
### Step 4. depth, ammPoolSnapshot ,tickMap
```ts
const [{depth}, {ammPoolSnapshot}] = await Promise.all([
LoopringAPI.exchangeAPI.getMixDepth({
market: AMM_MAP["AMM-LRC-ETH"].market,
}),
LoopringAPI.ammpoolAPI.getAmmPoolSnapshot({
poolAddress: AMM_MAP["AMM-LRC-ETH"].address,
}),
]);
```
### Step 5. check MinAmt see log and calc mini receive and ouput value & maxfeeBips & priceImpact
```ts
const { calcTradeParams, maxFeeBips, minimumReceived } = calculateSwap(
sell,
buy,
isAtoB,
10, // user Input value no decimal 10 lrc,
0.1,
//TODO MOCK value
amountMap,
"LRC-ETH",
// close = ticker.tickers[7],
depth,
ammPoolSnapshot,
TOKEN_INFO.tokenMap,
AMM_MAP
);
console.log(
"Buy",
",ETH:",
LOOPRING_EXPORTED_ACCOUNT.tradeLRCValue.toString(),
",minAmountInput ETH:",
minAmountInput,
",LRC:",
calcTradeParams?.amountBOutSlip?.minReceivedVal
);
const response: { hash: string } | any =
await LoopringAPI.userAPI.submitOrder(
{
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
storageId: storageId.orderId,
sellToken: {
tokenId: TOKEN_INFO.tokenMap[sell].tokenId,
volume: calcTradeParams?.amountS as string,
},
buyToken: {
tokenId: TOKEN_INFO.tokenMap[buy].tokenId,
volume: calcTradeParams?.amountBOutSlip.minReceived as string,
},
allOrNone: false,
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
maxFeeBips: 63,
fillAmountBOrS: false, // amm only false
tradeChannel: calcTradeParams?.exceedDepth
? sdk.TradeChannel.BLANK
: sdk.TradeChannel.MIXED,
orderType: calcTradeParams?.exceedDepth
? sdk.OrderType.ClassAmm
: sdk.OrderType.TakerOnly,
eddsaSignature: "",
},
eddsaKey.sk,
apiKey
);
console.log("submitOrder", response);
```
### MockSwapData
```ts
//Default config value from getTokens & getMixMarkets
import * as sdk from "../index";
export const marketArray = ["LRC-ETH"];
export const marketMap = {
"LRC-ETH": {
baseTokenId: 1,
enabled: true,
market: "LRC-ETH",
orderbookAggLevels: 5,
precisionForPrice: 6,
quoteTokenId: 0,
status: 3,
isSwapEnabled: true,
createdAt: 1617967800000,
},
};
//v3/mix/depth?level=0&limit=50&market=LRC-ETH
export const deepMock = {
symbol: "LRC-ETH",
version: 23249677,
timestamp: 1655719492365,
mid_price: 0.00033248,
bids: [
{
price: 0.00030689,
amt: "12041160324514792497908",
vol: "3695372332571085210",
amtTotal: "618450503644320209925641",
volTotal: "198539605794234049017",
},
{
price: 0.00030752,
amt: "12016302126785109160251",
vol: "3695372332571085210",
amtTotal: "606409343319805417427733",
volTotal: "194844233461662963807",
},
{
price: 0.00030816,
amt: "11991520826895479525387",
vol: "3695372332571085210",
amtTotal: "594393041193020308267482",
volTotal: "191148861129091878597",
},
{
price: 0.00030881,
amt: "12329062048917727073625",
vol: "3807353312345966580",
amtTotal: "582401520366124828742095",
volTotal: "187453488796520793387",
},
{
price: 0.00030945,
amt: "11941442525358097768419",
vol: "3695372332571085210",
amtTotal: "570072458317207101668470",
volTotal: "183646135484174826807",
},
{
price: 0.0003102,
amt: "3223726000000000000000",
vol: "999999805200000000",
amtTotal: "558131015791849003900051",
volTotal: "179950763151603741597",
},
{
price: 0.0003104,
amt: "11904963012947201084062",
vol: "3695372332571085210",
amtTotal: "554907289791849003900051",
volTotal: "178950763346403741597",
},
{
price: 0.00031072,
amt: "11892800074855146120151",
vol: "3695372332571085210",
amtTotal: "543002326778901802815989",
volTotal: "175255391013832656387",
},
{
price: 0.00031137,
amt: "12227667622887455762012",
vol: "3807353312345966580",
amtTotal: "531109526704046656695838",
volTotal: "171560018681261571177",
},
{
price: 0.00031202,
amt: "11843337524732768607817",
vol: "3695372332571085210",
amtTotal: "518881859081159200933826",
volTotal: "167752665368915604597",
},
{
price: 0.00031266,
amt: "11819088718260537718160",
vol: "3695372332571085210",
amtTotal: "507038521556426432326009",
volTotal: "164057293036344519387",
},
{
price: 0.0003133,
amt: "11794914308461194855590",
vol: "3695372332571085210",
amtTotal: "495219432838165894607849",
volTotal: "160361920703773434177",
},
{
price: 0.00031395,
amt: "12127129883064173669497",
vol: "3807353312345966580",
amtTotal: "483424518529704699752259",
volTotal: "156666548371202348967",
},
{
price: 0.0003146,
amt: "11746060536480763829870",
vol: "3695372332571085210",
amtTotal: "471297388646640526082762",
volTotal: "152859195058856382387",
},
{
price: 0.00031524,
amt: "11722109721002274877424",
vol: "3695372332571085210",
amtTotal: "459551328110159762252892",
volTotal: "149163822726285297177",
},
{
price: 0.0003159,
amt: "12052351993023897680738",
vol: "3807353312345966580",
amtTotal: "447829218389157487375468",
volTotal: "145468450393714211967",
},
{
price: 0.00031655,
amt: "11673707113082743010268",
vol: "3695372332571085210",
amtTotal: "435776866396133589694730",
volTotal: "141661097081368245387",
},
{
price: 0.00031699,
amt: "615000000000000000000",
vol: "194954999999999949",
amtTotal: "424103159283050846684462",
volTotal: "137965724748797160177",
},
{
price: 0.00031719,
amt: "11649977142974837964110",
vol: "3695372332571085210",
amtTotal: "423488159283050846684462",
volTotal: "137770769748797160228",
},
{
price: 0.00031784,
amt: "11626319455782556517212",
vol: "3695372332571085210",
amtTotal: "411838182140076008720352",
volTotal: "134075397416226075018",
},
{
price: 0.0003185,
amt: "11953964321007990024755",
vol: "3807353312345966580",
amtTotal: "400211862684293452203140",
volTotal: "130380025083654989808",
},
{
price: 0.00031934,
amt: "11571837200722111826863",
vol: "3695372332571085210",
amtTotal: "388257898363285462178385",
volTotal: "126572671771309023228",
},
{
price: 0.00031979,
amt: "11555429099390519988949",
vol: "3695372332571085210",
amtTotal: "376686061162563350351522",
volTotal: "122877299438737938018",
},
{
price: 0.00032,
amt: "300000000000000000000",
vol: "96000000000000000",
amtTotal: "365130632063172830362573",
volTotal: "119181927106166852808",
},
{
price: 0.00032044,
amt: "11532058329906875386268",
vol: "3695372332571085210",
amtTotal: "364830632063172830362573",
volTotal: "119085927106166852808",
},
{
price: 0.0003211,
amt: "11857145662584872212009",
vol: "3807353312345966580",
amtTotal: "353298573733265954976305",
volTotal: "115390554773595767598",
},
{
price: 0.00032176,
amt: "11484826169666631095087",
vol: "3695372332571085210",
amtTotal: "341441428070681082764296",
volTotal: "111583201461249801018",
},
{
price: 0.00032241,
amt: "11461669156035188891431",
vol: "3695372332571085210",
amtTotal: "329956601901014451669209",
volTotal: "107887829128678715808",
},
{
price: 0.00032294,
amt: "22266286128259997368320",
vol: "7190674442260284416",
amtTotal: "318494932744979262777778",
volTotal: "104192456796107630598",
},
{
price: 0.00032307,
amt: "11784846142950476791130",
vol: "3807353312345966580",
amtTotal: "296228646616719265409458",
volTotal: "97001782353847346182",
},
{
price: 0.00032333,
amt: "31042151210389998665728",
vol: "10037169172367501312",
amtTotal: "284443800473768788618328",
volTotal: "93194429041501379602",
},
{
price: 0.00032354,
amt: "19082720347089998446592",
vol: "6174214168300968960",
amtTotal: "253401649263378789952600",
volTotal: "83157259869133878290",
},
{
price: 0.00032373,
amt: "11414868337793698506576",
vol: "3695372332571085210",
amtTotal: "234318928916288791506008",
volTotal: "76983045700832909330",
},
{
price: 0.00032438,
amt: "11391922481177051106050",
vol: "3695372332571085210",
amtTotal: "222904060578495092999432",
volTotal: "73287673368261824120",
},
{
price: 0.00032503,
amt: "11369045742792164433715",
vol: "3695372332571085210",
amtTotal: "211512138097318041893382",
volTotal: "69592301035690738910",
},
{
price: 0.00032512,
amt: "7101984539779999465472",
vol: "2308997213573273600",
amtTotal: "200143092354525877459667",
volTotal: "65896928703119653700",
},
{
price: 0.0003257,
amt: "11689707913498419991686",
vol: "3807353312345966580",
amtTotal: "193041107814745877994195",
volTotal: "63587931489546380100",
},
{
price: 0.00032636,
amt: "11322810509578528739940",
vol: "3695372332571085210",
amtTotal: "181351399901247458002509",
volTotal: "59780578177200413520",
},
{
price: 0.00032702,
amt: "11300141532643741902081",
vol: "3695372332571085210",
amtTotal: "170028589391668929262569",
volTotal: "56085205844629328310",
},
{
price: 0.00032709,
amt: "1511898000000000000000",
vol: "494541835799999898",
amtTotal: "158728447859025187360488",
volTotal: "52389833512058243100",
},
{
price: 0.00032767,
amt: "11277540564700637960582",
vol: "3695372332571085210",
amtTotal: "157216549859025187360488",
volTotal: "51895291676258243202",
},
{
price: 0.00032838,
amt: "11594014901713773553177",
vol: "3807353312345966580",
amtTotal: "145939009294324549399906",
volTotal: "48199919343687157992",
},
{
price: 0.00032899,
amt: "11232203228917728004878",
vol: "3695372332571085210",
amtTotal: "134344994392610775846729",
volTotal: "44392566031341191412",
},
{
price: 0.00032959,
amt: "31100749000000000753664",
vol: "10250806870400000000",
amtTotal: "123112791163693047841851",
volTotal: "40697193698770106202",
},
{
price: 0.00032965,
amt: "11209805337410429375102",
vol: "3695372332571085210",
amtTotal: "92012042163693047088187",
volTotal: "30446386828370106202",
},
{
price: 0.00033031,
amt: "11187474373893810850495",
vol: "3695372332571085210",
amtTotal: "80802236826282617713085",
volTotal: "26751014495799020992",
},
{
price: 0.00033098,
amt: "11503202913004006553102",
vol: "3807353312345966580",
amtTotal: "69614762452388806862590",
volTotal: "23055642163227935782",
},
{
price: 0.00033099,
amt: "26515451000000002129920",
vol: "8776614281000000512",
amtTotal: "58111559539384800309488",
volTotal: "19248288850881969202",
},
{
price: 0.0003313,
amt: "20499506300000000802816",
vol: "6791486437190000640",
amtTotal: "31596108539384798179568",
volTotal: "10471674569881968690",
},
{
price: 0.00033165,
amt: "11096602239384797376752",
vol: "3680188132691968050",
amtTotal: "11096602239384797376752",
volTotal: "3680188132691968050",
},
],
bids_prices: [
0.00030689, 0.00030752, 0.00030816, 0.00030881, 0.00030945, 0.0003102,
0.0003104, 0.00031072, 0.00031137, 0.00031202, 0.00031266, 0.0003133,
0.00031395, 0.0003146, 0.00031524, 0.0003159, 0.00031655, 0.00031699,
0.00031719, 0.00031784, 0.0003185, 0.00031934, 0.00031979, 0.00032,
0.00032044, 0.0003211, 0.00032176, 0.00032241, 0.00032294, 0.00032307,
0.00032333, 0.00032354, 0.00032373, 0.00032438, 0.00032503, 0.00032512,
0.0003257, 0.00032636, 0.00032702, 0.00032709, 0.00032767, 0.00032838,
0.00032899, 0.00032959, 0.00032965, 0.00033031, 0.00033098, 0.00033099,
0.0003313, 0.00033165,
],
bids_amtTotals: [
"618450503644320209925641",
"606409343319805417427733",
"594393041193020308267482",
"582401520366124828742095",
"570072458317207101668470",
"558131015791849003900051",
"554907289791849003900051",
"543002326778901802815989",
"531109526704046656695838",
"518881859081159200933826",
"507038521556426432326009",
"495219432838165894607849",
"483424518529704699752259",
"471297388646640526082762",
"459551328110159762252892",
"447829218389157487375468",
"435776866396133589694730",
"424103159283050846684462",
"423488159283050846684462",
"411838182140076008720352",
"400211862684293452203140",
"388257898363285462178385",
"376686061162563350351522",
"365130632063172830362573",
"364830632063172830362573",
"353298573733265954976305",
"341441428070681082764296",
"329956601901014451669209",
"318494932744979262777778",
"296228646616719265409458",
"284443800473768788618328",
"253401649263378789952600",
"234318928916288791506008",
"222904060578495092999432",
"211512138097318041893382",
"200143092354525877459667",
"193041107814745877994195",
"181351399901247458002509",
"170028589391668929262569",
"158728447859025187360488",
"157216549859025187360488",
"145939009294324549399906",
"134344994392610775846729",
"123112791163693047841851",
"92012042163693047088187",
"80802236826282617713085",
"69614762452388806862590",
"58111559539384800309488",
"31596108539384798179568",
"11096602239384797376752",
],
bids_volTotals: [
"198539605794234049017",
"194844233461662963807",
"191148861129091878597",
"187453488796520793387",
"183646135484174826807",
"179950763151603741597",
"178950763346403741597",
"175255391013832656387",
"171560018681261571177",
"167752665368915604597",
"164057293036344519387",
"160361920703773434177",
"156666548371202348967",
"152859195058856382387",
"149163822726285297177",
"145468450393714211967",
"141661097081368245387",
"137965724748797160177",
"137770769748797160228",
"134075397416226075018",
"130380025083654989808",
"126572671771309023228",
"122877299438737938018",
"119181927106166852808",
"119085927106166852808",
"115390554773595767598",
"111583201461249801018",
"107887829128678715808",
"104192456796107630598",
"97001782353847346182",
"93194429041501379602",
"83157259869133878290",
"76983045700832909330",
"73287673368261824120",
"69592301035690738910",
"65896928703119653700",
"63587931489546380100",
"59780578177200413520",
"56085205844629328310",
"52389833512058243100",
"51895291676258243202",
"48199919343687157992",
"44392566031341191412",
"40697193698770106202",
"30446386828370106202",
"26751014495799020992",
"23055642163227935782",
"19248288850881969202",
"10471674569881968690",
"3680188132691968050",
],
bids_amtTotal: "618450503644320209925641",
bids_volTotal: "198539605794234049017",
asks: [
{
price: 0.00033331,
amt: "26466599999999999737856",
vol: "8821317780000000000",
amtTotal: "26466599999999999737856",
volTotal: "8821317780000000000",
},
{
price: 0.0003336,
amt: "33880800000000001048576",
vol: "11302634880000000000",
amtTotal: "60347400000000000786432",
volTotal: "20123952660000000000",
},
{
price: 0.00033371,
amt: "11142477800817399987988",
vol: "3718356266910774549",
amtTotal: "71489877800817400774420",
volTotal: "23842308926910774549",
},
{
price: 0.00033439,
amt: "11410124103475892197402",
vol: "3815340399218399705",
amtTotal: "82900001904293292971822",
volTotal: "27657649326129174254",
},
{
price: 0.00033501,
amt: "39334199999999992922112",
vol: "13176957000000000000",
amtTotal: "122234201904293285893934",
volTotal: "40834606326129174254",
},
{
price: 0.00033506,
amt: "11052295534472154230337",
vol: "3703108939445215718",
amtTotal: "133286497438765440124271",
volTotal: "44537715265574389972",
},
{
price: 0.00033572,
amt: "11030456322913363709718",
vol: "3703093651997124565",
amtTotal: "144316953761678803833989",
volTotal: "48240808917571514537",
},
{
price: 0.00033638,
amt: "11008681778518069039476",
vol: "3703078409816047858",
amtTotal: "155325635540196872873465",
volTotal: "51943887327387562395",
},
{
price: 0.000337,
amt: "7188173683760000139264",
vol: "2422342649690282496",
amtTotal: "162513809223956873012729",
volTotal: "54366229977077844891",
},
{
price: 0.00033706,
amt: "11319571950108460741855",
vol: "3815277012711042502",
amtTotal: "173833381174065333754584",
volTotal: "58181506989788887393",
},
{
price: 0.00033773,
amt: "10964670732513311387215",
vol: "3703047602083844528",
amtTotal: "184798051906578645141799",
volTotal: "61884554591872731921",
},
{
price: 0.00033848,
amt: "10943090596879450870975",
vol: "3703921209677097807",
amtTotal: "195741142503458096012774",
volTotal: "65588475801549829728",
},
{
price: 0.00033893,
amt: "31086310012520000126976",
vol: "10535772189443278848",
amtTotal: "226827452515978096139750",
volTotal: "76124247990993108576",
},
{
price: 0.00033907,
amt: "10921574108084085072499",
vol: "3703126650187824910",
amtTotal: "237749026624062181212249",
volTotal: "79827374641180933486",
},
{
price: 0.00033934,
amt: "22061773569720001232896",
vol: "7486221625413088256",
amtTotal: "259810800193782182445145",
volTotal: "87313596266594021742",
},
{
price: 0.00033975,
amt: "11230093484570461106334",
vol: "3815326678720011608",
amtTotal: "271040893678352643551479",
volTotal: "91128922945314033350",
},
{
price: 0.00034042,
amt: "10878083875111520592396",
vol: "3703095772122414389",
amtTotal: "281918977553464164143875",
volTotal: "94832018717436447739",
},
{
price: 0.00034061,
amt: "19029641944770000453632",
vol: "6481686342808109056",
amtTotal: "300948619498234164597507",
volTotal: "101313705060244556795",
},
{
price: 0.00034109,
amt: "10856758733704286197912",
vol: "3703080631272015254",
amtTotal: "311805378231938450795419",
volTotal: "105016785691516572049",
},
{
price: 0.00034176,
amt: "10835496238854895014260",
vol: "3703065534900672185",
amtTotal: "322640874470793345809679",
volTotal: "108719851226417244234",
},
{
price: 0.00034244,
amt: "11141671799245742102774",
vol: "3815263899323431057",
amtTotal: "333782546270039087912453",
volTotal: "112535115125740675291",
},
{
price: 0.00034312,
amt: "10792518633700140402041",
vol: "3703035020801012310",
amtTotal: "344575064903739228314494",
volTotal: "116238150146541687601",
},
{
price: 0.00034379,
amt: "10771444484888773263977",
vol: "3703020058155356239",
amtTotal: "355346509388628001578471",
volTotal: "119941170204697043840",
},
{
price: 0.00034447,
amt: "11075875299655656611658",
vol: "3815217183808722096",
amtTotal: "366422384688283658190129",
volTotal: "123756387388505765936",
},
{
price: 0.00034515,
amt: "10728847020295584791583",
vol: "3702989813955495075",
amtTotal: "377151231708579242981712",
volTotal: "127459377202461261011",
},
{
price: 0.00034582,
amt: "10707958999548106661900",
vol: "3702974983460764366",
amtTotal: "387859190708127349643612",
volTotal: "131162352185922025377",
},
{
price: 0.00034649,
amt: "10687131919892014508549",
vol: "3702960196234208540",
amtTotal: "398546322628019364152161",
volTotal: "134865312382156233917",
},
{
price: 0.00034718,
amt: "10989265205593964126102",
vol: "3815155690641938295",
amtTotal: "409535587833613328278263",
volTotal: "138680468072798172212",
},
{
price: 0.00034809,
amt: "10645033127428079147754",
vol: "3705341637309061860",
amtTotal: "420180620961041407426017",
volTotal: "142385809710107234072",
},
{
price: 0.00034854,
amt: "10624389276271547157517",
vol: "3703021892850000724",
amtTotal: "430805010237312954583534",
volTotal: "146088831602957234796",
},
{
price: 0.00034922,
amt: "10603805418694082174472",
vol: "3703007072472544949",
amtTotal: "441408815656007036758006",
volTotal: "149791838675429779745",
},
{
price: 0.00034991,
amt: "10903667052066234563130",
vol: "3815203952623454269",
amtTotal: "452312482708073271321136",
volTotal: "153607042628053234014",
},
{
price: 0.00035059,
amt: "10562197544947631702552",
vol: "3702977114803447505",
amtTotal: "462874680253020903023688",
volTotal: "157310019742856681519",
},
{
price: 0.00035127,
amt: "10541794072549149477757",
vol: "3702962424303320597",
amtTotal: "473416474325570052501445",
volTotal: "161012982167160002116",
},
{
price: 0.00035196,
amt: "10839964505283434387937",
vol: "3815158086789770653",
amtTotal: "484256438830853486889382",
volTotal: "164828140253949772769",
},
{
price: 0.00035265,
amt: "10500550295026604907238",
vol: "3702932728783504366",
amtTotal: "494756989125880091796620",
volTotal: "168531072982733277135",
},
{
price: 0.00035333,
amt: "10480325106225117837726",
vol: "3702918166647567295",
amtTotal: "505237314232105209634346",
volTotal: "172233991149380844430",
},
{
price: 0.00035401,
amt: "10460158295034970667917",
vol: "3702903646543510388",
amtTotal: "515697472527140180302263",
volTotal: "175936894795924354818",
},
{
price: 0.0003547,
amt: "10756101480844670483856",
vol: "3815097705412174743",
amtTotal: "526453574007984850786119",
volTotal: "179751992501336529561",
},
{
price: 0.000355,
amt: "2879934000000000000000",
vol: "1022376570000000000",
amtTotal: "529333508007984850786119",
volTotal: "180774369071336529561",
},
{
price: 0.00035539,
amt: "10419392212908119384882",
vol: "3702874294964379056",
amtTotal: "539752900220892970171001",
volTotal: "184477243366300908617",
},
{
price: 0.00035607,
amt: "10399400937404414745812",
vol: "3702859901246016389",
amtTotal: "550152301158297384916813",
volTotal: "188180103267546925006",
},
{
price: 0.00035675,
amt: "10379467141462596339294",
vol: "3702845548912938279",
amtTotal: "560531768299759981256107",
volTotal: "191882948816459863285",
},
{
price: 0.00035781,
amt: "10673207910450037674513",
vol: "3818930797471485007",
amtTotal: "571204976210210018930620",
volTotal: "195701879613931348292",
},
{
price: 0.00035815,
amt: "10339171406073422424770",
vol: "3702919927697518809",
amtTotal: "581544147616283441355390",
volTotal: "199404799541628867101",
},
{
price: 0.00035883,
amt: "10319410450646547471681",
vol: "3702905502200057190",
amtTotal: "591863558066929988827071",
volTotal: "203107705043828924291",
},
{
price: 0.00035887,
amt: "1253970999999999795200",
vol: "449999996860000051",
amtTotal: "593117529066929988622271",
volTotal: "203557705040688924342",
},
{
price: 0.00035952,
amt: "10299706093934767574874",
vol: "3702891118019657590",
amtTotal: "603417235160864756197145",
volTotal: "207260596158708581932",
},
{
price: 0.00036,
amt: "491031000000000000000",
vol: "176771040000000000",
amtTotal: "603908266160864756197145",
volTotal: "207437367198708581932",
},
{
price: 0.00036022,
amt: "10591268908994289896668",
vol: "3815084938649532411",
amtTotal: "614499535069859046093813",
volTotal: "211252452137358114343",
},
],
asks_prices: [
0.00033331, 0.0003336, 0.00033371, 0.00033439, 0.00033501, 0.00033506,
0.00033572, 0.00033638, 0.000337, 0.00033706, 0.00033773, 0.00033848,
0.00033893, 0.00033907, 0.00033934, 0.00033975, 0.00034042, 0.00034061,
0.00034109, 0.00034176, 0.00034244, 0.00034312, 0.00034379, 0.00034447,
0.00034515, 0.00034582, 0.00034649, 0.00034718, 0.00034809, 0.00034854,
0.00034922, 0.00034991, 0.00035059, 0.00035127, 0.00035196, 0.00035265,
0.00035333, 0.00035401, 0.0003547, 0.000355, 0.00035539, 0.00035607,
0.00035675, 0.00035781, 0.00035815, 0.00035883, 0.00035887, 0.00035952,
0.00036, 0.00036022,
],
asks_amtTotals: [
"26466599999999999737856",
"60347400000000000786432",
"71489877800817400774420",
"82900001904293292971822",
"122234201904293285893934",
"133286497438765440124271",
"144316953761678803833989",
"155325635540196872873465",
"162513809223956873012729",
"173833381174065333754584",
"184798051906578645141799",
"195741142503458096012774",
"226827452515978096139750",
"237749026624062181212249",
"259810800193782182445145",
"271040893678352643551479",
"281918977553464164143875",
"300948619498234164597507",
"311805378231938450795419",
"322640874470793345809679",
"333782546270039087912453",
"344575064903739228314494",
"355346509388628001578471",
"366422384688283658190129",
"377151231708579242981712",
"387859190708127349643612",
"398546322628019364152161",
"409535587833613328278263",
"420180620961041407426017",
"430805010237312954583534",
"441408815656007036758006",
"452312482708073271321136",
"462874680253020903023688",
"473416474325570052501445",
"484256438830853486889382",
"494756989125880091796620",
"505237314232105209634346",
"515697472527140180302263",
"526453574007984850786119",
"529333508007984850786119",
"539752900220892970171001",
"550152301158297384916813",
"560531768299759981256107",
"571204976210210018930620",
"581544147616283441355390",
"591863558066929988827071",
"593117529066929988622271",
"603417235160864756197145",
"603908266160864756197145",
"614499535069859046093813",
],
asks_volTotals: [
"8821317780000000000",
"20123952660000000000",
"23842308926910774549",
"27657649326129174254",
"40834606326129174254",
"44537715265574389972",
"48240808917571514537",
"51943887327387562395",
"54366229977077844891",
"58181506989788887393",
"61884554591872731921",
"65588475801549829728",
"76124247990993108576",
"79827374641180933486",
"87313596266594021742",
"91128922945314033350",
"94832018717436447739",
"101313705060244556795",
"105016785691516572049",
"108719851226417244234",
"112535115125740675291",
"116238150146541687601",
"119941170204697043840",
"123756387388505765936",
"127459377202461261011",
"131162352185922025377",
"134865312382156233917",
"138680468072798172212",
"142385809710107234072",
"146088831602957234796",
"149791838675429779745",
"153607042628053234014",
"157310019742856681519",
"161012982167160002116",
"164828140253949772769",
"168531072982733277135",
"172233991149380844430",
"175936894795924354818",
"179751992501336529561",
"180774369071336529561",
"184477243366300908617",
"188180103267546925006",
"191882948816459863285",
"195701879613931348292",
"199404799541628867101",
"203107705043828924291",
"203557705040688924342",
"207260596158708581932",
"207437367198708581932",
"211252452137358114343",
],
asks_amtTotal: "614499535069859046093813",
asks_volTotal: "211252452137358114343",
};
//v3/amm/balance?poolAddress=0xfEB069407df0e1e4B365C10992F1bc16c078E34b
export const ammPoolSnapshot: sdk.AmmPoolSnapshot = {
poolName: "AMM-LRC-ETH",
poolAddress: "0x18920d6e6fb7ebe057a4dd9260d6d95845c95036",
pooled: [
{
tokenId: 1,
volume: "11198097977488137000000000",
},
{
tokenId: 0,
volume: "3725368050950874300000",
},
],
lp: {
tokenId: 83,
volume: "34138981282200",
},
risky: false,
};
//v3/amm/balance?poolAddress=0xfEB069407df0e1e4B365C10992F1bc16c078E34b
export const ammPool = {
poolName: "AMM-LRC-ETH",
poolAddress: "0x18920d6e6fb7ebe057a4dd9260d6d95845c95036",
pooled: [
{ tokenId: 1, volume: "11215027899488137000000000" },
{ tokenId: 0, volume: "3720052711450874300000" },
],
lp: { tokenId: 83, volume: "34141365482200" },
risky: false,
};
//v3/mix/ticker?market=LRC-ETH
export const ticker = {
tickers: [
[
"COMBINE-LRC-ETH",
"1655625077879",
"2429371927000000000000000",
"814655525450000000000",
"0.00035052",
"0.00035222",
"0.00032201",
"0.00033367",
"772",
"",
"",
"",
"",
],
],
};
//v3/user/orderUserRateAmount?accountId=10427&market=LRC-ETH
export const userAmount = {
"LRC-ETH": {
LRC: {
tokenSymbol: "LRC",
baseOrderInfo: {
minAmount: "266240681576144834931",
makerRate: 0,
takerRate: 10,
},
userOrderInfo: {
minAmount: "266240681576144834931",
makerRate: 0,
takerRate: 10,
},
tradeCost: "231046501539337141",
},
ETH: {
tokenSymbol: "ETH",
baseOrderInfo: {
minAmount: "86598080986525339",
makerRate: 0,
takerRate: 10,
},
userOrderInfo: {
minAmount: "86598080986525339",
makerRate: 0,
takerRate: 10,
},
tradeCost: "75150737796750",
},
},
"AMM-LRC-ETH": {
LRC: {
tokenSymbol: "LRC",
baseOrderInfo: {
minAmount: "266240681576144834931",
makerRate: 0,
takerRate: 10,
},
userOrderInfo: {
minAmount: "266240681576144834931",
makerRate: 0,
takerRate: 10,
},
tradeCost: "231046501539337141",
},
ETH: {
tokenSymbol: "ETH",
baseOrderInfo: {
minAmount: "86598080986525339",
makerRate: 0,
takerRate: 10,
},
userOrderInfo: {
minAmount: "86598080986525339",
makerRate: 0,
takerRate: 10,
},
tradeCost: "75150737796750",
},
},
};
export const TokenMapMockSwap = {
ETH: {
type: "ETH",
tokenId: 0,
symbol: "ETH",
name: "Ethereum",
address: "0x0000000000000000000000000000000000000000",
decimals: 18,
precision: 7,
precisionForOrder: 3,
orderAmounts: {
minimum: "1700000000000000",
maximum: "1000000000000000000000",
dust: "200000000000000",
},
luckyTokenAmounts: {
minimum: "50000000000000",
maximum: "1000000000000000000000",
dust: "50000000000000",
},
fastWithdrawLimit: "100000000000000000000",
gasAmounts: {
distribution: "85000",
deposit: "110000",
},
enabled: true,
isLpToken: false,
tradePairs: ["LRC"],
},
LRC: {
type: "ERC20",
tokenId: 1,
symbol: "LRC",
name: "Loopring",
address: "0xbbbbca6a901c926f240b89eacb641d8aec7aeafd",
decimals: 18,
precision: 3,
precisionForOrder: 3,
orderAmounts: {
minimum: "5000000000000000000",
maximum: "5000000000000000000000000",
dust: "5000000000000000000",
},
luckyTokenAmounts: {
minimum: "50000000000000000",
maximum: "5000000000000000000000000",
dust: "50000000000000000",
},
fastWithdrawLimit: "750000000000000000000000",
gasAmounts: {
distribution: "101827",
deposit: "150000",
},
enabled: true,
isLpToken: false,
tradePairs: ["ETH"],
},
};
export const MAPFEEBIPS = 63;
```
================================================
FILE: docs/js_sdk/exchange/ammpool_api.md
================================================
# AmmPool API
## getAmmPoolConf
```typescript
const { ammpools, pairs } = await api.getAmmPoolConf();
```
## getAmmPoolUserRewards
```typescript
const response: any = await api.getAmmPoolUserRewards({
owner: acc.accountId.toString(),
});
```
## getAmmPoolActivityRules
```typescript
const response: any = await api.getAmmPoolActivityRules();
```
## getAmmPoolStats
```typescript
const response: any = await api.getAmmPoolStats();
```
## getAmmPoolSnapshot
```typescript
const request: GetAmmPoolSnapshotRequest = {
poolAddress,
};
const response = await api.getAmmPoolSnapshot(request, acc.apiKey);
```
## getAmmPoolBalances
```typescript
const response = await api.getAmmPoolBalances();
```
## getAmmPoolTrades
```typescript
const request: GetAmmPoolTradesRequest = {
ammPoolAddress: poolAddress,
};
const response = await api.getAmmPoolTrades(request);
```
## getUserAmmPoolTxs
```typescript
const request: GetUserAmmPoolTxsRequest = {
accountId: acc.accountId,
};
const response = await api.getUserAmmPoolTxs(request, acc.apiKey);
```
## joinAmmPool
```typescript
const request2: JoinAmmPoolRequest = {
owner: acc.address,
poolAddress,
joinTokens: {
pooled: [
{ tokenId: "1", volume: "1000000000000000000000" },
{ tokenId: "0", volume: "1000000000000000000" },
],
minimumLp: { tokenId: "4", volume: "100000" },
},
storageIds: [storageId_1.offchainId, storageId.offchainId],
fee: "1000000000000000000",
};
const patch: AmmPoolRequestPatch = {
chainId: ChainId.GORLI,
ammName: "LRCETH-Pool",
poolAddress,
eddsaKey: acc.eddsaKey,
};
const response = await api.joinAmmPool(request2, patch, acc.apiKey);
```
## exitAmmPool
```typescript
const request2: ExitAmmPoolRequest = {
owner: acc.address,
poolAddress,
exitTokens: {
unPooled: [
{ tokenId: "1", volume: "1000000000000000000000" },
{ tokenId: "0", volume: "1000000000000000000" },
],
burned: { tokenId: "4", volume: "100000" },
},
storageId: storageId_1.offchainId,
maxFee: "1000000000000000000",
};
const patch: AmmPoolRequestPatch = {
chainId: ChainId.GORLI,
ammName: "LRCETH-Pool",
poolAddress,
eddsaKey: acc.eddsaKey,
};
const response = await api.exitAmmPool(request2, patch, acc.apiKey);
```
================================================
FILE: docs/js_sdk/exchange/exchange.md
================================================
# Loopring Exchange
Definition: Loopring Dex Main API for get Exchange Information, L2 Block, ERC20 Token Information, AMM Information,
Market Config and so on static and dynamic information
***
## getExchangeInfo
```ts
const response = await LoopringAPI.exchangeAPI.getExchangeInfo();
console.log(response);
```
***
## getTokens
```ts
const {tokensMap, coinMap, totalCoinMap, idIndex, addressIndex} =
await LoopringAPI.exchangeAPI.getTokens<any>();
console.log(
"tokenMap:",
tokensMap,
coinMap,
totalCoinMap,
idIndex,
addressIndex
);
```
***
## getMixMarkets
```ts
const {markets, pairs, tokenArr, tokenArrStr, marketArr, marketArrStr} =
await LoopringAPI.exchangeAPI.getMixMarkets();
console.log("markets:", markets);
console.log("pairs:", pairs);
console.log("tokenArr:", tokenArr);
console.log("tokenArrStr:", tokenArrStr);
console.log("marketArr", marketArr);
console.log("marketArrStr", marketArrStr);
```
***
## getAmmPoolConf
```ts
const response = await LoopringAPI.ammpoolAPI.getAmmPoolConf();
console.log(response.ammpools);
console.log(response.pairs);
```
***
## getAvailableBroker
```ts
const result = await LoopringAPI.exchangeAPI.getAvailableBroker();
console.log(result);
```
***
## getTokenPrices
```ts
const response = await LoopringAPI.walletAPI.getTokenPrices({
token: TOKEN_INFO.tokenMap.LRC.address,
});
console.log(response);
```
***
## getLatestTokenPrices
```ts
const response = await LoopringAPI.walletAPI.getLatestTokenPrices();
console.log(response);
```
***
## getLatestTokenPrices_cny
```ts
const response = await LoopringAPI.walletAPI.getLatestTokenPrices({
currency: sdk.Currency.cny,
});
console.log(response);
```
***
## getWithdrawalAgents
```ts
const response = await LoopringAPI.exchangeAPI.getWithdrawalAgents({
tokenId: 1,
amount: "10000000000",
});
console.log(response);
```
***
## getCandlestick
```ts
const response = await LoopringAPI.exchangeAPI.getCandlestick({
market: "LRC-ETH",
interval: sdk.TradingInterval.min15,
limit: 96,
});
console.log(response);
```
***
## getAccountServices
```ts
const response = await LoopringAPI.exchangeAPI.getAccountServices({});
console.log(response);
```
***
## getExchangeFeeInfo
```ts
const response = await LoopringAPI.exchangeAPI.getExchangeFeeInfo<any>();
console.log(response);
console.log(
response.raw_data[sdk.VipCatergory.ORDERBOOK_TRADING_FEES_STABLECOIN]
);
```
***
## getProtocolPortrait
```ts
const response = await LoopringAPI.exchangeAPI.getProtocolPortrait();
console.log(response);
```
***
## getRecommendedMarkets
```ts
const response = await LoopringAPI.exchangeAPI.getRecommendedMarkets();
console.log(response);
```
***
## getGasPrice
```ts
const response = await LoopringAPI.exchangeAPI.getGasPrice();
console.log(response);
```
***
## getGasPriceRange
```ts
const response = await LoopringAPI.exchangeAPI.getGasPriceRange();
console.log(response);
```
***
## getMarketTrades
```ts
const response = await LoopringAPI.exchangeAPI.getMarketTrades<any>({
market: "ETH-USDT",
});
console.log(response.raw_data.trades);
```
***
## getRelayerCurrentTime
```ts
const response = await LoopringAPI.exchangeAPI.getRelayerCurrentTime();
console.log(response);
```
***
## getFiatPriceUSD
```ts
const response = await LoopringAPI.exchangeAPI.getFiatPrice({
legal: "USD",
});
console.log(response);
```
***
## getFiatPriceCNY
```ts
const response = await LoopringAPI.exchangeAPI.getFiatPrice({
legal: "CNY",
});
console.log(response);
```
***
## getMarkets
```ts
const response = await LoopringAPI.exchangeAPI.getMarkets();
console.log(response);
console.log(response.pairs.LRC.tokenList);
console.log(
"hasMarket LRC-ETH:",
sdk.hasMarket(response.marketArr, "LRC-ETH")
);
console.log(
"market 1:",
sdk.getExistedMarket(response.marketArr, "LRC", "ETH")
);
console.log(
"market 2:",
sdk.getExistedMarket(response.marketArr, "ETH", "LRC")
);
```
***
## getDepth
```ts
const response = await LoopringAPI.exchangeAPI.getDepth({
market: "LRC-ETH",
});
console.log(response);
```
***
## getTicker
```ts
const response = await LoopringAPI.exchangeAPI.getTicker({
market: "LRC-ETH",
});
console.log(response);
```
***
## getAllTickers
```ts
const response = await LoopringAPI.exchangeAPI.getAllTickers();
console.log(response);
```
***
## getMixDepth
```ts
const response = await LoopringAPI.exchangeAPI.getMixDepth({
market: "LRC-ETH",
});
console.log(response);
console.log(response.depth.bids);
```
***
## getMixTicker
```ts
const response = await LoopringAPI.exchangeAPI.getMixTicker({
market: ["LRC-ETH", "ETH-USDC", "DAI-USDT"].join(","),
});
console.log(response.tickMap["DAI-USDT"]);
```
***
## getAllMixTickers
```ts
const response: any = await LoopringAPI.exchangeAPI.getAllMixTickers();
console.log(response?.tickMap);
```
***
## getMixCandlestickAMM
```ts
const response = await LoopringAPI.exchangeAPI.getMixCandlestick({
market: "AMM-LRC-ETH",
interval: sdk.TradingInterval.min15,
limit: 96,
});
console.log(response);
```
});
================================================
FILE: docs/js_sdk/exchange/webSocket.md
================================================
#WebSocket Command
Definition: Loopring L2 websocket
### Loopring L2 websocket topic type:
WsTopicType
- `account`
- `orderbook`
- `mixorder`
- `mixtrade`
- `ticker`
- `candlestick`
- `ammpool`
## getWsKey (required by account related socket)
```ts
const response = await LoopringAPI.wsAPI.getWsKey();
console.log(response);
```
## getOrderBookArg
```ts
const arg1 = sdk.getMixOrderArg({ market: "LRC-ETH", level: 50 });
console.log(arg1);
const arg2 = sdk.getOrderBookArg({
market: "LRC-ETH",
level: 50,
count: 40,
snapshot: false,
});
console.log(arg2);
```
================================================
FILE: docs/js_sdk/transfer/transferERC20.md
================================================
# Transfer ERC20
Definition: Send ERC20 tokens to other account on Loopring L2,
> trade value should with decimals `sdk.toBig(value).times("1e" + TOKEN_INFO.tokenMap.LRC.decimals)`
***
## Step 1. get account Info
const { exchangeInfo } = await LoopringAPI.exchangeAPI.getExchangeInfo();
const LOOPRING_EXPORTED_ACCOUNT.exchangeAddress = exchangeInfo;
```ts
const { accInfo } = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
```
***
## Step 2. get eddsaKey
```ts
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
```
***
## Step 3. get apikey
```ts
const { apiKey } = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
const { userBalances } = await LoopringAPI.userAPI.getUserBalances(
{ accountId: LOOPRING_EXPORTED_ACCOUNT.accountId, tokens: "" },
apiKey
);
```
***
## Step 4. get storageId
```ts
const storageId = await LoopringAPI.userAPI.getNextStorageId(
{
accountId: accInfo.accountId,
sellTokenId: TOKEN_INFO.tokenMap["LRC"].tokenId,
},
apiKey
);
console.log("storageId:", storageId);
```
***
## Step 5. get fee
```ts
const fee = await LoopringAPI.userAPI.getOffchainFeeAmt({
accountId: accInfo.accountId,
requestType: sdk.OffchainFeeReqType.TRANSFER,
}, apiKey);
console.log("fee:", fee);
```
***
## Step 6. transfer
```ts
const transferResult = await LoopringAPI.userAPI.submitInternalTransfer({
request: {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
payerAddr: accInfo.owner,
payerId: accInfo.accountId,
payeeAddr: LOOPRING_EXPORTED_ACCOUNT.address2,
payeeId: LOOPRING_EXPORTED_ACCOUNT.accountId2,
storageId: storageId.offchainId,
token: {
tokenId: TOKEN_INFO.tokenMap.LRC.tokenId,
volume: LOOPRING_EXPORTED_ACCOUNT.tradeLRCValue.toString(),
},
maxFee: {
tokenId: TOKEN_INFO.tokenMap["LRC"].tokenId,
volume: fee.fees["LRC"].fee ?? "9400000000000000000",
},
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.Trezor,
eddsaKey: eddsaKey.sk,
apiKey: apiKey,
});
console.log("transferResult:", transferResult);
```
================================================
FILE: docs/js_sdk/transfer/transferNFT.md
================================================
# Transfer NFT
Definition: Send NFT to other account on Loopring L2
***
## Step 1. get account Info
```ts
const { exchangeInfo } = await LoopringAPI.exchangeAPI.getExchangeInfo();
const LOOPRING_EXPORTED_ACCOUNT.exchangeAddress = exchangeInfo;
const { accInfo } = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
```
***
## Step 2. get eddsaKey
```ts
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
```
***
## Step 3. get apiKey
```ts
const { apiKey } = await LoopringAPI.userAPI.getUserApiKey({
accountId: accInfo.accountId}, eddsaKey.sk
);
console.log("apiKey:", apiKey);
const { userNFTBalances } = await LoopringAPI.userAPI.getUserNFTBalances(
{ accountId: accInfo.accountId, limit: 20 },
apiKey
);
```
***
##Step 4. get storageId
```ts
const storageId = await LoopringAPI.userAPI.getNextStorageId({
accountId: accInfo.accountId,
sellTokenId: LOOPRING_EXPORTED_ACCOUNT.nftTokenId,
}, apiKey);
```
***
## Step 5. get fee
```ts
const fee = await LoopringAPI.userAPI.getNFTOffchainFeeAmt({
accountId: accInfo.accountId,
requestType: sdk.OffchainNFTFeeReqType.NFT_TRANSFER,
amount: "0",
}, apiKey);
console.log("fee:", fee);
```
***
## Step 6. Transfer NFT
```ts
const transferResult = await LoopringAPI.userAPI.submitNFTInTransfer({
request: {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
fromAccountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
fromAddress: LOOPRING_EXPORTED_ACCOUNT.address,
toAccountId: 0, // toAccountId is not required, input 0 as default
toAddress: LOOPRING_EXPORTED_ACCOUNT.address2,
token: {
tokenId: LOOPRING_EXPORTED_ACCOUNT.nftTokenId,
nftData: LOOPRING_EXPORTED_ACCOUNT.nftData,
amount: "1",
},
maxFee: {
tokenId: TOKEN_INFO.tokenMap["LRC"].tokenId,
amount: fee.fees["LRC"].fee ?? "9400000000000000000",
},
storageId: storageId.offchainId,
validUntil: LOOPRING_EXPORTED_ACCOUNT.validUntil,
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.Unknown,
eddsaKey: eddsaKey.sk,
apiKey,
});
console.log("transfer Result:", transferResult);
```
================================================
FILE: docs/js_sdk/withdraw/withdrawERC20.md
================================================
# Withdraw ERC20
Definition: Loopring L2 withdraw ERC20 to Ethereum L1,
> trade value should with decimals `sdk.toBig(value).times("1e" + TOKEN_INFO.tokenMap.LRC.decimals)`
***
## Step 1. getAccount
```ts
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
```
##Step 2. eddsaKey
```ts
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
```
***
## Step 3. apiKey
```ts
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey({
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
```
***
## Step 4. storageId
```ts
const storageId = await LoopringAPI.userAPI.getNextStorageId({
accountId: accInfo.accountId,
sellTokenId: TOKEN_INFO.tokenMap["LRC"].tokenId,
},
apiKey
);
console.log("storageId:", storageId);
```
***
## Step 5. fee
```ts
const fee = await LoopringAPI.userAPI.getOffchainFeeAmt({
accountId: accInfo.accountId,
requestType: sdk.OffchainFeeReqType.OFFCHAIN_WITHDRAWAL,
tokenSymbol: TOKEN_INFO.tokenMap["LRC"].symbol,
},
apiKey
);
console.log("fee:", fee);
```
***
## Step 6. withdraw
```ts
const response = await LoopringAPI.userAPI.submitOffchainWithdraw({
request: {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
counterFactualInfo: undefined,
fastWithdrawalMode: false,
hashApproved: "",
maxFee: {
tokenId: TOKEN_INFO.tokenMap["LRC"].tokenId,
volume: fee.fees["LRC"].fee ?? "9400000000000000000",
},
minGas: 0,
owner: LOOPRING_EXPORTED_ACCOUNT.address,
to: LOOPRING_EXPORTED_ACCOUNT.address,
storageId: 0,
token: {
tokenId: TOKEN_INFO.tokenMap.LRC.tokenId,
volume: LOOPRING_EXPORTED_ACCOUNT.tradeLRCValue.toString(),
},
validUntil: 0,
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.MetaMask,
eddsaKey: eddsaKey.sk,
apiKey,
});
console.log("response:", response);
```
================================================
FILE: docs/js_sdk/withdraw/withdrawNFT.md
================================================
# Withdraw NFT
Definition: Loopring L2 withdraw NFT to Ethereum L1
***
## Step 1. getAccount
```ts
const {accInfo} = await LoopringAPI.exchangeAPI.getAccount({
owner: LOOPRING_EXPORTED_ACCOUNT.address,
});
console.log("accInfo:", accInfo);
```
***
## Step 2. eddsaKey
```ts
const eddsaKey = await signatureKeyPairMock(accInfo);
console.log("eddsaKey:", eddsaKey.sk);
```
***
## Step 3. apiKey
```ts
const {apiKey} = await LoopringAPI.userAPI.getUserApiKey(
{
accountId: accInfo.accountId,
},
eddsaKey.sk
);
console.log("apiKey:", apiKey);
```
***
## Step 4. storageId
```ts
const storageId = await LoopringAPI.userAPI.getNextStorageId(
{
accountId: accInfo.accountId,
sellTokenId: LOOPRING_EXPORTED_ACCOUNT.nftTokenId,
},
apiKey
);
console.log("storageId:", storageId);
//Step 5. getUserNFTBalances
const {userNFTBalances} = await LoopringAPI.userAPI.getUserNFTBalances(
{accountId: LOOPRING_EXPORTED_ACCOUNT.accountId},
apiKey
);
const tokenInfo = userNFTBalances.find(
(item) =>
item.tokenAddress?.toLowerCase() ===
LOOPRING_EXPORTED_ACCOUNT.nftTokenAddress.toLowerCase() &&
item.nftId &&
web3.utils.hexToNumberString(item.nftId) ===
LOOPRING_EXPORTED_ACCOUNT.nftTokenId.toString()
);
```
***
## Step 5. fee
```ts
const fee = await LoopringAPI.userAPI.getNFTOffchainFeeAmt(
{
accountId: accInfo.accountId,
requestType: sdk.OffchainNFTFeeReqType.NFT_WITHDRAWAL,
tokenAddress: LOOPRING_EXPORTED_ACCOUNT.nftTokenAddress,
deployInWithdraw:
tokenInfo?.deploymentStatus === DEPLOYMENT_STATUS.NOT_DEPLOYED, // when token is not deploy the fee is diff
},
apiKey
);
console.log("fee:", fee);
```
***
## Step 6. withdraw
```ts
const response = await LoopringAPI.userAPI.submitNFTWithdraw({
request: {
exchange: LOOPRING_EXPORTED_ACCOUNT.exchangeAddress,
accountId: LOOPRING_EXPORTED_ACCOUNT.accountId,
counterFactualInfo: undefined,
hashApproved: "",
maxFee: {
tokenId: TOKEN_INFO.tokenMap["LRC"].tokenId,
amount: fee.fees["LRC"].fee ?? "9400000000000000000",
},
minGas: 0,
owner: LOOPRING_EXPORTED_ACCOUNT.address,
to: LOOPRING_EXPORTED_ACCOUNT.address,
storageId: 0,
token: {
tokenId: LOOPRING_EXPORTED_ACCOUNT.nftTokenId,
nftData: LOOPRING_EXPORTED_ACCOUNT.nftData,
amount: "1",
},
validUntil: 0,
},
web3,
chainId: sdk.ChainId.GOERLI,
walletType: sdk.ConnectorNames.MetaMask,
eddsaKey: eddsaKey.sk,
apiKey,
});
console.log("response:", response);
```
================================================
FILE: jest.config.cjs
================================================
module.exports = {
preset: 'ts-jest',
verbose: true,
transform: {
'^.+\\.(js|jsx|ts|tsx)$': './node_modules/babel-jest',
},
"moduleNameMapper": {
"axios": "axios/dist/node/axios.cjs"
},
"transformIgnorePatterns": ["node_modules\/(?!axios)"]
}
================================================
FILE: package.json
================================================
{
"name": "@loopring-web/loopring-sdk",
"version": "3.9.23",
"author": "Loopring Dev Team",
"description": "Loopring SDK",
"license": "SEE LICENSE IN LICENSE",
"main": "dist/index.cjs",
"module": "dist/index.esm.js",
"types": "dist/index.d.ts",
"source": "src/index.ts",
"exports": {
"require": "./dist/index.cjs",
"import": "./dist/index.esm.js"
},
"files": [
"dist",
"!tests",
"!__snapshots__",
"!*.test.js",
"!*.test.js.map",
"!*.test.ts",
"!*.test.d.ts"
],
"type": "module",
"prettier": {
"semi": false,
"tabWidth": 2,
"printWidth": 100,
"singleQuote": true,
"trailingComma": "all",
"jsxSingleQuote": true,
"bracketSpacing": true
},
"dependencies": {
"@ethereumjs/common": "^2.4.0",
"@ethereumjs/tx": "^3.3.0",
"@types/jsbn": "^1.2.30",
"axios": "^1.4.0",
"bignumber.js": "9.1.1",
"blake-hash": "^2.0.0",
"blake2b": "^2.1.3",
"bn.js": "^5.2.1",
"buffer": "^6.0.3",
"core-js": "3",
"crypto-js": "4.1.1",
"eth-sig-util": "2.3.0",
"ethereumjs-abi": "0.6.8",
"ethereumjs-util": "5.2.0",
"ethers": "^5.7.2",
"js-sha3": "^0.8.0",
"js-sha512": "^0.8.0",
"jsbn": "^1.1.0",
"multiformats": "^12.0.1",
"web-encoding": "^1.1.5",
"web3": "1.10.0"
},
"build": {
"files": [
"src/**/*",
"node_modules/**/*"
],
"publish": {
"provider": "custom",
"repo": "https://github.com/Loopring/loopring_sdk",
"owner": "Loopring Dev Team"
}
},
"scripts": {
"build": "rimraf dist && NODE_ENV=production cross-env BABEL_ENV=prod rollup -c --bundleConfigAsCjs",
"start": "NODE_ENV=development rollup -c --bundleConfigAsCjs -w",
"test": "tsdx test",
"test_calc": "tsdx test",
"lint": "eslint . --fix --quiet --ext .ts",
"prepublishDev": "NODE_ENV=dev build build",
"prepublishOnly": "yarn build",
"doc": "typedoc --out docs/detail src\\/",
"proxy": "export http_proxy=http://127.0.0.1:1087;export https_proxy=http://127.0.0.1:1087;",
"build-book": "npx honkit build",
"cp-file-doc": "cp README.md ./docs/README.md; cp Changelog.md ./docs/Changelog.md; ",
"build-b": "npm run doc; npm run build-book",
"serve-book": "npx honkit serve",
"deploy-book": "gh-pages -d _book"
},
"browserslist": {
"production": [
"last 2 chrome version",
"last 2 firefox version",
"last 2 safari version"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"lint-staged": {
"**/*": "prettier --write --ignore-unknown"
},
"devDependencies": {
"@babel/plugin-transform-optional-chaining": "^7.23.4",
"@babel/plugin-transform-typescript": "^7.14.6",
"@babel/preset-env": "^7.14.5",
"@babel/preset-typescript": "^7.14.5",
"@microsoft/tsdoc": "^0.13.2",
"@rollup/plugin-babel": "^6.0.3",
"@rollup/plugin-commonjs": "^25.0.2",
"@rollup/plugin-json": "^6.0.0",
"@rollup/plugin-node-resolve": "^15.1.0",
"@rollup/plugin-replace": "^5.0.2",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.0.0",
"@types/bignumber.js": "^5.0.0",
"@types/blake2b": "^2.1.0",
"@types/classnames": "^2.2.11",
"@types/collections": "^5.1.2",
"@types/crypto-js": "^4.0.1",
"@types/eth-sig-util": "^2.1.0",
"@types/ethereumjs-abi": "^0.6.3",
"@types/ethereumjs-tx": "^2.0.0",
"@types/ethereumjs-util": "5.2.0",
"@types/jest": "^26.0.23",
"@types/lodash": "^4.14.168",
"@types/mocha": "^8.2.2",
"@types/ms": "^0.7.31",
"@types/node": "^12.0.0",
"@types/node-fetch": "^3.0.3",
"@types/request": "^2.48.6",
"@types/request-promise": "^4.1.48",
"@types/truffle-privatekey-provider": "^1.1.0",
"@typescript-eslint/eslint-plugin": "^4.6.0",
"@typescript-eslint/parser": "^4.6.0",
"async": "^3.2.0",
"babel-jest": "^26.6.3",
"babel-plugin-import": "^1.13.3",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-env": "^1.7.0",
"chai": "^4.3.4",
"cross-env": "^7.0.3",
"gh-pages": "^3.2.3",
"honkit": "^3.6.20",
"jest": "^26.6.3",
"mocha": "^8.3.2",
"prettier": "2.8.8",
"request-promise": "^4.2.6",
"rimraf": "^5.0.1",
"rollup": "^3.25.3",
"rollup-plugin-typescript2": "^0.36.0",
"truffle-privatekey-provider": "1.5.0",
"ts-node": "^10.0.0",
"tslib": "^2.3.0",
"typedoc": "^0.22.9",
"typedoc-plugin-markdown": "^3.11.7",
"typescript": "^5.1.3"
}
}
================================================
FILE: rollup.config.mjs
================================================
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel'
import terser from '@rollup/plugin-terser'
import json from '@rollup/plugin-json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import typescript from 'rollup-plugin-typescript2';
import { builtinModules } from 'module';
import pkg from './package.json' assert { type: "json" };
// console.log('pkg',pkg)
module.exports = {
input: pkg.source,
output: [
{ file:pkg.main , format: 'cjs', sourcemap: true, plugins: [terser()], },
{ file: pkg.module , format: 'esm', sourcemap: true, plugins: [terser()], }
],
external: [
...builtinModules,
...(pkg.dependencies ? Object.keys(pkg.dependencies) : []),
...(pkg.devDependencies ? Object.keys(pkg.devDependencies) : []),
...(pkg.peerDependencies ? Object.keys(pkg.peerDependencies) : [])
],
watch: {
include: 'src/**',
},
plugins: [
json(),
typescript({
abortOnError: process.env.NODE_ENV === 'production',
tsconfig:'./tsconfig.json',
tsconfigDefaults: {
exclude: [
// all TS test files, regardless whether co-located or in test/ etc
'**/*.spec.ts',
'**/*.test.ts',
'**/*.spec.ts',
'**/*.test.ts',
// TS defaults below
'node_modules',
'bower_components',
'jspm_packages',
],
compilerOptions: {
sourceMap: true,
declaration: true,
jsx: 'react',
},
},
tsconfigOverride: {
compilerOptions: Object.assign({
// TS -> esnext, then leave the rest to babel-preset-env
target: 'esnext' }, { declaration: true, declarationMap: true }),
},
}
),
commonjs() ,
nodeResolve({
exportConditions: ['import', 'default', 'require'],
mainFields: ['module', 'main', 'browser'],
modulesOnly: true,
preferBuiltins: false,
}),
babel({
babelHelpers: 'bundled',
include: ['src/**/*.ts'],
exclude: './node_modules/**',
}),
]
};
================================================
FILE: src/api/ammpool_api.ts
================================================
/* eslint-disable camelcase */
import { BaseAPI } from './base_api'
import * as loopring_defs from '../defs'
import { LOOPRING_URLs } from '../defs'
import * as sign_tools from './sign/sign_tools'
import { makeAmmPool } from '../utils'
export class AmmpoolAPI extends BaseAPI {
/*
* Returns the fee rate of users placing orders in specific markets
*/
public async getAmmPoolConf<R>(): Promise<{
raw_data: R
ammpools: loopring_defs.LoopringMap<loopring_defs.AmmPoolInfoV3>
pairs: loopring_defs.LoopringMap<loopring_defs.TokenRelatedInfo>
}> {
const reqParams: loopring_defs.ReqParams = {
url: LOOPRING_URLs.GET_AMM_POOLS_CONF,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo) {
return {
...raw_data?.resultInfo,
}
}
const { ammpools, pairs } = makeAmmPool(raw_data)
// if (raw_data.code) {
// return {
// ...raw_data,
// };
// }
return {
ammpools,
pairs,
raw_data,
}
}
/*
*/
public async getAmmPoolUserRewards<R>(request: loopring_defs.GetAmmUserRewardsRequest): Promise<{
raw_data: R
ammUserRewardMap: loopring_defs.AmmUserRewardMap
}> {
const reqParams: loopring_defs.ReqParams = {
queryParams: request,
url: LOOPRING_URLs.GET_AMMPOOL_REWARDS,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo) {
return {
...raw_data?.resultInfo,
}
}
const ammUserRewardMap: loopring_defs.AmmUserRewardMap = {}
if (raw_data?.current) {
raw_data?.current.forEach((item: loopring_defs.AmmUserReward) => {
ammUserRewardMap[item.market] = {
current: item,
lastDay: undefined,
}
})
}
if (raw_data?.lastDay) {
raw_data?.lastDay.forEach((item: loopring_defs.AmmUserReward) => {
ammUserRewardMap[item.market] = {
...ammUserRewardMap[item.market],
lastDay: item,
}
})
}
return {
ammUserRewardMap,
raw_data,
}
}
/*
*/
public async getAmmPoolGameRank<R>(request: loopring_defs.GetAmmPoolGameRankRequest): Promise<{
raw_data: R
totalRewards: loopring_defs.TokenVolumeV3[]
userRankList: loopring_defs.GameRankInfo[]
}> {
const reqParams: loopring_defs.ReqParams = {
queryParams: request,
url: LOOPRING_URLs.GET_AMMPOOL_GAME_RANK,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo) {
return {
...raw_data?.resultInfo,
}
}
const totalRewards: loopring_defs.TokenVolumeV3[] = raw_data?.totalRewards
? raw_data.totalRewards
: []
const userRankList: loopring_defs.GameRankInfo[] = raw_data?.userRankList
? raw_data.userRankList
: []
return {
totalRewards,
userRankList,
raw_data,
}
}
/*
*/
public async getAmmPoolGameUserRank<R>(
request: loopring_defs.GetAmmPoolGameUserRankRequest,
apiKey: string,
): Promise<{
raw_data: R
userRank: loopring_defs.GameRankInfo
}> {
const reqParams: loopring_defs.ReqParams = {
queryParams: request,
apiKey,
url: LOOPRING_URLs.GET_AMMPOOL_GAME_USER_RANK,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo && raw_data?.resultInfo.code) {
return {
...raw_data.resultInfo,
}
}
const userRank: loopring_defs.GameRankInfo = raw_data.data
return {
userRank,
raw_data: raw_data.data,
}
}
private getOrderList(lst: loopring_defs.AmmPoolActivityRule[], order: loopring_defs.SortOrder) {
return lst.sort(
(a: loopring_defs.AmmPoolActivityRule, b: loopring_defs.AmmPoolActivityRule) => {
if (order === loopring_defs.SortOrder.ASC) {
return a.rangeFrom < b.rangeFrom ? 1 : 0
}
return a.rangeFrom > b.rangeFrom ? 1 : 0
},
)
}
/*
*/
public async getAmmPoolActivityRules<R>(): Promise<{
raw_data: R
activityInProgressRules: loopring_defs.LoopringMap<loopring_defs.AmmPoolInProgressActivityRule>
activityDateMap: loopring_defs.LoopringMap<{
AMM_MINING?: loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule>
ORDERBOOK_MINING?: loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule>
SWAP_VOLUME_RANKING?: loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule>
}>
groupByRuleType: loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule[]>
groupByActivityStatus: loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule[]>
groupByRuleTypeAndStatus: loopring_defs.LoopringMap<
loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule[]>
>
}> {
const reqParams: loopring_defs.ReqParams = {
url: LOOPRING_URLs.GET_AMM_ACTIVITY_RULES,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo) {
return {
...raw_data?.resultInfo,
}
}
let activityInProgressRules: loopring_defs.LoopringMap<loopring_defs.AmmPoolInProgressActivityRule> =
{}
const activityDateMap: loopring_defs.LoopringMap<{
AMM_MINING?: loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule>
ORDERBOOK_MINING?: loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule>
SWAP_VOLUME_RANKING?: loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule>
}> = {}
//{AMM_MINING:{},ORDERBOOK_MINING:{},SWAP_VOLUME_RANKING:{}}
const groupByRuleType: loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule[]> = {}
let groupByRuleTypeAndStatus: loopring_defs.LoopringMap<
loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule[]>
> = {}
const groupByActivityStatus: loopring_defs.LoopringMap<loopring_defs.AmmPoolActivityRule[]> = {}
const currentTs = new Date().getTime()
if (raw_data instanceof Array) {
raw_data.forEach((item: loopring_defs.AmmPoolActivityRule) => {
const status =
currentTs < item.rangeFrom
? loopring_defs.AmmPoolActivityStatus.NotStarted
: currentTs >= item.rangeFrom && currentTs <= item.rangeTo
? loopring_defs.AmmPoolActivityStatus.InProgress
: loopring_defs.AmmPoolActivityStatus.EndOfGame
item.status = status
if (status === loopring_defs.AmmPoolActivityStatus.InProgress) {
const ruleType = activityInProgressRules[item.market]
? [...activityInProgressRules[item.market].ruleType, item.ruleType]
: [item.ruleType]
activityInProgressRules = {
...activityInProgressRules,
[item.market]: { ...item, ruleType },
}
}
groupByRuleType[item.ruleType] = [
...(groupByRuleType[item.ruleType] ? groupByRuleType[item.ruleType] : []),
item,
]
groupByActivityStatus[status] = [
...(groupByActivityStatus[status] ? groupByActivityStatus[status] : []),
item,
]
activityDateMap[item.rangeFrom] = {
...(activityDateMap[item.rangeFrom] ? activityDateMap[item.rangeFrom] : {}),
[item.ruleType]: {
...(activityDateMap[item.rangeFrom]
? activityDateMap[item.rangeFrom][item.ruleType]
? activityDateMap[item.rangeFrom][item.ruleType]
: {}
: {}),
[item.market]: item,
},
}
groupByRuleTypeAndStatus = {
...groupByRuleTypeAndStatus,
[item.ruleType]: {
...(groupByRuleTypeAndStatus[item.ruleType]
? groupByRuleTypeAndStatus[item.ruleType]
: {}),
[status]: [
...(groupByRuleTypeAndStatus[item.ruleType]
? groupByRuleTypeAndStatus[item.ruleType][status]
? groupByRuleTypeAndStatus[item.ruleType][status]
: []
: []),
item,
],
},
}
})
}
return {
activityInProgressRules,
activityDateMap,
groupByRuleType,
groupByActivityStatus,
groupByRuleTypeAndStatus,
raw_data,
}
}
/*
*/
public async getAmmAssetHistory<R>(request: loopring_defs.GetAmmAssetRequest): Promise<{
raw_data: R
poolAddress: string
market: string
dataSeries: any
}> {
const reqParams: loopring_defs.ReqParams = {
queryParams: request,
url: LOOPRING_URLs.GET_AMM_ASSET_HISTORY,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo) {
return {
...raw_data?.resultInfo,
}
}
const poolAddress = raw_data.poolAddress
const market = raw_data.market
const dataSeries = raw_data.data
return {
poolAddress,
market,
dataSeries,
raw_data,
}
}
/*
*/
public async getAmmPoolStats<R>(): Promise<{
raw_data: R
ammPoolStats: loopring_defs.LoopringMap<loopring_defs.AmmPoolStat>
}> {
const reqParams: loopring_defs.ReqParams = {
url: LOOPRING_URLs.GET_AMM_POOL_STATS,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo && raw_data?.resultInfo.code) {
return {
...raw_data.resultInfo,
}
}
const ammPoolStats: loopring_defs.LoopringMap<loopring_defs.AmmPoolStat> = {}
if (raw_data instanceof Array) {
raw_data.forEach((item: loopring_defs.AmmPoolStat) => {
ammPoolStats[item.market] = item
})
}
return {
ammPoolStats,
raw_data,
}
}
/*
*/
public async getAmmPoolSnapshot<R>(request: loopring_defs.GetAmmPoolSnapshotRequest): Promise<{
raw_data: R
ammPoolSnapshot: loopring_defs.AmmPoolSnapshot
}> {
const reqParams: loopring_defs.ReqParams = {
url: LOOPRING_URLs.GET_AMM_POOLS_SNAPSHOT,
queryParams: request,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo) {
return {
...raw_data?.resultInfo,
}
}
const ammPoolSnapshot: loopring_defs.AmmPoolSnapshot = raw_data
return {
ammPoolSnapshot,
raw_data,
}
}
/*
*/
public async getAmmPoolBalances<R>(): Promise<{
raw_data: R
ammpoolsbalances: loopring_defs.LoopringMap<loopring_defs.AmmPoolBalance>
}> {
const reqParams: loopring_defs.ReqParams = {
url: LOOPRING_URLs.GET_AMM_POOLS_BALANCES,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo) {
return {
...raw_data?.resultInfo,
}
}
const ammpoolsbalances: loopring_defs.LoopringMap<loopring_defs.AmmPoolBalance> = {}
if (raw_data instanceof Array) {
raw_data.forEach((item: any) => {
const tempPooled: any = {}
if (item?.pooled instanceof Array) {
item.pooled.forEach((item2: any) => {
tempPooled[item2.tokenId] = item2
})
}
item.pooledMap = tempPooled
let poolName = item.poolName
if (poolName.indexOf('LRCETH') >= 0) {
poolName = 'AMM-LRC-ETH'
}
ammpoolsbalances[poolName] = item
})
}
return {
ammpoolsbalances,
raw_data,
}
}
/*
*/
public async getLiquidityMining<R>(
request: loopring_defs.GetLiquidityMiningRequest,
apiKey: string,
): Promise<{
raw_data: R
rewards: loopring_defs.RewardItem[]
}> {
const reqParams: loopring_defs.ReqParams = {
queryParams: request,
apiKey,
url: LOOPRING_URLs.GET_LIQUIDITY_MINING,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo && raw_data?.resultInfo.code) {
return {
...raw_data?.resultInfo,
}
}
return {
rewards: raw_data?.data ? (raw_data.data as loopring_defs.RewardItem[]) : [],
raw_data,
}
}
/*
*/
public async getLiquidityMiningUserHistory<R>(
request: loopring_defs.GetLiquidityMiningUserHistoryRequest,
): Promise<{
raw_data: R
userMiningInfos: loopring_defs.UserMiningInfo[]
}> {
const reqParams: loopring_defs.ReqParams = {
queryParams: request,
url: LOOPRING_URLs.GET_LIQUIDITY_MINING_USER_HISTORY,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo && raw_data?.resultInfo.code) {
return {
...raw_data?.resultInfo,
}
}
return {
userMiningInfos: raw_data.data as loopring_defs.UserMiningInfo[],
raw_data,
}
}
/*
*/
public async getUserAmmPoolTxs<R>(
request: loopring_defs.GetUserAmmPoolTxsRequest,
apiKey: string,
): Promise<{
raw_data: R
totalNum: number
userAmmPoolTxs: loopring_defs.UserAmmPoolTx[]
}> {
const reqParams: loopring_defs.ReqParams = {
queryParams: request,
apiKey,
url: LOOPRING_URLs.GET_USER_AMM_POOL_TXS,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo) {
return {
...raw_data?.resultInfo,
}
}
return {
totalNum: raw_data.totalNum,
userAmmPoolTxs: raw_data.transactions as loopring_defs.UserAmmPoolTx[],
raw_data,
}
}
/*
*/
public async getAmmPoolTxs<R>(request: loopring_defs.GetAmmPoolTxsRequest): Promise<{
raw_data: R
totalNum: number
transactions: loopring_defs.AmmPoolTx[]
}> {
const reqParams: loopring_defs.ReqParams = {
queryParams: request,
url: LOOPRING_URLs.GET_AMM_POOL_TXS,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo && raw_data?.resultInfo.code) {
return {
...raw_data?.resultInfo,
}
}
let transactions = undefined
if (raw_data?.transactions) {
transactions = raw_data?.transactions
}
return {
totalNum: raw_data.totalNum,
transactions: transactions as loopring_defs.AmmPoolTx[],
raw_data,
}
}
/*
*/
public async getAmmPoolTrades<R>(request: loopring_defs.GetAmmPoolTradesRequest): Promise<{
raw_data: R
totalNum: number
ammPoolTrades: loopring_defs.AmmPoolTrade[]
}> {
const reqParams: loopring_defs.ReqParams = {
queryParams: request,
url: LOOPRING_URLs.GET_AMM_POOL_TRADE_TXS,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo) {
return {
...raw_data?.resultInfo,
}
}
return {
totalNum: raw_data.totalNum,
ammPoolTrades: raw_data.transactions as loopring_defs.AmmPoolTrade[],
raw_data,
}
}
/*
*/
public async joinAmmPool<R>(
request: loopring_defs.JoinAmmPoolRequest,
patch: loopring_defs.AmmPoolRequestPatch,
apiKey: string,
): Promise<{
raw_data: R
joinAmmPoolResult: loopring_defs.JoinAmmPoolResult
}> {
if (!request?.validUntil) request.validUntil = Date.now()
const reqParams: loopring_defs.ReqParams = {
bodyParams: request,
apiKey,
url: LOOPRING_URLs.POST_JOIN_AMM_POOL,
method: loopring_defs.ReqMethod.POST,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const { eddsaSig } = sign_tools.get_EddsaSig_JoinAmmPool(request, patch)
request.eddsaSignature = eddsaSig
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo) {
return {
...raw_data?.resultInfo,
}
}
return {
joinAmmPoolResult: raw_data as loopring_defs.JoinAmmPoolResult,
raw_data,
}
}
/*
*/
public async exitAmmPool<R>(
request: loopring_defs.ExitAmmPoolRequest,
patch: loopring_defs.AmmPoolRequestPatch,
apiKey: string,
): Promise<{
raw_data: R
exitAmmPoolResult: loopring_defs.ExitAmmPoolResult
}> {
if (!request?.validUntil) request.validUntil = Date.now()
const reqParams: loopring_defs.ReqParams = {
bodyParams: request,
apiKey,
url: LOOPRING_URLs.POST_EXIT_AMM_POOL,
method: loopring_defs.ReqMethod.POST,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const { eddsaSig } = sign_tools.get_EddsaSig_ExitAmmPool(request, patch)
request.eddsaSignature = eddsaSig
const raw_data = (await this.makeReq().request(reqParams)).data
if (raw_data?.resultInfo) {
return {
...raw_data?.resultInfo,
}
}
return {
exitAmmPoolResult: raw_data as loopring_defs.ExitAmmPoolResult,
raw_data,
}
}
}
================================================
FILE: src/api/base_api.ts
================================================
import * as loopring_defs from '../defs'
import { Request } from './request'
import { addHexPrefix, toBuffer, toHex } from '../utils'
import { myLog } from '../utils/log_tools'
import { contracts as abi } from './ethereum/contracts'
import { AxiosResponse } from 'axios'
import * as ethUtil from 'ethereumjs-util'
import { isContract } from './contract_api'
import { getWindowSafely } from 'utils/window_utils'
export const KEY_MESSAGE =
'Sign this message to access Loopring Exchange: ' +
'${exchangeAddress}' +
' with key nonce: ' +
'${nonce}'
export class BaseAPI {
static KEY_MESSAGE: string = KEY_MESSAGE
protected baseUrl = ''
protected chainId: loopring_defs.ChainId = loopring_defs.ChainId.MAINNET
public genErr(err: Error | (AxiosResponse & Error)): loopring_defs.RESULT_INFO {
if (err.hasOwnProperty('request')) {
// const axiosError = errorInfo as AxiosResponse;
return {
// @ts-ignore;
message: loopring_defs.ConnectorError.HTTP_ERROR,
...err,
msg: loopring_defs.ConnectorError.HTTP_ERROR,
code: loopring_defs.LoopringErrorCode.HTTP_ERROR,
} as loopring_defs.RESULT_INFO
err?.message
} else if (!err || !err?.message) {
return {
message: 'unKnown',
code: loopring_defs.LoopringErrorCode.SKD_UNKNOW,
}
} else {
const key = Reflect.ownKeys(loopring_defs.ConnectorError).find(
(key) =>
err?.message.search(
loopring_defs.ConnectorError[key as keyof typeof loopring_defs.ConnectorError],
) !== -1,
)
if (key) {
return {
...err,
message: key as keyof typeof loopring_defs.ConnectorError,
code: loopring_defs.LoopringErrorCode[key as keyof typeof loopring_defs.ConnectorError],
} as loopring_defs.RESULT_INFO
}
return {
...(err instanceof Error
? Reflect.ownKeys(err).reduce((prev, item) => {
// @ts-ignore
return { ...prev, [item]: err[item.toString()] }
}, {})
: err),
code: loopring_defs.LoopringErrorCode.SKD_UNKNOW,
}
}
}
protected returnTxHash<T extends loopring_defs.TX_HASH_API>(
raw_data: T,
): (Omit<T, 'resultInfo'> & { raw_data: Omit<T, 'resultInfo'> }) | loopring_defs.RESULT_INFO {
if (raw_data?.resultInfo) {
return {
...raw_data.resultInfo,
message: raw_data.resultInfo?.msg ? raw_data.resultInfo?.msg : raw_data?.resultInfo.message,
}
}
return {
...raw_data,
raw_data,
}
}
private timeout: number
private baseUrlMap: { [key: number]: string } | undefined
public constructor(
param: InitParam,
timeout: number = 6000,
baseUrlMap = {
[loopring_defs.ChainId.MAINNET]: 'https://api3.loopring.io',
[loopring_defs.ChainId.GOERLI]: 'https://uat2.loopring.io',
},
) {
if (param.baseUrl) {
this.baseUrl = param.baseUrl
} else if (param.chainId !== undefined) {
this.setChainId(param.chainId)
} else {
this.setChainId(loopring_defs.ChainId.GOERLI)
}
this.baseUrlMap = baseUrlMap
this.timeout = timeout
}
public async getAvailableBroker(
request: loopring_defs.GetAvailableBrokerRequest,
): Promise<{ broker: string }> {
const reqParams: loopring_defs.ReqParams = {
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
queryParams: request,
url: loopring_defs.LOOPRING_URLs.GET_AVAILABLE_BROKER,
method: loopring_defs.ReqMethod.GET,
}
const result = (await this.makeReq().request(reqParams)).data
return result
}
public async getCounterFactualInfo<T extends any>(
request: loopring_defs.GetCounterFactualInfoRequest,
): Promise<{
raw_data: T
counterFactualInfo: loopring_defs.CounterFactualInfo | undefined
error?: loopring_defs.RESULT_INFO
}> {
const reqParams: loopring_defs.ReqParams = {
url: loopring_defs.LOOPRING_URLs.COUNTER_FACTUAL_INFO,
queryParams: request,
method: loopring_defs.ReqMethod.GET,
sigFlag: loopring_defs.SIG_FLAG.NO_SIG,
}
const raw_data = (await this.makeReq().request(reqParams)).data
let counterFactualInfo: loopring_defs.CounterFactualInfo | undefined
let error: loopring_defs.RESULT_INFO | undefined = undefined
if (raw_data && raw_data?.resultInfo) {
error = raw_data?.resultInfo
} else {
counterFactualInfo = {
...raw_data,
} as loopring_defs.CounterFactualInfo
}
return {
counterFactualInfo,
error,
raw_data,
}
}
public setChainId(chainId: loopring_defs.ChainId) {
this.baseUrl =
this.baseUrlMap && this.baseUrlMap[0]
? getBaseUrlByChainId(chainId, this.baseUrlMap as any)
: getBaseUrlByChainId(chainId)
this.chainId = chainId
}
public setBaseUrl(baseUrl: string) {
this.baseUrl = baseUrl
}
protected makeReq(): Request {
return new Request(this.baseUrl, this.timeout)
}
}
export function ecRecover(
account: string,
msg: string,
sig: any,
// time = 3000
) {
try {
// let timer;
const hash = ethUtil.hashPersonalMessage(toBuffer(msg))
const signature = ethUtil.fromRpcSig(sig)
const result = ethUtil.ecrecover(hash, signature.v, signature.r, signature.s)
const result2 = ethUtil.pubToAddress(result)
const recAddress = toHex(result2)
myLog('ecRecover recAddress', result, result2, recAddress)
return {
result: recAddress.toLowerCase() === account.toLowerCase(),
}
} catch (error) {
return { error }
}
}
export async function contractWalletValidate32(web3: any, account: string, msg: string, sig: any) {
return new Promise((resolve) => {
const hash = ethUtil.hashPersonalMessage(toBuffer(msg))
const data = abi.Contracts.ContractWallet.encodeInputs('isValidSignature(bytes32,bytes)', {
_data: hash,
_signature: toBuffer(sig),
})
web3.eth.call(
{
to: account, // contract addr
data: data,
},
function (err: any, result: any) {
if (!err) {
const valid = abi.Contracts.ContractWallet.decodeOutputs(
'isValidSignature(bytes32,bytes)',
result,
)
resolve({
result: toHex(toBuffer(valid[0])) === data.slice(0, 10),
})
} else resolve({ error: err })
},
)
})
}
export async function mykeyWalletValid(web3: any, account: string, msg: string, sig: any) {
const myKeyContract = '0xADc92d1fD878580579716d944eF3460E241604b7'
return new Promise((resolve) => {
web3.eth.call(
{
to: myKeyContract,
data: abi.Contracts.ContractWallet.encodeInputs('getKeyData', {
_account: account,
_index: 3,
}),
},
function (err: any, res: any) {
if (!err) {
const signature = ethUtil.fromRpcSig(sig)
const hash = ethUtil.hashPersonalMessage(ethUtil.keccak256(toBuffer(msg)))
const address = addHexPrefix(
abi.Contracts.ContractWallet.decodeOutputs('getKeyData', res)[0],
)
const recAddress = toHex(
ethUtil.pubToAddress(ethUtil.ecrecover(hash, signature.v, signature.r, signature.s)),
)
resolve({
result: recAddress.toLowerCase() === address.toLowerCase(),
})
} else {
resolve({ error: err })
}
},
)
})
}
export async function ecRecover2(account: string, message: string, signature: any) {
const messageBuffer = Buffer.from(message, 'utf8')
signature = signature.split('x')[1]
const parts = [
Buffer.from(`\x19Ethereum Signed Message:\n${messageBuffer.length}`, 'utf8'),
messageBuffer,
]
const totalHash = ethUtil.keccak(Buffer.concat(parts))
const r = Buffer.from(signature.substring(0, 64), 'hex')
const s = Buffer.from(signature.substring(64, 128), 'hex')
const old_v = Number(addHexPrefix(signature.substring(128, 130)))
let v = old_v
if (v <= 1) v += 27
const pub = ethUtil.ecrecover(totalHash, v, r, s)
const recoveredAddress = '0x' + ethUtil.pubToAddress(pub).toString('hex')
// if (account.toLowerCase() !== recoveredAddress.toLowerCase()) {
// myLog('v:', v, 'old_v:', old_v, ' recoveredAddress:', recoveredAddress)
// }
return new Promise((resolve) =>
resolve({
result: account.toLowerCase() === recoveredAddress.toLowerCase(),
}),
)
}
const getBaseUrlByChainId = (
id: loopring_defs.ChainId,
baseUrlMap = {
[loopring_defs.ChainId.MAINNET]: 'https://api3.loopring.io',
[loopring_defs.ChainId.GOERLI]: 'https://uat2.loopring.io',
},
) => {
let baseUrl = ''
switch (id) {
case loopring_defs.ChainId.MAINNET:
baseUrl = baseUrlMap[loopring_defs.ChainId.MAINNET]
gitextract_m37m1v1z/ ├── .babelrc ├── .eslintignore ├── .eslintrc ├── .gitignore ├── .gitpod.yml ├── .prettierignore ├── .prettierrc.json ├── Changelog.md ├── LICENSE ├── README.md ├── book.json ├── docs/ │ ├── .bookignore │ ├── Changelog.md │ ├── README.md │ ├── SUMMARY.md │ ├── about_us.md │ └── js_sdk/ │ ├── Deposit.md │ ├── NFTAction/ │ │ ├── collectionNFT.md │ │ ├── deployNFT.md │ │ ├── metaNFT.md │ │ ├── mintNFT.md │ │ ├── tradeNFT.md │ │ └── validateNFTOrder.md │ ├── README.md │ ├── account/ │ │ ├── activeAccount.md │ │ ├── fee.md │ │ ├── historyRecord.md │ │ ├── signature.md │ │ ├── wallet_api.md │ │ └── whitelisted_user_api.md │ ├── deposit/ │ │ ├── depositERC20.md │ │ └── depositNFT.md │ ├── erc20Trade/ │ │ └── orderERC20.md │ ├── exchange/ │ │ ├── ammpool_api.md │ │ ├── exchange.md │ │ └── webSocket.md │ ├── transfer/ │ │ ├── transferERC20.md │ │ └── transferNFT.md │ └── withdraw/ │ ├── withdrawERC20.md │ └── withdrawNFT.md ├── jest.config.cjs ├── package.json ├── rollup.config.mjs ├── src/ │ ├── api/ │ │ ├── ammpool_api.ts │ │ ├── base_api.ts │ │ ├── config/ │ │ │ ├── abis/ │ │ │ │ ├── contractWallet.ts │ │ │ │ ├── erc1155.ts │ │ │ │ ├── erc20.ts │ │ │ │ ├── erc721.ts │ │ │ │ ├── exchange_3_6.ts │ │ │ │ ├── hebao.ts │ │ │ │ ├── index.ts │ │ │ │ └── smartWallet.ts │ │ │ ├── guardianTypeData.ts │ │ │ └── index.ts │ │ ├── contacts_api.ts │ │ ├── contract_api.ts │ │ ├── defi_api.ts │ │ ├── delegate_api.ts │ │ ├── ethereum/ │ │ │ └── contracts/ │ │ │ ├── AbiFunction.ts │ │ │ ├── Contract.ts │ │ │ ├── Contracts.ts │ │ │ └── index.ts │ │ ├── exchange_api.ts │ │ ├── global_api.ts │ │ ├── index.ts │ │ ├── luckToken_api.ts │ │ ├── nft_api.ts │ │ ├── rabbitWithdraw_api.ts │ │ ├── request.ts │ │ ├── sign/ │ │ │ ├── poseidon/ │ │ │ │ ├── EDDSAUtil.ts │ │ │ │ ├── TestsEDDSAUtil_test.ts │ │ │ │ ├── babyJub.ts │ │ │ │ ├── eddsa.ts │ │ │ │ ├── eddsa_test.ts │ │ │ │ ├── field.ts │ │ │ │ ├── field_test.ts │ │ │ │ ├── jubjub.ts │ │ │ │ ├── jubjub_test.ts │ │ │ │ ├── permutation.ts │ │ │ │ └── permutation_test.ts │ │ │ └── sign_tools.ts │ │ ├── user_api.ts │ │ ├── vault_api.ts │ │ ├── wallet_api.ts │ │ ├── whitelisted_user_api.ts │ │ └── ws_api.ts │ ├── defs/ │ │ ├── account_defs.ts │ │ ├── error_codes.ts │ │ ├── index.ts │ │ ├── loopring_constants.ts │ │ ├── loopring_defs.ts │ │ ├── loopring_enums.ts │ │ ├── nft_defs.ts │ │ ├── url_defs.ts │ │ ├── web3_defs.ts │ │ └── ws_defs.ts │ ├── index.ts │ ├── tests/ │ │ ├── .eslintrc │ │ ├── .gitignore │ │ ├── MockData.ts │ │ ├── MockSwapData.ts │ │ ├── README.md │ │ ├── UTC--2021-02-04T02-55-36.490219109Z--ef439044717c3af35f4f46e52aa99280217a7114 │ │ ├── demo/ │ │ │ ├── NFTAction/ │ │ │ │ ├── collectionNFT.md │ │ │ │ ├── collectionNFT.test.ts │ │ │ │ ├── deployNFT.md │ │ │ │ ├── deployNFT.test.ts │ │ │ │ ├── metaNFT.md │ │ │ │ ├── metaNFT.test.ts │ │ │ │ ├── mintNFT.md │ │ │ │ ├── mintNFT.test.ts │ │ │ │ ├── tradeNFT.md │ │ │ │ ├── tradeNFT.test.ts │ │ │ │ ├── validateNFTOrder.md │ │ │ │ └── validateNFTOrder.test.ts │ │ │ ├── account/ │ │ │ │ ├── account.test.ts │ │ │ │ ├── activeAccount.md │ │ │ │ ├── activeAccount.test.ts │ │ │ │ ├── fee.md │ │ │ │ ├── fee.test.ts │ │ │ │ ├── historyRecord.md │ │ │ │ ├── historyRecord.test.ts │ │ │ │ ├── signature.md │ │ │ │ └── signature.test.ts │ │ │ ├── deposit/ │ │ │ │ ├── deposit.md │ │ │ │ ├── deposit.test.ts │ │ │ │ ├── depositNFT.md │ │ │ │ └── depositNFT.test.ts │ │ │ ├── erc20Trade/ │ │ │ │ ├── orderERC20.md │ │ │ │ └── orderERC20.test.ts │ │ │ ├── exchange/ │ │ │ │ ├── exchange.md │ │ │ │ ├── exchange.test.ts │ │ │ │ ├── webSocket.md │ │ │ │ └── webSocket.test.ts │ │ │ ├── transfer/ │ │ │ │ ├── transferERC20.md │ │ │ │ ├── transferERC20.test.ts │ │ │ │ ├── transferNFT.md │ │ │ │ └── transferNFT.test.ts │ │ │ └── withdraw/ │ │ │ ├── withdrawERC20.md │ │ │ ├── withdrawERC20.test.ts │ │ │ ├── withdrawNFT.md │ │ │ └── withdrawNFT.test.ts │ │ ├── formatter.test.ts │ │ └── unitTest/ │ │ ├── account/ │ │ │ ├── account.test.ts │ │ │ └── sign_tools.test.ts │ │ ├── appWallet/ │ │ │ └── wallet.test.ts │ │ ├── erc20Trade/ │ │ │ ├── amm.test.ts │ │ │ ├── amm_calc.test.ts │ │ │ └── defi.test.ts │ │ ├── exchange/ │ │ │ └── exchange.test.ts │ │ ├── transfer/ │ │ │ └── transferUT.test.ts │ │ └── withdraw/ │ │ ├── forceWithdrawls.test.ts │ │ └── withdrawUT.test.ts │ ├── types/ │ │ └── eddsa.d.ts │ ├── types.d.ts │ └── utils/ │ ├── formatter.ts │ ├── index.ts │ ├── log_tools.ts │ ├── network_tools.ts │ ├── obj_tools.ts │ ├── swap_calc_utils.ts │ ├── symbol_tools.ts │ └── window_utils.ts └── tsconfig.json
SYMBOL INDEX (964 symbols across 53 files)
FILE: src/api/ammpool_api.ts
class AmmpoolAPI (line 10) | class AmmpoolAPI extends BaseAPI {
method getAmmPoolConf (line 14) | public async getAmmPoolConf<R>(): Promise<{
method getAmmPoolUserRewards (line 48) | public async getAmmPoolUserRewards<R>(request: loopring_defs.GetAmmUse...
method getAmmPoolGameRank (line 94) | public async getAmmPoolGameRank<R>(request: loopring_defs.GetAmmPoolGa...
method getAmmPoolGameUserRank (line 129) | public async getAmmPoolGameUserRank<R>(
method getOrderList (line 158) | private getOrderList(lst: loopring_defs.AmmPoolActivityRule[], order: ...
method getAmmPoolActivityRules (line 172) | public async getAmmPoolActivityRules<R>(): Promise<{
method getAmmAssetHistory (line 288) | public async getAmmAssetHistory<R>(request: loopring_defs.GetAmmAssetR...
method getAmmPoolStats (line 321) | public async getAmmPoolStats<R>(): Promise<{
method getAmmPoolSnapshot (line 353) | public async getAmmPoolSnapshot<R>(request: loopring_defs.GetAmmPoolSn...
method getAmmPoolBalances (line 381) | public async getAmmPoolBalances<R>(): Promise<{
method getLiquidityMining (line 428) | public async getLiquidityMining<R>(
method getLiquidityMiningUserHistory (line 458) | public async getLiquidityMiningUserHistory<R>(
method getUserAmmPoolTxs (line 487) | public async getUserAmmPoolTxs<R>(
method getAmmPoolTxs (line 519) | public async getAmmPoolTxs<R>(request: loopring_defs.GetAmmPoolTxsRequ...
method getAmmPoolTrades (line 554) | public async getAmmPoolTrades<R>(request: loopring_defs.GetAmmPoolTrad...
method joinAmmPool (line 581) | public async joinAmmPool<R>(
method exitAmmPool (line 617) | public async exitAmmPool<R>(
FILE: src/api/base_api.ts
constant KEY_MESSAGE (line 11) | const KEY_MESSAGE =
class BaseAPI (line 16) | class BaseAPI {
method genErr (line 20) | public genErr(err: Error | (AxiosResponse & Error)): loopring_defs.RES...
method returnTxHash (line 61) | protected returnTxHash<T extends loopring_defs.TX_HASH_API>(
method constructor (line 79) | public constructor(
method getAvailableBroker (line 98) | public async getAvailableBroker(
method getCounterFactualInfo (line 111) | public async getCounterFactualInfo<T extends any>(
method setChainId (line 145) | public setChainId(chainId: loopring_defs.ChainId) {
method setBaseUrl (line 153) | public setBaseUrl(baseUrl: string) {
method makeReq (line 157) | protected makeReq(): Request {
function ecRecover (line 162) | function ecRecover(
function contractWalletValidate32 (line 184) | async function contractWalletValidate32(web3: any, account: string, msg:...
function mykeyWalletValid (line 212) | async function mykeyWalletValid(web3: any, account: string, msg: string,...
function ecRecover2 (line 244) | async function ecRecover2(account: string, message: string, signature: a...
type InitParam (line 301) | interface InitParam {
function formatSig (line 306) | function formatSig(rpcSig: string) {
function recoverSignType (line 310) | function recoverSignType(web3: any, account: string, msg: string, sig: s...
function personalSign (line 320) | async function personalSign(
function fcWalletValid (line 431) | async function fcWalletValid(
FILE: src/api/config/guardianTypeData.ts
function getApproveRecoverTypedData (line 23) | function getApproveRecoverTypedData({
function getApproveTransferTypedData (line 74) | function getApproveTransferTypedData({
function getRemoveGuardianTypedData (line 157) | function getRemoveGuardianTypedData({
function getUnlockWalletTypedData (line 201) | function getUnlockWalletTypedData({
function getApproveChangeMasterCopy (line 246) | function getApproveChangeMasterCopy({
function getDepositWalletTypedData (line 292) | function getDepositWalletTypedData({
function getApproveTokenCopy (line 341) | function getApproveTokenCopy({
function signHebaoApproveWrap (line 389) | async function signHebaoApproveWrap(
FILE: src/api/config/index.ts
function getTokenBySymbol (line 6) | function getTokenBySymbol(symbol, tokens) {
function fromWEI (line 13) | function fromWEI(symbol, valueInWEI, tokens, { precision, ceil }: any = ...
function toWEI (line 24) | function toWEI(symbol, value, tokens, rm = BigNumber.ROUND_FLOOR) {
FILE: src/api/contacts_api.ts
class ContactAPI (line 6) | class ContactAPI extends BaseAPI {
method getContacts (line 7) | public async getContacts<R = loopring_defs.GetContactsResponse>(
method createContact (line 34) | public async createContact(request: loopring_defs.CreateContactRequest...
method updateContact (line 55) | public async updateContact(request: loopring_defs.UpdateContactRequest...
method deleteContact (line 75) | public async deleteContact(
FILE: src/api/contract_api.ts
type ERC20Method (line 11) | enum ERC20Method {
function checkWeb3 (line 22) | function checkWeb3(web3: any) {
function sign (line 33) | async function sign(web3: any, account: string, pwd: string, hash: strin...
function signEthereumTx (line 58) | async function signEthereumTx(
function getNonce (line 86) | async function getNonce(web3: Web3, addr: string) {
function sendRawTx (line 91) | async function sendRawTx(
function _genContractData (line 131) | function _genContractData(Contract: any, method: string, data: any) {
function genERC20Data (line 135) | function genERC20Data(method: string, data: any) {
function genExchangeData (line 139) | function genExchangeData(method: string, data: any) {
function approve (line 143) | async function approve(
function approveZero (line 182) | async function approveZero(
function approveMax (line 215) | async function approveMax(
function deposit (line 244) | async function deposit(
function forceWithdrawal (line 293) | async function forceWithdrawal(
function sendTransaction (line 332) | async function sendTransaction(web3: any, tx: any) {
function isContract (line 352) | async function isContract(web3: any, address: string) {
FILE: src/api/defi_api.ts
class DefiAPI (line 11) | class DefiAPI extends BaseAPI {
method getDefiToken (line 15) | public async getDefiToken<R>(): Promise<{
method getDefiMarkets (line 67) | public async getDefiMarkets<R>(
method orderDefi (line 100) | public async orderDefi<R>(
method getDefiReward (line 138) | public async getDefiReward<R>(
method getDefiTransaction (line 173) | public async getDefiTransaction<R>(
method getDualInfos (line 207) | public async getDualInfos<R>(request: loopring_defs.GetDualInfosReques...
method getDualBalance (line 244) | public async getDualBalance<R>(request = undefined) {
method getDualPrices (line 266) | public async getDualPrices(request: loopring_defs.GetDualPricesRequest) {
method getDualIndex (line 288) | public async getDualIndex(request: { baseSymbol: string; quoteSymbol: ...
method getDualTransactions (line 308) | public async getDualTransactions(request: loopring_defs.GetUserDualTxR...
method orderDual (line 335) | public async orderDual(
method editDual (line 370) | public async editDual(
method getDualUserLocked (line 411) | public async getDualUserLocked(
method sendStakeClaim (line 439) | public async sendStakeClaim(
method sendStakeRedeem (line 503) | public async sendStakeRedeem(
method sendStake (line 534) | public async sendStake(
method getStakeProducts (line 565) | public async getStakeProducts<R>(): Promise<{
method getStakeSummary (line 584) | public async getStakeSummary<R>(
method getStakeTransactions (line 624) | public async getStakeTransactions<R>(
method getBtradeMarkets (line 661) | public async getBtradeMarkets<R>(): Promise<{
method getBtradeDepth (line 716) | public async getBtradeDepth<R>({
method getBtradeOrders (line 778) | public async getBtradeOrders<R>({
method sendBtradeOrder (line 806) | public async sendBtradeOrder({
method getDefiApys (line 851) | public async getDefiApys<
method getDefiDepositList (line 890) | public async getDefiDepositList<R = any>(
method getTaikoFarmingPositionInfo (line 930) | public async getTaikoFarmingPositionInfo<R = any>({
method getTaikoFarmingTransactions (line 970) | public async getTaikoFarmingTransactions(
method getTaikoFarmingUserSummary (line 1005) | public async getTaikoFarmingUserSummary(queryParams: {
method getTaikoFarmingAvailableNft (line 1046) | public async getTaikoFarmingAvailableNft(
method getTaikoFarmingTransactionByHash (line 1062) | public async getTaikoFarmingTransactionByHash(
method getTaikoFarmingDepositDurationList (line 1091) | public async getTaikoFarmingDepositDurationList(queryParams: {
method getTaikoFarmingGetRedeem (line 1124) | public async getTaikoFarmingGetRedeem(
method submitTaikoFarmingClaim (line 1146) | public async submitTaikoFarmingClaim({
FILE: src/api/delegate_api.ts
class DelegateAPI (line 5) | class DelegateAPI extends BaseAPI {
method getCode (line 6) | public async getCode(address: string): Promise<string> {
method getIPFS (line 23) | public async getIPFS(path: string): Promise<string> {
method getCollectionDomain (line 40) | public getCollectionDomain() {
FILE: src/api/ethereum/contracts/AbiFunction.ts
class AbiFunction (line 7) | class AbiFunction {
method constructor (line 15) | constructor({ inputs, name, outputs, constant }: any) {
method encodeInputs (line 30) | encodeInputs(inputs) {
method decodeOutputs (line 40) | decodeOutputs(outputs) {
method decodeEncodedInputs (line 49) | decodeEncodedInputs(encoded) {
method parseInputs (line 53) | parseInputs(inputs = {}) {
method parseOutputs (line 62) | parseOutputs(outputs) {
FILE: src/api/ethereum/contracts/Contract.ts
class Contract (line 7) | class Contract {
method constructor (line 9) | constructor(abi) {
method encodeInputs (line 31) | encodeInputs(method, inputs) {
method decodeOutputs (line 46) | decodeOutputs(method, outputs) {
method decodeEncodeInputs (line 60) | decodeEncodeInputs(encode) {
FILE: src/api/ethereum/contracts/Contracts.ts
constant ERC1155 (line 15) | const ERC1155 = new Contract(erc1155Abi.erc1155)
constant ERC721 (line 16) | const ERC721 = new Contract(erc721Abi.erc721)
FILE: src/api/exchange_api.ts
function getFeeMap (line 60) | function getFeeMap(feeArr: any[], type = 0) {
function genAB (line 81) | function genAB(data: any[], isReverse = false) {
function getMidPrice (line 130) | function getMidPrice({
function getBtradeMidPrice (line 160) | function getBtradeMidPrice({ _asks, _bids }: { _asks: any[]; _bids: any[...
class ExchangeAPI (line 173) | class ExchangeAPI extends BaseAPI {
method getRelayerCurrentTime (line 177) | public async getRelayerCurrentTime<R>(): Promise<
method getProtocolPortrait (line 203) | public async getProtocolPortrait<R>(): Promise<
method getExchangeFeeInfo (line 229) | public async getExchangeFeeInfo<R>(): Promise<{
method getWithdrawalAgents (line 259) | public async getWithdrawalAgents<R>(request: GetWithdrawalAgentsReques...
method getRecommendedMarkets (line 292) | public async getRecommendedMarkets<R>(): Promise<{
method getMarkets (line 327) | public async getMarkets<R>(url: string = LOOPRING_URLs.GET_MARKETS): P...
method getMixMarkets (line 369) | public async getMixMarkets<R>(): Promise<{
method getTokens (line 384) | public async getTokens<R>(): Promise<
method getEthBalances (line 488) | public async getEthBalances<R>(request: GetEthBalancesRequest): Promise<{
method getTokenBalances (line 516) | public async getTokenBalances<R, T = TokenAddress>(
method getAllTokenBalances (line 549) | public async getAllTokenBalances<R, T = TokenAddress>(
method getAllowances (line 577) | public async getAllowances<R, T = TokenAddress>(
method getExchangeInfo (line 617) | public async getExchangeInfo<R>(): Promise<{
method getMixDepth (line 652) | public async getMixDepth<R>(request: GetDepthRequest) {
method getDepth (line 659) | public async getDepth<R>(
method getMixTicker (line 719) | public async getMixTicker<R>(request: GetTickerRequest): Promise<{
method getTicker (line 731) | public async getTicker<R>(
method getAllMixTickers (line 803) | public async getAllMixTickers(markets: string | undefined = undefined) {
method getAllTickers (line 823) | public async getAllTickers(markets: string | undefined = undefined) {
method getMixCandlestick (line 843) | public async getMixCandlestick<R>(request: GetCandlestickRequest) {
method getCandlestick (line 850) | public async getCandlestick<R>(
method getFiatPrice (line 986) | public async getFiatPrice<R>(request: GetFiatPriceRequest) {
method disableWithdrawTokenList (line 1017) | public async disableWithdrawTokenList<R>(): Promise<{
method getMarketTrades (line 1043) | public async getMarketTrades<R>(request: GetMarketTradesRequest): Prom...
method getAccount (line 1092) | public async getAccount<R>(request: GetAccountRequest): Promise<{
method getEthNonce (line 1118) | public async getEthNonce<R>(
method getGasPrice (line 1142) | public async getGasPrice<R>(): Promise<{
method getGasPriceRange (line 1169) | public async getGasPriceRange<R>(): Promise<{
method getAccountServices (line 1193) | public async getAccountServices<R>(request: GetAccountServicesRequest)...
method getTokenInfo (line 1224) | public async getTokenInfo<R = DatacenterTokenInfo>(
method getSupportTokens (line 1247) | public async getSupportTokens<R = DatacenterTokenInfoSimple[]>(
method getQuoteTokenInfo (line 1275) | public async getQuoteTokenInfo<R = [][], _X = GetDatacenterTokenQuoteT...
method getQuoteTokenOhlcv (line 1299) | public async getQuoteTokenOhlcv<R = [][], _X = GetDatacenterTokenOhlcv...
method getCmcTokenRelations (line 1323) | public async getCmcTokenRelations<
method getLatestTokenPrices (line 1362) | public async getLatestTokenPrices(request?: getLatestTokenPricesReques...
method getUserTradeAmount (line 1393) | public async getUserTradeAmount(request: GetUserTradeAmount) {
FILE: src/api/global_api.ts
constant GLOBAL_KEY (line 5) | const GLOBAL_KEY = {
class GlobalAPI (line 16) | class GlobalAPI extends BaseAPI {
method getActiveFeeInfo (line 17) | public async getActiveFeeInfo(request: { accountId?: number }) {
method getUserBalanceForFee (line 56) | public async getUserBalanceForFee(request: { accountId: number; tokens...
method getAmmPoolGameUserRank (line 87) | public async getAmmPoolGameUserRank<R>(
method getBanxaAPI (line 115) | public async getBanxaAPI<R>(
FILE: src/api/luckToken_api.ts
class LuckTokenAPI (line 17) | class LuckTokenAPI extends BaseAPI {
method getLuckTokenAgents (line 18) | public async getLuckTokenAgents<R>(): Promise<{
method getLuckTokenAuthorizedSigners (line 55) | public async getLuckTokenAuthorizedSigners<R>(): Promise<{
method getLuckTokenClaimHistory (line 92) | public async getLuckTokenClaimHistory<R>(
method getLuckTokenLuckyTokens (line 123) | public async getLuckTokenLuckyTokens<R>(
method getLuckTokenDetail (line 168) | public async getLuckTokenDetail<R>(
method getBlindBoxDetail (line 198) | public async getBlindBoxDetail<R>(
method getLuckTokenWithdrawals (line 229) | public async getLuckTokenWithdrawals<R>(
method getLuckTokenBalances (line 267) | public async getLuckTokenBalances<R>(
method getLuckTokenClaimedLuckyTokens (line 310) | public async getLuckTokenClaimedLuckyTokens<R>(
method getLuckTokenSummary (line 344) | public async getLuckTokenSummary<R>(apiKey: string): Promise<{
method getLuckTokenNFTBalances (line 374) | public async getLuckTokenNFTBalances<R>(
method sendLuckTokenClaimLuckyToken (line 405) | public async sendLuckTokenClaimLuckyToken<R>({
method sendLuckTokenClaimBlindBox (line 444) | public async sendLuckTokenClaimBlindBox<R>({
method sendLuckTokenWithdraws (line 483) | public async sendLuckTokenWithdraws<T>(
method sendLuckTokenSend (line 549) | public async sendLuckTokenSend<
method getLuckTokenClaimedBlindBox (line 679) | public async getLuckTokenClaimedBlindBox<R>(
method getLuckTokenUnclaimNFTBlindboxCnt (line 714) | public async getLuckTokenUnclaimNFTBlindboxCnt<R>(
method getLuckTokenUserLuckyTokenTargets (line 743) | public async getLuckTokenUserLuckyTokenTargets<R>(
method sendLuckTokenSubmitAddTarget (line 780) | public async sendLuckTokenSubmitAddTarget<R>(
FILE: src/api/nft_api.ts
constant CREATION_CODE (line 23) | const CREATION_CODE = {
type NFTType (line 46) | enum NFTType {
type NFT_TYPE_STRING (line 51) | enum NFT_TYPE_STRING {
type NFTMethod (line 56) | enum NFTMethod {
class NFTAPI (line 68) | class NFTAPI extends BaseAPI {
method callContractMethod (line 69) | private async callContractMethod(
method _genContractData (line 81) | private _genContractData(Contract: any, method: string, data: any) {
method _genERC1155Data (line 85) | private _genERC1155Data(method: string, data: any) {
method _genERC721Data (line 89) | private _genERC721Data(method: string, data: any) {
method _genContract (line 93) | private _genContract(web3: any, contractAddress: string, type: NFTType...
method getNFTBalance (line 105) | public async getNFTBalance({
method getInfoForNFTTokens (line 157) | public async getInfoForNFTTokens({
method callRefreshNFT (line 195) | public async callRefreshNFT(
method getContractNFTMeta (line 238) | public async getContractNFTMeta(
method approveNFT (line 277) | public async approveNFT({
method ipfsCid0ToNftID (line 325) | public ipfsCid0ToNftID(cidV0Str: string): string {
method ipfsNftIDToCid (line 337) | public ipfsNftIDToCid(nftId: string) {
method isApprovedForAll (line 352) | public async isApprovedForAll({
method depositNFT (line 393) | public async depositNFT({
method computeNFTAddress (line 440) | public computeNFTAddress({
method getPublicCollectionById (line 483) | public async getPublicCollectionById<R extends loopring_defs.Collectio...
method getCollectionWholeNFTs (line 512) | async getCollectionWholeNFTs<R>(request: loopring_defs.GetCollectionWh...
method getHadUnknownCollection (line 554) | async getHadUnknownCollection<R>(request: { accountId: number }): Prom...
method getUserNFTBurnAddress (line 569) | async getUserNFTBurnAddress<R>(request: {
FILE: src/api/rabbitWithdraw_api.ts
type CounterFactualInfo (line 10) | interface CounterFactualInfo {
class RabbitWithdrawAPI (line 16) | class RabbitWithdrawAPI extends BaseAPI {
method getConfig (line 17) | public async getConfig(): Promise<{ config: string }> {
method getNetworkWithdrawalAgents (line 28) | public async getNetworkWithdrawalAgents(req: {
method submitRabitWithdraw (line 53) | public async submitRabitWithdraw(
method getUserCrossChainFee (line 142) | public async getUserCrossChainFee<R>(
FILE: src/api/request.ts
class Request (line 47) | class Request {
method getIns (line 52) | public getIns() {
method constructor (line 56) | constructor(baseUrl: string, timeout: number) {
method request (line 83) | public async request(params: ReqParams, options: any = {}) {
method updateOpt (line 177) | public updateOpt(reqOpt: ReqOptions) {
method addApiKey (line 198) | public addApiKey(apiKey: string) {
method addSig (line 202) | public addSig(signature: string) {
method updateBaseUrl (line 206) | public updateBaseUrl(baseUrl: string) {
method handle400 (line 210) | public handle400(callback: any = undefined) {
FILE: src/api/sign/poseidon/EDDSAUtil.ts
class EDDSAUtil (line 7) | class EDDSAUtil {
method sign (line 9) | static sign(PrivateKey: string | undefined, hash: any) {
method formatted (line 31) | static formatted(hexString: string) {
method generateKeyPair (line 44) | static generateKeyPair(seed: any) {
method pack (line 74) | static pack(publicKeyX: string, publicKeyY: string) {
FILE: src/api/sign/poseidon/TestsEDDSAUtil_test.ts
function testEddsaPack_1 (line 6) | function testEddsaPack_1() {
function testEddsaPack_2 (line 21) | function testEddsaPack_2() {
function testEddsaPack_3 (line 36) | function testEddsaPack_3() {
function testEddsaSign (line 51) | function testEddsaSign() {
function test_generateKeyPair (line 68) | function test_generateKeyPair() {
function main (line 84) | function main() {
FILE: src/api/sign/poseidon/babyJub.ts
class babyJub (line 6) | class babyJub {
method packPoint (line 8) | static packPoint(P0: BigNumber, P1: BigNumber) {
method lt (line 20) | static lt(a: BigNumber, b: BigNumber) {
method gt (line 39) | static gt(a: BigNumber, b: BigNumber) {
FILE: src/api/sign/poseidon/eddsa.ts
class Signature (line 36) | class Signature {
method constructor (line 40) | constructor(R: Point, s: FQ) {
method toStr (line 45) | toStr() {
class SignedMessage (line 50) | class SignedMessage {
method constructor (line 55) | constructor(A: Point, sig: Signature, msg: BigNumber) {
method toStr (line 61) | toStr() {
class SignatureScheme (line 68) | class SignatureScheme {
method to_bytes (line 69) | static to_bytes(arg: BigNumber) {
method prehash_message (line 98) | static prehash_message(M: BigNumber) {
method hash_secret_python (line 114) | static hash_secret_python(k: FQ, arg: BigNumber) {
method B (line 148) | static B() {
method sign (line 152) | static sign(msg: BigNumber, key: FQ, B: Point) {
method as_scalar (line 194) | static as_scalar(point: Point) {
method hash_public (line 199) | static hash_public(R: Point, A: Point, M: BigNumber) {
function bnToBuf (line 219) | function bnToBuf(bn: string) {
function bnToBufWithFixedLength (line 238) | function bnToBufWithFixedLength(bn: string, outputLength: number) {
function bufToBn (line 271) | function bufToBn(buf: any) {
function bytesToHexString (line 287) | function bytesToHexString(bytes: any) {
FILE: src/api/sign/poseidon/eddsa_test.ts
function test_sign_1 (line 7) | function test_sign_1() {
function test_prehash_message_1 (line 21) | function test_prehash_message_1() {
function test_to_bytes_1 (line 29) | function test_to_bytes_1() {
function test_hash_secret_1 (line 37) | function test_hash_secret_1() {
function test_hash_public_1 (line 51) | function test_hash_public_1() {
function main (line 61) | function main() {
FILE: src/api/sign/poseidon/field.ts
class field (line 4) | class field {
class FQ (line 14) | class FQ {
method constructor (line 18) | constructor(n: BigNumber, field_modulus = field.SNARK_SCALAR_FIELD) {
method add (line 27) | add(other: BigNumber) {
method mul (line 33) | mul(other: BigNumber) {
method sub (line 39) | sub(other: BigNumber) {
method div (line 50) | div(other: BigNumber) {
method one (line 60) | static one(modulus: BigNumber = field.SNARK_SCALAR_FIELD) {
method zero (line 64) | static zero(modulus: BigNumber = field.SNARK_SCALAR_FIELD) {
function modulo (line 70) | function modulo(n: BigNumber, p: BigNumber, m: BigNumber) {
FILE: src/api/sign/poseidon/field_test.ts
function test_constants (line 6) | function test_constants() {
function test_half (line 13) | function test_half() {
function test_p (line 20) | function test_p() {
function test_FQ_1 (line 27) | function test_FQ_1() {
function test_FQ_add_1 (line 36) | function test_FQ_add_1() {
function test_FQ_mul_1 (line 48) | function test_FQ_mul_1() {
function test_FQ_mul_2 (line 59) | function test_FQ_mul_2() {
function test_FQ_mul_3 (line 70) | function test_FQ_mul_3() {
function test_FQ_mul_4 (line 82) | function test_FQ_mul_4() {
function test_FQ_module (line 103) | function test_FQ_module() {
function test_FQ_sub (line 112) | function test_FQ_sub() {
function test_modulo (line 119) | function test_modulo() {
function main (line 129) | function main() {
FILE: src/api/sign/poseidon/jubjub.ts
class jubjub (line 22) | class jubjub {
class Point (line 32) | class Point {
method constructor (line 36) | constructor(x: FQ, y: FQ) {
method generate (line 41) | static generate() {
method mul (line 48) | mul(scaler: BigNumber) {
method add (line 68) | add(other: Point) {
method infinity (line 93) | static infinity() {
FILE: src/api/sign/poseidon/jubjub_test.ts
function test_constants (line 7) | function test_constants() {
function test_add_1 (line 18) | function test_add_1() {
function test_add_2 (line 30) | function test_add_2() {
function test_divide_1 (line 42) | function test_divide_1() {
function test_divide_2 (line 50) | function test_divide_2() {
function test_bitwiseand_1 (line 58) | function test_bitwiseand_1() {
function test_bitwiseand_2 (line 66) | function test_bitwiseand_2() {
function test_mul_1 (line 74) | function test_mul_1() {
function test_mul_2 (line 86) | function test_mul_2() {
function test_mul_3 (line 98) | function test_mul_3() {
function main (line 112) | function main() {
FILE: src/api/sign/poseidon/permutation.ts
class PoseidonParams (line 23) | class PoseidonParams {
method constructor (line 34) | constructor(
class permunation (line 68) | class permunation {
method H (line 69) | static H(arg: string) {
method H_Bigint (line 95) | static H_Bigint(arg: BigNumber) {
method poseidon_constants (line 119) | static poseidon_constants(p: BigNumber, seed: string, n: number) {
method poseidon_matrix (line 133) | static poseidon_matrix(p: BigNumber, seed: string, t: number) {
method poseidon_sbox (line 155) | static poseidon_sbox(state: [BigNumber], i: number, params: PoseidonPa...
method poseidon_mix (line 184) | static poseidon_mix(state: [BigNumber], M: [[BigNumber]], p: BigNumber) {
method poseidon (line 229) | static poseidon(inputs: [BigNumber], params: PoseidonParams) {
FILE: src/api/sign/poseidon/permutation_test.ts
function test_PoseidonParams (line 6) | function test_PoseidonParams() {
function test_H_1 (line 44) | function test_H_1() {
function test_H_2 (line 52) | function test_H_2() {
function test_H_3 (line 60) | function test_H_3() {
function test_poseidon_constants (line 68) | function test_poseidon_constants() {
function test_poseidon_matrix (line 82) | function test_poseidon_matrix() {
function test_poseidon_1 (line 96) | function test_poseidon_1() {
function test_poseidon_2 (line 109) | function test_poseidon_2() {
function test_poseidon_3 (line 123) | function test_poseidon_3() {
function main (line 143) | function main() {
FILE: src/api/sign/sign_tools.ts
type GetEcDSASigType (line 65) | enum GetEcDSASigType {
constant MIN_NFT_TOKENID (line 71) | const MIN_NFT_TOKENID = 32768
constant SNARK_SCALAR_FIELD (line 73) | const SNARK_SCALAR_FIELD = new BigInteger(
type KeyPairParams (line 78) | interface KeyPairParams {
function generatePrivateKey (line 89) | function generatePrivateKey(result: { sig: string; counterFactualInfo: a...
function generateKeyPair (line 118) | async function generateKeyPair(
function getEdDSASig (line 269) | function getEdDSASig(
function creatEdDSASigHasH (line 304) | function creatEdDSASigHasH({
function verifyEdDSASig (line 341) | function verifyEdDSASig(
function signEip712 (line 382) | async function signEip712(web3: any, account: string, method: string, pa...
function signEip712WalletConnect (line 398) | async function signEip712WalletConnect(web3: any, account: string, typed...
function getEcDSASig (line 442) | async function getEcDSASig(
function convertPublicKey2 (line 525) | function convertPublicKey2(pk: PublicKey) {
function convertPublicKey (line 530) | function convertPublicKey(pk: PublicKey) {
function getUpdateAccountEcdsaTypedData (line 538) | function getUpdateAccountEcdsaTypedData(data: UpdateAccountRequestV3, ch...
function get_EddsaSig_OffChainWithdraw (line 581) | function get_EddsaSig_OffChainWithdraw(
function getOrderHash (line 613) | function getOrderHash(request: SubmitOrderRequestV3) {
function getWithdrawTypedData (line 651) | function getWithdrawTypedData(
function offchainWithdrawWrap (line 703) | async function offchainWithdrawWrap({
function get_EddsaSig_NFT_Withdraw (line 739) | function get_EddsaSig_NFT_Withdraw(request: NFTWithdrawRequestV3, eddsaK...
function getNftData (line 768) | function getNftData(request: NFTMintRequestV3) {
function getNFTMintTypedData (line 811) | function getNFTMintTypedData(
function getNFTWithdrawTypedData (line 866) | function getNFTWithdrawTypedData(
function withdrawNFTWrap (line 918) | async function withdrawNFTWrap({
function get_EddsaSig_NFT_Mint (line 954) | function get_EddsaSig_NFT_Mint(request: NFTMintRequestV3, eddsaKey: stri...
function get_Is_Nft_Token (line 969) | function get_Is_Nft_Token(tokenId: number) {
function get_EddsaSig_NFT_Order (line 974) | function get_EddsaSig_NFT_Order(request: NFTOrderRequestV3, eddsaKey: st...
function get_EddsaSig_Dual_Order (line 997) | function get_EddsaSig_Dual_Order(request: DualOrderRequest, eddsaKey: st...
function mintNFTWrap (line 1015) | async function mintNFTWrap({
function get_EddsaSig_Transfer (line 1051) | function get_EddsaSig_Transfer(request: OriginTransferRequestV3, eddsaKe...
function getTransferOldTypedData (line 1069) | function getTransferOldTypedData(
function getTransferTypedData (line 1114) | function getTransferTypedData(
function transferWrap (line 1159) | async function transferWrap({
function transferNFTWrap (line 1194) | async function transferNFTWrap({
function get_EddsaSig_NFT_Transfer (line 1229) | function get_EddsaSig_NFT_Transfer(request: OriginNFTTransferRequestV3, ...
function getNftTradeHash (line 1247) | function getNftTradeHash(request: NFTTradeRequestV3) {
function getNFTTransferTypedData (line 1280) | function getNFTTransferTypedData(
function eddsaSign (line 1325) | function eddsaSign(typedData: any, eddsaKey: string) {
function eddsaSignWithDomain (line 1339) | function eddsaSignWithDomain(
function getAmmJoinEcdsaTypedData (line 1362) | function getAmmJoinEcdsaTypedData(data: JoinAmmPoolRequest, patch: AmmPo...
function get_EddsaSig_JoinAmmPool (line 1402) | function get_EddsaSig_JoinAmmPool(data: JoinAmmPoolRequest, patch: AmmPo...
function getAmmExitEcdsaTypedData (line 1418) | function getAmmExitEcdsaTypedData(data: ExitAmmPoolRequest, patch: AmmPo...
function get_EddsaSig_ExitAmmPool (line 1457) | function get_EddsaSig_ExitAmmPool(data: ExitAmmPoolRequest, patch: AmmPo...
FILE: src/api/user_api.ts
class UserAPI (line 18) | class UserAPI extends BaseAPI {
method updateUserApiKey (line 23) | public async updateUserApiKey<R>(
method getNextStorageId (line 61) | public async getNextStorageId<R>(
method getOrderDetails (line 90) | public async getOrderDetails<R>(
method getOrders (line 115) | public async getOrders<R>(
method submitOrder (line 153) | public async submitOrder(
method submitStopOrder (line 197) | public async submitStopOrder(
method cancelOrder (line 254) | public async cancelOrder<R>(
method cancelMultiOrdersByHash (line 291) | public async cancelMultiOrdersByHash<R>(
method cancelMultiOrdersByCreditOrderId (line 325) | public async cancelMultiOrdersByCreditOrderId<R>(
method getUserRegTxs (line 359) | public async getUserRegTxs<R>(
method getUserPwdResetTxs (line 392) | public async getUserPwdResetTxs<R>(
method getUserBalances (line 425) | public async getUserBalances<R>(
method getAssetLookRecords (line 460) | public async getAssetLookRecords<R>(
method getUserDepositHistory (line 498) | public async getUserDepositHistory<R>(
method getUserOnchainWithdrawalHistory (line 530) | public async getUserOnchainWithdrawalHistory<R>(
method getUserTransferList (line 563) | public async getUserTransferList<R>(
method getUserTxs (line 595) | public async getUserTxs<R>(
method getUserTrades (line 635) | public async getUserTrades<R>(
method getUserFeeRate (line 685) | public async getUserFeeRate<R>(
method getUserOrderFeeRate (line 724) | public async getUserOrderFeeRate<R>(
method getMinimumTokenAmt (line 758) | public async getMinimumTokenAmt<R>(
method getOffchainFeeAmt (line 806) | public async getOffchainFeeAmt<R>(
method getNFTOffchainFeeAmt (line 848) | public async getNFTOffchainFeeAmt<R>(
method submitNFTValidateOrder (line 886) | public async submitNFTValidateOrder<T extends loopring_defs.TX_HASH_API>(
method submitNFTTrade (line 911) | public async submitNFTTrade<T extends loopring_defs.TX_HASH_API>(
method getUserOwenCollection (line 945) | async getUserOwenCollection<R>(
method getUserLegacyCollection (line 978) | async getUserLegacyCollection<R>(
method getUserNFTCollection (line 1011) | async getUserNFTCollection(request: loopring_defs.GetUserNFTCollection...
method getUserNFTLegacyTokenAddress (line 1041) | async getUserNFTLegacyTokenAddress(request: { accountId: number }, api...
method getUserNFTDepositHistory (line 1066) | public async getUserNFTDepositHistory<R>(
method getUserNFTWithdrawalHistory (line 1098) | public async getUserNFTWithdrawalHistory<R>(
method getUserNFTTransferHistory (line 1130) | public async getUserNFTTransferHistory<R>(
method getUserNFTMintHistory (line 1164) | public async getUserNFTMintHistory<R>(
method getUserNFTTransactionHistory (line 1196) | public async getUserNFTTransactionHistory<R>(
method getUserNFTTradeHistory (line 1248) | public async getUserNFTTradeHistory<R>(
method SetReferrer (line 1282) | public async SetReferrer<R>(
method getUserNFTBalances (line 1319) | public async getUserNFTBalances<R>(
method getUserNFTBalancesByCollection (line 1375) | public async getUserNFTBalancesByCollection<R>(
method getUserNFTLegacyBalance (line 1431) | public async getUserNFTLegacyBalance<R>(
method getUserVIPAssets (line 1487) | public async getUserVIPAssets<R>(
method getUserVIPInfo (line 1509) | public async getUserVIPInfo<R>(
method unLockAccount (line 1548) | public async unLockAccount<R>(
method submitOffchainWithdraw (line 1619) | public async submitOffchainWithdraw<T extends loopring_defs.TX_HASH_API>(
method submitInternalTransfer (line 1669) | public async submitInternalTransfer<T extends loopring_defs.TX_HASH_API>(
method submitForceWithdrawals (line 1720) | public async submitForceWithdrawals<T extends loopring_defs.TX_HASH_API>(
method submitDeployNFT (line 1788) | public async submitDeployNFT<T extends loopring_defs.TX_HASH_API>(
method submitNFTInTransfer (line 1857) | public async submitNFTInTransfer<T extends loopring_defs.TX_HASH_API>(
method submitNFTWithdraw (line 1908) | public async submitNFTWithdraw<T extends loopring_defs.TX_HASH_API>(
method submitNFTMint (line 1959) | public async submitNFTMint<T extends loopring_defs.TX_HASH_API>(
method submitNFTCollection (line 2018) | async submitNFTCollection<R>(
method deleteNFTCollection (line 2054) | async deleteNFTCollection<R>(
method submitNFTLegacyCollection (line 2083) | async submitNFTLegacyCollection<R>(
method submitEditNFTCollection (line 2118) | async submitEditNFTCollection<R>(
method submitUpdateNFTLegacyCollection (line 2154) | async submitUpdateNFTLegacyCollection<R>(
method submitUpdateNFTGroup (line 2187) | async submitUpdateNFTGroup<R>(
method submitDeployCollection (line 2223) | public async submitDeployCollection<T extends loopring_defs.TX_HASH_API>(
method updateAccount (line 2288) | public async updateAccount<T extends loopring_defs.TX_HASH_API>(
method getUserApiKey (line 2356) | public async getUserApiKey<R>(
method getUserBills (line 2396) | public async getUserBills<R>(
method getReferDownsides (line 2433) | public async getReferDownsides<R>(
method getReferSelf (line 2462) | public async getReferSelf<R>(
method geReferStatistic (line 2491) | public async geReferStatistic<R = loopring_defs.ReferStatistic>(
method getUserRewards (line 2519) | public async getUserRewards<R>(
method getUserLockSummary (line 2554) | public async getUserLockSummary<R = loopring_defs.UserLockSummary>(
method sendTotalClaim (line 2588) | public async sendTotalClaim(
method getUserTotalClaim (line 2650) | public async getUserTotalClaim<R>(
method getNotificationAll (line 2684) | public async getNotificationAll<R = loopring_defs.UserNotification>(
method submitNotificationClear (line 2727) | public async submitNotificationClear<R>(
method submitNotificationReadAll (line 2768) | public async submitNotificationReadAll<R>(
method submitNotificationReadOne (line 2809) | public async submitNotificationReadOne<R>(
method checkUpdateAccount (line 2850) | public async checkUpdateAccount<T extends loopring_defs.TX_HASH_API>(
method submitEncryptedEcdsaKey (line 2879) | public async submitEncryptedEcdsaKey(
method getEncryptedEcdsaKey (line 2912) | public async getEncryptedEcdsaKey(
FILE: src/api/vault_api.ts
class VaultAPI (line 7) | class VaultAPI extends BaseAPI {
method getVaultTokens (line 8) | public async getVaultTokens<R = loopring_defs.VaultToken[]>(apiVersion...
method getVaultBalance (line 30) | public async getVaultBalance<R = loopring_defs.UserBalanceInfo>(
method getVaultMarkets (line 70) | public async getVaultMarkets<R = loopring_defs.VaultMarket[]>(apiVersi...
method getVaultGetAvailableNFT (line 92) | public async getVaultGetAvailableNFT<R = loopring_defs.VaultAvaiableNFT>(
method getVaultInfoAndBalance (line 119) | public async getVaultInfoAndBalance<R = loopring_defs.VaultAccountInfo>(
method getVaultGetOperationHistory (line 147) | public async getVaultGetOperationHistory<
method getVaultGetOperationByHash (line 190) | public async getVaultGetOperationByHash<
method getVaultDepth (line 224) | public async getVaultDepth<R>({
method submitVaultJoin (line 290) | public async submitVaultJoin<R = loopring_defs.VaultOrderResult>({
method submitVaultOrder (line 324) | public async submitVaultOrder<R>({
method submitVaultExit (line 372) | public async submitVaultExit<R>({
method submitVaultTransfer (line 406) | public async submitVaultTransfer<R>(apiVersion?: string) {
method submitVaultBorrow (line 425) | public async submitVaultBorrow<R>({
method submitVaultRepay (line 459) | public async submitVaultRepay<R>(
method getVaultConfig (line 496) | public async getVaultConfig(apiKey: string, apiVersion?: string): Prom...
method getVaultInfos (line 517) | public async getVaultInfos<R>(): Promise<{ raw_data: R }> {
method sendVaultResetToken (line 532) | public async sendVaultResetToken(
method getVaultPrice (line 574) | public async getVaultPrice(request: { tokenIds: string | number[] }, a...
method getCredit (line 604) | public async getCredit(request: { accountId: number }, apiKey: string,...
method getCollaterals (line 634) | public async getCollaterals(request: { accountId: number }, apiKey: st...
method submitLeverage (line 666) | public async submitLeverage<R>({
method submitDustCollector (line 696) | public async submitDustCollector(
method getMaxBorrowable (line 732) | public async getMaxBorrowable(request: { accountId: number, symbol: st...
method closeShort (line 760) | public async closeShort<R>(
FILE: src/api/wallet_api.ts
class WalletAPI (line 11) | class WalletAPI extends BaseAPI {
method getUserAssets (line 15) | public async getUserAssets(request: loopring_defs.GetUserAssetsRequest) {
method rejectHebao (line 55) | public async rejectHebao(req: loopring_defs.RejectHebaoRequestV3WithPa...
method submitApproveSignature (line 101) | public async submitApproveSignature<T extends loopring_defs.TX_HASH_API>(
method getAddressByENS (line 152) | public async getAddressByENS<R extends any, T extends string>(
method getWalletType (line 179) | public async getWalletType<T extends any>(
method getContractType (line 206) | public async getContractType<T = loopring_defs.ContractType>(
method getWalletModules (line 233) | public async getWalletModules<T = loopring_defs.ModuleType>(
method getEnsByAddress (line 260) | public async getEnsByAddress<R extends any, T extends string>(
method lockHebaoWallet (line 287) | public async lockHebaoWallet({
method getHebaoConfig (line 332) | public async getHebaoConfig(request: { network?: loopring_defs.Network...
method sendMetaTx (line 348) | public async sendMetaTx<R extends any, T extends any>(
method getGuardianApproveList (line 370) | public async getGuardianApproveList<R extends any, T extends loopring_...
method getProtectors (line 414) | public async getProtectors<R extends any, T extends loopring_defs.Prot...
method getHebaoOperationLogs (line 452) | public async getHebaoOperationLogs<R extends any, T extends loopring_d...
method getUserTradeAmount (line 479) | public async getUserTradeAmount(request: loopring_defs.GetUserTradeAmo...
method getTokenPrices (line 501) | public async getTokenPrices(request: loopring_defs.GetTokenPricesReque...
method getLatestTokenPrices (line 537) | public async getLatestTokenPrices(request?: loopring_defs.getLatestTok...
method getAccountServices (line 564) | public async getAccountServices<R>(request: loopring_defs.GetAccountSe...
FILE: src/api/whitelisted_user_api.ts
class WhitelistedUserAPI (line 7) | class WhitelistedUserAPI extends BaseAPI {
method submitOffchainWithdraw (line 12) | private async submitOffchainWithdraw(
method submitInternalTransfer (line 41) | public async submitInternalTransfer(
FILE: src/api/ws_api.ts
class WsAPI (line 5) | class WsAPI extends BaseAPI {
method getWsKey (line 9) | public async getWsKey() {
FILE: src/defs/account_defs.ts
type AccountInfo (line 14) | interface AccountInfo {
type CounterFactualInfo (line 28) | interface CounterFactualInfo {
type NFTCounterFactualInfo (line 36) | interface NFTCounterFactualInfo {
FILE: src/defs/error_codes.ts
type LoopringErrorCode (line 3) | enum LoopringErrorCode {
type ConnectorError (line 60) | enum ConnectorError {
type RESULT_INFO (line 74) | interface RESULT_INFO {
type ERROR_INFO (line 79) | type ERROR_INFO = {
FILE: src/defs/index.ts
type Ethereum (line 49) | type Ethereum = any
type Window (line 51) | interface Window {
type Global (line 57) | interface Global {
FILE: src/defs/loopring_constants.ts
type HEBAO_LOCK_STATUS (line 1) | enum HEBAO_LOCK_STATUS {
type HEBAO_META_TYPE (line 10) | enum HEBAO_META_TYPE {
FILE: src/defs/loopring_defs.ts
type Without (line 39) | type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never }
type XOR (line 40) | type XOR<T, U> = T | U extends { [key: string]: any }
type VipFeeRateInfo (line 44) | interface VipFeeRateInfo {
type VipFeeRateInfoMap (line 50) | type VipFeeRateInfoMap = { [key: string]: VipFeeRateInfo }
type TX_HASH_RESULT (line 52) | type TX_HASH_RESULT<T> = T & { raw_data: T }
type LoopringMap (line 54) | interface LoopringMap<T> {
type ExchangeInfo (line 58) | interface ExchangeInfo {
type TickerData (line 71) | interface TickerData {
type ABInfo (line 90) | interface ABInfo {
type DepthData (line 98) | interface DepthData {
type Candlestick (line 121) | interface Candlestick {
type TradesData (line 132) | interface TradesData {
type OrdersData (line 137) | interface OrdersData {
type QuotesData (line 142) | interface QuotesData {
type TokenInfo (line 146) | interface TokenInfo {
type AmmPoolStat (line 175) | interface AmmPoolStat {
type AmmPoolActivityRule (line 188) | interface AmmPoolActivityRule {
type AmmPoolInProgressActivityRule (line 200) | interface AmmPoolInProgressActivityRule {
type AmmTrade (line 212) | interface AmmTrade {
type AmmPoolInfoV3 (line 223) | interface AmmPoolInfoV3 {
type TokenRelatedInfo (line 242) | interface TokenRelatedInfo {
type AmmPoolConfResponse (line 247) | interface AmmPoolConfResponse {
type PooledMap (line 253) | interface PooledMap {
type AmmPoolBalance (line 257) | interface AmmPoolBalance {
type AmmPoolBalancesResponse (line 266) | interface AmmPoolBalancesResponse {
type TokensResponse (line 271) | interface TokensResponse {
type MarketInfo (line 289) | interface MarketInfo {
type DefiMarketStatus (line 301) | enum DefiMarketStatus {
type DefiMarketInfo (line 314) | interface DefiMarketInfo {
type MarketsResponse (line 347) | interface MarketsResponse {
type TokenVolumeV3 (line 359) | interface TokenVolumeV3 {
type TokenVolumeV5 (line 374) | interface TokenVolumeV5 {
type TokenVolumeNFT (line 389) | interface TokenVolumeNFT {
type AmmPoolJoinTokens (line 410) | interface AmmPoolJoinTokens {
type AmmPoolExitTokens (line 415) | interface AmmPoolExitTokens {
type GameRankInfo (line 420) | interface GameRankInfo {
type SetReferrerRequest (line 427) | interface SetReferrerRequest {
type GetAmmUserRewardsRequest (line 435) | interface GetAmmUserRewardsRequest {
type AmmUserReward (line 440) | interface AmmUserReward {
type AmmUserRewardMap (line 447) | interface AmmUserRewardMap {
type GetAmmPoolGameRankRequest (line 454) | interface GetAmmPoolGameRankRequest {
type GetAmmAssetRequest (line 458) | interface GetAmmAssetRequest {
type GetAmmPoolGameUserRankRequest (line 463) | interface GetAmmPoolGameUserRankRequest {
type GetAmmPoolSnapshotRequest (line 468) | interface GetAmmPoolSnapshotRequest {
type AmmPoolSnapshot (line 472) | interface AmmPoolSnapshot {
type AmmPoolRequestPatch (line 480) | interface AmmPoolRequestPatch {
type JoinAmmPoolRequest (line 487) | interface JoinAmmPoolRequest {
type JoinAmmPoolResult (line 499) | interface JoinAmmPoolResult {
type ExitAmmPoolRequest (line 505) | interface ExitAmmPoolRequest {
type ExitAmmPoolResult (line 517) | interface ExitAmmPoolResult {
type GetAmmPoolTradesRequest (line 523) | interface GetAmmPoolTradesRequest {
type AmmPoolTrade (line 529) | interface AmmPoolTrade {
type GetAmmPoolTxsRequest (line 540) | interface GetAmmPoolTxsRequest {
type AmmPoolTxOld (line 553) | interface AmmPoolTxOld {
type TokenVolumeV4 (line 572) | interface TokenVolumeV4 {
type AmmPoolTx (line 579) | interface AmmPoolTx {
type AMMtxTypes (line 591) | enum AMMtxTypes {
type GetUserAmmPoolTxsRequest (line 596) | interface GetUserAmmPoolTxsRequest {
type PooledToken (line 607) | interface PooledToken {
type UserAmmPoolTx (line 614) | interface UserAmmPoolTx {
type GetLiquidityMiningRequest (line 626) | interface GetLiquidityMiningRequest {
type RewardItem (line 632) | interface RewardItem {
type GetLiquidityMiningUserHistoryRequest (line 642) | interface GetLiquidityMiningUserHistoryRequest {
type UserMiningInfo (line 648) | interface UserMiningInfo {
type GetFiatPriceRequest (line 656) | interface GetFiatPriceRequest {
type FiatPriceInfo (line 660) | interface FiatPriceInfo {
type GetMarketTradesRequest (line 666) | interface GetMarketTradesRequest {
type OrderMakerType (line 671) | enum OrderMakerType {
type MarketTradeInfo (line 676) | interface MarketTradeInfo {
type GetWithdrawalAgentsRequest (line 687) | interface GetWithdrawalAgentsRequest {
type GetEthBalancesRequest (line 692) | interface GetEthBalancesRequest {
type TokenAddress (line 696) | type TokenAddress = string
type GetTokenBalancesRequest (line 698) | interface GetTokenBalancesRequest {
type GetALLTokenBalancesRequest (line 703) | interface GetALLTokenBalancesRequest {
type GetAllowancesRequest (line 707) | interface GetAllowancesRequest {
type GetDepthRequest (line 712) | interface GetDepthRequest {
type GetTickerRequest (line 718) | interface GetTickerRequest {
type GetCandlestickRequest (line 722) | interface GetCandlestickRequest {
type GetAccountRequest (line 730) | type GetAccountRequest =
type GetCounterFactualInfoRequest (line 738) | interface GetCounterFactualInfoRequest {
type GetAvailableBrokerRequest (line 742) | interface GetAvailableBrokerRequest {
type GetEthNonceRequest (line 746) | interface GetEthNonceRequest {
type GetUserApiKeyRequest (line 750) | interface GetUserApiKeyRequest {
type UpdateUserApiKeyRequest (line 754) | interface UpdateUserApiKeyRequest {
type GetOffchainFeeAmtRequest (line 758) | type GetOffchainFeeAmtRequest =
type GetNFTOffchainFeeAmtRequest (line 803) | type GetNFTOffchainFeeAmtRequest = {
type OrderInfo (line 827) | interface OrderInfo {
type TokenAmount (line 833) | interface TokenAmount {
type GetMinimumTokenAmtRequest (line 841) | interface GetMinimumTokenAmtRequest {
type OffchainFeeInfo (line 846) | interface OffchainFeeInfo {
type GetUserBalancesRequest (line 852) | interface GetUserBalancesRequest {
type UserBalanceInfo (line 871) | interface UserBalanceInfo {
type GetOrderDetailsRequest (line 881) | interface GetOrderDetailsRequest {
type OrderDetail (line 886) | interface OrderDetail {
type GetUserOrderFeeRateRequest (line 908) | interface GetUserOrderFeeRateRequest {
type FeeRateInfo (line 915) | interface FeeRateInfo {
type GetUserFeeRateRequest (line 921) | interface GetUserFeeRateRequest {
type UserFeeRateInfo (line 926) | interface UserFeeRateInfo {
type GetNextStorageIdRequest (line 932) | interface GetNextStorageIdRequest {
type OffChainWithdrawalRequestV3 (line 942) | interface OffChainWithdrawalRequestV3 {
type EXTRA_ORDER_TYPES (line 1034) | enum EXTRA_ORDER_TYPES {
type GetOrdersRequest (line 1041) | interface GetOrdersRequest {
type GetUserRegTxsRequest (line 1055) | interface GetUserRegTxsRequest {
type UserRegTx (line 1064) | interface UserRegTx {
type GetUserPwdResetTxsRequest (line 1078) | interface GetUserPwdResetTxsRequest {
type UserPwdResetTx (line 1087) | type UserPwdResetTx = UserRegTx
type GetUserDepositHistoryRequest (line 1089) | interface GetUserDepositHistoryRequest {
type UserDepositHistoryTx (line 1100) | interface UserDepositHistoryTx {
type UserOnchainWithdrawalHistoryTx (line 1113) | interface UserOnchainWithdrawalHistoryTx {
type GetUserOnchainWithdrawalHistoryRequest (line 1132) | interface GetUserOnchainWithdrawalHistoryRequest {
type GetUserTransferListRequest (line 1144) | interface GetUserTransferListRequest {
type UserTransferRecord (line 1156) | interface UserTransferRecord {
type UserAssetInfo (line 1174) | interface UserAssetInfo {
type GetUserAssetsRequest (line 1180) | interface GetUserAssetsRequest {
type GetUserTradeAmount (line 1189) | interface GetUserTradeAmount {
type TokenPriceInfo (line 1195) | interface TokenPriceInfo {
type GetTokenPricesRequest (line 1200) | interface GetTokenPricesRequest {
type getLatestTokenPricesRequest (line 1208) | interface getLatestTokenPricesRequest {
type GetUserTxsRequest (line 1213) | interface GetUserTxsRequest {
type GetUserBillsRequest (line 1223) | interface GetUserBillsRequest {
type GetReferSelf (line 1234) | interface GetReferSelf {
type ReferSelf (line 1242) | interface ReferSelf {
type GetReferStatisticReason (line 1249) | enum GetReferStatisticReason {
type GetReferStatistic (line 1254) | interface GetReferStatistic {
type ReferStatistic (line 1259) | interface ReferStatistic {
type GetReferDownsides (line 1270) | interface GetReferDownsides {
type ReferDownsides (line 1278) | interface ReferDownsides {
type REWARD_TYPE (line 1285) | enum REWARD_TYPE {
type GetUserRewardRequest (line 1291) | interface GetUserRewardRequest {
type GetUserNFTTxsRequest (line 1297) | interface GetUserNFTTxsRequest {
type NFT_TRADE (line 1308) | enum NFT_TRADE {
type GetUserNFTTradeRequest (line 1313) | interface GetUserNFTTradeRequest {
type UserTx (line 1326) | interface UserTx {
type SendMetaTxRequest (line 1353) | interface SendMetaTxRequest {
type GetGuardianApproveListRequest (line 1377) | interface GetGuardianApproveListRequest {
type GetEnsNameRequest (line 1385) | interface GetEnsNameRequest {
type GET_WALLET_TYPE (line 1390) | interface GET_WALLET_TYPE {
type GetEnsAddressRequest (line 1398) | interface GetEnsAddressRequest {
type SubmitApproveSignatureRequestWithPatch (line 1403) | interface SubmitApproveSignatureRequestWithPatch {
type ApproveSignatureRequest (line 1422) | interface ApproveSignatureRequest {
type GetProtectorRequest (line 1435) | interface GetProtectorRequest {
type TradesFillTypes (line 1441) | enum TradesFillTypes {
type GetUserTradesRequest (line 1446) | interface GetUserTradesRequest {
type UserTrade (line 1456) | type UserTrade = MarketTradeInfo
type UserTrades (line 1458) | interface UserTrades {
type CancelOrderRequest (line 1463) | interface CancelOrderRequest {
type CancelMultiOrdersByHashRequest (line 1469) | interface CancelMultiOrdersByHashRequest {
type CancelMultiOrdersByClientOrderIdRequest (line 1474) | interface CancelMultiOrdersByClientOrderIdRequest {
type EXTRAORDER_TYPE (line 1479) | enum EXTRAORDER_TYPE {
type STOP_SIDE (line 1484) | enum STOP_SIDE {
type SubmitOrderRequestV3 (line 1490) | interface SubmitOrderRequestV3 {
type OriginTransferRequestV3 (line 1594) | interface OriginTransferRequestV3 {
type OriginForcesWithdrawalsV3 (line 1700) | interface OriginForcesWithdrawalsV3 {
type OriginDeployNFTRequestV3 (line 1739) | interface OriginDeployNFTRequestV3 {
type OriginDeployCollectionRequestV3 (line 1768) | interface OriginDeployCollectionRequestV3 {
type OriginNFTTransferRequestV3 (line 1814) | interface OriginNFTTransferRequestV3 {
type NFTWithdrawRequestV3 (line 1920) | interface NFTWithdrawRequestV3 {
type NFTMintRequestV3 (line 2013) | interface NFTMintRequestV3 {
type NFTOrderRequestV3 (line 2239) | type NFTOrderRequestV3<R = 'Taker' | 'Maker'> = {
type NFTTradeRequestV3 (line 2358) | interface NFTTradeRequestV3 {
type OffChainWithdrawalRequestV3 (line 2390) | interface OffChainWithdrawalRequestV3 {
type UpdateAccountRequestV3 (line 2483) | interface UpdateAccountRequestV3 {
type OffChainWithdrawalRequestV3WithPatch (line 2550) | interface OffChainWithdrawalRequestV3WithPatch {
type OriginTransferRequestV3WithPatch (line 2560) | interface OriginTransferRequestV3WithPatch {
type OriginForcesWithdrawalsRequestV3WithPatch (line 2570) | interface OriginForcesWithdrawalsRequestV3WithPatch {
type OriginDeployNFTRequestV3WithPatch (line 2580) | interface OriginDeployNFTRequestV3WithPatch {
type OriginDeployCollectionRequestV3WithPatch (line 2590) | interface OriginDeployCollectionRequestV3WithPatch {
type OriginNFTTransferRequestV3WithPatch (line 2600) | interface OriginNFTTransferRequestV3WithPatch {
type OriginNFTWithdrawRequestV3WithPatch (line 2610) | interface OriginNFTWithdrawRequestV3WithPatch {
type OriginNFTMINTRequestV3WithPatch (line 2620) | interface OriginNFTMINTRequestV3WithPatch {
type OriginNFTCreateCollectionRequestV3WithPatch (line 2630) | interface OriginNFTCreateCollectionRequestV3WithPatch {
type OriginNFTValidateOrderRequestV3WithPatch (line 2640) | interface OriginNFTValidateOrderRequestV3WithPatch {
type OriginNFTTradeRequestV3WithPatch (line 2650) | interface OriginNFTTradeRequestV3WithPatch {
type UpdateAccountRequestV3WithPatch (line 2660) | interface UpdateAccountRequestV3WithPatch {
type GetAccountServicesRequest (line 2669) | interface GetAccountServicesRequest {
type GetUserNFTBalancesRequest (line 2677) | interface GetUserNFTBalancesRequest {
type GetUserNFTBalancesByCollectionRequest (line 2688) | interface GetUserNFTBalancesByCollectionRequest {
type LegacyNFT (line 2700) | enum LegacyNFT {
type GetUserNFTLegacyBalanceRequest (line 2706) | interface GetUserNFTLegacyBalanceRequest {
type DEPLOYMENT_STATUS (line 2716) | enum DEPLOYMENT_STATUS {
type NFT_IMAGE_SIZES (line 2723) | enum NFT_IMAGE_SIZES {
type IPFS_METADATA (line 2729) | type IPFS_METADATA = {
type UserNFTBalanceInfo (line 2757) | interface UserNFTBalanceInfo<I = NFT_IMAGE_SIZES> extends NFTTokenInfo {
type GetUserVIPInfoRequest (line 2776) | interface GetUserVIPInfoRequest {
type getUserVIPAssetsRequest (line 2780) | interface getUserVIPAssetsRequest {
type NftData (line 2788) | type NftData = string
type NFTTokenInfo (line 2790) | interface NFTTokenInfo {
type NFTTokenAmountInfo (line 2799) | interface NFTTokenAmountInfo {
type GetUserNFTTransferHistoryRequest (line 2805) | type GetUserNFTTransferHistoryRequest = {
type GetUserNFTMintHistoryRequest (line 2817) | type GetUserNFTMintHistoryRequest = {
type GetUserNFTDepositHistoryRequest (line 2830) | type GetUserNFTDepositHistoryRequest = {
type GetUserNFTWithdrawalHistoryRequest (line 2841) | type GetUserNFTWithdrawalHistoryRequest = {
type UserNFTDepositHistoryTx (line 2852) | interface UserNFTDepositHistoryTx {
type UserNFTWithdrawalHistoryTx (line 2875) | interface UserNFTWithdrawalHistoryTx {
type UserNFTTransferHistoryTx (line 2905) | interface UserNFTTransferHistoryTx {
type UserNFTMintHistoryTx (line 2933) | type UserNFTMintHistoryTx = {
type UserNFTTxsHistory (line 2961) | interface UserNFTTxsHistory {
type NFTOrderInfo (line 3004) | type NFTOrderInfo = {
type UserNFTTradeHistory (line 3012) | interface UserNFTTradeHistory {
type Protector (line 3032) | type Protector = {
type HebaoOperationLog (line 3037) | type HebaoOperationLog = {
type Guardian (line 3047) | type Guardian = {
type GuardiaContractAddress (line 3063) | type GuardiaContractAddress = string
type ApproveHebaoRequestV3WithPatch (line 3065) | interface ApproveHebaoRequestV3WithPatch {
type RejectHebaoRequestV3WithPatch (line 3074) | interface RejectHebaoRequestV3WithPatch {
type LockHebaoHebaoParam (line 3083) | interface LockHebaoHebaoParam {
type HebaoOperationLogs (line 3097) | interface HebaoOperationLogs {
type WalletType (line 3108) | interface WalletType {
type ContractType (line 3114) | interface ContractType {
type ModuleType (line 3126) | interface ModuleType {
type DefiOrderRequest (line 3134) | interface DefiOrderRequest {
type DefiResult (line 3215) | interface DefiResult {
constant SEP (line 3222) | const SEP = ','
type DefiAction (line 3224) | enum DefiAction {
type UserDefiTxsHistory (line 3229) | interface UserDefiTxsHistory {
type GetDefiMarketRequest (line 3247) | interface GetDefiMarketRequest {
type GetUserDefiRewardRequest (line 3251) | interface GetUserDefiRewardRequest {
type GetUserDefiTxRequest (line 3255) | interface GetUserDefiTxRequest {
type CollectionExtendsKey (line 3263) | type CollectionExtendsKey = {
type CollectionBasicMeta (line 3300) | type CollectionBasicMeta = {
type CollectionDelete (line 3309) | type CollectionDelete = {
type CollectionLegacyMeta (line 3314) | type CollectionLegacyMeta = Omit<CollectionBasicMeta, 'owner'> & {
type NFT_PREFERENCE_TYPE (line 3319) | enum NFT_PREFERENCE_TYPE {
type UpdateNFTLegacyCollectionRequest (line 3324) | type UpdateNFTLegacyCollectionRequest = {
type UpdateNFTGroupRequest (line 3330) | type UpdateNFTGroupRequest = {
type CollectionMeta (line 3353) | type CollectionMeta = CollectionExtendsKey & CollectionBasicMeta
type GetUserOwnerCollectionRequest (line 3355) | interface GetUserOwnerCollectionRequest {
type GetUserLegacyCollectionRequest (line 3363) | interface GetUserLegacyCollectionRequest {
type GetCollectionWholeNFTsRequest (line 3370) | interface GetCollectionWholeNFTsRequest {
type GetUserNFTCollectionRequest (line 3377) | interface GetUserNFTCollectionRequest {
type DUAL_TYPE (line 3385) | enum DUAL_TYPE {
type GetDualInfosRequest (line 3390) | type GetDualInfosRequest = {
type GetDualPricesRequest (line 3401) | type GetDualPricesRequest = {
type GetDualRuleRequest (line 3405) | type GetDualRuleRequest = { baseSymbol: string; currency?: string }
type DualBid (line 3407) | type DualBid = {
type DualPrice (line 3411) | type DualPrice = {
type DualIndex (line 3417) | type DualIndex = {
type DualProductAndPrice (line 3424) | type DualProductAndPrice = {
type DualRulesCoinsInfo (line 3439) | type DualRulesCoinsInfo = {
type DualBalance (line 3452) | type DualBalance = {
type LABEL_INVESTMENT_STATUS (line 3458) | enum LABEL_INVESTMENT_STATUS {
type SETTLEMENT_STATUS (line 3474) | enum SETTLEMENT_STATUS {
type DUAL_RETRY_STATUS (line 3480) | enum DUAL_RETRY_STATUS {
type GetUserDualTxRequest (line 3487) | interface GetUserDualTxRequest {
type DUAL_REINVEST_INFO (line 3500) | type DUAL_REINVEST_INFO = {
type UserDualTxsHistory (line 3507) | interface UserDualTxsHistory {
type DualOrderRequest (line 3544) | interface DualOrderRequest {
type DualEditRequest (line 3625) | type DualEditRequest = {
type CalDualResult (line 3634) | type CalDualResult = {
type DualUserLockedRequest (line 3649) | interface DualUserLockedRequest {
type LuckyTokenItemStatusIndex (line 3655) | enum LuckyTokenItemStatusIndex {
type LuckyTokenWithdrawStatus (line 3664) | enum LuckyTokenWithdrawStatus {
type LuckyTokenItemStatus (line 3672) | enum LuckyTokenItemStatus {
type LuckyTokenAmountType (line 3681) | enum LuckyTokenAmountType {
type LuckyTokenViewType (line 3686) | enum LuckyTokenViewType {
type LuckyTokenClaimType (line 3692) | enum LuckyTokenClaimType {
type ClaimRecordStatus (line 3698) | enum ClaimRecordStatus {
type BlindBoxStatus (line 3705) | enum BlindBoxStatus {
type LuckyTokenChampion (line 3711) | type LuckyTokenChampion = {
type LuckyTokenAmount (line 3717) | type LuckyTokenAmount = {
type LuckyTokenType (line 3725) | type LuckyTokenType = {
type LuckyTokenInfo (line 3730) | type LuckyTokenInfo = {
type LuckyTokenSender (line 3736) | type LuckyTokenSender = {
type LuckyTokenItemForReceive (line 3741) | type LuckyTokenItemForReceive = {
type BlindBoxClaimInfo (line 3761) | type BlindBoxClaimInfo = {
type LuckyTokenBlindBoxItemReceive (line 3779) | type LuckyTokenBlindBoxItemReceive = {
type LuckTokenClaim (line 3783) | type LuckTokenClaim = {
type LuckyTokenSignerFlag (line 3806) | type LuckyTokenSignerFlag = 0 | 1
type LuckTokenHistory (line 3807) | type LuckTokenHistory = {
type LuckTokenClaimDetail (line 3824) | type LuckTokenClaimDetail = {
type LuckTokenWithdraw (line 3846) | type LuckTokenWithdraw = {
type TOKENMAPLIST (line 3865) | type TOKENMAPLIST = {
type OriginLuckTokenWithdrawsRequestV3 (line 3885) | interface OriginLuckTokenWithdrawsRequestV3 {
type OriginLuckTokenWithdrawsRequestV3WithPatch (line 3903) | interface OriginLuckTokenWithdrawsRequestV3WithPatch {
type LuckyTokenItemForSendV3 (line 3917) | type LuckyTokenItemForSendV3 = {
type OriginLuckTokenSendRequestV3WithPatch (line 3946) | interface OriginLuckTokenSendRequestV3WithPatch {
type OriginTransfer3RequestV3 (line 3956) | interface OriginTransfer3RequestV3 {
type STACKING_PRODUCT (line 4033) | type STACKING_PRODUCT = {
type StakeStatus (line 4047) | enum StakeStatus {
type StakeInfoOrigin (line 4055) | type StakeInfoOrigin = {
type STACKING_SUMMARY (line 4071) | type STACKING_SUMMARY = {
type StakeTransactionType (line 4079) | enum StakeTransactionType {
type STACKING_TRANSACTIONS (line 4085) | type STACKING_TRANSACTIONS = {
type OriginClaimRequestV3 (line 4096) | interface OriginClaimRequestV3 {
type OriginStakeClaimRequestV3 (line 4105) | type OriginStakeClaimRequestV3 = OriginClaimRequestV3
type OriginClaimRequestV3WithPatch (line 4107) | interface OriginClaimRequestV3WithPatch {
type OriginStakeClaimRequestV3WithPatch (line 4117) | type OriginStakeClaimRequestV3WithPatch = Omit<OriginClaimRequestV3WithP...
type GetContactsRequest (line 4121) | interface GetContactsRequest {
type AddressTypeKeys (line 4154) | type AddressTypeKeys = keyof typeof AddressType
type GetContactsResponse (line 4156) | interface GetContactsResponse {
type CreateContactRequest (line 4169) | interface CreateContactRequest {
type UpdateContactRequest (line 4179) | interface UpdateContactRequest {
type DeleteContactRequest (line 4188) | interface DeleteContactRequest {
type BTRADE_MARKET (line 4196) | type BTRADE_MARKET = {
type OriginBTRADEV3OrderRequest (line 4221) | interface OriginBTRADEV3OrderRequest {
type BtradeResult (line 4288) | type BtradeResult<R> = {
constant BTRADENAME (line 4317) | const BTRADENAME = 'BTRADE-'
type LOCK_TYPE (line 4319) | enum LOCK_TYPE {
type getUserLockSummaryRequest (line 4329) | type getUserLockSummaryRequest = {
type UserLockSummary (line 4335) | type UserLockSummary = {
type GetTotalClaimRequest (line 4343) | interface GetTotalClaimRequest {
type GetUserCrossChainFeeRequest (line 4347) | interface GetUserCrossChainFeeRequest {
type CLAIM_TYPE (line 4356) | enum CLAIM_TYPE {
type ClaimItem (line 4364) | type ClaimItem = {
type VaultToken (line 4374) | type VaultToken = Omit<TokenInfo, 'type'> & {
type VaultMarket (line 4403) | type VaultMarket = {
type VaultAvaiableNFT (line 4447) | type VaultAvaiableNFT = {
type VaultBalance (line 4456) | type VaultBalance = {
type CollateralInfo (line 4466) | type CollateralInfo = {
type VaultAccountStatus (line 4475) | enum VaultAccountStatus {
type VaultAccountInfo (line 4481) | type VaultAccountInfo = {
type VaultOperationType (line 4497) | enum VaultOperationType {
type VaultOperationEnum (line 4508) | enum VaultOperationEnum {
type VaultOperationStatus (line 4516) | enum VaultOperationStatus {
type VaultOperation (line 4525) | type VaultOperation = {
type VaultOrder (line 4541) | type VaultOrder = {
type VaultJoinRequest (line 4558) | type VaultJoinRequest = NFTOrderRequestV3 & { joinHash: string }
type VaultExitRequest (line 4560) | type VaultExitRequest = {
type VaultOrderRequest (line 4566) | type VaultOrderRequest = OriginBTRADEV3OrderRequest
type VaultOrderResult (line 4568) | interface VaultOrderResult {
type VaultOrderNFTRequestV3WithPatch (line 4578) | interface VaultOrderNFTRequestV3WithPatch {
type VaultBorrowRequest (line 4588) | interface VaultBorrowRequest {
type VaultRepayRequestV3WithPatch (line 4597) | interface VaultRepayRequestV3WithPatch {
type VaultDustCollectorRequest (line 4607) | interface VaultDustCollectorRequest {
type DatacenterTokenQuote (line 4631) | interface DatacenterTokenQuote {
type GetDatacenterTokenInfoRequest (line 4643) | interface GetDatacenterTokenInfoRequest {
type DatacenterTokenInfoSimple (line 4647) | interface DatacenterTokenInfoSimple {
type DatacenterTokenInfo (line 4660) | interface DatacenterTokenInfo {
type DatacenterRange (line 4683) | enum DatacenterRange {
type OHLCVDatacenterRange (line 4689) | enum OHLCVDatacenterRange {
type GetDatacenterTokenQuoteTrendRequest (line 4697) | interface GetDatacenterTokenQuoteTrendRequest {
type GetCmcTokenRelationsRequest (line 4704) | interface GetCmcTokenRelationsRequest {
type GetDatacenterTokenOhlcvQuoteTrendRequest (line 4708) | interface GetDatacenterTokenOhlcvQuoteTrendRequest {
type GetDatacenterTokenQuoteTrend (line 4714) | enum GetDatacenterTokenQuoteTrend {
type NotificationMessageType (line 4725) | enum NotificationMessageType {
type UserNotification (line 4761) | type UserNotification = {
type TaikoFarmingAvaiableNFT (line 4771) | type TaikoFarmingAvaiableNFT = {
type RabbitWithdrawRequest (line 4780) | interface RabbitWithdrawRequest {
type TaikoFarmingSubmitRequest (line 4787) | type TaikoFarmingSubmitRequest = NFTOrderRequestV3 & { preOrderHash?: st...
type TaikoFarmingSubmitOrderNFTRequestV3WithPatch (line 4788) | interface TaikoFarmingSubmitOrderNFTRequestV3WithPatch {
FILE: src/defs/loopring_enums.ts
type ReqMethod (line 3) | enum ReqMethod {
type SigPatchField (line 9) | enum SigPatchField {
type MarketStatus (line 13) | enum MarketStatus {
type VipCatergory (line 19) | enum VipCatergory {
type TradeChannel (line 26) | enum TradeChannel {
type OrderType (line 33) | enum OrderType {
type OrderTypeResp (line 40) | enum OrderTypeResp {
type Currency (line 47) | enum Currency {
type OffchainFeeReqType (line 52) | enum OffchainFeeReqType {
type OffchainNFTFeeReqType (line 69) | enum OffchainNFTFeeReqType {
type TradingInterval (line 78) | enum TradingInterval {
type TxStatus (line 91) | enum TxStatus {
type OrderStatus (line 98) | enum OrderStatus {
type Side (line 107) | enum Side {
type WithdrawalTypes (line 112) | enum WithdrawalTypes {
type UserTxTypes (line 118) | enum UserTxTypes {
type UserBillTypes (line 134) | enum UserBillTypes {
type UserNFTTxTypes (line 140) | enum UserNFTTxTypes {
type TransferType (line 147) | enum TransferType {
type BillType (line 152) | enum BillType {
type FilledType (line 161) | enum FilledType {
type TxType (line 166) | enum TxType {
type TxNFTType (line 172) | enum TxNFTType {
type AmmTxType (line 183) | enum AmmTxType {
type SortOrder (line 188) | enum SortOrder {
type RuleType (line 193) | enum RuleType {
type AmmPoolActivityStatus (line 199) | enum AmmPoolActivityStatus {
type SIG_FLAG (line 205) | enum SIG_FLAG {
type AssetType (line 211) | enum AssetType {
type IntervalType (line 216) | enum IntervalType {
type ReqOptions (line 221) | interface ReqOptions {
type TX_HASH_API (line 228) | type TX_HASH_API = { hash?: string; resultInfo?: RESULT_INFO }
type ReqParams (line 229) | interface ReqParams {
type PublicKey (line 256) | interface PublicKey {
type NetworkWallet (line 270) | enum NetworkWallet {
FILE: src/defs/nft_defs.ts
type DepositNFTParam (line 23) | interface DepositNFTParam {
type IsApproveParam (line 47) | interface IsApproveParam {
type ApproveParam (line 69) | interface ApproveParam {
type ContractNFTParam (line 84) | type ContractNFTParam = {
type ContractNFTMetaParam (line 90) | type ContractNFTMetaParam = ContractNFTParam & { _id?: string };
type UserNFTBalanceParam (line 92) | type UserNFTBalanceParam = ContractNFTParam & { account: string };
type CallRefreshNFT (line 95) | type CallRefreshNFT = {
FILE: src/defs/url_defs.ts
type LOOPRING_URLs (line 1) | enum LOOPRING_URLs {
FILE: src/defs/web3_defs.ts
type ChainId (line 1) | enum ChainId {
type ConnectorNames (line 13) | enum ConnectorNames {
type SigSuffix (line 26) | enum SigSuffix {
FILE: src/defs/ws_defs.ts
type WsProps (line 3) | interface WsProps {
type WsOps (line 9) | enum WsOps {
type WsTopicType (line 14) | enum WsTopicType {
type WsAccount (line 46) | interface WsAccount {
type WsOrder (line 60) | interface WsOrder {
type OrderWsRequest (line 77) | type OrderWsRequest = {
type WS_ACTIONT_YPE (line 183) | enum WS_ACTIONT_YPE {
type WsL2Common (line 186) | interface WsL2Common {
FILE: src/tests/MockData.ts
constant DEFAULT_TIMEOUT (line 49) | const DEFAULT_TIMEOUT = 30000
constant LOOPRING_EXPORTED_ACCOUNT (line 68) | const LOOPRING_EXPORTED_ACCOUNT = {
constant CUSTOMER_KEY_SEED (line 120) | const CUSTOMER_KEY_SEED = 'XXXXXX' + ' with key nonce: ' + '${nonce}'
constant TOKEN_INFO (line 124) | let TOKEN_INFO = {
constant AMM_MAP (line 417) | let AMM_MAP = {
function signatureKeyPairMock (line 487) | async function signatureKeyPairMock(accInfo: sdk.AccountInfo, _web3: Web...
FILE: src/tests/MockSwapData.ts
constant MAPFEEBIPS (line 1171) | const MAPFEEBIPS = 63;
FILE: src/tests/formatter.test.ts
constant NUMBER (line 31) | const NUMBER = 40244024;
constant BUFFER (line 32) | const BUFFER = Buffer.from("40244024", "utf8");
constant BIG_NUMBER (line 33) | const BIG_NUMBER = new BigNumber(123.4567);
constant TIMEOUT (line 34) | const TIMEOUT = 30000;
FILE: src/types.d.ts
type Ethereum (line 2) | type Ethereum = any;
type Window (line 3) | interface Window {
FILE: src/utils/formatter.ts
function addHexPrefix (line 32) | function addHexPrefix(input: any) {
function toBuffer (line 44) | function toBuffer(mixed: any): Buffer {
function zeroPad (line 60) | function zeroPad(num: any, places: any) {
function toHex (line 69) | function toHex(mixed: number | BigNumber | BN | Buffer | string | Uint8A...
function toNumber (line 93) | function toNumber(mixed: number | BigNumber | BN | Buffer | string | Uin...
function toBig (line 118) | function toBig(mixed: number | BigNumber | BN | Buffer | string | Uint8A...
function toBN (line 142) | function toBN(mixed: any) {
function fromGWEI (line 151) | function fromGWEI(value: any) {
function toGWEI (line 160) | function toGWEI(value: any) {
function formatKey (line 169) | function formatKey(mixed: Buffer | string | Uint8Array) {
function formatAddress (line 185) | function formatAddress(mixed: Buffer | string | Uint8Array) {
function clearHexPrefix (line 201) | function clearHexPrefix(input: any) {
function padLeftEven (line 213) | function padLeftEven(hex: any) {
function getDisplaySymbol (line 222) | function getDisplaySymbol(settingsCurrency: any) {
function toFixed (line 240) | function toFixed(number: any, precision: any, ceil: any) {
function formatEddsaKey (line 258) | function formatEddsaKey(key: any) {
function numberWithCommas (line 268) | function numberWithCommas(number: any) {
function sortObjDictionary (line 286) | function sortObjDictionary(obj: { [key: string]: any }): Map<string, any> {
function makeMarket (line 297) | function makeMarket<R extends TokenInfo = TokenInfo>(raw_data: R[]): TOK...
function makeAmmPool (line 349) | function makeAmmPool<R>(raw_data: any): {
function makeMarkets (line 391) | function makeMarkets<R, C extends MarketInfo>(
function makeMarketsWithIdIndex (line 470) | function makeMarketsWithIdIndex<C extends MarketInfo>(
function makeInvestMarkets (line 551) | function makeInvestMarkets<C extends loopring_defs.DefiMarketInfo>(
FILE: src/utils/index.ts
type RequiredPart (line 5) | type RequiredPart<T, K> = Required<{ [K in keyof T]: Pick<T, K> }> & T;
FILE: src/utils/network_tools.ts
function sleep (line 13) | function sleep(milliseconds: number) {
FILE: src/utils/swap_calc_utils.ts
constant BIG0 (line 33) | const BIG0 = fm.toBig(0)
constant BIG1 (line 35) | const BIG1 = fm.toBig(1)
constant BIG10 (line 37) | const BIG10 = fm.toBig(10)
constant BIG10K (line 39) | const BIG10K = fm.toBig(10000)
function fromWEI (line 61) | function fromWEI(tokens: any, symbol: any, valueInWEI: any, precision?: ...
function toWEI (line 73) | function toWEI(tokens: any, symbol: any, value: any, rm: any = undefined) {
function isEmpty (line 84) | function isEmpty(input: any) {
function getAmountOutWithFeeBips (line 92) | function getAmountOutWithFeeBips(
function getAmountInWithFeeBips (line 115) | function getAmountInWithFeeBips(
function getOutputOrderbook (line 137) | function getOutputOrderbook(
function getReserveInfo (line 306) | function getReserveInfo(
function getPriceImpactStr (line 366) | function getPriceImpactStr(curPrice: string, toPrice: string) {
function getCurPrice (line 382) | function getCurPrice(reserveIn: string, reserveOut: string) {
function getToPrice (line 400) | function getToPrice(amountS: string, amountB: string) {
function getPriceImpact (line 418) | function getPriceImpact(
function updatePriceImpact_new (line 433) | function updatePriceImpact_new(
function getMinReceived (line 478) | function getMinReceived(amountBOut: string, minimumDecimal: number, slip...
function getOutputAmount (line 490) | function getOutputAmount({
function ammPoolCalc (line 714) | function ammPoolCalc(
function makeJoinAmmPoolRequest (line 759) | function makeJoinAmmPoolRequest(
function makeExitAmmPoolMini (line 823) | function makeExitAmmPoolMini(
function makeExitAmmCoverFeeLP (line 844) | function makeExitAmmCoverFeeLP(
function makeExitAmmPoolRequest2 (line 876) | function makeExitAmmPoolRequest2(
function calcDefi (line 971) | function calcDefi({
function calcDual (line 1062) | function calcDual({
function calcDex (line 1185) | function calcDex<R = BTRADE_MARKET | VaultMarket>({
FILE: src/utils/symbol_tools.ts
function getBaseQuote (line 5) | function getBaseQuote(symbol: string) {
Condensed preview — 165 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,210K chars).
[
{
"path": ".babelrc",
"chars": 660,
"preview": "{\n \"env\": {\n \"esmBundled\": {\n \"presets\": [\n [\"@babel/env\", {\n \"targets\": \"> 0.25%, not dead\"\n "
},
{
"path": ".eslintignore",
"chars": 63,
"preview": "# Ignore artifacts:\nbuild\ncoverage\n_book\ndist\nnode_modules\ndist"
},
{
"path": ".eslintrc",
"chars": 347,
"preview": "{\n \"root\": true,\n \"parser\": \"@typescript-eslint/parser\",\n \"plugins\": [\n \"@typescript-eslint\"\n ],\n \"extends\": [\n "
},
{
"path": ".gitignore",
"chars": 88,
"preview": "yarn-error.log\n*.tgz\n*testfile*\n.idea\n_book\ndist\nnode_modules\ncoverage\n./docs\n.DS_Store\n"
},
{
"path": ".gitpod.yml",
"chars": 314,
"preview": "# This configuration file was automatically generated by Gitpod.\n# Please adjust to your needs (see https://www.gitpod.i"
},
{
"path": ".prettierignore",
"chars": 58,
"preview": "# Ignore artifacts:\nbuild\ncoverage\n_book\ndist\nnode_modules"
},
{
"path": ".prettierrc.json",
"chars": 3,
"preview": "{}\n"
},
{
"path": "Changelog.md",
"chars": 3571,
"preview": "# CHANGELOG\n\n## JS SDK Version ChangeLog\n#### 3.6.14\n 1) Guardian approve\n#### v3.5.0\n 1)ecdsaSignature update to "
},
{
"path": "LICENSE",
"chars": 2020,
"preview": "Licensor: Loopring Technology Limited\n\nLicensed Work: Loopring-web/loopring-sdk\n "
},
{
"path": "README.md",
"chars": 1950,
"preview": "# Loopring SDK\n\n[](https://raw.githubusercontent.com/Loopr"
},
{
"path": "book.json",
"chars": 217,
"preview": "{\n \"root\": \"./docs\",\n \"description\": \"loopring sdk\",\n \"author\": \"Loopring Dev Team\",\n \"title\": \"Loopring SDK\",\n \"gi"
},
{
"path": "docs/.bookignore",
"chars": 46,
"preview": "docs/detail\ndocs/README.md\ndocs/Changelog.mdv\n"
},
{
"path": "docs/Changelog.md",
"chars": 3100,
"preview": "# CHANGELOG\n\n## JS SDK Version ChangeLog\n#### v3.6.0\n 1) dual Invest autoReinvest\n 2) guardina singature typeData\n"
},
{
"path": "docs/README.md",
"chars": 1925,
"preview": "# Loopring SDK\n\n[](https://raw.githubusercontent.com/Loopr"
},
{
"path": "docs/SUMMARY.md",
"chars": 1559,
"preview": "# Summary\n\n### Overview\n\n- [Introduction](README.md)\n- [Changelog](Changelog.md)\n- [GitHub](https://github.com/Loopring/"
},
{
"path": "docs/about_us.md",
"chars": 36,
"preview": "##### written by loopring dev team.\n"
},
{
"path": "docs/js_sdk/Deposit.md",
"chars": 10377,
"preview": "# Deposit from Ethereum L1 to Loopring, First Step for Start L2\n\n- [Step1: getUser Layer1 ETH balance](#step1️⃣-getuser-"
},
{
"path": "docs/js_sdk/NFTAction/collectionNFT.md",
"chars": 4691,
"preview": "# Collection NFT\n\nDefinition: allow user create a NFT Collection with different Contract(token) address.\n\n- allow user m"
},
{
"path": "docs/js_sdk/NFTAction/deployNFT.md",
"chars": 2048,
"preview": "# Deploy NFT\n\nDefinition: Only nft minter can deploy NFT\n\n***\n\n## Step 1. get Account\n\n```ts \nconst {accInfo} = await Lo"
},
{
"path": "docs/js_sdk/NFTAction/metaNFT.md",
"chars": 1401,
"preview": "# NFT META METHODS\n\n***\n\n## getContractNFTMeta\n\n```ts\nconst result = await LoopringAPI.nftAPI.getContractNFTMeta({\n web"
},
{
"path": "docs/js_sdk/NFTAction/mintNFT.md",
"chars": 5533,
"preview": "# Mint NFT\n\nDefinition: Mint Layer2 NFT, Loopring follow the ipfs NFT format, IPFS CID will convert to nftId, please vie"
},
{
"path": "docs/js_sdk/NFTAction/tradeNFT.md",
"chars": 3764,
"preview": "# Trade NFT\n\nDefinition: This method is help for understand how to match a maker with a taker order\n\n***\n\n## tradeNFT \n>"
},
{
"path": "docs/js_sdk/NFTAction/validateNFTOrder.md",
"chars": 3218,
"preview": "# Validate NFT Order\n\nDefinition: Loopring L2 support a method help for Validate NFT one side Order, validate NFT Order "
},
{
"path": "docs/js_sdk/README.md",
"chars": 13765,
"preview": "# Loopring SDK \nLoopring SDK Initialize and Mock Data structure\n\n***\n## SDK Initialize \n```ts\nimport * as sdk from \"../"
},
{
"path": "docs/js_sdk/account/activeAccount.md",
"chars": 2152,
"preview": "# Active Account\n\nDefinition: After user Deposit or (Third-Part Transfer), how to active Loopring L2 account.\n\n***\n\n## S"
},
{
"path": "docs/js_sdk/account/fee.md",
"chars": 9134,
"preview": "# Fee\n\nLoopring have 2 get Fee api:\n\n- getOffchainFeeAmt:\n - `ORDER`,\n - `FFCHAIN_WITHDRAWAL`,\n - `UPDATE_ACCOUNT`,\n "
},
{
"path": "docs/js_sdk/account/historyRecord.md",
"chars": 1500,
"preview": "# User Actions History\nFor check account Actions, more detail such as filters please read SDK interface or API .\n\n***\n\n#"
},
{
"path": "docs/js_sdk/account/signature.md",
"chars": 7391,
"preview": "# Signature\n\nLoopring SDK support EOA (EOA hardware wallet) & Loopring Smart wallet Signature\n\n- For Browser extension, "
},
{
"path": "docs/js_sdk/account/wallet_api.md",
"chars": 626,
"preview": "# Whitelisted User Part\n\n##### 1) getUserAssets\n\n```javascript\n// step 1. get account info\nconst request: GetUserAssetsR"
},
{
"path": "docs/js_sdk/account/whitelisted_user_api.md",
"chars": 1532,
"preview": "# Whitelisted User Part\n\n## submitInternalTransfer\n\n```javascript\n// step 1. get account info\n\nlet addressWhitlisted = \""
},
{
"path": "docs/js_sdk/deposit/depositERC20.md",
"chars": 2721,
"preview": "# Deposit ERC20\n\nDefinition: Move user L1 ERC20 assets to Loopring L2\n> **All Deposit Method, User should have enough `E"
},
{
"path": "docs/js_sdk/deposit/depositNFT.md",
"chars": 2596,
"preview": "# Deposit NFT\n\nDefinition: Move user L1 NFT assets to Loopring L2\n\n> **All Deposit Method, User should have enough `ETH`"
},
{
"path": "docs/js_sdk/erc20Trade/orderERC20.md",
"chars": 54717,
"preview": "# Order ERC20\n\n***\n> ### mini-order\nTo support small quantity trading, we introduce an additional concept \"tradeCost\", w"
},
{
"path": "docs/js_sdk/exchange/ammpool_api.md",
"chars": 2273,
"preview": "# AmmPool API\n\n## getAmmPoolConf\n\n```typescript\nconst { ammpools, pairs } = await api.getAmmPoolConf();\n```\n\n## getAmmPo"
},
{
"path": "docs/js_sdk/exchange/exchange.md",
"chars": 5076,
"preview": "# Loopring Exchange\n\nDefinition: Loopring Dex Main API for get Exchange Information, L2 Block, ERC20 Token Information, "
},
{
"path": "docs/js_sdk/exchange/webSocket.md",
"chars": 571,
"preview": "#WebSocket Command\nDefinition: Loopring L2 websocket\n\n### Loopring L2 websocket topic type:\nWsTopicType\n- `account`\n- `o"
},
{
"path": "docs/js_sdk/transfer/transferERC20.md",
"chars": 2322,
"preview": "# Transfer ERC20 \nDefinition: Send ERC20 tokens to other account on Loopring L2, \n> trade value should with decimals `sd"
},
{
"path": "docs/js_sdk/transfer/transferNFT.md",
"chars": 2189,
"preview": "# Transfer NFT\nDefinition: Send NFT to other account on Loopring L2\n\n***\n## Step 1. get account Info\n```ts\nconst { excha"
},
{
"path": "docs/js_sdk/withdraw/withdrawERC20.md",
"chars": 2072,
"preview": "# Withdraw ERC20\n\nDefinition: Loopring L2 withdraw ERC20 to Ethereum L1,\n> trade value should with decimals `sdk.toBig(v"
},
{
"path": "docs/js_sdk/withdraw/withdrawNFT.md",
"chars": 2545,
"preview": "# Withdraw NFT\n\nDefinition: Loopring L2 withdraw NFT to Ethereum L1\n\n***\n\n## Step 1. getAccount\n\n```ts\nconst {accInfo} "
},
{
"path": "jest.config.cjs",
"chars": 265,
"preview": "module.exports = {\n preset: 'ts-jest',\n verbose: true,\n transform: {\n '^.+\\\\.(js|jsx|ts|tsx)$': './node_modules/ba"
},
{
"path": "package.json",
"chars": 4621,
"preview": "{\n \"name\": \"@loopring-web/loopring-sdk\",\n \"version\": \"3.9.23\",\n \"author\": \"Loopring Dev Team\",\n \"description\": \"Loop"
},
{
"path": "rollup.config.mjs",
"chars": 2192,
"preview": "import commonjs from '@rollup/plugin-commonjs';\nimport babel from '@rollup/plugin-babel'\nimport terser from '@rollup/plu"
},
{
"path": "src/api/ammpool_api.ts",
"chars": 18006,
"preview": "/* eslint-disable camelcase */\nimport { BaseAPI } from './base_api'\nimport * as loopring_defs from '../defs'\n\nimport { "
},
{
"path": "src/api/base_api.ts",
"chars": 14375,
"preview": "import * as loopring_defs from '../defs'\nimport { Request } from './request'\nimport { addHexPrefix, toBuffer, toHex } fr"
},
{
"path": "src/api/config/abis/contractWallet.ts",
"chars": 1251,
"preview": "export const contractWallet = [\n {\n inputs: [\n {\n internalType: 'bytes',\n name: '_data',\n "
},
{
"path": "src/api/config/abis/erc1155.ts",
"chars": 5890,
"preview": "export const erc1155 = [\n {\n inputs: [\n {\n internalType: 'string',\n name: 'uri_',\n type: '"
},
{
"path": "src/api/config/abis/erc20.ts",
"chars": 3277,
"preview": "export const erc20 = [\n {\n constant: true,\n inputs: [],\n name: 'name',\n outputs: [\n {\n name: ''"
},
{
"path": "src/api/config/abis/erc721.ts",
"chars": 6136,
"preview": "export const erc721 = [\n {\n inputs: [\n {\n internalType: 'string',\n name: 'name_',\n type: '"
},
{
"path": "src/api/config/abis/exchange_3_6.ts",
"chars": 3363,
"preview": "export const exchange = [\n {\n inputs: [\n {\n internalType: \"address\",\n name: \"owner\",\n type"
},
{
"path": "src/api/config/abis/hebao.ts",
"chars": 570,
"preview": "export const hebao = [\n {\n inputs: [\n {\n internalType: 'address',\n name: 'wallet',\n type: "
},
{
"path": "src/api/config/abis/index.ts",
"chars": 294,
"preview": "export * as contractWalletAbi from './contractWallet'\nexport * as erc20Abi from './erc20'\nexport * as erc721Abi from './"
},
{
"path": "src/api/config/abis/smartWallet.ts",
"chars": 15404,
"preview": "export default [\n {\n inputs: [\n { internalType: 'contract PriceOracle', name: '_priceOracle', type: 'address' }"
},
{
"path": "src/api/config/guardianTypeData.ts",
"chars": 15421,
"preview": "import { ChainId, ConnectorNames, HEBAO_META_TYPE, SigSuffix } from '../../defs'\nimport { myLog } from '../../utils/log_"
},
{
"path": "src/api/config/index.ts",
"chars": 1001,
"preview": "/* tslint:disable */\n// @ts-nocheck\nimport { toBig, toFixed } from '../../utils/formatter'\nimport BigNumber from 'bignum"
},
{
"path": "src/api/contacts_api.ts",
"chars": 2763,
"preview": "/* eslint-disable camelcase */\nimport { BaseAPI } from './base_api'\n\nimport * as loopring_defs from '../defs'\n\nexport c"
},
{
"path": "src/api/contract_api.ts",
"chars": 7562,
"preview": "import Web3 from 'web3'\nimport { Transaction } from '@ethereumjs/tx'\n\nimport * as loopring_defs from '../defs'\n\nimport *"
},
{
"path": "src/api/defi_api.ts",
"chars": 32413,
"preview": "/* eslint-disable camelcase */\nimport { BaseAPI } from './base_api'\nimport * as loopring_defs from '../defs'\nimport { m"
},
{
"path": "src/api/delegate_api.ts",
"chars": 1293,
"preview": "import { BaseAPI } from './base_api'\n\nimport * as loopring_defs from '../defs'\n\nexport class DelegateAPI extends BaseAPI"
},
{
"path": "src/api/ethereum/contracts/AbiFunction.ts",
"chars": 1810,
"preview": "/* tslint:disable */\n// @ts-nocheck\nimport { addHexPrefix, clearHexPrefix, toBuffer, toHex } from '../../../utils/format"
},
{
"path": "src/api/ethereum/contracts/Contract.ts",
"chars": 2099,
"preview": "/* tslint:disable */\n// @ts-nocheck\nimport { methodID } from 'ethereumjs-abi'\nimport { toHex } from '../../../utils/form"
},
{
"path": "src/api/ethereum/contracts/Contracts.ts",
"chars": 634,
"preview": "/* eslint-disable */\nimport {\n contractWalletAbi,\n erc20Abi,\n erc721Abi,\n erc1155Abi,\n exchange36Abi,\n hebao,\n} fr"
},
{
"path": "src/api/ethereum/contracts/index.ts",
"chars": 210,
"preview": "import { AbiFunction } from './AbiFunction'\nimport { Contract } from './Contract'\nimport * as Contracts from './Contract"
},
{
"path": "src/api/exchange_api.ts",
"chars": 34150,
"preview": "/* eslint-disable camelcase */\nimport { BaseAPI } from './base_api'\nimport {\n LOOPRING_URLs,\n SIG_FLAG,\n ReqMethod,\n"
},
{
"path": "src/api/global_api.ts",
"chars": 4911,
"preview": "import { BaseAPI } from './base_api'\nimport * as loopring_defs from '../defs'\nimport { sortObjDictionary } from '../util"
},
{
"path": "src/api/index.ts",
"chars": 621,
"preview": "export * from './ws_api'\nexport * from './exchange_api'\nexport * from './ammpool_api'\nexport * from './user_api'\nexport "
},
{
"path": "src/api/luckToken_api.ts",
"chars": 20295,
"preview": "/* eslint-disable camelcase */\nimport { BaseAPI } from './base_api'\nimport {\n LOOPRING_URLs,\n NFTTokenInfo,\n ReqMeth"
},
{
"path": "src/api/nft_api.ts",
"chars": 16112,
"preview": "/* eslint-disable @typescript-eslint/no-var-requires */\nimport { BaseAPI } from './base_api'\nimport CID from 'cids'\nimpo"
},
{
"path": "src/api/rabbitWithdraw_api.ts",
"chars": 5473,
"preview": "import { BaseAPI } from './base_api'\nimport * as loopring_defs from '../defs'\nimport {RabbitWithdrawRequest} from '../de"
},
{
"path": "src/api/request.ts",
"chars": 5655,
"preview": "import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'\nimport { SIG_FLAG, ReqParams, ReqOptions"
},
{
"path": "src/api/sign/poseidon/EDDSAUtil.ts",
"chars": 2555,
"preview": "import { BigNumber } from \"ethers\";\nimport { SignatureScheme } from \"./eddsa\";\nimport { FQ } from \"./field\";\nimport { ju"
},
{
"path": "src/api/sign/poseidon/TestsEDDSAUtil_test.ts",
"chars": 3490,
"preview": "import { BigNumber } from \"ethers\";\nimport { EDDSAUtil } from \"./EDDSAUtil\";\nimport { bnToBuf, bnToBufWithFixedLength, S"
},
{
"path": "src/api/sign/poseidon/babyJub.ts",
"chars": 1438,
"preview": "import { BigNumber } from \"ethers\";\nimport { SignatureScheme, bytesToHexString } from \"./eddsa\";\nimport { field } from \""
},
{
"path": "src/api/sign/poseidon/eddsa.ts",
"chars": 7548,
"preview": "/*\nImplements Pure-EdDSA and Hash-EdDSA\n\nThe signer has two secret values:\n\n * k = Secret key\n * r = Per-(message,"
},
{
"path": "src/api/sign/poseidon/eddsa_test.ts",
"chars": 3737,
"preview": "import { assert } from \"console\"\nimport { BigNumber } from \"ethers\"\nimport { SignatureScheme } from \"./eddsa\"\nimport { F"
},
{
"path": "src/api/sign/poseidon/field.ts",
"chars": 2198,
"preview": "import { BigNumber } from \"ethers\";\nimport { BigInteger } from \"jsbn\";\n\nexport class field {\n // Fq is the base field o"
},
{
"path": "src/api/sign/poseidon/field_test.ts",
"chars": 6965,
"preview": "import { assert } from \"console\";\nimport { BigNumber } from \"ethers\";\n\nimport { field, FQ, modulo } from \"./field\";\n\nfun"
},
{
"path": "src/api/sign/poseidon/jubjub.ts",
"chars": 3138,
"preview": "/*\nThis module implements the extended twisted edwards and extended affine coordinates\ndescribed in the paper \"Twisted E"
},
{
"path": "src/api/sign/poseidon/jubjub_test.ts",
"chars": 6923,
"preview": "import { assert } from \"console\";\nimport { BigNumber } from \"ethers\";\nimport { FQ } from \"./field\";\n\nimport { jubjub, Po"
},
{
"path": "src/api/sign/poseidon/permutation.ts",
"chars": 7445,
"preview": "/*\n Implements the Poseidon permutation:\n\n Starkad and Poseidon: New Hash Functions for Zero Knowledge Proof Systems\n -"
},
{
"path": "src/api/sign/poseidon/permutation_test.ts",
"chars": 7601,
"preview": "import { assert } from \"console\";\nimport { BigNumber } from \"ethers\";\nimport { field } from \"./field\";\nimport { permunat"
},
{
"path": "src/api/sign/sign_tools.ts",
"chars": 40061,
"preview": "// import sha256 from 'crypto-js/sha256'\nimport * as crypto from 'crypto-js'\n\nimport * as abi from 'ethereumjs-abi'\nimpo"
},
{
"path": "src/api/user_api.ts",
"chars": 83689,
"preview": "/* eslint-disable camelcase */\n\nimport { BaseAPI } from './base_api'\nimport * as loopring_defs from '../defs'\nimport * "
},
{
"path": "src/api/vault_api.ts",
"chars": 22580,
"preview": "import { BaseAPI } from './base_api'\nimport * as loopring_defs from '../defs'\nimport { get_EddsaSig_NFT_Order, getMidPri"
},
{
"path": "src/api/wallet_api.ts",
"chars": 16820,
"preview": "import { BaseAPI, personalSign } from './base_api'\nimport { sendRawTx } from './contract_api'\nimport * as loopring_defs "
},
{
"path": "src/api/whitelisted_user_api.ts",
"chars": 1733,
"preview": "import { BaseAPI } from './base_api'\n\nimport * as loopring_defs from '../defs'\n\nimport * as sign_tools from './sign/sign"
},
{
"path": "src/api/ws_api.ts",
"chars": 650,
"preview": "import { BaseAPI } from './base_api'\n\nimport * as loopring_defs from '../defs'\n\nexport class WsAPI extends BaseAPI {\n /"
},
{
"path": "src/defs/account_defs.ts",
"chars": 1201,
"preview": "import { PublicKey } from './loopring_enums'\n\n/**\n * AccountInfo\n * @property accountId number Account ID\n * @property o"
},
{
"path": "src/defs/error_codes.ts",
"chars": 2850,
"preview": "import { AxiosResponse } from \"axios\";\n\nexport enum LoopringErrorCode {\n Unknown_Error = 100000,\n Invalid_Args = 10000"
},
{
"path": "src/defs/index.ts",
"chars": 1714,
"preview": "import { getNavigatorSafely, getWindowSafely } from 'utils/window_utils'\n\nexport * from './loopring_enums'\nexport * from"
},
{
"path": "src/defs/loopring_constants.ts",
"chars": 485,
"preview": "export enum HEBAO_LOCK_STATUS {\n LOCK_FAILED = 'LOCK_FAILED',\n CREATED = 'CREATED',\n LOCK_WAITING = 'LOCK_WAITING',\n "
},
{
"path": "src/defs/loopring_defs.ts",
"chars": 97172,
"preview": "import { ChainId, ConnectorNames } from './web3_defs'\n\nimport Web3 from 'web3'\n\nimport {\n AmmPoolActivityStatus,\n AmmT"
},
{
"path": "src/defs/loopring_enums.ts",
"chars": 5367,
"preview": "import { RESULT_INFO } from './error_codes'\n\nexport enum ReqMethod {\n GET = 'GET',\n POST = 'POST',\n DELETE = 'DELETE'"
},
{
"path": "src/defs/nft_defs.ts",
"chars": 2694,
"preview": "import Web3 from \"web3\";\nimport { ChainId } from \"./web3_defs\";\nimport { NFT_TYPE_STRING, NFTType } from \"../api\";\n\n/**\n"
},
{
"path": "src/defs/url_defs.ts",
"chars": 13286,
"preview": "export enum LOOPRING_URLs {\n GET_AVAILABLE_BROKER = '/api/v3/getAvailableBroker',\n GET_RELAYER_CURRENT_TIME = '/api/v3"
},
{
"path": "src/defs/web3_defs.ts",
"chars": 1186,
"preview": "export enum ChainId {\n MAINNET = 1,\n GOERLI = 5,\n SEPOLIA = 11155111,\n TAIKO = 167000,\n TAIKOHEKLA = 167009,\n BASE"
},
{
"path": "src/defs/ws_defs.ts",
"chars": 3592,
"preview": "import { OrderStatus, Side, NetworkWallet } from './'\n\nexport interface WsProps {\n topics: any[]\n needApiKey: boolean\n"
},
{
"path": "src/index.ts",
"chars": 69,
"preview": "export * from './utils'\nexport * from './defs'\nexport * from './api'\n"
},
{
"path": "src/tests/.eslintrc",
"chars": 406,
"preview": "{\n \"root\": true,\n \"parser\": \"@typescript-eslint/parser\",\n \"plugins\": [\n \"@typescript-eslint\"\n ],\n \"extends\": [\n "
},
{
"path": "src/tests/.gitignore",
"chars": 7,
"preview": "output\n"
},
{
"path": "src/tests/MockData.ts",
"chars": 15181,
"preview": "import {\n AmmpoolAPI,\n ExchangeAPI,\n UserAPI,\n WalletAPI,\n WsAPI,\n NFTAPI,\n DelegateAPI,\n GlobalAPI,\n Whitelist"
},
{
"path": "src/tests/MockSwapData.ts",
"chars": 32884,
"preview": "//Default config value from getTokens & getMixMarkets\nimport * as sdk from \"../index\";\n\nexport const marketArray = [\"LRC"
},
{
"path": "src/tests/README.md",
"chars": 13765,
"preview": "# Loopring SDK \nLoopring SDK Initialize and Mock Data structure\n\n***\n## SDK Initialize \n```ts\nimport * as sdk from \"../"
},
{
"path": "src/tests/UTC--2021-02-04T02-55-36.490219109Z--ef439044717c3af35f4f46e52aa99280217a7114",
"chars": 491,
"preview": "{'address':'ef439044717c3af35f4f46e52aa99280217a7114','crypto':{'cipher':'aes-128-ctr','ciphertext':'143482fb2ed65e3abc9"
},
{
"path": "src/tests/demo/NFTAction/collectionNFT.md",
"chars": 2431,
"preview": "# Collection NFT\n\nDefinition: allow user create a NFT Collection with different Contract(token) address.\n\n- allow user m"
},
{
"path": "src/tests/demo/NFTAction/collectionNFT.test.ts",
"chars": 3222,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n signatureKeyPairMock,\n} from \"../../MockData\";"
},
{
"path": "src/tests/demo/NFTAction/deployNFT.md",
"chars": 2048,
"preview": "# Deploy NFT\n\nDefinition: Only nft minter can deploy NFT\n\n***\n\n## Step 1. get Account\n\n```ts \nconst {accInfo} = await Lo"
},
{
"path": "src/tests/demo/NFTAction/deployNFT.test.ts",
"chars": 2551,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n TOKEN_INFO,\n signatureKeyPairMock,\n} "
},
{
"path": "src/tests/demo/NFTAction/metaNFT.md",
"chars": 1401,
"preview": "# NFT META METHODS\n\n***\n\n## getContractNFTMeta\n\n```ts\nconst result = await LoopringAPI.nftAPI.getContractNFTMeta({\n web"
},
{
"path": "src/tests/demo/NFTAction/metaNFT.test.ts",
"chars": 1954,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n} from \"../../MockData\";\nimport * as sdk"
},
{
"path": "src/tests/demo/NFTAction/mintNFT.md",
"chars": 5465,
"preview": "# Mint NFT\n\nDefinition: Mint Layer2 NFT, Loopring follow the ipfs NFT format, IPFS CID will convert to nftId, please vie"
},
{
"path": "src/tests/demo/NFTAction/mintNFT.test.ts",
"chars": 7335,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n TOKEN_INFO,\n signatureKeyPairMock,\n} "
},
{
"path": "src/tests/demo/NFTAction/tradeNFT.md",
"chars": 3764,
"preview": "# Trade NFT\n\nDefinition: This method is help for understand how to match a maker with a taker order\n\n***\n\n## tradeNFT \n>"
},
{
"path": "src/tests/demo/NFTAction/tradeNFT.test.ts",
"chars": 5546,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n signatureKeyPairMock,\n web3_2,\n TOKE"
},
{
"path": "src/tests/demo/NFTAction/validateNFTOrder.md",
"chars": 3218,
"preview": "# Validate NFT Order\n\nDefinition: Loopring L2 support a method help for Validate NFT one side Order, validate NFT Order "
},
{
"path": "src/tests/demo/NFTAction/validateNFTOrder.test.ts",
"chars": 4007,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n signatureKeyPairMock,\n} from \"../../Mo"
},
{
"path": "src/tests/demo/account/account.test.ts",
"chars": 5720,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n signatureKeyPairMock,\n TOKEN_INFO,\n} "
},
{
"path": "src/tests/demo/account/activeAccount.md",
"chars": 2152,
"preview": "# Active Account\n\nDefinition: After user Deposit or (Third-Part Transfer), how to active Loopring L2 account.\n\n***\n\n## S"
},
{
"path": "src/tests/demo/account/activeAccount.test.ts",
"chars": 4292,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n TOKEN_INFO,\n web3,\n CUSTOMER_KEY_SEED,\n} fro"
},
{
"path": "src/tests/demo/account/fee.md",
"chars": 9134,
"preview": "# Fee\n\nLoopring have 2 get Fee api:\n\n- getOffchainFeeAmt:\n - `ORDER`,\n - `FFCHAIN_WITHDRAWAL`,\n - `UPDATE_ACCOUNT`,\n "
},
{
"path": "src/tests/demo/account/fee.test.ts",
"chars": 11509,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n signatureKeyPairMock,\n TOKEN_INFO,\n LoopringAPI,\n} from \".."
},
{
"path": "src/tests/demo/account/historyRecord.md",
"chars": 1500,
"preview": "# User Actions History\nFor check account Actions, more detail such as filters please read SDK interface or API .\n\n***\n\n#"
},
{
"path": "src/tests/demo/account/historyRecord.test.ts",
"chars": 2465,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n signatureKeyPairMock,\n} from \"../../MockData\";"
},
{
"path": "src/tests/demo/account/signature.md",
"chars": 7144,
"preview": "# Signature\n\nLoopring SDK support EOA (EOA hardware wallet) & Loopring Smart wallet Signature\n\n- For Browser extension, "
},
{
"path": "src/tests/demo/account/signature.test.ts",
"chars": 2122,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n signatureKeyPairMock,\n testTypedData,\n web3,"
},
{
"path": "src/tests/demo/deposit/deposit.md",
"chars": 2721,
"preview": "# Deposit ERC20\n\nDefinition: Move user L1 ERC20 assets to Loopring L2\n> **All Deposit Method, User should have enough `E"
},
{
"path": "src/tests/demo/deposit/deposit.test.ts",
"chars": 3117,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n TOKEN_INFO,\n} from \"../../MockData\";\ni"
},
{
"path": "src/tests/demo/deposit/depositNFT.md",
"chars": 2596,
"preview": "# Deposit NFT\n\nDefinition: Move user L1 NFT assets to Loopring L2\n\n> **All Deposit Method, User should have enough `ETH`"
},
{
"path": "src/tests/demo/deposit/depositNFT.test.ts",
"chars": 3882,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n TOKEN_INFO,\n web3,\n} from \"../../MockData\";\ni"
},
{
"path": "src/tests/demo/erc20Trade/orderERC20.md",
"chars": 54386,
"preview": "# Order ERC20\n\n*** \n## mini-order\nTo support small quantity trading, we introduce an additional concept \"tradeCost\", whi"
},
{
"path": "src/tests/demo/erc20Trade/orderERC20.test.ts",
"chars": 26250,
"preview": "import {\n AMM_MAP,\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n signatureKeyPairMock,\n TOKEN_INFO,"
},
{
"path": "src/tests/demo/exchange/exchange.md",
"chars": 5079,
"preview": "# Loopring Exchange\n\nDefinition: Loopring Dex Main API for get Exchange Information, L2 Block, ERC20 Token Information, "
},
{
"path": "src/tests/demo/exchange/exchange.test.ts",
"chars": 7212,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n TOKEN_INFO,\n signatureKeyPairMock,\n} "
},
{
"path": "src/tests/demo/exchange/webSocket.md",
"chars": 575,
"preview": "#WebSocket Command\nDefinition: Loopring L2 websocket \n\n### Loopring L2 websocket topic type: \nWsTopicType\n- `account`\n- "
},
{
"path": "src/tests/demo/exchange/webSocket.test.ts",
"chars": 812,
"preview": "import * as sdk from \"../../../index\";\nimport { DEFAULT_TIMEOUT, LoopringAPI } from \"../../MockData\";\n\n/**\n * @define Ws"
},
{
"path": "src/tests/demo/transfer/transferERC20.md",
"chars": 2701,
"preview": "# Transfer ERC20 \nDefinition: Send ERC20 tokens to other account on Loopring L2, \n> trade value should with decimals `sd"
},
{
"path": "src/tests/demo/transfer/transferERC20.test.ts",
"chars": 3256,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n TOKEN_INFO,\n signatureKeyPairMock,\n web3,\n} "
},
{
"path": "src/tests/demo/transfer/transferNFT.md",
"chars": 3254,
"preview": "# Transfer NFT\nDefinition: Send NFT to other account on Loopring L2\n\n***\n## Step 1. get account Info\n```ts\nconst { excha"
},
{
"path": "src/tests/demo/transfer/transferNFT.test.ts",
"chars": 3145,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n TOKEN_INFO,\n signatureKeyPairMock,\n} "
},
{
"path": "src/tests/demo/withdraw/withdrawERC20.md",
"chars": 2072,
"preview": "# Withdraw ERC20\n\nDefinition: Loopring L2 withdraw ERC20 to Ethereum L1,\n> trade value should with decimals `sdk.toBig(v"
},
{
"path": "src/tests/demo/withdraw/withdrawERC20.test.ts",
"chars": 2913,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n TOKEN_INFO,\n signatureKeyPairMock,\n} "
},
{
"path": "src/tests/demo/withdraw/withdrawNFT.md",
"chars": 2545,
"preview": "# Withdraw NFT\n\nDefinition: Loopring L2 withdraw NFT to Ethereum L1\n\n***\n\n## Step 1. getAccount\n\n```ts\nconst {accInfo} "
},
{
"path": "src/tests/demo/withdraw/withdrawNFT.test.ts",
"chars": 3419,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n TOKEN_INFO,\n signatureKeyPairMock,\n} "
},
{
"path": "src/tests/formatter.test.ts",
"chars": 11178,
"preview": "import { IsMobile, LoopringErrorCode } from \"../defs\";\n// import fetch from \"node-fetch\";\n\nimport {\n addHexPrefix,\n cl"
},
{
"path": "src/tests/unitTest/account/account.test.ts",
"chars": 6407,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n signatureKeyPairMock,\n TOKEN_INFO,\n} "
},
{
"path": "src/tests/unitTest/account/sign_tools.test.ts",
"chars": 7958,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n signatureKeyPairMock,\n testTypedData,\n web3,"
},
{
"path": "src/tests/unitTest/appWallet/wallet.test.ts",
"chars": 7407,
"preview": "import {\n TOKEN_INFO,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n DEFAULT_TIMEOUT,\n web3,\n} from '../../MockData'\nim"
},
{
"path": "src/tests/unitTest/erc20Trade/amm.test.ts",
"chars": 9542,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n TOKEN_INFO,\n signatureKeyPairMock,\n} from \".."
},
{
"path": "src/tests/unitTest/erc20Trade/amm_calc.test.ts",
"chars": 6126,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n TOKEN_INFO,\n signatureKeyPairMock,\n} "
},
{
"path": "src/tests/unitTest/erc20Trade/defi.test.ts",
"chars": 4291,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n TOKEN_INFO,\n signatureKeyPairMock,\n} "
},
{
"path": "src/tests/unitTest/exchange/exchange.test.ts",
"chars": 6604,
"preview": "import { DEFAULT_TIMEOUT, LoopringAPI } from \"../../MockData\";\nimport * as sdk from \"../../../index\";\ndescribe(\"Exchange"
},
{
"path": "src/tests/unitTest/transfer/transferUT.test.ts",
"chars": 4501,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n} from \"../../MockData\";\n\ndescribe(\"Transfer UT\""
},
{
"path": "src/tests/unitTest/withdraw/forceWithdrawls.test.ts",
"chars": 2452,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n signatureKeyPairMock,\n TOKEN_INFO,\n web3,\n} "
},
{
"path": "src/tests/unitTest/withdraw/withdrawUT.test.ts",
"chars": 4089,
"preview": "import {\n DEFAULT_TIMEOUT,\n LOOPRING_EXPORTED_ACCOUNT,\n LoopringAPI,\n web3,\n TOKEN_INFO,\n signatureKeyPairMock,\n} "
},
{
"path": "src/types/eddsa.d.ts",
"chars": 114,
"preview": "declare module 'ffjavascript'\n\ndeclare module 'blake-hash'\n\ndeclare module 'circomlib'\n\ndeclare module \"blake2b\";\n"
},
{
"path": "src/types.d.ts",
"chars": 345,
"preview": "declare global {\n type Ethereum = any;\n interface Window {\n ethereum?: {\n [key: string]: boolean;\n isLoop"
},
{
"path": "src/utils/formatter.ts",
"chars": 16116,
"preview": "import * as ethUtil from 'ethereumjs-util'\nimport BN from 'bn.js'\nimport BigNumber from 'bignumber.js'\nimport { Buffer }"
},
{
"path": "src/utils/index.ts",
"chars": 208,
"preview": "export * from \"./network_tools\";\nexport * from \"./symbol_tools\";\nexport * from \"./formatter\";\nexport * from \"./swap_calc"
},
{
"path": "src/utils/log_tools.ts",
"chars": 670,
"preview": "/* eslint-disable no-console, @typescript-eslint/ban-ts-comment */\nlet _myLog;\n\nif (\n process.env.NODE_ENV !== \"product"
},
{
"path": "src/utils/network_tools.ts",
"chars": 382,
"preview": "/* eslint-disable no-console */\nexport const dumpError400 = (reason: any, src = '') => {\n if (src) {\n console.debug"
},
{
"path": "src/utils/obj_tools.ts",
"chars": 119,
"preview": "export const sortObject = (o: any) =>\n Object.keys(o)\n .sort()\n .reduce((r: any, k) => ((r[k] = o[k]), r), {});\n"
},
{
"path": "src/utils/swap_calc_utils.ts",
"chars": 36178,
"preview": "import * as fm from './formatter'\nimport { toBig } from './formatter'\nimport {\n ABInfo,\n AmmPoolSnapshot,\n CalDualRes"
},
{
"path": "src/utils/symbol_tools.ts",
"chars": 2522,
"preview": "import { TokenInfo } from \"defs\";\n\nconst specialSymbols = [\"ETH2x-FIL\"];\n\nexport function getBaseQuote(symbol: string) {"
},
{
"path": "src/utils/window_utils.ts",
"chars": 360,
"preview": "export const getWindowSafely = () => {\n if (typeof global.window === 'undefined' || typeof window === 'undefined') {\n "
},
{
"path": "tsconfig.json",
"chars": 832,
"preview": "{\n \"compilerOptions\": {\n \"baseUrl\": \"./src\",\n \"rootDir\": \"./src\",\n \"outDir\": \"./dist\",\n \"module\": \"esnext\","
}
]
About this extraction
This page contains the full source code of the Loopring/loopring_sdk GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 165 files (1.1 MB), approximately 331.8k tokens, and a symbol index with 964 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.