Code Monkey home page Code Monkey logo

dsteem's Introduction

Robust steem blockchain client library that runs in both node.js and the browser.


note As of version 0.7.0 WebSocket support has been removed. The only transport provided now is HTTP(2). For most users the only change required is to swap wss:// to https:// in the address. If you run your own full node make sure to set the proper CORS headers if you plan to access it from a browser.


Browser compatibility

Build Status

Installation

Via npm

For node.js or the browser with browserify or webpack.

npm install dsteem

From cdn or self-hosted script

Grab dist/dsteem.js from a release and include in your html:

<script src="dsteem.js"></script>

Or from the unpkg cdn:

<script src="https://unpkg.com/dsteem@^0.8.0/dist/dsteem.js"></script>

Make sure to set the version you want when including from the cdn, you can also use dsteem@latest but that is not always desirable. See unpkg.com for more information.

Usage

In the browser

<script src="https://unpkg.com/dsteem@latest/dist/dsteem.js"></script>
<script>
    var client = new dsteem.Client('https://api.steemit.com')
    client.database.getDiscussions('trending', {tag: 'writing', limit: 1}).then(function(discussions){
        document.body.innerHTML += '<h1>' + discussions[0].title + '</h1>'
        document.body.innerHTML += '<h2>by ' + discussions[0].author + '</h2>'
        document.body.innerHTML += '<pre style="white-space: pre-wrap">' + discussions[0].body + '</pre>'
    })
</script>

See the demo source for an example on how to setup a livereloading TypeScript pipeline with wintersmith and browserify.

In node.js

With TypeScript:

import {Client} from 'dsteem'

const client = new Client('https://api.steemit.com')

for await (const block of client.blockchain.getBlocks()) {
    console.log(`New block, id: ${ block.block_id }`)
}

With JavaScript:

var dsteem = require('dsteem')

var client = new dsteem.Client('https://api.steemit.com')
var key = dsteem.PrivateKey.fromLogin('username', 'password', 'posting')

client.broadcast.vote({
    voter: 'username',
    author: 'almost-digital',
    permlink: 'dsteem-is-the-best',
    weight: 10000
}, key).then(function(result){
   console.log('Included in block: ' + result.block_num)
}, function(error) {
   console.error(error)
})

With ES2016 (node.js 7+):

const {Client} = require('dsteem')

const client = new Client('https://api.steemit.com')

async function main() {
    const props = await client.database.getChainProperties()
    console.log(`Maximum blocksize consensus: ${ props.maximum_block_size } bytes`)
    client.disconnect()
}

main().catch(console.error)

With node.js streams:

var dsteem = require('dsteem')
var es = require('event-stream') // npm install event-stream
var util = require('util')

var client = new dsteem.Client('https://api.steemit.com')

var stream = client.blockchain.getBlockStream()

stream.pipe(es.map(function(block, callback) {
    callback(null, util.inspect(block, {colors: true, depth: null}) + '\n')
})).pipe(process.stdout)

Bundling

The easiest way to bundle dsteem (with browserify, webpack etc.) is to just npm install dsteem and require('dsteem') which will give you well-tested (see browser compatibility matrix above) pre-bundled code guaranteed to JustWork™. However, that is not always desirable since it will not allow your bundler to de-duplicate any shared dependencies dsteem and your app might have.

To allow for deduplication you can require('dsteem/lib/index-browser'), or if you plan to provide your own polyfills: require('dsteem/lib/index'). See src/index-browser.ts for a list of polyfills expected.


Share and Enjoy!

dsteem's People

Contributors

bonustrack avatar drov0 avatar fbslo avatar jnordberg avatar joticajulian avatar netuoso avatar roadscape avatar therealwolf42 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

Watchers

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

dsteem's Issues

getOperationsStream() does not stream on mode: BlockchainMode.Latest

I tried the following codes but it seems that blocks are not returned as 'data' by the stream.

const dsteem = require("dsteem")

// Steem Init
const client = new dsteem.Client('https://api.steemit.com')
let stream = client.blockchain.getOperationsStream({ mode: dsteem.BlockchainMode.Latest })

// Stream Steem Blockchain
stream.on('data', (operation) => {
  console.log('operation', operation)
})  // end: stream.on()

Change Date.now() to props.time

In this line the time is taken from the local PC:
const expiration = new Date(Date.now() + this.expireTime) ...

However, if the computer clock is out of phase for at least 1 minute, the expiration time will be in the past and the broadcast will not work. I propose to take the time from the blockchain props.time

Unexpected token < in JSON at position 0 - while stream.on()

I understand that I have to handle promise rejections in the code (I'm still trying to figure out how I do this) but might it be possible that the underlying problem is somewhere else?

I get the error whenever I try to read from the stream at a random time. Sometimes after 1 minute sometimes after 10 minutes. Depending on the input that is generated.

The full error:

(node:64920) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): ResponseError: Unable to read response data: Unexpected token < in JSON at position 0 (node:64920) [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.

Man your syntax is freaking confusing

Can you work on the docs to make it clearer? for example
getBlock(blockNum: number): Promise
the blocknum object is not even needed here, maybe specify it on docs?
but on this syntax
getCurrentBlock(mode?: BlockchainMode): Promise
I do need to include the object mode...

Please create api for get_account_votes

get_account_votes is a much needed feature for checking the latest post that an account upvoted. This will be helpful for others who want to keep track of their upvoted posts. I tried client.database.call('get_account_votes',['someone']) resulted in timeout in fetching data. It seems that the data is too big to retrieve? But with steemjs worked perfectly

Best way to load post comments

What is the best way to load comments for a particular post? Currently, I am using:

 getPostComments: function (author, permlink) {
      return client.database.call('get_content_replies', [author, permlink])
    }

however, this doesn't seem to return active_votes which means I have nothing to check against as to whether or not a user has voted on a particular post. Potentially there is a better way to do this, hence my adding why I want active_votes

Also what is the best way to get the children of a comment, I know I could do it the long way just wondering if there is anything that makes this really quick and efficient.

Apologies if this is quite vague and let me know if I need to add any more info.

Missing get_follow_count

SteemJS has the function steem.api.getFollowCount which is missing with dsteem.

I've tried client.database.call('get_follow_count', [ name ] ) but get the following error:

Main Error itr != _by_name.end(): no method with name 'get_follow_count

Would be amazing if you could fix this or tell me if I made a mistake :)

Missing Active Authority Bug

When using broadcast.transfer I have a very weird bug that I get: RPCError: Missing Active Authority therealwolf when I try to send a transfer that is bigger than the transfer that I received.

For example: User A sends me X amount and I send X (-0 to max. X) amount back - then everything works fine. But when User A sends me X amount and I send X + 1 - then everything breaks apart.

cannot remove delegation to user I created

Hi, I created some accounts with client.broadcast.createAccount but I don't seem to be able to remove my delegation from those users. I used delegateVestingShares to delegate 0.000000 from kellyjanderson to user rgb14, the delegation got recorded in the blockchain but I still have delegation coming off my account.

client.broadcast.comment does not return a status

hi, when I try to post a new post, I use this code:

var dsteem = require('dsteem');
var client = new dsteem.Client('https://api.steemit.com');
....

client.broadcast.comment({
category: "a1",
parent_author:parent_author,
parent_permlink:primaryTag,
author:author,
permlink:permlink,
title:title,
body:body,
json_metadata: JSON.stringify({ tags: ['test', 'test-2', 'test-3'] }),
last_update: "string",
created:new Date().toDateString(),
children: 7,
max_accepted_payout:'1000000.000 SBD',
percent_steem_dollars: 10000,
allow_replies: true,
allow_votes: true,
allow_curation_rewards: true,
//beneficiaries:[{ account: 'gastonve', weight: 1000 }]
extensions: [
[0, {
beneficiaries: [{
account: "gastonve",
weight: 1000
}]
}]
]
},key, (err, steemResponse) => {
if (err) {
console.log(err);
return res.status(500).send({ message: 'Error:' + err });
}
else {
return res.status(200).send({ message: steemResponse });
}
});

but this does not return any status. what am I missing? please let me know

DeleteCommentOperation get Internal Error

Hello! Nice weekend.

I have something to ask you while using dsteem.

