Code Monkey home page Code Monkey logo

neb.rb's Introduction

Nebulas Ruby API

This is the Nebulas compatible Ruby API. Users can use it in Ruby and Rails. This ruby library also support API for our Repl console. Users can sign/send transactions and deploy/call smart contract with it. neb.rb

Install Secp256k1

https://github.com/cryptape/ruby-bitcoin-secp256k1

Installation

Add this line to your application's Gemfile:

gem 'neb', '0.1.3'

And then execute:

$ bundle

Or install it yourself as:

$ gem install neb

Usage

API Example

Neb.configure(host: 'https://testnet.nebulas.io')
client = Neb::Client.new

resp = client.api.get_neb_state
resp.code     # => 200
resp.success? # => true
resp.result   # =>  {:chain_id=>100, :tail=>"xxxx", :lib=>"xxxx", :height=>"1085", :protocol_version=>"/neb/1.0.0", :synchronized=>false, :version=>"1.0.1"}

client.api.subscribe(
  topics: ["chain.pendingTransaction"],
  on_download_progress: ->(c) { puts c }
)

resp = client.admin.accounts
resp.code     # => 200
resp.success? # => true
resp.result   # => {:addresses=>["n1FF1nz6tarkDVwWQkMnnwFPuPKUaQTdptE", "n1FNj5aZhKFeFJ8cQ26Lvsr84NDvNSVRu67"]}

Account Example

# Create a new account with random private_key
account = Neb::Account.create
account = Neb::Account.create(password: YOUR_PASSOWRD)

account.private_key         # => "b5e53a1582a48d243ebd478a7722d1bfea4805ff7c1da4cc7084043e8263c5a8"
account.public_key          # => "35a80ac8a27e2bf072ae84b2cb019e3af0c06547ad939fab1c6d12f713d26ae178d1fd6677aef3e6e94bc7cc1a39f4ca80fc2409a5ef59f97ee55dbd6efc7714"
account.address             # => "n1NfnKqgXBixjiDkJZDSVwqf7ps5roGwFyJ"
account.password = "123456" # or account.set_password("123456")
account.to_key              # => {:version=>4, :id=>"becde267-902e-4f23-ac01-53a4ba6edac7", :address=>"n1VYLxkZoehWEWPHxi351HgZ2R8Hfn2DGpa" ....}
account.to_key_file(file_path: "/tmp/mykey.json")

# Create a new account from exist private_key
account = Neb::Account.new(private_key: YOUR_PRIVATE_KEY)
account = Neb::Account.new(private_key: YOUR_PRIVATE_KEY, password: YOUR_PASSOWRD)

# Restore account from key
account = Neb::Account.from_key(key: YOUR_KEY, password: YOUR_PASSOWRD)

# Restore account from a key file
account = Neb::Account.from_key_file(key_file: YOUR_KEY_FILE, password: YOUR_PASSOWRD)

Transaction Example

Neb.configure(host: 'https://testnet.nebulas.io')
client = Neb::Client.new

account = Neb::Account.new(private_key: YOUR_KEY)
tx = Neb::Transaction.new(
  chain_id: 1,
  from_account: account,
  to_address: 'n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17',
  value: 10,
  nonce: 1,
  gas_price: 1000000,
  gas_limit: 2000000
)

tx.sign_hash

resp = client.api.send_raw_transaction(data: tx.to_proto_str)
resp.code     # => 200
resp.success? # => true
resp.result   # => {:txhash=>"8524384dce7e122bfd007e0ba465e597d821e22db6d563b87dfc55d703fb008c", :contract_address=>""}

resp = client.api.get_transaction_receipt(hash: "8524384dce7e122bfd007e0ba465e597d821e22db6d563b87dfc55d703fb008c")
resp.result[:status] # => 1

client.api.get_account_state(address: 'n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17').result # => {:balance=>"10", :nonce=>"0", :type=>87}

Documentation

API list

Ruby Client API list

Ruby Admin API list

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Test

  1. Install ruby-bitcoin-secp256k1
  2. Start go-nebulas at localhost, ./neb -c conf/default/config.conf, ./neb -c conf/example/miner.conf
  3. Install dependency, cd ~/neb.rb and bundle install
  4. Run test, rake test or rake test test/account_test.rb
  5. Also you can use guard to autotest

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/NaixSpirit/neb.rb. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Neb project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

