Jump to content

Trouble using ripple-lib to create, sign, and submit new offers


Recommended Posts

  • Replies 31
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Popular Posts

api.connect().then(() => {}); // connect and when connected do nothing console.log('Connected...'); // is called regardless if you're connected or not. Actually called while still connecting

() => {} Also in case you're wondering the above is the syntax for an anonymous function. It's a function without a name.    function myfunction () { } or var myfunction = () => {

Alrighty, thanks so much to you @jargoman@jn_r and also to Chris Clark for all of the lessons you've taught me about the functionality of Javascript and ripple-lib as well as all of the code examples

...I should have realized it was asking me to install a module.  Ugh.

Well, I have been met with some more unexpected behavior after getting the XRP price in CAD.  I am able to retrieve the response from the goldapi.io API but when I try to output a line to the console to check if the regular expression matches the data found in the JSON, it doesn't print out to the console, instead the error message from the catch block prints out.

 

Quote

tw@tw-VirtualBox:~/Downloads/my_ripple_experiment$ node asyncrippletest.js
end of script
(node:2038) Warning: N-API is an experimental feature and could change at any time.
connected
The XRP price in Canadian dollars is: 0.325809
$resp is: {"timestamp":1603995585,"metal":"XAG","currency":"CAD","exchange":"OANDA","symbol":"OANDA:XAGCAD","prev_close_price":31.1499,"open_price":31.1499,"low_price":30.20776,"high_price":31.4519,"open_time":1603918800,"price":31.09412,"ch":-0.05578,"chp":-0.18,"ask":31.10862,"bid":31.07963}
$data is: {"timestamp":1603995585,"metal":"XAG","currency":"CAD","exchange":"OANDA","symbol":"OANDA:XAGCAD","prev_close_price":31.1499,"open_price":31.1499,"low_price":30.20776,"high_price":31.4519,"open_time":1603918800,"price":31.09412,"ch":-0.05578,"chp":-0.18,"ask":31.10862,"bid":31.07963}
Gold api error
disconnected, code: 1000
tw@tw-VirtualBox:~/Downloads/my_ripple_experiment$ cat asyncrippletest.js
const RippleAPI = require('ripple-lib').RippleAPI;

// npm install node-fetch@2.6.0
const fetch = require('node-fetch');

const address = "rG83NMzArGuNPWyVyumuQLkj3EVJsrkDbA";

const secret = '';

const instructions = {maxLedgerVersionOffset: 5};

const https = require('https');

const request = require("request-promise");

let url = "https://api.coingecko.com/api/v3/simple/price?ids=ripple&vs_currencies=cad";

const api = new RippleAPI({
  server: 'wss://s1.ripple.com' // Public rippled server hosted by Ripple, Inc.
});
api.on('error', (errorCode, errorMessage) => {
  console.log(errorCode + ': ' + errorMessage);
});
api.on('connected', () => {
  console.log('connected');
});
api.on('disconnected', (code) => {
  // code - [close code](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent) sent by the server
  // will be 1000 if this was normal closure
  console.log('disconnected, code:', code);
});


// Declare functions as async
async function  cancelOrder(orderSequence) {
  console.log('Cancelling order: ' + orderSequence.toString());
  let prepared = await api.prepareOrderCancellation(address, {orderSequence}, instructions);

  let signing = api.sign(prepared.txJSON, secret);

  try {
    let result = await api.submit(signing.signedTransaction);
  } catch (submitError) {
    console.log("Submit Error");
    console.log(submitError);
  }
}

async function cancelAllOrders(orderSequences) {
  if (orderSequences.length === 0) {
    return Promise.resolve();
  }

  for (let i = 0; i < orderSequences.length; i++) {
    let orderSequence = orderSequences[i];
    await cancelOrder(orderSequence);
  }


}

// begin async code
(async () => {

await api.connect();


let orders = await api.getOrders(address);

let orderSequences = orders.map(order => order.properties.sequence);

await cancelAllOrders(orderSequences);

var theresponse = await fetch(url);
var thebody = await theresponse.text();

try {
  //let json = JSON.parse(theresponse.body);
  // do something with JSON
  //console.log(thebody);
  //console.log(theresponse.text());
  var searchxrpprice = await new RegExp('[0-9]+\.[0-9]+');
  //console.log('Test regex ${body}:'+searchxrpprice.test(thebody));
  var xrpprice = await searchxrpprice.exec(thebody);
  //console.log("The $xrpprice is: "+xrpprice);
  var thexrpprice = await searchxrpprice.exec(xrpprice[0]);
  console.log("The XRP price in Canadian dollars is: " + thexrpprice[0]);

} catch (jsonError) {
  console.log("coingecko Json Error");
  console.log(jsonError);
}

try {

  let options = {
    'method': 'GET',
    'url': 'https://www.goldapi.io/api/XAG/CAD',
    'headers': {
      'x-access-token': 'SECRET',
      'Content-Type': 'application/json'
    }};

  let resp = await request(options);
  console.log("$resp is: "+resp);
  //if (error) throw new Error(error);
  //Create new variable called data to hold the response's body
  var data = resp;
  console.log("$data is: "+data); //Here is where the script prints out to the console last

  //Regular expression to find the price from the goldapi.io response
  //Find the price data in the form of "price":31.121655
  var searchcadpriceregex = new RegExp('\"price\":([0-9]+\.[0-9]+)');
  console.log("Test regex ${data}:"+cadpriceregex.test(data));
  console.log("Past the regex test line.  Onto storing the $data in an array"); //Doesn't print out to the console, instead the "Gold api error" message is logged to the console from the catch block
  //Store the matched data to an array
  var searchcadpricearray = searchcadpriceregex.exec(data);
  console.log("$searchcadpricearray[0]: "+searchcadpricearray[0]);
  //Regular expression to find the price of silver in CAD
  var cadpriceregex = new RegExp('([0-9]+.[0-9]+)');
  //Store the integer as cadprice
  var cadprice = cadpriceregex.exec(searchcadpricearray[0]);
  console.log("The CAD price of silver is: " + cadprice[0]);
  //console.log(response.body);

  var premium = Number(5.50);

  var sellingsilverfor = Number(cadprice[0]) + premium;

  console.log("Selling silver for: " + sellingsilverfor);

  var xrpxagprice = sellingsilverfor / Number(thexrpprice[0]);
  console.log("The XRP/XAG price is: " + xrpxagprice);

  var trimxrpxagpriceregex = new RegExp('([0-9]+.[0-9]{3})');
  let trimxrpxagprice = trimxrpxagpriceregex.exec(xrpxagprice);
  console.log("The XRP/XAG price to 3 decimal places is: " + trimxrpxagprice[0]);

  let xrppriceindrops = trimxrpxagprice[0] * 1000000;
  console.log("The price in drops is: " + xrppriceindrops);

} catch (requestError) {
  console.log("Gold api error");
}

await api.disconnect();

})(); // end async code then call it

console.log('end of script');

 

Link to post
Share on other sites

Just change 
 

var data = resp;
// to
var data = JSON.parse(resp);

Then access data as an object. 

You don't even need to bother with creating multiple variables such as
let price = data.price; // and so on

just
console.log(data.price);

Also there is no array in the json output. It's an object. 

Edited by jargoman
Link to post
Share on other sites
8 hours ago, TaylorWarden said:

I changed the function lines to include async before function and I added a '}' which was missing, and now I am receiving an even more cryptic error message about module.js throwing an error about 'request'-promise.'  I tried to add the code to the forum with a [code][/code] tag but it didn't take; What's up with that too?
 

 

I think you are looking for these lines:

// 'GET' without specific headers  
const json = await fetch(url).then(res => res.json());

// 'GET' with specific headers
const data = await fetch('https://www.goldapi.io/api/XAG/CAD', {
  'method': 'GET',
  'headers': {
    'x-access-token': 'SECRET',
    'Content-Type': 'application/json'
  }
}).then(res => res.json());

It is a bit mixed, the 'await' and also using 'then'. You can also use a 2nd await, but that would require another line with another variable. So this seems short and clear

Link to post
Share on other sites

Thank you for your responses @jargoman& @jn_r! :)  I am receiving a ReferenceError in my code for the xrppriceindrops variable I have defined.  Is this because it fell out of scope or is it throwing this because of some other reason?

