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.

ripple-binding.ts 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import { Instructions, LedgerClosedEvent, RippleAPI } from 'ripple-lib'
  2. import { Memo, Wallet } from '../util/types'
  3. import { MIN_XRP_FEE, MIN_XRP_TX_VALUE } from '../util/protocol.constants';
  4. import * as zlib from 'zlib'
  5. import * as util from 'util'
  6. import { Payment } from 'ripple-lib/dist/npm/transaction/payment';
  7. const chunkString = (str: string, length: number) => str.match(new RegExp('.{1,' + length + '}', 'gs'));
  8. const PAYLOAD_SIZE = 925
  9. const debug = false
  10. const cloneApi = async (api: RippleAPI): Promise<RippleAPI> => {
  11. const subApi = new RippleAPI({ server: api.connection['_url'] })
  12. await subApi.connect()
  13. return subApi
  14. }
  15. export const getLatestSequence = async (api: RippleAPI, accountAddress: string): Promise<number> => {
  16. if(debug) console.log("Getting acc info for", accountAddress)
  17. const accountInfo = await api.getAccountInfo(accountAddress, {})
  18. return Number(accountInfo.sequence-1)
  19. }
  20. const compressB64 = async (data: string) => (await util.promisify(zlib.deflate)(Buffer.from(data, 'utf-8'))).toString('base64')
  21. const decompressB64 = async (data: string) => (await util.promisify(zlib.inflate)(Buffer.from(data, 'base64'))).toString('utf-8')
  22. const sendReliably = (api: RippleAPI, signed: any, preparedPayment,): Promise<any> => new Promise((res, rej) => {
  23. const ledgerClosedCallback = async (event: LedgerClosedEvent) => {
  24. let status
  25. try {
  26. status = await api.getTransaction(signed.id, {
  27. minLedgerVersion: 20368096
  28. })
  29. } catch (e) {
  30. // Typical error when the tx hasn't been validated yet:
  31. if ((e as Error).name !== 'MissingLedgerHistoryError') {
  32. //console.log(e)
  33. }
  34. if (event.ledger_index > preparedPayment.instructions.maxLedgerVersion + 3) {
  35. // Assumptions:
  36. // - We are still connected to the same rippled server
  37. // - No ledger gaps occurred
  38. // - All ledgers between the time we submitted the tx and now have been checked for the tx
  39. status = {
  40. finalResult: 'Transaction was not, and never will be, included in a validated ledger'
  41. }
  42. return rej(status);
  43. } else {
  44. // Check again later:
  45. api.connection.once('ledgerClosed', ledgerClosedCallback)
  46. return
  47. }
  48. }
  49. return res(status)
  50. }
  51. api.connection.once('ledgerClosed', ledgerClosedCallback)
  52. })
  53. export const sendPayment = async (api: RippleAPI, data: Memo[], from: string, to: string, secret: string, sequence: number) => {
  54. if(debug) console.log("Sending payment with seq", sequence)
  55. const options: Instructions = {
  56. maxLedgerVersionOffset: 5,
  57. fee: MIN_XRP_FEE,
  58. sequence: sequence,
  59. };
  60. const payment: Payment = {
  61. source: {
  62. address: from,
  63. maxAmount: {
  64. value: MIN_XRP_TX_VALUE,
  65. currency: 'XRP'
  66. },
  67. },
  68. destination: {
  69. address: to,
  70. amount: {
  71. value: MIN_XRP_TX_VALUE,
  72. currency: 'XRP'
  73. },
  74. },
  75. memos: data,
  76. };
  77. try {
  78. const _api = await cloneApi(api)
  79. const prepared = await _api.preparePayment(from, payment, options)
  80. const signed = _api.sign(prepared.txJSON, secret);
  81. const txHash = await _api.submit(signed.signedTransaction)
  82. if(debug) console.log("Transaction submitted", txHash)
  83. await sendReliably(_api, signed, prepared)
  84. _api.disconnect()
  85. return txHash
  86. } catch (error) {
  87. //console.log("SENDPAYMENT ERROR", error)
  88. throw error
  89. }
  90. }
  91. export const getTransactions = async (api: RippleAPI, address: string, minLedgerVersion: number = 19832467): Promise<any[]> => {
  92. const txs = await api.getTransactions(address, {
  93. minLedgerVersion: minLedgerVersion,
  94. earliestFirst: true,
  95. excludeFailures: true,
  96. })
  97. return txs
  98. }
  99. export const writeRaw = async (api: RippleAPI, data: Memo, from: string, to: string, secret: string, sequence?: number): Promise<string> => {
  100. //if (memoSize(data) > 1000) throw new Error("data length exceeds capacity")
  101. try {
  102. if (!sequence) {
  103. const accountInfo = await getLatestSequence(api, from)
  104. sequence = accountInfo + 1
  105. }
  106. const resp = await sendPayment(api, [data], from, to, secret, sequence)
  107. return resp['tx_json'].hash
  108. } catch (error) {
  109. console.log("WRITERAW ERR", error);
  110. }
  111. }
  112. export const readRaw = async (api: RippleAPI, hash: string): Promise<Memo> => {
  113. const tx = await api.getTransaction(hash, {
  114. minLedgerVersion: 16392480
  115. })
  116. if (!tx || !tx.specification || !tx.specification['memos'] || !tx.specification['memos'][0]) {
  117. throw new Error('Invalid Transaction ' + hash)
  118. }
  119. return tx.specification['memos'][0]
  120. }
  121. export const subscribe = async (api: RippleAPI, address: string, callback: (tx) => any) => {
  122. api.connection.on('transaction', (tx) => callback(tx))
  123. await api.connection.request({
  124. command: 'subscribe',
  125. accounts: [address],
  126. })
  127. }
  128. export const treeWrite = async (api: RippleAPI, data: string, wallet: Wallet, to: string, format: 'L'|'N' = 'L'): Promise<string> => {
  129. data = await compressB64(data)
  130. const chunks = chunkString(data, PAYLOAD_SIZE)
  131. const latestSequence = await getLatestSequence(api, wallet.address)
  132. const hashes = await Promise.all(Object.entries(chunks).map(([i, chunk]) => writeRaw(api, { data: chunk, format: format }, wallet.address, to, wallet.secret, latestSequence + Number(i) + 1)))
  133. if (hashes.length === 1) {
  134. return hashes[0]
  135. }
  136. return await treeWrite(api, JSON.stringify(hashes), wallet, to, 'N')
  137. }
  138. export const treeRead = async (api: RippleAPI, hashes: string[]): Promise<string> => {
  139. const memos = await Promise.all(hashes.map(hash => readRaw(api, hash)))
  140. const payload: string = await decompressB64(memos.map(memo => memo.data).join(''))
  141. if (memos.some(memo => memo.format === 'N')) {
  142. return await treeRead(api, JSON.parse(payload))
  143. }
  144. return payload
  145. }