Coder Social home page Coder Social logo

xrplf / xrpl.js Goto Github PK

View Code? Open in Web Editor NEW
1.2K 203.0 499.0 49.4 MB

A JavaScript/TypeScript API for interacting with the XRP Ledger in Node.js and the browser

Home Page: https://xrpl.org/

JavaScript 3.50% TypeScript 96.50%
ripple xrp-ledger javascript api xrp blockchain typescript rippleapi xrpl nodejs

xrpl.js's Introduction

xrpl.js

A JavaScript/TypeScript library for interacting with the XRP Ledger

NPM npm bundle size

This is the recommended library for integrating a JavaScript/TypeScript app with the XRP Ledger, especially if you intend to use advanced functionality such as IOUs, payment paths, the decentralized exchange, account settings, payment channels, escrows, multi-signing, and more.

➡️ Reference Documentation

See the full reference documentation for all classes, methods, and utilities.

Features

  1. Managing keys & creating test credentials (Wallet && Client.fundWallet())
  2. Submitting transactions to the XRP Ledger (Client.submit(...) & transaction types)
  3. Sending requests to observe the ledger (Client.request(...) using public API methods)
  4. Subscribing to changes in the ledger (Ex. ledger, transactions, & more...)
  5. Parsing ledger data into more convenient formats (xrpToDrops and rippleTimeToISOTime)

All of which works in Node.js (tested for v16+) & web browsers (tested for Chrome).

Quickstart

Requirements

  • Node.js v16 is recommended. We also support v18 and v20. Other versions may work but are not frequently tested.

Installing xrpl.js

In an existing project (with package.json), install xrpl.js with:

$ npm install --save xrpl

Or with yarn:

$ yarn add xrpl

Example usage:

const xrpl = require("xrpl");
async function main() {
  const client = new xrpl.Client("wss://s.altnet.rippletest.net:51233");
  await client.connect();

  const response = await client.request({
    command: "account_info",
    account: "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe",
    ledger_index: "validated",
  });
  console.log(response);

  client.disconnect();
}
main();

For a more in-depth example, you can copy/forking this Code Sandbox template!
https://codesandbox.io/s/xrpl-intro-pxgdjr?file=/src/App.js

It goes through:

  1. Creating a new test account
  2. Sending a payment transaction
  3. And sending requests to see your account balance!

Case by Case Setup Steps

If you're using xrpl.js with React or Deno, you'll need to do a couple extra steps to set it up:

Documentation

As you develop with xrpl.js, there's two sites you'll use extensively:

  1. xrpl.org is the primary source for:
  2. js.xrpl.org has the reference docs for this library

Mailing Lists

If you want to hear when we release new versions of xrpl.js, you can join our low-traffic mailing list (About 1 email per week):

If you're using the XRP Ledger in production, you should run a rippled server and subscribe to the ripple-server mailing list as well.

Asking for help

One of the best spots to ask for help is in the XRPL Developer Discord - There's a channel for xrpl.js where other community members can help you figure out how to accomplish your goals.

You are also welcome to create an issue here and we'll do our best to respond within 3 days.

Key Links

xrpl.js's People

Contributors

0xclarity avatar ahbritto avatar alandotcom avatar boxbag avatar ckniffen avatar clark800 avatar darkdarkdragon avatar dependabot-preview[bot] avatar dependabot[bot] avatar elmurci avatar emschwartz avatar fksripple avatar fredkschott avatar geertweening avatar intelliot avatar jatchili avatar jst5000 avatar justinr1234 avatar justmoon avatar khancode avatar ledhed2222 avatar mduo13 avatar mukulljangid avatar mvadari avatar natenichols avatar shekenahglory avatar sublimator avatar vhpoet avatar wilsonianb avatar wltsmrz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

xrpl.js's Issues

Transaction succeed,but return error

I submit transaction, the transaction is success,but return a error to me.
some code like this:
var _amount = Amount.from_human(amount + currency); // 100CNY or 100XRP

