stellar / js-stellar-sdk Goto Github PK
View Code? Open in Web Editor NEWMain Stellar client library for the JavaScript language.
Home Page: https://stellar.github.io/js-stellar-sdk/
License: Apache License 2.0
Main Stellar client library for the JavaScript language.
Home Page: https://stellar.github.io/js-stellar-sdk/
License: Apache License 2.0
credit_alphanum4
is hardcoded:
https://github.com/stellar/js-stellar-sdk/blob/master/src/orderbook_call_builder.js#L14
Actually, do the horizon API really need the asset type ?
When trying to send a transaction and horizon errors.
can someone research this transaction 2051301d6d63edb7e62890f81a01c92260e1066596d42281d8fb1ba5b1d5e4b3
assetCode: �����b�B�x�?#р���?�o� ������ d�������EURR�.���.[��Jw��[L�D��Vj�����=�waE�Hv��'���� @�kT�}�o��n��i�^i5[����z�]Y6@��{ae�Y?9�fA�T��<ύ�Z�Q4�H���c�� rO�
i get this javascript Error: Asset code must be 12 characters at max
When I try to submit a transaction using my system Node (v0.10.35), I get the error
{ type: 'https://stellar.org/horizon-errors/transaction_malformed',
title: 'Transaction Malformed',
status: 400,
detail: 'TODO',
instance: 'horizon-testnet-001.prd.stellar001.internal.stellar-ops.com/dZf7zwqQ7x-000442',
extras: { envelope_xdr: '' } }
which is an error that's supposed to not happen in stellar-sdk 0.2.10+ (https://stellar-public.slack.com/archives/dev/p1443625140002129).
The transaction I was trying to submit worked for both Bartek and Iris.
When I switched to v0.10.40 on Iris's deduction, this problem disappears. We say that stellar-sdk should work as expected on Node v0.10+
we should check all API parameters for correctness to ease in developer debugging
Horizon response for transaction contains ledger
property but _requestFnForLink function overrrides this with a function to call ledger endpoint.
var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
server
.transactions()
.transaction('d03abccc9acd75a8c4ba16a6b31af1e81e4d5432c8a4f801f0ca87a8a35ea8df')
.call()
.then(function(transaction) {
console.log(typeof transaction.ledger); // function
})
Steps to reproduce:
It appears that this is not a general issue of navigation from operation to transaction but rather using a linkhelper on a linkhelper.
It has already been analyzed by Scott:
[from slack] Looks like a bug to me. https://github.com/stellar/js-stellar-sdk/blob/master/src/call_builder.js#L69 should be followed by a call to
_parseResponse
to populate the link helpers on the result <<
LedgerCallBuilder#ledger
currently requires its argument to be a string, but the JSON data for a ledger sequence is of type Number
. To allow using the value from a response, match the API docs for Horizon, and just for least surprise, it would be nice if it accepted a number instead of just a string.
The actual error is when calling url.segment()
in CallBuilder
. It could most easily be solved by calling url.segmentCoded()
instead. If that’s too permissive or broad, though, LedgerCallBuilder#ledger
explicitly convert the input to a string.
For requests for ledgers, transactions, and accounts that don't exist, we should return an error object that rather than the http response.
Copy+paste from Slack
"OK, so I think the problem is in the eventsource polyfiller stellar-sdk is using. It reconnects every 45s, but the url isn’t updated with the new cursor information"
"the polyfiller updates a lastEventId
query parameter, that is the same as what the cursor
should have been but horizon only looks at cursor, so it resends all the previous events"
Support for clients to resolve federated names according to the federation concept.
For my needs the following setup would be sufficient:
As a general library, a more general approach might be reasonable however:
It requires additional webpack config value to work.
_parseRecord(json) {
if (!json._links) {
return json;
}
var self = this;
var linkFn = function (link) {
return function (opts) {
if (link.template) {
let template = URITemplate(link.href);
return self._sendNormalRequest(URI(template.expand(opts)));
} else {
return self._sendNormalRequest(URI(link.href));
}
};
};
Object.keys(json._links).map(function(value, index) {
var link = json._links[value];
json[value] = linkFn(link);
});
return json;
}
would benefit from
linkFn
into something like_requestFnForLink(link) {
return opts => {
...just use this like normal in here...
}
}
var self = this
lodash
to map the valuesRepro: https://jsfiddle.net/u3bsnwt3/1/ Observe Network tab in Dev Tools. Second request to /transactions is always delayed for about 20 seconds. Note: probably you'll be only able to repro this in Chrome.
This function should take in what a user would type into a send form for example a stellar address(ex. [email protected]
) or an accountID(ex. GCFRSK5SBUWDUUDZ7UPWD2WB5HZ7GLZSCQ2HTB3BMXSQ5VGB5PYRTRZP
)
and spit out the accountID and memo resolved by federation or the given accountID or an error.
When I try to run code such as
server.ledgers()
.then(function (page) {
// page 1
console.log(page.records)
return page.next()
})
.then(function (page) {
console.log(page.records)
})
.catch(function(err) {
console.log(err)
})
I get an error
[TypeError: Object #<Server> has no method '_sendLinkRequest']
instead of the next page of results.
The code for stream()
in call_builder.js
is such:
stream(options) {
this.checkFilter();
var es = new EventSource(this.url.toString());
es.onmessage = function (message) {
var result = message.data ? JSON.parse(message.data) : message;
options.onmessage(result);
};
es.onerror = options.onerror;
return es;
}
It parses the message from the stream as JSON, but doesn't run parseRecord
on it to get the links. This means that there's no way to follow the links when streaming.
Actually does it just return the whole federation json reply?
quote from slack:
" However as you require the memoType id
I have some trouble building the memo out of the federation response. StellarSdk.Memo.id(federationRecord.memo)
throws error Expects a int64 as a string. Got 100001
(edited)
ah ok it wants a string."
In Node.js, I can't do this:
import StellarSdk from 'stellar-sdk';
Instead, I have to do this (which is annoying):
import {Account, TransactionBuilder, Memo} from 'stellar-sdk';
I ran this code:
var StellarLib = require('./js-stellar-lib')
var server = new StellarLib.Server({hostname:'horizon-testnet.stellar.org/', secure:true, port: 3000});
server.accounts("gspbxqXqEUZkiCCEFFCN9Vu4FLucdjLLdLcsV6E82Qc1T7ehsTC")
.then(function (accountResult) {
console.log(accountResult);
})
.catch(function (err) {
console.error(err.stack);
})
which should have returned successfully because
curl -X GET 'https://horizon-testnet.stellar.org/accounts/gspbxqXqEUZkiCCEFFCN9Vu4FLucdjLLdLcsV6E82Qc1T7ehsTC'
did so. Instead, I got
{ [NotFoundError: [object Object]]
name: 'NotFoundError',
message:
{ type: 'not_found',
title: 'Resource Missing',
status: 404,
detail: 'The resource at the url requested was not found. This is usually occurs for one of two reasons: The url requested is not valid, or no data in our database could be found with the parameters provided.',
instance: 'horizon-testnet-001.prd.stellar001.internal.stellar-ops.com/hCYL7oezXs-581889' },
data:
{ data:
{ type: 'not_found',
title: 'Resource Missing',
status: 404,
detail: 'The resource at the url requested was not found. This is usually occurs for one of two reasons: The url requested is not valid, or no data in our database could be found with the parameters provided.',
instance: 'horizon-testnet-001.prd.stellar001.internal.stellar-ops.com/hCYL7oezXs-581889' },
status: 404,
statusText: undefined,
headers:
{ 'content-type': 'application/problem+json',
'x-ratelimit-limit': '3600',
'x-ratelimit-remaining': '3590',
'x-ratelimit-reset': '2877',
date: 'Wed, 22 Jul 2015 00:29:51 GMT',
'content-length': '385' },
config:
{ method: 'get',
headers: {},
transformRequest: [Object],
transformResponse: [Object],
url: 'https://horizon-testnet.stellar.org/:3000/ledgers',
withCredentials: undefined } } }
undefined
As we discussed, this indicates two issues
From the doc, a mocha test case has been added to send a transaction:
https://github.com/FredericHeem/js-stellar-sdk/blob/master/test/functional/transaction_send.js
Here is the error:
1) transactions end to end send transaction to itself, Invalid sequence number:
Uncaught TypeError: msecs must be a number
at TLSSocket.Socket.setTimeout (net.js:306:12)
at ClientRequest.<anonymous> (_http_client.js:558:10)
at tickOnSocket (_http_client.js:484:7)
at onSocketNT (_http_client.js:496:5)
node version: v4.1.1
Getting the next page of accounts works as expected, but not payments.
var StellarLib = require('./js-stellar-lib')
var server = new StellarLib.Server({hostname:'horizon-testnet.stellar.org', secure:true, port:443});
server.accounts()
.then(function (accountResults) {
//page 1
console.log(accountResults.records)
return accountResults.next()
})
.then(function (accountResults) {
//page 2
console.log(accountResults.records)
})
.catch(function (err) {
console.log(err)
})
works, but not
var StellarLib = require('./js-stellar-lib')
var server = new StellarLib.Server({hostname:'horizon-testnet.stellar.org', secure:true, port:443});
server.payments()
.then(function (paymentResults) {
//page 1
console.log(paymentResults.records)
return paymentResults.next()
})
.then(function (paymentResults) {
//page 2
console.log(paymentResults.records)
})
.catch(function (err) {
console.log(err)
})
returns the error
[TypeError: Cannot read property 'records' of undefined]
eventsource polyfill doesn’t reconnect when the backend gives a 504
eg. https://stellarchain.io
I know that's what the spec says, but it's still quite an assumption that people are still using www subdomains.
for each operation, we should add tests for
creating operation -> xdr string -> back to operation
returns the expected values
Request timeout support: axios/axios@cc451b3
http://medialize.github.io/URI.js/
Instead of manually construction urls (such as _buildEndpointPath
), we should use a helper library, such as uri.js.
It's brittle and potentially insecure to modify urls as strings, and so we should avoid it if possible
Trying to install stellar-sdk on a ubuntu 16.04 server the below error is displayed. I've installed stellar and horizon from source code. All other packages was installed using apt command.
thanks
Christian
npm install --save stellar-sdk
[email protected] install /home/stellar/test/node_modules/stellar-base/node_modules/ed25519
node-gyp rebuild/bin/sh: 1: node: not found
gyp: Call to 'node -e "require('nan')"' returned exit status 127 while in binding.gyp. while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error:gyp
failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (/usr/share/node-gyp/lib/configure.js:354:16)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 4.4.0-22-generic
gyp ERR! command "/usr/bin/nodejs" "/usr/bin/node-gyp" "rebuild"
gyp ERR! cwd /home/stellar/test/node_modules/stellar-base/node_modules/ed25519
gyp ERR! node -v v4.2.6
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
[email protected] /home/stellar/test
└── (empty)npm WARN [email protected] No repository field.
npm ERR! Linux 4.4.0-22-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "--save" "stellar-sdk"
npm ERR! node v4.2.6
npm ERR! npm v3.5.2
npm ERR! code ELIFECYCLEnpm ERR! [email protected] install:
node-gyp rebuild
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ed25519 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs ed25519
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls ed25519
npm ERR! There is likely additional logging output above.npm ERR! Please include the following file with any support request:
npm ERR! /home/stellar/test/npm-debug.log
npm ERR! code 1
We should add a warning to the readme.
Would be great if Server.submitTransaction
was throwing specific errors for a transaction result error codes.
For example, in case of txINSUFFICIENT_BALANCE
js lib should throw InsufficientBalance
error.
Implement features in js-stellar-lib until parity is reached.
Where can I find documentation for this library?
Would it be possible to create a server with a full url like this:
let url = "https://horizon-testnet.stellar.org"
let server = new StellarSdk.Server(url);
By the way, the default port is no longer 3000 but 8000.
Thanks.
Looks like stellarSdk.Server internal this
usage is not compatible with promises, because if server object is passed to promises it doesn't recognize its internal properties. Example below.
I suppose it is low priority, because it is easy work around that. But it took a long time to figure out what exactly caused the error because those two versions looks like and imo should be identical.
var horizon = new stellarSdk.Server('https://horizon-testnet.stellar.org');
/* ... */
horizon.loadAccount(myAccountId)
.then(function(myAccount){
te = new stellarSdk.TransactionBuilder(myAccount)
/* ... add operatins ... */
.build();
te.sign(stellarSdk.Keypair.fromSeed(mySeed));
return te;
})
/* ... do other stuff on te ... */
.then(function(te){ return horizon.submitTransaction(te); }) // <--- This workaround works
// .then(horizon.submitTransaction) // <--- This instead would throw error as below
.then( /* handle response */ )
.catch( /* handle error */ );
Cannot read property 'serverURL' of undefined
at submitTransaction ($PATH/node_modules/stellar-sdk/lib/server.js:91:50)
at tryCatcher ($PATH/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler ($PATH/node_modules/bluebird/js/release/promise.js:504:31)
at Promise._settlePromise ($PATH/node_modules/bluebird/js/release/promise.js:561:18)
at Promise._settlePromise0 ($PATH/node_modules/bluebird/js/release/promise.js:606:10)
at Promise._settlePromises ($PATH/node_modules/bluebird/js/release/promise.js:685:18)
at Async._drainQueue ($PATH/node_modules/bluebird/js/release/async.js:138:16)
at Async._drainQueues ($PATH/node_modules/bluebird/js/release/async.js:148:10)
at Immediate.Async.drainQueues [as _onImmediate] ($PATH/node_modules/bluebird/js/release/async.js:17:14)
at tryOnImmediate (timers.js:534:15)
at processImmediate [as _immediateCallback] (timers.js:514:5)
Line 91 in server.js
var promise = axios.post(URI(this.serverURL).path("transactions").toString(), "tx=" + tx, { timeout: SUBMIT_TRANSACTION_TIMEOUT }).then(function (response) {
This one’s a bit interesting. If you stream payments from a non-existent account, like so:
var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
var paymentStream = server
.payments()
.forAccount('GAA2LEFZVJU63SP5B7C77AJXT5PRYDVCWGLFKNVMJTLZU4IXAMXGAATZ')
.stream({
onmessage: function(payment) { /* handle payment */ },
onerror: function(error) {
console.log('Error:', error);
}
});
You'll just get a message like Error: Event { type: 'error' }
over and over again. There’s more useful info in the response, though:
retry: 1000
event: open
data: "hello"
event: err
data: sql: no rows in result set
…but to get it, you'd also have to listen for the err
event:
var paymentStream = [payments query].stream({
onmessage: function(payment) { /* handle payment */ },
onerror: function(error) {}
});
paymentStream.addEventListener('err', function(event) {
console.log('Error:', event.data);
});
…which is both a little inconvenient and hard to discover (no docs). It might be nice if the onerror
handler was called when err
events occur (even though EventSource.onerror
is generally intended for network errors). Barring that, this should at least be documented—and perhaps the object passed to CallBuilder.stream()
could take a handler for it.
Additionally, the server closes the connection after this error, but that just causes the event stream to attempt to reconnect and you get the same error over and over again (the basic idea of the EventSource API is that any kind disconnect not explicitly requested by the client was a network interruption of some sort and a reconnect should be attempted).
I imagine there could be some rare scenario where Horizon might send an error in the middle of the stream and keep going, but maybe if an err
event is immediately followed by a disconnect, the client should hang up? Or Horizon could perhaps send some kind of "end of stream" event to indicate that the client should hang up/not retry.
I propose to add a simplified API for creating a single operation transactions. New methods will be added to Server
class and names representing operations that will be created:
var StellarSdk = require('stellar-sdk');
var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
server.payment({
source: 'SCZZ5GHGUAY4OVME5G5FRQEF5XWBWMAIISB3GXPU24F3VHLMU75NAM4S',
destination: 'GC3FALN2RUQIYG2T4I5JIMSFQO6ZAVSRBC22E5TS3Q7Y7MUDIHM5X5M6',
amount: '10',
asset: StellarSdk.Asset.native()
}).then(result => {
console.log(result);
});
is equivalent of the following code built using current API:
var StellarSdk = require('stellar-sdk');
var keypair = StellarSdk.Keypair.fromSeed('SCZZ5GHGUAY4OVME5G5FRQEF5XWBWMAIISB3GXPU24F3VHLMU75NAM4S');
var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
server.loadAccount(keypair.accountId())
.then(function(source) {
var transaction = new StellarSdk.TransactionBuilder(source)
.addOperation(StellarSdk.Operation.payment({
destination: 'GD6WU64OEP5C4LRBH6NK3MHYIA2ADN6K6II6EXPNVUR3ERBXT4AN4ACD',
amount: "10",
asset: StellarSdk.Asset.native()
}))
.build();
transaction.sign(keypair);
server.submitTransaction(transaction)
.then(function(result) {
console.log(result);
});
});
In the /docs/README
, there is an example of how to stream an account's transaction history. I tried the code below, basically copy-and-pasted from the example:
var StellarLib = require('./js-stellar-lib')
var server = new StellarLib.Server({hostname:'horizon-testnet.stellar.org', secure:true, port:443});
var streamingMessageHandler = function (message) {
console.log(message);
};
server.accounts("gcEuhxySh58bKtCY3UPaWQDR7a1BzGB3ePdxc4UrinkBJyxESe", "transactions",
{
streaming: {
onmessage: streamingMessageHandler
}
})
.then(function (es) {
console.log(es)
})
.catch(function (err) {
console.log(err);
});
and I get the error
/Users/diyang/workspace/client_endpoints_examples.js:89
.then(function (es) {
^
TypeError: Object #<EventSource> has no method 'then'
at Object.<anonymous> (/Users/diyang/workspace/client_endpoints_examples.js:89:6)
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:929:3
A new user would [probably quite reasonably] assume calling the following would get them an object with all the data about an account (e.g. balances, signers, flags, inflation destination, etc):
var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
server.loadAccount(sourcePublicKey).then(function(account) { ... });
But while it does retrieve all that info from the server, most of it (excepting the sequence number) gets thrown out. To get that info, a user is forced to go through a rather obtuse call:
var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
server
.accounts()
.accountId(id)
.call()
.then(function(rawAccountData) { ... });
I’m pretty sure the above is only documented in one spot (https://www.stellar.org/developers/horizon/reference/accounts-single.html, then switch to the JS example), while the rest of the less hidden JS documentation never describes doing anything even along these lines to get account data.
The new getting started docs will demonstrate the above, but it sure would be simpler to suggest simply calling Server.loadAccount(accountId)
!
(As a bonus, it’d be great if the balance objects had Asset
instances. Not sure there are any other types it would make sense to instantiate, though.)
In order to just run the node tests, I have to run gulp clean test:run-server test:node
manually. After the tests are run, I have to kill the server too.
As the code says,
gulp.task('test', function(done) {
runSequence('clean', 'test:run-server', 'test:node', 'test:browser', function (err) {
server.kill();
done();
});
});
If I just run gulp test:node
by itself, the server isn't created.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.