I now realize that because my Virtual Machine is scaled down to a really small resolution that the full menu for this forum editor isn't showing the insert code functionality. 

Quote

tw@tw-VirtualBox:~/Downloads/my_ripple_experiment$ node asyncrippletest.js
end of script
(node:4319) Warning: N-API is an experimental feature and could change at any time.
connected
The XRP price in Canadian dollars is: 0.325216
$data.price is: 30.9989
The CAD price of silver is: 30.9989
Selling silver for: 36.4989
The XRP/XAG price is: 112.22971809505067
The XRP/XAG price to 3 decimal places is: 112.229
The price in drops is: 112229000
(node:4319) UnhandledPromiseRejectionWarning: ReferenceError: xrppriceindrops is not defined
    at /home/tw/Downloads/my_ripple_experiment/asyncrippletest.js:157:14
    at <anonymous>
(node:4319) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:4319) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
^Z
[19]+  Stopped                 node asyncrippletest.js
tw@tw-VirtualBox:~/Downloads/my_ripple_experiment$ cat asyncrippletest.js
const RippleAPI = require('ripple-lib').RippleAPI;

// npm install node-fetch@2.6.0
const fetch = require('node-fetch');

const address = "rG83NMzArGuNPWyVyumuQLkj3EVJsrkDbA";

