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 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import { defaultOptions, Memo, Options } from '../util/types'
  2. import { Client, Payment, RippledError, TxResponse, Wallet } from 'xrpl'
  3. import * as zlib from 'zlib'
  4. import * as util from 'util'
  5. import { NON_ZERO_TX_HASH } from '../util/protocol.constants'
  6. import { ERR_BAD_TX_HASH, ERR_NO_VERIFY_OWNER } from '../util/errors'
  7. const compressB64 = async (data: string) => (await util.promisify(zlib.deflate)(Buffer.from(data, 'utf-8'))).toString('base64')
  8. const decompressB64 = async (data: string) => (await util.promisify(zlib.inflate)(Buffer.from(data, 'base64'))).toString('utf-8')
  9. const hexDecode = (str: string) => Buffer.from(str, 'hex').toString('utf8')
  10. const hexEncode = (str: string) => Buffer.from(str, 'utf8').toString('hex').toUpperCase()
  11. const chunkString = (str: string, length: number) => str.match(new RegExp('.{1,' + length + '}', 'gs'));
  12. const genRandHex = size => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');
  13. const PAYLOAD_SIZE = 925
  14. const XRP_PER_DROP = 0.000001
  15. const DROP_PER_XRP = 1000000
  16. export class xrpIO {
  17. private api: Client
  18. constructor(
  19. private server: string,
  20. private options: Options = defaultOptions
  21. ) {
  22. this.options.debug = options.debug ? Boolean(options.debug) : defaultOptions.debug
  23. this.options.connectionTimeout = options.connectionTimeout ? Number(options.connectionTimeout) : defaultOptions.connectionTimeout
  24. this.options.readMaxRetry = options.readMaxRetry ? Number(options.readMaxRetry) : defaultOptions.readMaxRetry
  25. this.options.readRetryTimeout = options.readRetryTimeout ? Number(options.readRetryTimeout) : defaultOptions.readRetryTimeout
  26. this.options.readFreshApi = options.readFreshApi ? Boolean(options.readFreshApi) : defaultOptions.readFreshApi
  27. this.api = new Client(server, {
  28. connectionTimeout: this.options.connectionTimeout
  29. })
  30. }
  31. public async connect(): Promise<void> {
  32. if (!this.api.isConnected())
  33. await this.api.connect()
  34. }
  35. public async disconnect(): Promise<void> {
  36. try {
  37. await this.api.disconnect()
  38. } catch (e) {
  39. console.log("DISCONNECT ERROR", e)
  40. }
  41. }
  42. private async cloneApi(): Promise<Client> {
  43. let _api = new Client(this.server, {
  44. connectionTimeout: this.options.connectionTimeout
  45. })
  46. while (!_api.isConnected()) {
  47. try {
  48. await _api.connect()
  49. return _api
  50. } catch (e) {
  51. this.dbg('CLONEAPI ERR', 'Connection failed', String(e['message']))
  52. await _api.disconnect()
  53. _api = new Client(this.server, {
  54. connectionTimeout: this.options.connectionTimeout
  55. })
  56. }
  57. }
  58. }
  59. public async sendPayment(data: Memo, to: string, secret: string, sequence?: number, amount: string = "1"): Promise<TxResponse> {
  60. const wallet = Wallet.fromSecret(secret)
  61. this.dbg("Sending payment", wallet.address, '->', to)
  62. const _api = await this.cloneApi()
  63. const payment: Payment = await _api.autofill({
  64. TransactionType: 'Payment',
  65. Account: wallet.address,
  66. Destination: to,
  67. Sequence: sequence,
  68. Amount: amount,
  69. Memos: [{
  70. Memo: {
  71. MemoData: hexEncode(data.data || ""),
  72. MemoFormat: hexEncode(data.format || ""),
  73. MemoType: hexEncode(data.type || "")
  74. }
  75. }]
  76. })
  77. try {
  78. const response = await _api.submitAndWait(payment, { wallet })
  79. this.dbg("Tx finalized", response.result.hash, response.result.Sequence)
  80. return response
  81. } catch (error: any) {
  82. this.dbg("SENDPAYMENT ERROR", error)
  83. console.log("SENDPAYMENT ERROR", error)
  84. throw error
  85. }finally{
  86. await _api.disconnect()
  87. }
  88. }
  89. public async writeRaw(data: Memo, to: string, secret: string, sequence?: number, amount: string = "1"): Promise<string> {
  90. this.dbg("Writing data", data)
  91. const tx = await this.sendPayment(data, to, secret, sequence, amount)
  92. return tx.result.hash
  93. }
  94. public async getTransaction(hash: string, retry = 0): Promise<TxResponse> {
  95. if (!NON_ZERO_TX_HASH.test(hash)) {
  96. throw ERR_BAD_TX_HASH(hash)
  97. }
  98. this.dbg("Getting Tx", hash)
  99. const _api = this.options.readFreshApi ? await this.cloneApi() : this.api
  100. try {
  101. return await _api.request({
  102. command: 'tx',
  103. transaction: hash,
  104. })
  105. } catch (e: any) {
  106. this.dbg("getTransaction err", e)
  107. if(e.data){ //RippledError
  108. switch(e.data.error){
  109. //irrecoverable errors
  110. case 'amendmentBlocked': //server is amendment blocked and needs to be updated to the latest version to stay synced with the XRP Ledger network.
  111. case 'invalid_API_version': //The server does not support the API version number from the request.
  112. case 'jsonInvalid': //(WebSocket only) The request is not a proper JSON object.
  113. case 'missingCommand': //(WebSocket only) The request did not specify a command field
  114. case 'noClosed': //The server does not have a closed ledger, typically because it has not finished starting up.
  115. case 'txnNotFound': //Either the transaction does not exist, or it was part of an ledger version that rippled does not have available
  116. case 'unknownCmd': //The request does not contain a command that the rippled server recognizes
  117. case 'wsTextRequired': //(WebSocket only) The request's opcode is not text.
  118. case 'invalidParams': //One or more fields are specified incorrectly, or one or more required fields are missing.
  119. case 'excessiveLgrRange': //The min_ledger and max_ledger fields of the request are more than 1000 apart
  120. case 'invalidLgrRange': //The specified min_ledger is larger than the max_ledger, or one of those parameters is not a valid ledger index
  121. throw e
  122. //potentially recoverable errors
  123. case 'failedToForward': //(Reporting Mode servers only) The server tried to forward this request to a P2P Mode server, but the connection failed
  124. case 'noCurrent': //The server does not know what the current ledger is, due to high load, network problems, validator failures, incorrect configuration, or some other problem.
  125. case 'noNetwork': //The server is having trouble connecting to the rest of the XRP Ledger peer-to-peer network (and is not running in stand-alone mode).
  126. case 'tooBusy': //The server is under too much load to do this command right now. Generally not returned if you are connected as an admin
  127. default: //some undocumented error, might as well give it a re-try
  128. //fall through
  129. }
  130. }
  131. //some other error, potentially recoverable
  132. if (this.options.readMaxRetry != -1 && retry >= this.options.readMaxRetry) { //not doing infinite retries and exhausted retry quota
  133. throw e
  134. }else{
  135. await new Promise(res => setTimeout(res, this.options.readRetryTimeout))
  136. return await this.getTransaction(hash, retry + 1)
  137. }
  138. }finally{
  139. if(this.options.readFreshApi) await _api.disconnect()
  140. }
  141. }
  142. public async readRaw(hash: string, verifyOwner?: string): Promise<Memo> {
  143. if (!NON_ZERO_TX_HASH.test(hash)) {
  144. throw ERR_BAD_TX_HASH(hash)
  145. }
  146. const tx = await this.getTransaction(hash)
  147. if(verifyOwner && tx.result.Account != verifyOwner){
  148. throw ERR_NO_VERIFY_OWNER(hash, tx.result.Account, verifyOwner)
  149. }
  150. const memo = tx.result.Memos[0].Memo
  151. const memoParsed = {
  152. data: hexDecode(memo.MemoData),
  153. format: hexDecode(memo.MemoFormat),
  154. type: hexDecode(memo.MemoType)
  155. }
  156. this.dbg(hash, "data", memoParsed)
  157. return memoParsed
  158. }
  159. public async treeWrite(data: string, to: string, secret: string, format: 'L' | 'N' = 'L'): Promise<string> {
  160. const wallet = Wallet.fromSecret(secret)
  161. data = await compressB64(data)
  162. const chunks = chunkString(data, PAYLOAD_SIZE)
  163. const latestSequence = await this.getAccountSequence(wallet.address)
  164. const hashes = await Promise.all(Object.entries(chunks).map(([i, chunk]) => this.writeRaw({ data: chunk, format: format }, to, secret, latestSequence + Number(i))))
  165. if (hashes.length === 1) {
  166. return hashes[0]
  167. }
  168. return await this.treeWrite(JSON.stringify(hashes), to, secret, 'N')
  169. }
  170. public async treeRead(hashes: string[], verifyOwner?:string): Promise<string> {
  171. const bad_hash = hashes.find(hash => !NON_ZERO_TX_HASH.test(hash))
  172. if (bad_hash)
  173. throw ERR_BAD_TX_HASH(bad_hash)
  174. const memos = await Promise.all(hashes.map(hash => this.readRaw(hash, verifyOwner)))
  175. const payload: string = await decompressB64(memos.map(memo => memo.data).join(''))
  176. if (memos.some(memo => memo.format === 'N')) {
  177. return await this.treeRead(JSON.parse(payload), verifyOwner)
  178. }
  179. return payload
  180. }
  181. public async getAccountSequence(address: string): Promise<number> {
  182. this.dbg("Getting acc info for", address)
  183. const accountInfo = await this.api.request({
  184. command: 'account_info',
  185. account: address,
  186. strict: true,
  187. })
  188. this.dbg("Got account_info", accountInfo)
  189. return Number(accountInfo.result.account_data.Sequence)
  190. }
  191. public async estimateFee(data: string, denomination: 'XRP' | 'DROPS' = 'DROPS', cost = 0): Promise<number> {
  192. data = await compressB64(data)
  193. const chunks = chunkString(data, PAYLOAD_SIZE)
  194. if (chunks.length === 1) {
  195. return (denomination === "DROPS" ? (cost + 1) : this.dropsToXrp(cost + 1))
  196. }
  197. return this.estimateFee(JSON.stringify(chunks.map(_ => genRandHex(64))), denomination, cost + chunks.length)
  198. }
  199. public xrpToDrops(xrp: number): number {
  200. return xrp * DROP_PER_XRP
  201. }
  202. public dropsToXrp(drops: number): number {
  203. return drops * XRP_PER_DROP
  204. }
  205. private dbg(...args: any[]) {
  206. if (this.options.debug) {
  207. console.log.apply(console, args)
  208. }
  209. }
  210. }