if (currency != 'XRP') _amount.set_issuer(CONST.GATEWAY_ADDR);
else _amount.set_issuer(_from);

var tx = _remote.transaction();

tx.payment({
  from: _from,
  to: payto,
  amount: _amount
});

tx.submit(function (txerr, res) {
if (txerr) {
//log txerr ==RippleError: Path could not send partial amount
//res is undefined
}
});

I get message is RippleError: Path could not send partial amount;
But transaction succeed. why?
This led me to repeatedly send IOU to my users,How can I avoid this situation?

Amount rounding

Currently Amount.to_human() with a precision of 0 rounds 49.999 to 49 . It should round to the nearest integer. 3.4 => 3, 3.5 => 4, 3.6 => 4.

Submitting transactions with parameter object

It would be great to be able to submit transactions with a parameter object instead of as individual parameters to functions like transaction.payment() and transaction.offer_create(). Particularly with offer_create(), getting the order wrong would result in submitting an offer that is exactly the opposite of what you want.

It would also be more intuitive to submit offers with the phrasing "buy/sell" or "get/give" and have the library convert that into "TAKER_PAYS/TAKER_GIVES" automatically.

Explain more clearly who might want this, for what, and how this fits into the ecosystem.

Now that there are so many ripple repositories, it would help to clarify, both in README.md and perhaps even in the github description (now "JS library for talking to the Ripple API"), how this repo fits in, for folks that aren't up to speed with all the parts and technologies. Who would want it, what are some very high-level examples of how different kinds of users might use it, what other repos require it, etc.

E.g. the info at https://ripple.com/wiki/Rippled_setup_instructions is helpful for those just browsing (and would also be useful if excerpted for the rippled README.md).

Perhaps just moving the link to https://ripple.com/wiki/Ripple_JavaScript_library which is already in the README.md up higher into the intro (rather than where it can get overlooked below links to more in-depth info) would help, along with excerpting the Overview.

Bobby Sharp's Laws of LastLedgerSequence

  1. CLIENT submits a transaction without a max ledger field == RTS resubmits indefinitely, RTS can use the max ledger field as it sees fit.
  2. CLIENT submits a transaction with a max ledger field == RTS MUST stop resubmitting at that ledger. RTS can NOT change the value of the max ledger field.

Running test on master branch

I cloned the latest version of the master branch today and followed the build instructions. The build was successful but running the tests failed.

npm test

