Skip to content

Instantly share code, notes, and snippets.

@akirattii
Last active August 17, 2018 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akirattii/6e0b71330d246c8ef9d8c4da5ed7c2a2 to your computer and use it in GitHub Desktop.
Save akirattii/6e0b71330d246c8ef9d8c4da5ed7c2a2 to your computer and use it in GitHub Desktop.
Ripple: How to validate a tx's result after submitting it. (private memo)
// submit tx:
submitTx(signedTx, (err, res) => {
  if (err) throw err;
  // Check if `engine_result` is "tesSUCCESS": 
  if (res.engine_result !== "tesSUCCESS") {
    // the tx's failed immediately.
    return;
  }
  const txhash = res.tx_json.hash;
  // Start to check the tx validity periodically until the validated is set as true or false:
  checkValidated(txhash, (err, validated, resdata) => {
    if (err) throw err;
    if (validated === true) {
      // the tx's validation OK!
    } else {
      // the tx's validation NG.
    }
  });
});

function checkValidated(txhash, cb) {
  /*
   * レジャーへの取込成功の条件 (以下の全てがtrue):
   * - status === "success"
   * - result.meta is existed AND result.meta.TransactionResult === "tesSUCCESS"
   * - result.validated === true
   *
   * NOTE: checkValidatedを終了させるタイミング:
   * - status !== "success" ならリクエストエラーで終了
   * - result.meta.TransactionResult !== "tesSUCCESS" ならエラーで終了
   * - result.meta.TransactionResult === "tesSUCCESS" なら validated を確認
   *   - validated が存在するまで5秒間隔ぐらいでループ、 vaidated === false ならエラーで終了
   */
  const onmessage = function(e) {
    wsclient.close();
    const data = JSON.parse(e.data);
    if (data.status !== "success") {
      return cb && cb(null, false, data);
    }
    if (!data.result.meta) {
      // retry...
      return setTimeout(() => {
        checkValidated(txhash, cb);
      }, 5000);
    }
    if (data.result.meta.TransactionResult !== "tesSUCCESS") {
      return cb && cb(null, false, data);
    }
    if (data.result.validated === true) {
      return cb && cb(null, true, data);
    } else {
      // retry...
      return setTimeout(() => {
        checkValidated(txhash, cb);
      }, 5000);
    }
  };
  wsclient.open(onmessage, (e) => {
    console.log("ws opened:", e);
    const param = {
      "id": 1,
      "command": "tx",
      "transaction": txhash,
    };
    wsclient.send(param);
  });
}

see also: https://gist.github.com/akirattii/5a37cd116ee3a4c071cb65618777cc9a (WsCient.js)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment