You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

xrpl-binding.ts 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import { defaultOptions, Memo, Options } from '../util/types'
  2. import { Client, Payment, TxResponse, Wallet } from 'xrpl'
  3. import * as zlib from 'zlib'
  4. import * as util from 'util'
  5. const compressB64 = async (data: string) => (await util.promisify(zlib.deflate)(Buffer.from(data, 'utf-8'))).toString('base64')
  6. const decompressB64 = async (data: string) => (await util.promisify(zlib.inflate)(Buffer.from(data, 'base64'))).toString('utf-8')
  7. const hexDecode = (str: string) => Buffer.from(str, 'hex').toString('utf8')
  8. const hexEncode = (str: string) => Buffer.from(str, 'utf8').toString('hex').toUpperCase()
  9. const chunkString = (str: string, length: number) => str.match(new RegExp('.{1,' + length + '}', 'gs'));
  10. const PAYLOAD_SIZE = 925
  11. export class xrpIO {
  12. private api: Client
  13. constructor(
  14. private server: string,
  15. private options: Options = defaultOptions
  16. ) {
  17. this.options.debug = options.debug ? Boolean(options.debug) : defaultOptions.debug
  18. this.options.connectionTimeout = options.connectionTimeout ? Number(options.connectionTimeout) : defaultOptions.connectionTimeout
  19. this.options.readMaxRetry = options.readMaxRetry ? Number(options.readMaxRetry) : defaultOptions.readMaxRetry
  20. this.options.readRetryTimeout = options.readRetryTimeout ? Number(options.readRetryTimeout) : defaultOptions.readRetryTimeout
  21. this.api = new Client(server, {
  22. connectionTimeout: this.options.connectionTimeout
  23. })
  24. }
  25. public async connect(): Promise<void> {
  26. if (!this.api.isConnected())
  27. await this.api.connect()
  28. }
  29. public async disconnect(): Promise<void> {
  30. try {
  31. await this.api.disconnect()
  32. } catch (e) {
  33. console.log("DISCONNECT ERROR", e)
  34. }
  35. }
  36. private async cloneApi(): Promise<Client> {
  37. let _api = new Client(this.server, {
  38. connectionTimeout: this.options.connectionTimeout
  39. })
  40. while (!_api.isConnected()) {
  41. try {
  42. await _api.connect()
  43. return _api
  44. } catch (e) {
  45. this.dbg('CLONEAPI ERR', 'Connection failed', String(e['message']))
  46. await _api.disconnect()
  47. _api = new Client(this.server, {
  48. connectionTimeout: this.options.connectionTimeout
  49. })
  50. }
  51. }
  52. }
  53. private async sendPayment(data: Memo, to: string, secret: string, sequence?: number): Promise<TxResponse> {
  54. const wallet = Wallet.fromSecret(secret)
  55. this.dbg("Sending payment", wallet.address, '->', to)
  56. const _api = await this.cloneApi()
  57. try {
  58. const payment: Payment = await _api.autofill({
  59. TransactionType: 'Payment',
  60. Account: wallet.address,
  61. Destination: to,
  62. Sequence: sequence,
  63. Amount: "1",
  64. Memos: [{
  65. Memo: {
  66. MemoData: hexEncode(data.data || ""),
  67. MemoFormat: hexEncode(data.format || ""),
  68. MemoType: hexEncode(data.type || "")
  69. }
  70. }]
  71. })
  72. const response = await _api.submitAndWait(payment, { wallet })
  73. await _api.disconnect()
  74. this.dbg("Tx finalized", response.result.hash, response.result.Sequence)
  75. return response
  76. } catch (error: any) {
  77. this.dbg("SENDPAYMENT ERROR", error)
  78. await _api.disconnect()
  79. throw error
  80. }
  81. }
  82. public async writeRaw(data: Memo, to: string, secret: string, sequence?: number): Promise<string> {
  83. this.dbg("Writing data", data)
  84. const tx = await this.sendPayment(data, to, secret, sequence)
  85. return tx.result.hash
  86. }
  87. private async getTransaction(hash: string, retry=0): Promise<TxResponse> {
  88. this.dbg("Getting Tx", hash)
  89. try{
  90. return await this.api.request({
  91. command: 'tx',
  92. transaction: hash,
  93. })
  94. }catch(e){
  95. this.dbg(e)
  96. if(this.options.readMaxRetry != -1){
  97. if(retry >= this.options.readMaxRetry)
  98. console.error("Retry limit exceeded for", hash, ". this is an irrecoverable error")
  99. throw e
  100. }
  101. await new Promise(res => setTimeout(res, this.options.readRetryTimeout))
  102. return await this.getTransaction(hash, retry+1)
  103. }
  104. }
  105. public async readRaw(hash: string): Promise<Memo> {
  106. const tx = await this.getTransaction(hash)
  107. const memo = tx.result.Memos[0].Memo
  108. const memoParsed = {
  109. data: hexDecode(memo.MemoData),
  110. format: hexDecode(memo.MemoFormat),
  111. type: hexDecode(memo.MemoType)
  112. }
  113. this.dbg(hash, "data", memoParsed)
  114. return memoParsed
  115. }
  116. public async treeWrite(data: string, to: string, secret: string, format: 'L' | 'N' = 'L'): Promise<string> {
  117. const wallet = Wallet.fromSecret(secret)
  118. data = await compressB64(data)
  119. const chunks = chunkString(data, PAYLOAD_SIZE)
  120. const latestSequence = await this.getAccountSequence(wallet.address)
  121. const hashes = await Promise.all(Object.entries(chunks).map(([i, chunk]) => this.writeRaw({ data: chunk, format: format }, to, secret, latestSequence + Number(i))))
  122. if (hashes.length === 1) {
  123. return hashes[0]
  124. }
  125. return await this.treeWrite(JSON.stringify(hashes), to, secret, 'N')
  126. }
  127. public async treeRead(hashes: string[]): Promise<string> {
  128. const memos = await Promise.all(hashes.map(hash => this.readRaw(hash)))
  129. const payload: string = await decompressB64(memos.map(memo => memo.data).join(''))
  130. if (memos.some(memo => memo.format === 'N')) {
  131. return await this.treeRead(JSON.parse(payload))
  132. }
  133. return payload
  134. }
  135. public async getAccountSequence(address: string): Promise<number> {
  136. this.dbg("Getting acc info for", address)
  137. const accountInfo = await this.api.request({
  138. command: 'account_info',
  139. account: address,
  140. strict: true,
  141. })
  142. this.dbg("Got account_info", accountInfo)
  143. return Number(accountInfo.result.account_data.Sequence)
  144. }
  145. private dbg(...args: any[]) {
  146. if (this.options.debug) {
  147. console.log.apply(console, args)
  148. }
  149. }
  150. }