How to use @cityofzion/neon-js - 10 common examples

To help you get started, we’ve selected a few @cityofzion/neon-js examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github CityOfZion / neo-js / examples / regression-test / validate-block.js View on Github external
dataAccessOptions: {
        connectOnInit: true,
        connectionString: DB_CONNECTION_STRING,
        collectionNames: {
          blocks: 'b_neo_t_blocks',
          transactions: 'b_neo_t_transactions',
          addresses: 'b_neo_t_addresses'
        }
      }
    }
  }
  const neo = new Neo(options)

  // Instantiate RPC via NeonJS
  const url = 'http://seed2.neo.org:20332'
  const rpc = Neon.rpc.default.create.rpcClient(url)

  // Keep looking and cherrypick blocks, and examine them
  setInterval(async () => {
    // Fetch local node height
    const localBlockHeight = await neo.storage.getBlockCount()

    // Generate random number in between
    const randomHeight = parseInt(Math.random() * localBlockHeight)
    // logger.info('localBlockHeight:', localBlockHeight, 'randomHeight:', randomHeight)

    // Fetch block from local node
    const localBlock = await neo.storage.getBlock(randomHeight)
    // logger.info('localBlock:', localBlock.hash)

    // Fetch block from remote node via NodeJs
    const remoteBlock = await rpc.getBlock(randomHeight)
github CityOfZion / neon-wallet / app / modules / transactions.js View on Github external
if (isHardwareSend && !isWatchOnly) {
      dispatch(
        showInfoNotification({
          message: 'Please sign the transaction on your hardware device',
          autoDismiss: 0,
        }),
      )
    }

    const config = {
      net,
      tokensBalanceMap,
      address: fromAddress,
      publicKey,
      privateKey: new wallet.Account(wif).privateKey,
      signingFunction: isHardwareSend ? signingFunction : null,
      fees,
      url,
      balance: undefined,
      tx: undefined,
      intents: undefined,
      script: undefined,
      gas: undefined,
    }
    const balanceResults = await api
      .getBalanceFrom({ net, address: fromAddress }, api.neoscan)
      .catch(e => {
        // indicates that neo scan is down and that api.sendAsset and api.doInvoke
        // will fail unless balances are supplied
        console.error(e)
        config.balance = generateBalanceInfo(tokensBalanceMap, fromAddress, net)
github be-neo / neoblog / packages / smart-contract-js-lib / src / getfromstorage.js View on Github external
import '@babel/polyfill';
import Neon, { api, u } from '@cityofzion/neon-js';
import { scriptHash, localHost } from './blockchain/config';

const client = Neon.create.rpcClient(localHost);
const s2h = u.str2hexstring;

const store_key = u.str2hexstring('post.')+u.int2hex(1);

/* (async function main() {
  queryBlockchain(store_key).then((result) => {
    console.log(result);
  }).catch((e) => {
    console.log(e);
  });
})(); */

export default function queryBlockchain(key) {
  const query = Neon.create.query({
    'method': 'getstorage',
    'params': [
github PacktPublishing / Foundations-of-Blockchain / Chapter07 / NEO / proof_of_ownership_app / interface / src / App.js View on Github external
let invoke = {

                scriptHash: '60a7ed582c6885addf1f9bec7e413d01abe54f1a',

                operation: 'register',

                args: [

                    'asdsd'.hexEncode(),
                    'AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y'.hexEncode()

                ]

            }

            let sb = Neon.create.scriptBuilder();

            sb.emitAppCall(invoke.scriptHash, invoke.operation, invoke.args, false);
            let script = sb.str;
            let unsignedTx = Neon.create.invocationTx();


            let signedTx = unsignedTx.addIntent(intents).sign(account.privateKey);
            console.log(signedTx)

            // send the transaction to our net

            rpc.queryRPC('http://139.59.25.30:30333', {

                method: 'sendrawtransaction',

                params: [signedTx],
github be-neo / neoblog / packages / smart-contract-js-lib / src / invokesmartcontract.js View on Github external
export default async function main() {
  // Actual invoke params
  const account = Neon.create.account(privnetWif);
  const invoke = createInvoke(operation, args);
  const gasCost = 0;
  const intents = [
    { assetId: assets.GAS, value: 0.00000001, scriptHash: Neon.get.scriptHashFromAddress(account.address)}
  ];

  // Test invoke
  const testResponse = await testInvoke(invoke);
  if (testResponse.result.gas_consumed < 10) {
    const invokeResponse = await executeInvoke(account, invoke, gasCost, intents);
    console.log(invokeResponse);
  }
};
github CityOfZion / neon-js / examples / basic / sendasset.js View on Github external
const { default: Neon, api, wallet } = require("@cityofzion/neon-js");

const sendingKey =
  "9ab7e154840daca3a2efadaf0df93cd3a5b51768c632f5433f86909d9b994a69";
const receivingAddress = "ASo1RcNVLiV3yQ8j3ZyZv5EWfqBBT8s2Yd";
const network = "TestNet";

/**
## Creating intents
To send an asset, we first have to create an `Intent`. Intents represent the instructions to send assets to a specific address.

> Do note that intents are only used for UTXO assets. If you are looking to send NEP5 tokens, this is not the correct way.
*/

// We want to send 1 NEO and 1 GAS to ALq7AWrhAueN6mJNqk6FHJjnsEoPRytLdW
const intent = api.makeIntent({ NEO: 1, GAS: 0.00000001 }, receivingAddress);

console.log("\n\n--- Intents ---");
intent.forEach(i => console.log(i));

/**
To add more intents, simple use`api.makeIntent` to create your intents. The method returns an array of intent objects so make sure to concatenate them together.

## Selecting the API provider and network
We need to decide which provider shall we use. In this example, I shall be using `TestNet` with neoscan. As `TestNet` is built into the `neon-js` networks, we can retrieve it using its name `TestNet` instead of stating a url. For other networks such as your own private network, you will input the url of your private neoscan (for example, https://localhost:4000/api/main_net)
*/

const apiProvider = new api.neoscan.instance(network);

console.log("\n\n--- API Provider ---");
console.log(apiProvider);
github be-neo / neoblog / packages / smart-contract-js-lib / src / getfromstorage.js View on Github external
import '@babel/polyfill';
import Neon, { api, u } from '@cityofzion/neon-js';
import { scriptHash, localHost } from './blockchain/config';

const client = Neon.create.rpcClient(localHost);
const s2h = u.str2hexstring;

const store_key = u.str2hexstring('post.')+u.int2hex(1);

/* (async function main() {
  queryBlockchain(store_key).then((result) => {
    console.log(result);
  }).catch((e) => {
    console.log(e);
  });
})(); */

export default function queryBlockchain(key) {
  const query = Neon.create.query({
    'method': 'getstorage',
    'params': [
      scriptHash,
      key
    ]
github CityOfZion / neon-wallet / app / actions / balancesActions.js View on Github external
determineIfBalanceUpdated(
      { [token.symbol]: token.balance },
      soundEnabled,
      networkHasChanged,
      adressHasChanged,
    )
    inMemoryBalances[token.symbol] = token.balance
    parsedTokenBalances.push({
      [token.scriptHash]: {
        ...token,
      },
    })
  })

  // asset balances
  const assetBalances = await api
    .getBalanceFrom({ net, address }, api.neoscan)
    .catch(e => console.error(e))

  const assets = get(assetBalances, 'balance.assets', {})
  // The API doesn't always return NEO or GAS keys if, for example, the address only has one asset
  const neoBalance = assets.NEO ? assets.NEO.balance.toString() : '0'
  const gasBalance = assets.GAS
    ? assets.GAS.balance.round(COIN_DECIMAL_LENGTH).toString()
    : '0'
  const parsedAssets = [
    { [ASSETS.NEO]: neoBalance },
    { [ASSETS.GAS]: gasBalance },
  ]
  determineIfBalanceUpdated(
    { [ASSETS.NEO]: neoBalance },
    soundEnabled,
github CityOfZion / neon-wallet / app / modules / transactions.js View on Github external
const config = {
      net,
      tokensBalanceMap,
      address: fromAddress,
      publicKey,
      privateKey: new wallet.Account(wif).privateKey,
      signingFunction: isHardwareSend ? signingFunction : null,
      fees,
      url,
      balance: undefined,
      tx: undefined,
      intents: undefined,
      script: undefined,
      gas: undefined,
    }
    const balanceResults = await api
      .getBalanceFrom({ net, address: fromAddress }, api.neoscan)
      .catch(e => {
        // indicates that neo scan is down and that api.sendAsset and api.doInvoke
        // will fail unless balances are supplied
        console.error(e)
        config.balance = generateBalanceInfo(tokensBalanceMap, fromAddress, net)
      })
    if (balanceResults) config.balance = balanceResults.balance

    try {
      const script = buildTransferScript(
        config.net,
        sendEntries,
        config.address,
        // $FlowFixMe
        config.tokensBalanceMap,
github PacktPublishing / Foundations-of-Blockchain / Chapter07 / NEO / proof_of_ownership_app / interface / src / App.js View on Github external
registerAsset(assetID)
    {

        try {
            let account = new wallet.Account('KxDgvEKzgSBPPfuVfw67oPQBSjidEiqTHURKSDL1R7yGaGYAeYnr');

            let intents = [{

                assetId: Neon.CONST.ASSET_ID.GAS,

                value: new Neon.u.Fixed8(1),  // I gueesed this :)

                scriptHash: '60a7ed582c6885addf1f9bec7e413d01abe54f1a'

            }];

            // the interesting part: what do we want to do :)

            let invoke = {

                scriptHash: '60a7ed582c6885addf1f9bec7e413d01abe54f1a',