public deletePost(permLink: string): Promise<TransactionConfirmation> {
        let deleteOperation: DeleteCommentOperation = {
            0: "delete_comment",
            1: {
                author: this.authorNickname,
                permlink: permLink
            }
        };

        return this.client.broadcast.sendOperations([deleteOperation], this.PrivateApiKey).then(response => {
            return Promise.resolve(response);
        }, reason => {
            console.warn(reason.message);
            return Promise.resolve(undefined);
        })
    }

I put my nickname to the author, and also put permLink. But It doesn't warn and tells me Internal Error.

But unfortunately, I cannot find any example of using delete disqussion.

Do I correctly use API or, any other precondition?

ps: I can upload blog with this ApiKey.

Getting account stream and transaction stream

I want to subscribe to latest transactions at a specific account. I want to know that if there is any method available in your client library to do that. Will be highly appreciated.

validateAccountName for dsteem?

I was wondering if there is a function similar to validateAccountName from steemjs in dsteem - which checks if the account name is valid. (not too long, not too short etc.)

runing problem

When I use dsteem in react-native, I import dsteem from "dsteem" in redux-saga, and he'll report errors. I don't know why. This seems to be my problem.

v lygt n q x i 6 hs z6

Can't post due to error "_step.value.sign is not a function"

I'm getting an error no matter what I try. I followed this guide and copied its code almost literally, and I also read the documentation. I came to a piece of code that seems very valid to me, but the error I get is unexpectedly vague and untraceable.

I'm guessing it has something to do with the key. It's just my posting key... I'll copy and paste my results here:

The error:

TypeError: "_step.value.sign is not a function"
dsteemlatest/dist/dsteem.js:1:702943
dsteemlatest/dist/dsteem.js:1:721854
dsteemlatest/dist/dsteem.js:1:721599
dsteemlatest/dist/dsteem.js:1:610346
dsteemlatest/dist/dsteem.js:1:609954
dsteemlatest/dist/dsteem.js:1:610628
dsteemlatest/dist/dsteem.js:1:714703
dsteemlatest/dist/dsteem.js:1:330462
dsteemlatest/dist/dsteem.js:1:330737
dsteemlatest/dist/dsteem.js:1:284977

My code:

<!DOCTYPE html>
<html>
<head>
	<title>Copy of tutorial code</title>
	<script src="https://unpkg.com/dsteem@latest/dist/dsteem.js"></script>
</head>
<body>

	<h1>Title</h1>

	<script>
		const client = new dsteem.Client('https://api.steemit.com');
		const logAll = (...args) => args.forEach(console.log)
		const body = "This is my first test post!<br><br>I'm trying to use the code here: https://jnordberg.github.io/dsteem/classes/broadcastapi.html#comment<br><br>And while we're at it, here's a meme:<br><br>https://i.imgur.com/7Yp65sF.jpg"
		const taglist = "test development".split(' ')
		const json_metadata = JSON.stringify({ tags: taglist });

		client.broadcast.comment({
			author: '(my account)',
			body: body,
			json_metadata: json_metadata,
			parent_author: '',
			parent_permlink: taglist[0],
			permlink: 'test1',
			title: 'First test ever ever on this account!',
		}, '(my posting key)').then(logAll);
	</script>

</body>
</html>

Get the block id when streaming the chain

I'm trying to get the block number when streaming the chain so in case the server stop i can restart the streaming at the proper block number.

I'm using something like this to stream the chain:

const from = 10000000; // The block num of the last block i saw
const stream = client.blockchain.getBlockStream({ from });

stream.on('data', (block) => {
  // Do some work here
});

The thing is that the block object may not include the block number, the block number is only visible in transactions array, which may be empty and not included in block object, example: https://api.steemjs.com/getBlock?blockNum=1000000

Could we have the block number directly on the stream callback? Something like this:

stream.on('data', (block, blockNum) => {
  // Do some work here
});

Add Injectable signing/encryption

As a web/mobile developer I want to be able to choose my own crypto libraries so that I can tune performance and overcome issues in default libraries should the need arise.

AC

  • developer can inject their own, compatible, libs & dsteem will utilize them
  • there are tests to cover this injection mechanism
  • there is documentation showing how to inject a lib
  • there is documentation defining the interface required of an injectable lib.

Missing Get Content

the SteemJS lib has a call api.getContent(author, permlink) but I am not finding any equivalent call in the DSteem lib. This is a useful function for loading referenced Posts. Is it available via another call that I am just not finding?

dsteem.Price incorrect?

I looked through the docs but wasn't sure how to call "Price" so I wrote:

dsteem.Price(totalShares,totalFund)

but this gives an error

Error { AssertionError [ERR_ASSERTION]: false == true at new Price (/Users/wolf/node_modules/dsteem/lib/steem/asset.js:181:9) at client.database.getDynamicGlobalProperties.then (/Users/wolf/Bots/script/vote.js:34:31) at <anonymous> at process._tickCallback (internal/process/next_tick.js:188:7) generatedMessage: true, name: 'AssertionError [ERR_ASSERTION]', code: 'ERR_ASSERTION', actual: false, expected: true, operator: '==' }

Documentation Enhancement request

The DSteem library has some of the best documentation out there and is a great starting point for learning the Steem API. However there is one thing missing in a lot of cases that would be very helpful, a description of what the higher level constructs are for/do. As an example Authority, it does not say what and Authority object is for and what you would use it for.

Adding a simple summary that describes what it is and how you would use it would be very helpful when learning one's way around the API.

Can't use get_reblogged_by

I am trying to get a list of all authors that reblog my post using get_reblogged_by but i get the following error:

i've try both follow_api and condenser_api but the results are the same

RPCError: _follow_api: follow_api_plugin not enabled.

`comment` broadcast returns Transaction instead of TransactionConfirmation

I tested your comment broadcast function which didn't work for me, getting a Missing Posting Authority all the time, haven't figured out why. Anywat I just figured if I use steemJS a successfull comment operation returns a Transaction object. Your documentation states it should return a TransactionConfirmation?!

Cannot find name AsyncIterableIterator

I'm trying to replace steem-js with dsteem in my Angular 5 project.
I installed dsteem 0.8.7 via npm but I get an error trying to import it.

import {Client} from 'dsteem';
const client = new Client('https://api.steemit.com');

results in
ERROR in node_modules/dsteem/lib/helpers/blockchain.d.ts(83,66): error TS2304: Cannot find name 'AsyncIterableIterator'. node_modules/dsteem/lib/helpers/blockchain.d.ts(91,60): error TS2304: Cannot find name 'AsyncIterableIterator'. node_modules/dsteem/lib/helpers/blockchain.d.ts(99,64): error TS2304: Cannot find name 'AsyncIterableIterator'. node_modules/dsteem/lib/utils.d.ts(48,53): error TS2304: Cannot find name 'AsyncIterableIterator'.

What am I missing?

One problem on build dsteem

I am trying to build the dsteem.
but when use 'npm run prepublishOnly' ,It report an error:

$ npm run prepublishOnly

> @steemit/[email protected] prepublishOnly /home/sdu/web/dsteem
> make all

tsc -p tsconfig.json --outDir lib && \
VERSION="$(node -p 'require("./package.json").version')"; \
echo "module.exports = '${VERSION}';" > lib/version.js
touch lib
browserify src/index-browser.ts --debug --full-paths \
	--standalone dsteem --plugin tsify \
	--transform [ babelify --extensions .ts ] \
	| derequire > dist/dsteem.js
uglifyjs dist/dsteem.js \
	--source-map "content=inline,url=dsteem.js.map,filename=dist/dsteem.js.map" \
	--compress "dead_code,collapse_vars,reduce_vars,keep_infinity,drop_console,passes=2" \
	--output dist/dsteem.js || rm dist/dsteem.js

Parse error at dist/dsteem.js:3078,0
const Buffer = _dereq_('safe-buffer').Buffer
^
ERROR: Unexpected token: keyword (const)
    at JS_Parse_Error.get (eval at <anonymous> (/home/sdu/web/dsteem/node_modules/uglify-js/tools/node.js:21:1), <anonymous>:73:23)
    at fatal (/home/sdu/web/dsteem/node_modules/uglify-js/bin/uglifyjs:291:53)
    at run (/home/sdu/web/dsteem/node_modules/uglify-js/bin/uglifyjs:235:9)
    at Object.<anonymous> (/home/sdu/web/dsteem/node_modules/uglify-js/bin/uglifyjs:160:5)
    at Module._compile (module.js:624:30)
    at Object.Module._extensions..js (module.js:635:10)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Function.Module._load (module.js:500:3)
    at Function.Module.runMain (module.js:665:10)