resulted in this npm-debug-log (I'm a novice node/js developer so cant make much sense of it yet)

0 info it worked if it ends with ok
1 verbose cli [ 'c:\Program Files\nodejs\node.exe',
1 verbose cli 'c:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'test' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'pretest', 'test', 'posttest' ]
5 info pretest [email protected]
6 info test [email protected]
7 verbose unsafe-perm in lifecycle true
8 error Error: spawn ENOENT
8 error at errnoException (child_process.js:980:11)
8 error at Process.ChildProcess._handle.onexit (child_process.js:771:34)
9 error If you need help, you may report this log at:
9 error http://github.com/isaacs/npm/issues
9 error or email it to:
9 error [email protected]
10 error System Windows_NT 6.2.9200
11 error command "c:\Program Files\nodejs\node.exe" "c:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "test"
12 error cwd c:\Users\filip\My Documents\GitHub\ripple-lib
13 error node -v v0.10.21
14 error npm -v 1.3.11
15 error syscall spawn
16 error code ENOENT
17 error errno ENOENT
18 verbose exit [ 1, true ]

Amount.multiply(v) and divide(d) compute unexpected results if argument's currency is XRP

I expected Amount's divide() to compute 2 XRP / 50 XRP = 0.04 XRP and multiply() to compute 2 XRP * 3 XRP = 6 XRP, because the currency of the argument to the function, i.e. the second operand in the formula, is ignored.

But the current implementation computes different results if the function argument's currency is XRP. The following tests (coffeescript) fail:

Amount = require('ripple-lib').Amount
expect = require('chai').expect

describe 'ripple Amount', ->
  describe 'divide()', ->
    it 'should compute 2 XRP / 50 XRP = 0.04', ->
      n = Amount.from_human '2 XRP'
      d = Amount.from_human '50 XRP'
      expect(n.divide(d).to_human()).eql '0.04'

  describe 'multiply()', -> 
    it 'should compute 2 XRP * 3 XRP = 6', ->
      a = Amount.from_human '2 XRP'
      b = Amount.from_human '3 XRP'
      expect(a.multiply(b).to_human()).eql '6'

They pass with the diff below applied. It corrects the result by xns_precision or equivalently bi_xns_unit if necessary. I'm unsure what the expected behavior is and if more changes are needed.

diff --git a/src/js/ripple/amount.js b/src/js/ripple/amount.js
index ce740ed..edc0300 100644
--- a/src/js/ripple/amount.js
+++ b/src/js/ripple/amount.js
@@ -318,6 +318,8 @@ Amount.prototype.divide = function (d) {
        _d._value  = _d._value.multiply(consts.bi_10);
        _d._offset -= 1;
    }
+
+      _n._value = _n._value.multiply(consts.bi_xns_unit)
    }

    result              = new Amount();
@@ -484,6 +486,7 @@ Amount.prototype.multiply = function (v) {
    var o1 = this._offset;
    var v2 = v._value;
    var o2 = v._offset;
+    var shift2 = 0;

    if (this.is_native()) {
    while (v1.compareTo(consts.bi_man_min_value) < 0) {
@@ -497,10 +500,11 @@ Amount.prototype.multiply = function (v) {
        v2 = v2.multiply(consts.bi_10);
        o2 -= 1;
    }
+      shift2 = consts.xns_precision;
    }

    result              = new Amount();
-    result._offset      = o1 + o2 + 14;
+    result._offset      = o1 + o2 + 14 - shift2;
    result._value       = v1.multiply(v2).divide(consts.bi_1e14).add(consts.bi_7);
    result._is_native   = this._is_native;
    result._is_negative = this._is_negative !== v._is_negative;

TransactionManager enchancements for ripple-rest and ripple-gateway

ripple-lib should allow asynchronous presubmission hooks for transactions,
that allow deferring until calledback.

Why ?

If it's possible to have multiple transactionIDs what really defines a
a transaction?

Maybe is possible to simply use binary serialization to to create a hash
of all the fields that would be static over a submission lifecycle.

This would be all fields, excluding the following, which float with automated
transaction resubmission:

  • Fee
  • LastLedgerSequence
  • AccountTxnID
  • PreviousTxnID
  • TxnSignature

Unfortunately, this also includes:

  • Sequence

The problem is, with Sequence floating, there's no way of discriminating 2
(or even more) like transactions other than using the SourceTag, which may or
may not be already used.

You can't just inject a ripple-rest specific SourceTag (auto incrementing id
for example) automatically, where it's omitted, as you'd be open to
collisions.

Going forward, well assume that demanding a unique SourceTag for each
transaction is out of the question.

Therefore, you must track all submitted transaction IDs. If you submit a
transaction id BEFORE you save to the database, there's the possibility of
failure to save to the database, and you'd be prone to duplicate submissions.

ripple-lib may need to be updated to allow deferring of submit requests until
submitted transaction ids have been logged.

It's safer to record a transaction ID as submitted and not actually submit it
than submit with a given transaction ID and fail to record it. The ripple-rest
design should be resilient to logged actions that didn't follow through (or
implement robust nuanced logging)

  • Thus all actions must be preceded by database modification.
  • All database actions should use transactions

Duplicate transactions

This only seems to happen once in a blue moon, and I don't have much useful information in my logs. I'm 99% certain that it isn't my script, as transactions are never looped or repeated and the logs show only payment issued by the pay-out function when this occurs.

Configuration looks like this:

  // see the API Reference for available options
    trusted:        true,
    local_signing:  true,
    local_fee:      false,
    servers: [
      {
          host:    's1.ripple.com'
        , port:    443
        , secure:  true
      }
  ]

I wish I could give you more, except to say it's a rare, intermittent occurrence.

Has anyone else run into this? I see one previous issue and it's been closed.

OrderBook bug

screen shot 2014-02-21 at 4 10 07 pm

rippled notifies order book subscribers of any affecting transactions, via
sending "type":"transaction" message.

The Remote class keeps a taker_gets/taker_pays keyed cache of OrderBook
classes. When a transaction message is received it iterates over all the offers
in the metadata, to find one or more books affected (1), and notifies any cached
OrderBooks (2).

The problem seems to be that each order book assumes that any and all offers are
matching the taker_gets/taker_pays of the orderbook. In fact, the transaction
could be a payment with multiple currency conversions (3).

See ripple-client: (4)

this project makes me get a headache

i have to say, this project is the most confusing one i've ever touched. sorry for that, but i must say it.

'ripple-lib connects to the Ripple network via the WebSocket protocol and runs in Node.js as well as in the browser.'

it says this project can run in browser as well, but all demos are wrote for node! how to run in the browser?

ok, then i found a demo for browser finally on your wiki, and it works, but that is just the most basic connection demo!

how can i call Amount.from_human?

var amount = new ripple.Amount(); var buy_amount = amount.from_human('1000XRP') never works! but it should be that as demo for node.

ok, your website should work with this lib.

when i check codes on ripple.com/client, ok, i'm dead, it's just a mess!

i just want a js lib that works in browser, and when i put it in pages, call some functions, then all work! that's it, that's all! i do not have a linux, i do not have npm installed! and wtf is grunt???

sorry again for that, but it really makes me get a headache

Ripple use what kind of date format?

I use request_account_tx to get transaction records?
In the response json contain date like:
"date": 442209610

It's not UTC, I want to ask it's what kind of date format and how to transmit to current time in node.js?

[Bug] Callback on connect

https://github.com/ripple/ripple-lib/tree/5b0dd33fa87fd3386ad42bf7ed93adaa1a3e7c2e
Will call the callback on connect

However,

https://github.com/ripple/ripple-lib/tree/bdb299e085b75dcda534d7580588669ba26634c6
will not (which is a newer commit)

Blobvault is dependent on this callback to happen

This is some source code you can try to illustrate

First

1.  npm install https://github.com/ripple/ripple-lib/archive/bdb299e085b75dcda534d7580588669ba26634c6.tar.gz

var RL = require('ripple-lib');
var ripplelib = {
    trusted:        true,
    servers: [
    {
    host: 's1.ripple.com'
    , port:    443
    , secure:  false
    }]
}
var remote = new RL.Remote(ripplelib);
remote.connect(function() {
    console.log("I'm connected!")
});

Then try the older version here

2. npm install https://github.com/ripple/ripple-lib/archive/5b0dd33fa87fd3386ad42bf7ed93adaa1a3e7c2e.tar.gz

And rerun this

This will call the callback but the first will not.

ripple-lib on npm is out of date

The available package on NPM is currently out of date and missing critical fixes. Expectation is that the package is kept up to date with the latest release. Propose, keep the package up to date with official releases or unpublish and point people to the git repository.

how to create a payment transaction with XRP ?

i have been successfully creating payment transaction from IOU 2 IOU but i have issues dealing with XRP -

if i want to buy XRP with some IOU i should specify Amount: (some integer string) as XRP

for example Amount:"100000"

but i get

invalid Amoun Type as error.

so i change it to Amount: Amount.from_human("100XRP")

expecting this should work .. but it give me

XRP may not be specified as object error..

then i read some issues on this, thought i should give XRP an issuer .. but it still does not work .....

it now gives std:bad_cast as error ..

plz help ..

Some error while cleaning self trust line

I had issue with offers and self trust lines - ripple/ripple-client#538
I tried to clear the self trust line using the node rsign.js from ripple-lib but stack with error.

put data into command
node rsign.js $Belarus_SECRET $json_TrustSet

'{"Account":"rBztYvjByTk1DsokHb28bGS2SAPJTkQd2A","Fee":"10","Flags":0,"Sequence":45,"TransactionType":"TrustSet","LimitAmount":{"currency":"BYC","issuer":"rBztYvjByTk1DsokHb28bGS2SAPJTkQd2A","value":"0"}}'

got tx_blob - [1200142200000000240000002D638000000000000000000000000000000000000000425943000000000078A3FFF3A91C3533D793EB5236CC0A3991F8562B68400000000000000A73210286E69311019AFDE1D54EE7324E525ED7617960F7390855DD6EEBA19C3BDA6B72744730450220650F0004D2B8FC8C36CA6AD99EB0BA205F34F6015266706D0CAF666E3D82A000022100E38E3FEECDDF4366E27DCF762D2EE0AF2278A78BE9E4930E7A912544A7AF4993811478A3FFF3A91C3533D793EB5236CC0A3991F8562B]"

ready send self trust clearing command
node rsign.js -v $Belarus_SECRET $json_TrustSet
{
"tx_blob": "[...same big hex number...]",
"tx_json": {
"Account": "rBztYvjByTk1DsokHb28bGS2SAPJTkQd2A",
"Fee": "10",
"Flags": 0,
"Sequence": 45,
"TransactionType": "TrustSet",
"LimitAmount": {
"currency": "BYC",
"issuer": "rBztYvjByTk1DsokHb28bGS2SAPJTkQd2A",
"value": "0"
},
"SigningPubKey": "[...hex number...]",
"TxnSignature": "[...hex number...]"
},
"tx_signing_hash": "[...hex number...]",
"tx_unsigned": "[...hex number...]"
}

sending:
node rsign.js -v sxx..............xxx ' { "tx_blob": "[1200142200000000240000002D638000000000000000000000000000000000000000425943000000000078A3FFF3A91C3533D793EB5236CC0A3991F8562B68400000000000000A73210286E69311019AFDE1D54EE7324E525ED7617960F7390855DD6EEBA19C3BDA6B72744730450220650F0004D2B8FC8C36CA6AD99EB0BA205F34F6015266706D0CAF666E3D82A000022100E38E3FEECDDF4366E27DCF762D2EE0AF2278A78BE9E4930E7A912544A7AF4993811478A3FFF3A91C3533D793EB5236CC0A3991F8562B]", "tx_json": { "Account": "rBztYvjByTk1DsokHb28bGS2SAPJTkQd2A", "Fee": "10", "Flags": 0, "Sequence": 45, "TransactionType": "TrustSet", "LimitAmount": { "currency": "BYC", "issuer": "rBztYvjByTk1DsokHb28bGS2SAPJTkQd2A", "value": "0" }, "SigningPubKey": "[1200142200000000240000002D638000000000000000000000000000000000000000425943000000000078A3FFF3A91C3533D793EB5236CC0A3991F8562B68400000000000000A73210286E69311019AFDE1D54EE7324E525ED7617960F7390855DD6EEBA19C3BDA6B72744730450220650F0004D2B8FC8C36CA6AD99EB0BA205F34F6015266706D0CAF666E3D82A000022100E38E3FEECDDF4366E27DCF762D2EE0AF2278A78BE9E4930E7A912544A7AF4993811478A3FFF3A91C3533D793EB5236CC0A3991F8562B]", "TxnSignature": "[1200142200000000240000002D638000000000000000000000000000000000000000425943000000000078A3FFF3A91C3533D793EB5236CC0A3991F8562B68400000000000000A73210286E69311019AFDE1D54EE7324E525ED7617960F7390855DD6EEBA19C3BDA6B72744730450220650F0004D2B8FC8C36CA6AD99EB0BA205F34F6015266706D0CAF666E3D82A000022100E38E3FEECDDF4366E27DCF762D2EE0AF2278A78BE9E4930E7A912544A7AF4993811478A3FFF3A91C3533D793EB5236CC0A3991F8562B]" }, "tx_signing_hash": "[1200142200000000240000002D638000000000000000000000000000000000000000425943000000000078A3FFF3A91C3533D793EB5236CC0A3991F8562B68400000000000000A73210286E69311019AFDE1D54EE7324E525ED7617960F7390855DD6EEBA19C3BDA6B72744730450220650F0004D2B8FC8C36CA6AD99EB0BA205F34F6015266706D0CAF666E3D82A000022100E38E3FEECDDF4366E27DCF762D2EE0AF2278A78BE9E4930E7A912544A7AF4993811478A3FFF3A91C3533D793EB5236CC0A3991F8562B]", "tx_unsigned": "[1200142200000000240000002D638000000000000000000000000000000000000000425943000000000078A3FFF3A91C3533D793EB5236CC0A3991F8562B68400000000000000A73210286E69311019AFDE1D54EE7324E525ED7617960F7390855DD6EEBA19C3BDA6B72744730450220650F0004D2B8FC8C36CA6AD99EB0BA205F34F6015266706D0CAF666E3D82A000022100E38E3FEECDDF4366E27DCF762D2EE0AF2278A78BE9E4930E7A912544A7AF4993811478A3FFF3A91C3533D793EB5236CC0A3991F8562B]" } '

got error massage:

C:\Windows\System32\node_modules\ripple-lib\src\js\transaction.js:188
if (undefined === tx_json.Fee && this.remote.local_fee) {
^
TypeError: Cannot read property 'local_fee' of undefined
at Transaction.complete (C:\Windows\System32\node_modules\ripple-lib\src\js
transaction.js:188:47)
at Object. (C:\Windows\System32\node_modules\ripple-lib\bin\rsign
.js:44:8)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3

Same happen under linux.
For me is not so important to get rid of selftrust, but understand how to use rsign.js

if this report was valuable please send some XRP for non-profit P2P Time Bank
r4hZtWkSW8EbeFG5QXqB7ohohkrZg8zLQ8

not allowing XRP as part of an offer

When I go:
var takerPays=Amount.from_json("100/BTC/rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B");
var takerGets=Amount.from_json("20/USD/rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B");

transaction.offer_create(order.pubKey,takerPays,takerGets);

it is fine but if instead I go:
var takerPays=Amount.from_json("100/XRP");
var takerGets=Amount.from_json("20/USD/rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B");
transaction.offer_create(order.pubKey,takerPays,takerGets);

it throws:

TypeError: Error serializing "TakerPays": Cannot read property 'length' of null
at SerializedObject.append (node_modules\ripple-lib\src\js\ripple\serializedobject.js:115:24)
at exports.Amount.SerializedType.serialize (node_modules\ripple-lib\src\js\ripple\serializedtypes.js:348:10)

transaction.offer_create(order.pubKey,takerPays,takerGets);

Get a error when submitting a trade offer to the network.

/* Loading ripple-lib Remote and Amount modules in Node.js */ 
var Remote = require('ripple-lib').Remote;
var Amount = require('ripple-lib').Amount;

/* Loading ripple-lib Remote and Amount modules in a webpage */
// var Remote = ripple.Remote;
// var Amount = ripple.Amount;

var MY_ADDRESS = 'rrrMyAddress';
var MY_SECRET  = 'secret';

var BUY_AMOUNT = Amount.from_human('100XRP');
var SELL_AMOUNT = Amount.from_human('1USD');

var remote = new Remote({ /* Remote options */ });

remote.connect(function() {
  remote.set_secret(MY_ADDRESS, MY_SECRET);

  var transaction = remote.transaction();

  transaction.offer_create({
    from: MY_ADDRESS, 
    buy: BUY_AMOUNT, 
    sell: SELL_AMOUNT
  });

  transaction.submit(function(err, res) {
    /* handle submission errors / success */
  });
});

I run the demo code with my ripple address and secret, but got this error.

TypeError: Error serializing "TakerGets": Cannot read property 'length' of null

Hash160 fields which should have json string representation of hex use base58

{
"TakerGetsCurrency": "rrrrrrrrrrrrrpEbg48c88zPDvqQjU",
"TakerGetsIssuer": "rNPRNzBB92BVpAhhZr4iXDTveCgV5Pofm9",
"TakerPaysCurrency": "rrrrrrrrrrrrrrrrrrrrrhoLvTp",
"TakerPaysIssuer": "rrrrrrrrrrrrrrrrrrrrrhoLvTp"
}

The above is taken from some ledger dumps created using ripple-lib, with 160 bits rendered as account ids.
(Those fields are the only ones which use the STHash160 type)

The correct json serialization is a hex string:

Remote config validation

If a port is specified in the host string as well as via port a less than useful invalid string error is raised.

In general we should validate and present useful programmer time saving information

Use VER_ACCOUNT_PRIVATE for remote.set_secret

Related to #76 #73

There was a recent patch merged, fixing Seed.get_key to honor passed account id arguments (finding the KeyPair matching the account id). Unfortunately this had the side effect of making it impossible to use seeds matching a RegularKey.

Note the following two lines in transaction.js which pass along the tx_json.Account to seed.get_key

With regard to Seed.get_key(account_id): generating multiple keyPairs per seed is somewhat pointless if you're just going to be passing around the seed anyway.

It seems it may be possible to fix the regression, and actually make it sensible to use multiple accounts per seed, if we allowed passing a VER_ACCOUNT_PRIVATE base58 encoded secret key to remote.set_secret, and skip altogether any tx_json.Account checks (or requesting the RegularKey from the network)

I propose, for discussion, the following changes:

  • remote.set_secret, in the background stores cached KeyPair objects
  • remote.set_secret(account, seed) takes the first KeyPair from the seed
  • remote.set_secret(account, privateKey) generates a KeyPair using KeyPair.from_bn_secret
  • add a remote.keyPairs in lieu of remote.secrets
  • if you use a RegularKey, you must use VER_ACCOUNT_PRIVATE to set the secret
  • rsign be updated to allow use of private key as well as seed

I haven't given this a great deal of thought, but there definitely needs to be some improvement in this area. See

removeListener for order books does not unsubscribe from the rippled feed

calling book.removeListener('model', modeListener) does not result in an unsubscribe message being sent to the remote server.

In addition, subscribing to an order book results in the creation of a prepare_subscribe function on the remote server, that gets called every time the remote reconnects, resulting in 'subscribe' calls being sent to the server for order books that are no longer wanted.

logic should be added to remove the unwanted prepare_subscribe functions from the remote when the user unsubscribes from an order book.

TransactionManager timeout handling (and non subscription based validated clearing)

For whatever reason, there's no guarantee you'll get a submit response or transaction subscription notification, for a given submit, that will ultimately be successful.

Currently account_tx sweeps are only ever done on disconnect, and in a non systematic way, requesting the last 100 transactions (including outbound / inbound transactions)

Reporting that a transaction has timed out, when it's in fact successful could potentially cause people to manually resubmit. Transactions should be resubmitted until a final result has been determined.

ripple-lib should periodically do sweeps of ledger ranges, using account_tx, to clear transactions that had no submit response/notification.

It should only really report timeouts (tejLost for example) when transactions are submitted using LastLedgerSequence.

If remote.connect fails to validate SSL certificate, does not throw an error

I had a client trying to secure connect to a websockets server. However, the hostname and certificate had a mismatch, which caused the client to repeatedly disconnect and attempt to reconnect. rippled server logs include repeated entries that include this when the client disconnects and reconnects:

2014-Apr-16 18:11:00 WebSocket:ERR Error reading HTTP request. code: asio.ssl:335544539

It would better if ripple-lib emitted an error event rather than repeatedly trying to connect to a host with a mismatched certificate.

Memory Leaks Audit

Things like:

The above would likely take quite some time to cause an issue, but it's just an example of the things we should look for. ripple-lib evolved mostly for use in the client but will soon be used in ripple-rest / ripple-gateway.

When a TransactionQueue becomes empty, it might be reasonable to empty the cache of transactions and sequences?

Transactions sometimes fail and sometimes say they fail when they succeed - any idempotent way to resubmit manually?

I apologize ahead of time that I'm not familiar with the inner workings of ripple-lib. I'm trying to get automated payments working. My code is pretty boilerplate.

var remote = new rpRemote({
  trusted:        true,
  local_signing:  true,
  local_fee:      true,
  fee_cushion:     1.5,
  servers: [
    {
        host:    's1.ripple.com'
      , port:    443
      , secure:  true
    }
  ]
});

var JR_ADDRESS = 'blah';
var JR_SECRET  = 'blah';
remote.set_secret(JR_ADDRESS, JR_SECRET);.


remote.connect(function() {
    var transaction = remote.transaction();

    transaction.payment({
        from:       JR_ADDRESS,
        to:         address,
        amount:     rpAmount.from_human(amount + 'XRP')
    });

    transaction.submit(function(err, res) { /* do stuff */ });
});

Sometimes -- just once in a while -- transactions just will spit out an error but eventually succeed; sometimes, transactions say error and actually fail. In either case, I get this:

{ result: 'tejLost',
  result_message: 'Transaction lost',
  message: 'Transaction lost' }

... and have no way to tell what actually happened.

I can't be too clever about this and try to resubmit on error a few times, because it might result in duplicate transactions.

Is there no idempotent way of issuing this command? Can I glean some id from this and check transaction status later? I've looked over the documentation and haven't found much detail.

Error submitting transaction with parameter object

When I try to submit a payment transaction using the form:

transaction.payment({
            from: SENDER,
            to: RECEIVER,
            amount: AMOUNT
        });

I get the error copied below, even though there is no problem when I submit it using the form:

transaction.payment(SENDER, RECEIVER, AMOUNT);

and UInt160.is_valid(SENDER) and UInt160.is_valid(RECEIVER) both return true.

This is the error:

/Users/<me>/node_modules/ripple-lib/src/js/ripple/transaction.js:463
    throw new Error('Payment source address invalid');
          ^
Error: Payment source address invalid
    at Transaction.payment (/Users/<me>/node_modules/ripple-lib/src/js/ripple/transaction.js:463:11)
    at Remote.<anonymous> (/Users/<me>/code/ripple/fundAccount/fundaccount.js:42:21)
    at Remote.g (events.js:175:14)
    at Remote.EventEmitter.emit (events.js:92:17)
    at Remote._set_state (/Users/<me>/node_modules/ripple-lib/src/js/ripple/remote.js:312:14)
    at Server.server_connect (/Users/<me>/node_modules/ripple-lib/src/js/ripple/remote.js:269:10)
    at Server.EventEmitter.emit (events.js:92:17)
    at Server._set_state (/Users/<me>/node_modules/ripple-lib/src/js/ripple/server.js:76:14)
    at Server._handle_response_subscribe (/Users/<me>/node_modules/ripple-lib/src/js/ripple/server.js:310:10)
    at Server.<anonymous> (/Users/<me>/node_modules/ripple-lib/src/js/ripple/server.js:43:10)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.