const secret = '';

const instructions = {maxLedgerVersionOffset: 5};

const https = require('https');

const request = require("request-promise");

let url = "https://api.coingecko.com/api/v3/simple/price?ids=ripple&vs_currencies=cad";

const api = new RippleAPI({
  server: 'wss://s1.ripple.com' // Public rippled server hosted by Ripple, Inc.
});
api.on('error', (errorCode, errorMessage) => {
  console.log(errorCode + ': ' + errorMessage);
});
api.on('connected', () => {
  console.log('connected');
});
api.on('disconnected', (code) => {
  // code - [close code](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent) sent by the server
  // will be 1000 if this was normal closure
  console.log('disconnected, code:', code);
});


// Declare functions as async
async function  cancelOrder(orderSequence) {
  console.log('Cancelling order: ' + orderSequence.toString());
  let prepared = await api.prepareOrderCancellation(address, {orderSequence}, instructions);

  let signing = api.sign(prepared.txJSON, secret);

  try {
    let result = await api.submit(signing.signedTransaction);
  } catch (submitError) {
    console.log("Submit Error");
    console.log(submitError);
  }
}

async function cancelAllOrders(orderSequences) {
  if (orderSequences.length === 0) {
    return Promise.resolve();
  }

  for (let i = 0; i < orderSequences.length; i++) {
    let orderSequence = orderSequences[i];
    await cancelOrder(orderSequence);
  }


}

// begin async code
(async () => {

await api.connect();


let orders = await api.getOrders(address);

let orderSequences = orders.map(order => order.properties.sequence);

await cancelAllOrders(orderSequences);

var theresponse = await fetch(url);
var thebody = await theresponse.text();

try {
  //let json = JSON.parse(theresponse.body);
  // do something with JSON
  //console.log(thebody);
  //console.log(theresponse.text());
  var searchxrpprice = await new RegExp('[0-9]+\.[0-9]+');
  //console.log('Test regex ${body}:'+searchxrpprice.test(thebody));
  var xrpprice = await searchxrpprice.exec(thebody);
  //console.log("The $xrpprice is: "+xrpprice);
  var thexrpprice = await searchxrpprice.exec(xrpprice[0]);
  console.log("The XRP price in Canadian dollars is: " + thexrpprice[0]);

} catch (jsonError) {
  console.log("coingecko Json Error");
  console.log(jsonError);
}

try {

  let options = {
    'method': 'GET',
    'url': 'https://www.goldapi.io/api/XAG/CAD',
    'headers': {
      'x-access-token': 'SECRET',
      'Content-Type': 'application/json'
    }};

  let resp = await request(options);
  //console.log("$resp is: "+resp);
  //if (error) throw new Error(error);
  //Create new variable called data to hold the response's body
  var data = JSON.parse(resp);
  //console.log("$data is: "+data);
  console.log("$data.price is: "+data.price);
  //Regular expression to find the price from the goldapi.io response
  //Find the price data in the form of "price":31.121655
  //var searchcadpriceregex = new RegExp('\"price\":([0-9]+\.[0-9]+)');
  //console.log("Test regex ${data}:"+cadpriceregex.test(data.price));
  //console.log("Past the regex test line.  Onto storing the $data in an array");
  //Store the matched data to an array
  //var searchcadpricearray = searchcadpriceregex.exec(data.price);
  //console.log("$searchcadpricearray[0]: "+searchcadpricearray[0]);
  //Regular expression to find the price of silver in CAD
  //var cadpriceregex = new RegExp('([0-9]+.[0-9]+)');
  //Store the integer as cadprice
  //var cadprice = cadpriceregex.exec(searchcadpricearray[0]);
  console.log("The CAD price of silver is: " + data.price);
  //console.log(response.body);

  var premium = Number(5.50);

  var sellingsilverfor = Number(data.price) + premium;

  console.log("Selling silver for: " + sellingsilverfor);

  var xrpxagprice = sellingsilverfor / Number(thexrpprice[0]);
  console.log("The XRP/XAG price is: " + xrpxagprice);

  var trimxrpxagpriceregex = new RegExp('([0-9]+.[0-9]{3})');
  let trimxrpxagprice = trimxrpxagpriceregex.exec(xrpxagprice);
  console.log("The XRP/XAG price to 3 decimal places is: " + trimxrpxagprice[0]);

  let xrppriceindrops = trimxrpxagprice[0] * 1000000;
  console.log("The price in drops is: " + xrppriceindrops);

} catch (requestError) {
  console.log("Gold api error");
}

var order = {
  "direction": "sell",
  "quantity": {
    "currency": "XAG",
    "counterparty": "rVSB2uzC9cjKfoMQdpQW78qUdSkdHiU4y",
    "value": "15"
  },
  "totalPrice": {
    "currency": "drops",
    "value": xrppriceindrops
  },
  "passive": false,
  "fillOrKill": true
};
return api.prepareOrder(address, order)
  .then(prepared => {
console.log(prepared);
var txJSON = prepared.txJSON;

console.log(txJSON);
var signresponse = api.sign(txJSON, secret);
//console.log(signresponse);
var signedtxn = signresponse.signedTransaction;
console.log("The signedTransaction is: "+signedtxn);
//submit the transaction
//api.submit(signedtxn);

}).catch(console.error);


await api.disconnect();

})(); // end async code then call it