gzip -9 -f -c dist/dsteem.js > dist/dsteem.js.gz
gzip: dist/dsteem.js: No such file or directory
Makefile:32: recipe for target 'dist/dsteem.js.gz' failed
make: *** [dist/dsteem.js.gz] Error 1
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! @steemit/[email protected] prepublishOnly: `make all`
npm ERR! Exit status 2

Does anyone know how to fix it?
I hava not changed the code of dsteem,
OR , Is there another way to build dsteem with dsteem.js?

Maintainers wanted

I've moved on to other projects and don't have time to maintain this project. Let me know if you want to take it over.

User Creation Error on testnet

I was just working on a script to create users in NodeJS. I was sending the createAccount broadcast and I got an error that looks like it is saying that the creating account does not have enough vesting shares, but the numbers that it outputs in the error look like it totally has enough vests:

{
    RPCError: creator.vesting_shares - creator.delegated_vesting_shares - asset(creator.to_withdraw - creator.withdrawn, VESTS_SYMBOL) >= o.delegation: Insufficient vesting shares to delegate to new account.creator.vesting_shares = 20318.544734 VESTS creator.delegated_vesting_shares = 10.400643 VESTS required = 0.746401 VESTS
    at Client. < anonymous > (/Users/kellyanderson / projects / SteemUtils / node_modules / dsteem / lib / client.js: 163: 23)
    at Generator.next( < anonymous > )
    at fulfilled(/Users/kellyanderson / projects / SteemUtils / node_modules / dsteem / lib / client.js: 38: 58)
    at process._tickCallback(internal / process / next_tick.js: 103: 7)
    name: 'RPCError',
    jse_shortmsg: 'creator.vesting_shares - creator.delegated_vesting_shares - asset( creator.to_withdraw - creator.withdrawn, VESTS_SYMBOL ) >= o.delegation: Insufficient vesting shares to delegate to new account. creator.vesting_shares=20318.544734 VESTS creator.delegated_vesting_shares=10.400643 VESTS required=0.746401 VESTS',
    jse_info: {
        code: 10,
        name: 'assert_exception',
        message: 'Assert Exception',
        stack: [
            [Object],
            [Object],
            [Object],
            [Object],
            [Object]
        ]
    },
    message: 'creator.vesting_shares - creator.delegated_vesting_shares - asset( creator.to_withdraw -creator.withdrawn, VESTS_SYMBOL ) >= o.delegation: Insufficient vesting shares to delegate to new account. creator.vesting_shares=20318.544734 VESTS creator.delegated_vesting_shares=10.400643 VESTS required=0.746401 VESTS'
}

Am I reading the output incorrectly? To me it looks like it says that the creator account has 20318.544734 vests and it requires 0.746401 vests to create the account.

total_reward_fund_steem and total_reward_shares2 EMPTY

I'm trying to calculate the upvote-price and for this I need "Reward Balance" and "Recent Claims".

My guess was that total_reward_fund_steem and total_reward_shares2 are those. The rest of dynamicGlobalProperties works just fine only those two give me "0" or "0.000 STEEM" as return.

Comment broadcast permalink helper

Broadcasting a top level post requires the parent_permlink to be set to the category, this is very hard to guess...

Add a validator for permlink in broadcast.comment and docstring to explain further

Error occuredTypeError: Network request failed

Hello,

I've got this messages only on Android side. I've running on iOS devices with no errors. What is that ?

I'm using react-native and expo together. I've just get this error in only Android devices and emulator. I've checked network and other issues.
Internet reachable.
Network reachable.

    const client = new Client('https://api.steemit.com');
      
      const query = {
          tag: '',
          limit: limit,
      };
      client.database
          .getDiscussions("trending", query)
          .then(result => {
              
              //var posts = [];
              result.forEach(post => {
                  const json = JSON.parse(post.json_metadata);
                  const image = json.image ? json.image[0] : '';
                  const title = post.title;
                  const author = post.author;
                  const created = new Date(post.created).toDateString();
                  const last = {json:json,image:image,title:title,author:author,created:created};
                  //posts.push({last});
              });
              //console.log(result);
              this.setState({
                  dataSource: result
              });
            this.setState({isLoading:false});
          })
          .catch(err => {
            console.log('Error occured' + err);
          });

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.