token-lib.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const {web3} = require("hardhat");
  2. const ierc20abi = require("../../abi/IERC20_ABI.json");
  3. const BaseModel = require("../../model/base-model");
  4. module.exports = class TokenLib {
  5. static LEVEL = {
  6. NOT: 'not',
  7. DISCARD: 'discard',
  8. INIT: 'init',
  9. NORMAL: 'normal',
  10. TOP: 'top'
  11. }
  12. constructor(web3, chain) {
  13. this.web3 = web3
  14. this.chain = chain
  15. this.tokenContractMap = {}
  16. this.tokenModel = new BaseModel(this.chain.id, BaseModel.MODULES.TOKEN)
  17. }
  18. getTokenContract(tokenAddress) {
  19. if (!this.tokenContractMap[tokenAddress]) {
  20. this.tokenContractMap[tokenAddress] = new this.web3.eth.Contract(ierc20abi, tokenAddress)
  21. }
  22. return this.tokenContractMap[tokenAddress]
  23. }
  24. async parseToken(lp, isZero) {
  25. const token = {
  26. 'hash': isZero ? lp.token0 : lp.token1,
  27. 'symbol': isZero ? lp.symbol0 : lp.symbol1,
  28. 'decimals': isZero ? lp.decimals0 : lp.decimals1
  29. }
  30. let tokenContract = this.getTokenContract(token.hash)
  31. token.name = await tokenContract.methods.name().call()
  32. token.name = this.getEffectiveName(token.name)
  33. token.level = TokenLib.LEVEL.INIT
  34. return token
  35. }
  36. getEffectiveSymbol(originSymbol) {
  37. return originSymbol.replace(/[^A-Za-z0-9]+/g, '').substring(0, 10)
  38. }
  39. getEffectiveName(originName) {
  40. return originName.replace(/[^A-Za-z0-9]+/g, '').substring(0, 37)
  41. }
  42. async saveToken(token) {
  43. return await this.tokenModel.appendOrUpdate(token)
  44. }
  45. }