console.log('end of script');

 

Link to post
Share on other sites
5 hours ago, TaylorWarden said:

Thank you for your responses @jargoman& @jn_r! :)  I am receiving a ReferenceError in my code for the xrppriceindrops variable I have defined.  Is this because it fell out of scope or is it throwing this because of some other reason?

I now realize that because my Virtual Machine is scaled down to a really small resolution that the full menu for this forum editor isn't showing the insert code functionality. 

 

It fell out of scope. It is defined in the try {} block above so you should define it before that block if you want to also use it outside that block

Link to post
Share on other sites

I am so near completing this project now.  When I run the script, it hangs and I need to press ctrl+z to stop the process.  It signs and submits the transaction successfully though! :D  I just had to go back and multiply the xrppriceindrops by the amount I have hard coded in the amount section of the offer for the XAG IOUs to sell.

I'm putting the script on GitHub and attributing both of you for your help and linking back to this thread for posterity.

 

Link to post
Share on other sites
6 minutes ago, TaylorWarden said:

I am so near completing this project now.  When I run the script, it hangs and I need to press ctrl+z to stop the process.  It signs and submits the transaction successfully though! :D  I just had to go back and multiply the xrppriceindrops by the amount I have hard coded in the amount section of the offer for the XAG IOUs to sell.

I'm putting the script on GitHub and attributing both of you for your help and linking back to this thread for posterity.

 

Does it print end of script?

Link to post
Share on other sites

You should also change 

return api.prepareOrder(address, order)
  .then(prepared => {
console.log(prepared);
var txJSON = prepared.txJSON;

console.log(txJSON);
var signresponse = api.sign(txJSON, secret);
//console.log(signresponse);
var signedtxn = signresponse.signedTransaction;
console.log("The signedTransaction is: "+signedtxn);
//submit the transaction
//api.submit(signedtxn);

}).catch(console.error);


To

try {
let prepared = await api.prepareOrder(address, order);
  console.log(prepared);

let txJSON = prepared.txJSON;
console.log(txJSON);

let signresponse = api.sign(txJSON, secret);
//console.log(signresponse);

var signedtxn = signresponse.signedTransaction;
console.log("The signedTransaction is: "+signedtxn);

//submit the transaction
//let submitResp = await api.submit(signedtxn);
//console.log(submitResp);

} catch (orderError) {
  console.log("Order Error : ");
  console.log(orderError);
}

There's nothing wrong with your code except again it's running asynchronously and api.disconnect is being called at the same time as api.sign and submit. It may work but the connection is being closed prematurely, you should be waiting for the response before terminating. Also it may not work every time.  

Link to post
Share on other sites
4 minutes ago, TaylorWarden said:

Yes, that is the very first output to the console before the async code runs.

Sorry my bad it's supposed to be inside the async code. Notice that the end of the script executes first. move end of script to the line directly after api.disconect();

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.