neb.rb's People

Contributors

xuanyu-h avatar yupnano avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

Forkers

1c7

neb.rb's Issues

about the subscribe api implementation

The subscribe api is an keep-alive connection, and the subscribed events is downloaded as stream, hence a callback function should be provided to handle the events, such as onDownloadProcess in neb.js and HttpClientListener in neb.java, or $onDownloadProgress in neb.php

You could refer to the subscribe api implemented in other languages, although they are not handled very elegantly. I think you can make it better!

using subscribe api in neb.java

nebulasClient.subscribe(new SubscribeRequest("chain.linkBlock", "chain.pendingTransaction"), new HttpClientListener() {
@OverRide
public void onMessage(Response event) {
System.out.println(event.getResult().getTopic());
System.out.println(event.getResult().getData());
}
});
using subscribe api in neb.js

var api = new Neb().api;
var topics = ["chain.linkBlock", "chain.pendingTransaction"]
var onDownloadProces = function (event) {
console.log(event)
}
api.subscribe(topics , onDownloadProces)
using subscribe api in neb.php

$topics = ["chain.linkBlock", "chain.pendingTransaction","chain.newTailBlock"];
/**

  • Explanation of eventCallback function:
  • It is the function that handle the subscribed data,
  • Actually it is the "CURLOPT_WRITEFUNCTION" option for curl, please refer @link http://php.net/manual/en/function.curl-setopt.php *
    */
    function eventCallback($curlHandle, $data){
    echo "received data: $data",PHP_EOL; //handle the subscribed event data
    return strlen($data); //return the received data length, or the http connection will close.
    }

$neb->api->subscribe($topics, "eventCallback");

(Doc) password at lease 9 digit

为什么用中文

因为看到你关注的一些人以及一些库都是用中文。我就假设你会中文了。所以以下用中文写

提议:README 里 Account Example 部分,password 改成9位

image
123456 改成 123456789(至少9位)

为什么

因为这是星云链的要求
image

我用如上 123456 的代码跑了一趟。
如下:

   account.to_key_file(file_path: "/Users/remote_edit/Desktop/#{account.address}.json")

(放这个文件到桌面上)

发现在 Chrome 扩展的星云链里,选择这个文件无法 unlock。提示密码错误
改成 123456789 就可以了。

这是个提议,希望得知你的看法,此 issue 可随时关闭。
谢谢~

'call' seem doesn't work

What I am trying to do: call Smart Contract on Nebulas

Contract Address: n1f4tzQJjoQaUQzDmf7uXP8SC2LTzYYjvAE

And I found call in neb.rb

https://github.com/NaixSpirit/neb.rb/blob/a0d1a4dc54e52d65bd195c556395584d24cbee56/lib/neb/client/api.rb#L30-L42

Usage

    client = Neb::Client.new
    resp = client.api.call(
      from: account.address, 
      to: 'n1f4tzQJjoQaUQzDmf7uXP8SC2LTzYYjvAE',
      value: 0,
      nonce: account_state[:nonce].to_i + 1,
      gas_price: 1000000,
      gas_limit: 2000000,
      contract: contract.to_json,
    )

seem doesn't work.

So I use following, (send request myself)

    testnet = 'https://testnet.nebulas.io'
    query_address = 'n1XL3BsqPiGMFkL9tAxnKziRyQ1L57kDWRz'
    response = RestClient.post("#{testnet}/v1/user/call",{
        "from": "n1XL3BsqPiGMFkL9tAxnKziRyQ1L57kDWRz", # 用测试网钱包
        "to": "n1f4tzQJjoQaUQzDmf7uXP8SC2LTzYYjvAE",   # 合约地址
        "value": "0",
        "nonce": 20,
        "gasPrice": "1000000",
        "gasLimit": "200000", 
        "contract": {
          "function" => "balanceOf",
          "args" => "[\"#{query_address}\"]"
        }
      }.to_json
    )

    render json: response.body

not sure what's going on for now, I am opening this issue to just let you know.

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.