Code Monkey home page Code Monkey logo

near-cli's Introduction

NEAR CLI (command line interface)

NEAR CLI is a Node.js application that relies on near-api-js to connect to and interact with the NEAR blockchain. Create accounts, access keys, sign & send transactions with this versatile command line interface tool.

Note: Node.js version 16+ is required to run NEAR CLI.

๐Ÿšจ v4.0.0 Notes

This release is a major reorganization of the codebase to simplify its maintenance. It also includes a few new features and a multitude of small fixes.

The most notable changes are:

  • Ledger users, please notice that the --useLedger does not set the path anymore, use --ledgerPath for this
    • Please check the commands that support Ledger for more details
  • Users can now import credentials using the add-credentials command
  • The generate-key command now has a --saveImplicit option to save the key as an implicit account
  • Users can create testnet pre-funded accounts using the --useFaucet option
  • Accounts cannot create TLA with less than 32 characters anymore (this is a NEAR protocol change)
  • Removed unnecessary options from commands, e.g. view now does not take an --accountId or --masterAccount
  • If a command does not work, please first check the commands help to see if the options have changed
    • For example, run near create-account to see how options might have changed

Release notes

Release notes and unreleased changes can be found in the CHANGELOG

Overview

Click on a command for more information and examples.

Command Description
ACCESS KEYS
near add-credentials Stores credentials for an account locally
near add-key adds a new access key to an account
near delete-key deletes an access key from an account
near generate-key generates a key pair and optionally stores it locally as credentials for an accountId
near list-keys displays all access keys and their details for a given account
near login stores a full access key locally using NEAR Wallet
ACCOUNTS
near create-account creates a new account, either using a faucet to fund it, or an account saved locally
near delete-account deletes an account and transfers remaining balance to a beneficiary account
near list-keys displays all access keys for a given account
near send-near sends tokens from one account to another
near state shows general details of an account
CONTRACTS
near call makes a contract call which can invoke change or view methods
near deploy deploys a smart contract to the NEAR blockchain
near storage Shows the storage state of a given contract, i.e. the data stored in a contract
near view makes a contract call which can only invoke a view method
TRANSACTIONS
near tx-status queries a transaction's status by txHash

Setup

Installation

Make sure you have a current version of npm and NodeJS installed.

Mac and Linux

  1. Install npm and node using a package manager like nvm as sometimes there are issues using Ledger due to how OS X handles node packages related to USB devices. [click here]
  2. Ensure you have installed Node version 12 or above.
  3. Install near-cli globally by running:
npm install -g near-cli

For example, on Ubuntu 20.04 near-cli can be installed by running:

# Install nvm (https://github.com/nvm-sh/nvm?tab=readme-ov-file#installing-and-updating)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc

# Install node
nvm install node

# Install near-cli
npm install -g near-cli

# near-cli works!
near --help

Windows

For Windows users, we recommend using Windows Subsystem for Linux (WSL).

  1. Install WSL [click here]
  2. Install npm [click here]
  3. Install Node.js [ click here ]
  4. Change npm default directory [ click here ]
    • This is to avoid any permission issues with WSL
  5. Open WSL and install near-cli globally by running:
npm install -g near-cli

Network selection

The default network for near-cli is testnet.

  • You can change the network by prepending an environment variable to your command.
NEAR_NETWORK=testnet near send ...
  • Alternatively, you can set up a global environment variable by running:
export NEAR_NETWORK=mainnet
  • All commands that interact with the network also allow to pass the --networkId option.
near send-near ... --networkId mainnet

Warning

In previous versions, near-cli used NEAR_ENV to set the network. This can still be used, but NEAR_NETWORK has priority over NEAR_ENV if both are set.


Custom RPC server selection

You can set custom RPC server URL by setting this env variables:

NEAR_MAINNET_RPC
NEAR_TESTNET_RPC

Clear them in case you want to get back to the default RPC server.

Example:

export NEAR_TESTNET_RPC=https://rpc.testnet.near.org

Access Keys

All keys are stored locally at the root of your HOME directory:

  • ~/.near-credentials (MAC / Linux)
  • C:\Users\YOUR_ACCOUNT\.near-credentials (Windows)

Inside .near-credentials, access keys are organized in network subdirectories: testnet, and mainnet.

These network subdirectories contain .JSON objects with an:

  • account_id
  • private_key
  • public_key

near add-credentials <accountId>

Stores credentials (full-access-key) locally for an already existing account.

  • arguments: accountId
  • options: --seedPhrase or --secretKey

Examples:

near add-credentials example-acct.testnet --seedPhrase "antique attitude say evolve ring arrive hollow auto wide bronze usual unfold"

near add-key

Adds either a full access or function access key to a given account.

Optionally allows to sign with a Ledger: --signWithLedger --ledgerPath

Note: You will use an existing full access key for the account you would like to add a new key to. (near login)

1) add a full access key

  • arguments: accountId publicKey

Example:

near add-key example-acct.testnet Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S
Example Response

Adding full access key = Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S to example-acct.testnet.
Transaction Id EwU1ooEvkR42HvGoJHu5ou3xLYT3JcgQwFV3fAwevGJg
To see the transaction in the transaction explorer, please open this url in your browser
https://testnet.nearblocks.io/txns/EwU1ooEvkR42HvGoJHu5ou3xLYT3JcgQwFV3fAwevGJg

2) add a function call key

  • arguments: accountId publicKey --contract-id
  • options: --method-names --allowance

accountId is the account you are adding the key to

--contract-id is the contract you are allowing methods to be called on

--method-names are optional and if omitted, all methods of the --contract-id can be called.

--allowance is the amount of โ“ƒ the key is allowed to spend on gas fees only (default: 0).

Note: Each transaction made with this key will have gas fees deducted from the initial allowance and once it runs out a new key must be issued.

Example:

near add-key example-acct.testnet GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi --contract-id example-contract.testnet --method-names example_method --allowance 30000000000
Example Response

Adding function call access key = GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi to example-acct.testnet.
Transaction Id H2BQL9fXVmdTbwkXcMFfZ7qhZqC8fFhsA8KDHFdT9q2r
To see the transaction in the transaction explorer, please open this url in your browser
https://testnet.nearblocks.io/txns/H2BQL9fXVmdTbwkXcMFfZ7qhZqC8fFhsA8KDHFdT9q2r


near delete-key

Deletes an existing key for a given account. Optionally allows to sign with a Ledger: --signWithLedger --ledgerPath

  • arguments: accountId publicKey
  • options: --networkId, force

Note: You will need separate full access key for the account you would like to delete a key from. (near login)

Example:

near delete-key example-acct.testnet Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S
Example Response

Transaction Id 4PwW7vjzTCno7W433nu4ieA6FvsAjp7zNFwicNLKjQFT
To see the transaction in the transaction explorer, please open this url in your browser
https://testnet.nearblocks.io/txns/4PwW7vjzTCno7W433nu4ieA6FvsAjp7zNFwicNLKjQFT


near generate-key

Displays a key-pair and seed-phrase and optionally stores it locally in .near-credentials.

  • arguments: accountId or none
  • options: --fromSeedPhrase, --saveImplicit, --queryLedgerPK

Note: There are several ways to use generate-key that return very different results. Please reference the examples below for further details.


1a) near generate-key

Creates and displays a key pair

near generate-key
Example Response

Seed phrase: antique attitude say evolve ring arrive hollow auto wide bronze usual unfold
Key pair: {"publicKey":"ed25519:BW5Q957u1rTATGpanKUktjVmixEmT56Df4Dt9hoGWEXz","secretKey":"ed25519:5StmPDg9xVNzpyudwxT8Y72iyRq7Fa86hcpsRk6Cq5eWGWqwsPbPT9woXbJs9Qe69crZJHh4DMkrGEPGDDfmXmy2"}
Implicit account: 9c07afc7673ea0f9a20c8a279e8bbe1dd1e283254263bb3b07403e4b6fd7a411


1b) near generate-key --saveImplicit

Creates and displays a key pair, saving it locally in .near-credentials as an implicit account.

near generate-key --saveImplicit
Example Response

Seed phrase: antique attitude say evolve ring arrive hollow auto wide bronze usual unfold
Key pair: {"publicKey":"ed25519:BW5Q957u1rTATGpanKUktjVmixEmT56Df4Dt9hoGWEXz","secretKey":"ed25519:5StmPDg9xVNzpyudwxT8Y72iyRq7Fa86hcpsRk6Cq5eWGWqwsPbPT9woXbJs9Qe69crZJHh4DMkrGEPGDDfmXmy2"}
Implicit account: 9c07afc7673ea0f9a20c8a279e8bbe1dd1e283254263bb3b07403e4b6fd7a411

Storing credentials for account: 9d6e4506ac06ab66a25f6720e400ae26bad40ecbe07d49935e83c7bdba5034fa (network: testnet)
Saving key to '~/.near-credentials/testnet/9d6e4506ac06ab66a25f6720e400ae26bad40ecbe07d49935e83c7bdba5034fa.json'


2) near generate-key accountId

Creates a key pair locally in .near-credentials with an accountId that you specify.

Note: This does NOT create an account with this name.

near generate-key example.testnet
Example Response

Seed phrase: antique attitude say evolve ring arrive hollow auto wide bronze usual unfold
Key pair: {"publicKey":"ed25519:BW5Q957u1rTATGpanKUktjVmixEmT56Df4Dt9hoGWEXz","secretKey":"ed25519:5StmPDg9xVNzpyudwxT8Y72iyRq7Fa86hcpsRk6Cq5eWGWqwsPbPT9woXbJs9Qe69crZJHh4DMkrGEPGDDfmXmy2"}
Implicit account: 9c07afc7673ea0f9a20c8a279e8bbe1dd1e283254263bb3b07403e4b6fd7a411

Storing credentials for account: example.testnet (network: testnet)
Saving key to '~/.near-credentials/testnet/example.testnet.json'


3a) near generate-key --fromSeedPhrase="your seed phrase"

Uses a seed phrase to display a public key and implicit account

near generate-key --seedPhrase="antique attitude say evolve ring arrive hollow auto wide bronze usual unfold"
Example Response
Seed phrase: antique attitude say evolve ring arrive hollow auto wide bronze usual unfold
Key pair: {"publicKey":"ed25519:BW5Q957u1rTATGpanKUktjVmixEmT56Df4Dt9hoGWEXz","secretKey":"ed25519:5StmPDg9xVNzpyudwxT8Y72iyRq7Fa86hcpsRk6Cq5eWGWqwsPbPT9woXbJs9Qe69crZJHh4DMkrGEPGDDfmXmy2"}
Implicit account: 9c07afc7673ea0f9a20c8a279e8bbe1dd1e283254263bb3b07403e4b6fd7a411

3b) near generate-key accountId --seedPhrase="your seed phrase"

Will store the key pair corresponding to the seedPhrase in .near-credentials with an accountId that you specify.

Example Response

Seed phrase: antique attitude say evolve ring arrive hollow auto wide bronze usual unfold
Key pair: {"publicKey":"ed25519:BW5Q957u1rTATGpanKUktjVmixEmT56Df4Dt9hoGWEXz","secretKey":"ed25519:5StmPDg9xVNzpyudwxT8Y72iyRq7Fa86hcpsRk6Cq5eWGWqwsPbPT9woXbJs9Qe69crZJHh4DMkrGEPGDDfmXmy2"}
Implicit account: 9c07afc7673ea0f9a20c8a279e8bbe1dd1e283254263bb3b07403e4b6fd7a411


4a) near generate-key --queryLedgerPK

Uses a connected Ledger device to display a public key and implicit account using the default HD path ("44'/397'/0'/0'/1'")

near generate-key --queryLedgerPK

You should then see the following prompt to confirm this request on your Ledger device:

Make sure to connect your Ledger and open NEAR app Getting Public Key from Ledger...

After confirming the request on your Ledger device, a public key and implicit accountId will be displayed.

Example Response

Using public key: ed25519:B22RP10g695wyeRvKIWv61NjmQZEkWTMzAYgdfx6oSeB2
Implicit account: 42c320xc20739fd9a6bqf2f89z61rd14efe5d3de234199bc771235a4bb8b0e1


3b) near generate-key --queryLedgerPK --ledgerPath="HD path you specify"

Uses a connected Ledger device to display a public key and implicit account using a custom HD path.

near generate-key --queryLedgerPK --ledgerPath="44'/397'/0'/0'/2'"

You should then see the following prompt to confirm this request on your Ledger device:

Make sure to connect your Ledger and open NEAR app
Waiting for confirmation on Ledger...

After confirming the request on your Ledger device, a public key and implicit accountId will be displayed.

Example Response

Using public key: ed25519:B22RP10g695wye3dfa32rDjmQZEkWTMzAYgCX6oSeB2
Implicit account: 42c320xc20739ASD9a6bqf2Dsaf289z61rd14efe5d3de23213789009afDsd5bb8b0e1


near list-keys

Displays all access keys for a given account.

  • arguments: accountId

Example:

near list-keys client.chainlink.testnet
Example Response

Keys for account client.chainlink.testnet
[
  {
    public_key: 'ed25519:4wrVrZbHrurMYgkcyusfvSJGLburmaw7m3gmCApxgvY4',
    access_key: { nonce: 97, permission: 'FullAccess' }
  },
  {
    public_key: 'ed25519:H9k5eiU4xXS3M4z8HzKJSLaZdqGdGwBG49o7orNC4eZW',
    access_key: {
      nonce: 88,
      permission: {
        FunctionCall: {
          allowance: '18483247987345065500000000',
          receiver_id: 'client.chainlink.testnet',
          method_names: [ 'get_token_price', [length]: 1 ]
        }
      }
    }
  },
  [length]: 2
]


near login

locally stores a full access key of an account you created with MyNEARWallet.

  • arguments: none
  • options: --networkId

Example:

near login

Custom wallet url:

Default wallet url is https://testnet.mynearwallet.com/. But if you want to change to a different wallet url, you can setup the environmental variable NEAR_MAINNET_WALLET or NEAR_TESTNET_WALLET.

export NEAR_TESTNET_WALLET=https://wallet.testnet.near.org/
near login

Accounts

near create-account

Creates an account using an existing account or a faucet service to pay for the account's creation and initial balance.

  • arguments: accountId
  • options: --initialBalance, --useFaucet, --useAccount, --seedPhrase, --publicKey, --signWithLedger, --ledgerPath, --useLedgerPK, --PkLedgerPath

Examples::

# Creating account using `example-acct.testnet` to fund it
near create-account new-acc.testnet --useAccount example-acct.testnet
# Creating account using the faucet to fund it
near create-account new-acc.testnet --useFaucet
# Creating a pre-funded account that can be controlled by the Ledger's public key
near create-account new-acc.testnet --useFaucet --useLedgerPK 
# Creating an account using a Ledger account
near create-account new-acc.testnet --useAccount ledger-acct.testnet --signWithLedger

Subaccount example:

# Using an account to create a sub-account
near create-account sub-acct.example-acct.testnet --useAccount example-acct.testnet
# Creating a sub-account using the Ledger that can also be controlled by the ledger
near create-account sub.acc.testnet --useAccount sub.acc.testnet --signWithLedger --useLedgerPK

Example using --initialBalance:

near create-account sub-acct2.example-acct.testnet --useAccount example-acct.testnet --initialBalance 10
Example Response

Saving key to '/HOME_DIR/.near-credentials/default/sub-acct2.example-acct.testnet.json'
Account sub-acct2.example-acct.testnet for network "default" was created.


near delete-account

Deletes an account and transfers remaining balance to a beneficiary account.

  • arguments: accountId beneficiaryId
  • options: force, --signWithLedger, --ledgerPath

Example:

near delete-account sub-acct2.example-acct.testnet example-acct.testnet
Example Response

Deleting account. Account id: sub-acct2.example-acct.testnet, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, beneficiary: example-acct.testnet
Transaction Id 4x8xohER1E3yxeYdXPfG8GvXin1ShiaroqE5GdCd5YxX
To see the transaction in the transaction explorer, please open this url in your browser
https://testnet.nearblocks.io/txns/4x8xohER1E3yxeYdXPfG8GvXin1ShiaroqE5GdCd5YxX
Account sub-acct2.example-acct.testnet for network "default" was deleted.


near send-near

Sends NEAR tokens (โ“ƒ) from one account to another.

  • arguments: senderId receiverId amount
  • options: --signWithLedger, --ledgerPath

Note: You will need a full access key for the sending account. (near login)

Example:

near send-near sender.testnet receiver.testnet 10
Example Response

Sending 10 NEAR to receiver.testnet from sender.testnet
Transaction Id BYTr6WNyaEy2ykAiQB9P5VvTyrJcFk6Yw95HPhXC6KfN
To see the transaction in the transaction explorer, please open this url in your browser
https://testnet.nearblocks.io/txns/BYTr6WNyaEy2ykAiQB9P5VvTyrJcFk6Yw95HPhXC6KfN


near state

Shows details of an account's state.

  • arguments: accountId

Example:

near state example.testnet
Example Response

{
    "amount": "99999999303364037168535000",
    "locked": "0",
    "code_hash": "G1PCjeQbvbUsJ8piXNb7Yg6dn3mfivDQN7QkvsVuMt4e",
    "storage_usage": 53528,
    "storage_paid_at": 0,
    "block_height": 21577354,
    "block_hash": "AWu1mrT3eMJLjqyhNHvMKrrbahN6DqcNxXanB5UH1RjB",
    "formattedAmount": "99.999999303364037168535"
}


Contracts

near call

makes a contract call which can modify or view state.

Note: Contract calls require a transaction fee (gas) so you will need an access key for the --accountId that will be charged. (near login)

  • arguments: contractName method_name { args } --accountId
  • options: --gas --deposit --signWithLedger --ledgerPath

Example:

near call guest-book.testnet addMessage '{"text": "Aloha"}' --account-id example-acct.testnet
Example Response

Scheduling a call: guest-book.testnet.addMessage({"text": "Aloha"})
Transaction Id FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK
To see the transaction in the transaction explorer, please open this url in your browser
https://testnet.nearblocks.io/txns/FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK
''


near deploy

Deploys a smart contract to a given accountId.

  • arguments: accountId .wasmFile
  • options: initFunction initArgs initGas initDeposit

Note: You will need a full access key for the account you are deploying the contract to. (near login)

Example:

near deploy example-contract.testnet out/example.wasm

Initialize Example:

near deploy example-contract.testnet out/example.wasm --initFunction new --initArgs '{"owner_id": "example-contract.testnet", "total_supply": "10000000"}'
Example Response

Starting deployment. Account id: example-contract.testnet, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: main.wasm
Transaction Id G8GhhPuujMHTRnwursPXE1Lv5iUZ8WUecwiST1PcKWMt
To see the transaction in the transaction explorer, please open this url in your browser
https://testnet.nearblocks.io/txns/G8GhhPuujMHTRnwursPXE1Lv5iUZ8WUecwiST1PcKWMt
Done deploying to example-contract.testnet


near storage

Shows the storage state of a given contract, i.e. the data stored in a contract.

  • arguments: contractName
  • options: --finality, --utf8, --blockId, --prefix

Example:

near storage hello.near-examples.testnet --finality optimistic --utf8
Example Response
[ { key: 'STATE', value: '\x10\x00\x00\x00Passei por aqui!' } ]

near view

Makes a contract call which can only view state. (Call is free of charge)

  • arguments: contractName method_name { args }
  • options: default

Example:

near view guest-book.testnet getMessages '{}'
Example Response

View call: guest-book.testnet.getMessages({})
[
  { premium: false, sender: 'waverlymaven.testnet', text: 'TGIF' },
  {
    premium: true,
    sender: 'waverlymaven.testnet',
    text: 'Hello from New York ๐ŸŒˆ'
  },
  { premium: false, sender: 'fhr.testnet', text: 'Hi' },
  { premium: true, sender: 'eugenethedream', text: 'test' },
  { premium: false, sender: 'dongri.testnet', text: 'test' },
  { premium: false, sender: 'dongri.testnet', text: 'hello' },
  { premium: true, sender: 'dongri.testnet', text: 'hey' },
  { premium: false, sender: 'hirokihori.testnet', text: 'hello' },
  { premium: true, sender: 'eugenethedream', text: 'hello' },
  { premium: false, sender: 'example-acct.testnet', text: 'Aloha' },
  [length]: 10
]


Transactions

near tx-status

Queries transaction status by hash and accountId.

  • arguments: txHash --accountId
  • options: default

Example:

near tx-status FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK --accountId guest-book.testnet
Example Response

Transaction guest-book.testnet:FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK
{
  status: { SuccessValue: '' },
  transaction: {
    signer_id: 'example-acct.testnet',
    public_key: 'ed25519:AXZZKnp6ZcWXyRNdy8FztYrniKf1qt6YZw6mCCReXrDB',
    nonce: 20,
    receiver_id: 'guest-book.testnet',
    actions: [
      {
        FunctionCall: {
          method_name: 'addMessage',
          args: 'eyJ0ZXh0IjoiQWxvaGEifQ==',
          gas: 300000000000000,
          deposit: '0'
        }
      },
      [length]: 1
    ],
    signature: 'ed25519:5S6nZXPU72nzgAsTQLmAFfdVSykdKHWhtPMb5U7duacfPdUjrj8ipJxuRiWkZ4yDodvDNt92wcHLJxGLsyNEsZNB',
    hash: 'FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK'
  },
  transaction_outcome: {
    proof: [ [length]: 0 ],
    block_hash: '6nsjvzt6C52SSuJ8UvfaXTsdrUwcx8JtHfnUj8XjdKy1',
    id: 'FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK',
    outcome: {
      logs: [ [length]: 0 ],
      receipt_ids: [ '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU', [length]: 1 ],
      gas_burnt: 2427979134284,
      tokens_burnt: '242797913428400000000',
      executor_id: 'example-acct.testnet',
      status: {
        SuccessReceiptId: '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU'
      }
    }
  },
  receipts_outcome: [
    {
      proof: [ [length]: 0 ],
      block_hash: 'At6QMrBuFQYgEPAh6fuRBmrTAe9hXTY1NzAB5VxTH1J2',
      id: '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU',
      outcome: {
        logs: [ [length]: 0 ],
        receipt_ids: [ 'FUttfoM2odAhKNQrJ8F4tiBpQJPYu66NzFbxRKii294e', [length]: 1 ],
        gas_burnt: 3559403233496,
        tokens_burnt: '355940323349600000000',
        executor_id: 'guest-book.testnet',
        status: { SuccessValue: '' }
      }
    },
    {
      proof: [ [length]: 0 ],
      block_hash: 'J7KjpMPzAqE7iX82FAQT3qERDs6UR1EAqBLPJXBzoLCk',
      id: 'FUttfoM2odAhKNQrJ8F4tiBpQJPYu66NzFbxRKii294e',
      outcome: {
        logs: [ [length]: 0 ],
        receipt_ids: [ [length]: 0 ],
        gas_burnt: 0,
        tokens_burnt: '0',
        executor_id: 'example-acct.testnet',
        status: { SuccessValue: '' }
      }
    },
    [length]: 2
  ]
}


Global Options

Option Description
--help Show help [boolean]
--version Show version number [boolean]
-v, --verbose Prints out verbose output [boolean] [default: false]

Got a question? Ask it on StackOverflow!

License

This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See LICENSE and LICENSE-APACHE for details.

near-cli's People

Contributors

ailisp avatar amgando avatar behaviary avatar bowenwang1996 avatar chadoh avatar chaotictempest avatar chefsale avatar dependabot-preview[bot] avatar dependabot[bot] avatar eriktrautman avatar forwardslashback avatar gagdiez avatar icerove avatar ilblackdragon avatar ilyar avatar itegulov avatar janedegtiareva avatar judith-near avatar june07 avatar kucharskim avatar maximushaximus avatar mehtaphysical avatar mikedotexe avatar mm-near avatar narwalsandeep avatar nikurt avatar thisisjoshford avatar vgrichina avatar volovyks avatar willemneal 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

near-cli's Issues

`near call` does not display result as JSON anymore

This one actually blocks development, since now we cannot see the result of contract execution when using near shell.

For instance:

near call near.test benchmark_sum_n "{\"n\": 10}" --accountId near.test                                     ๎‚ฒ 1 โ†ต ๎‚ฒ 10030 ๎‚ฒ 13:41:58
[WARNING] Didn't find config at /Users/zaver/Projects/nearcore/src/config

Scheduling a call: near.test.benchmark_sum_n({"n": 10}) with attached 1000000000 NEAR
Loaded master account near.max key from /Users/zaver/.near/validator_key.json with public key = JBozFzsVw3j1KSZs1vnbtRtgdbv5m6RsoFDLnxHYB2Cv
Result: {
  logs: [
    {
      hash: '5Lcdu4GJDbgJWGSaAV5hf4yFsiudhWuVBqQaV5FEX7yW',
      lines: [],
      receipts: [],
      result: [Array]
    }
  ],
  status: 'Completed'
}

Displays [Array] instead of actually printing the JSON form. It was not the case before.

listFiles in gulp-utils

Currently in gulp-utils.js, the listFiles function passed to asc.main is listFiles: () => []. Previously this function was only used if you provided a library argument. However, now with the module resolution it's used to determine if a folder is valid. e.g.../z/v/node_modules. Is there a reason for this? Otherwise I'll remove it in the PR.
`

Expected behavior of NEAR CLI tool from new user

Here are some things I tried when I first used the tool installing globally from npm.

These are based on experiences with other CLI tools that generate apps.
E.g.

generating a project

near new .
# generates a new generic hello world in the current dir

near new my-project ---project_dir=~/directory
# generates project in new dir ~/directory/my-project 

near new $TEMPLATE $PROJECT
# generates a project in current dir from one of the studio templates (https://github.com/nearprotocol/near-shell/issues/14)

getting help

near --help
near -h
# returns help for all commands

near $CMD -h
# returns help for specific command

making an error in the commands

near ne
# tells me what commands I have at my disposal

Allow using without gulp

Right now typical build process would be like:

Compile:
npm -> near -> gulp -> asc (compile)

Deploy:
npm -> near (deploy)

I think it instead should be:

Compile:
npm -> gulp -> near as a lib -> asc

Deploy:
npm -> gulp -> near (deploy)

I think this will make our CLI tools even better cause:

  • gulp is a versatile tool which can be used for a lot of other app build tasks, web dev folks know it โ€“ no need to hide behind our CLI
  • but people should be able to replace gulp easily as still not everyone wants to use it. This is much easier when near doesn't call gulp.

Near create_account reports unclear error when account already exists

near create_account nearproject

Error:  { BadRequestError: Transaction PwxM38gabyPbmtsi3RcOzvsDUwF/Lu9o6sjVbDnl4wQ= on unknown contract failed. 
    at sendJson (/usr/local/lib/node_modules/near-shell/node_modules/nearlib/internal/send-json.js:12:15)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:182:7)
  message: 'Transaction PwxM38gabyPbmtsi3RcOzvsDUwF/Lu9o6sjVbDnl4wQ= on unknown contract failed. ' }

master account defaults to validator_key file even with flag

Observed:

  1. Successfully log in with new master account @@@@@@@@

Screenshot 2019-08-06 10 51 11

2. Attempt to use this as default account without adding flag. It errors, telling me that I need to use the masterAccount flag.

Screenshot 2019-08-06 10 51 42

3. Run `create_account` again with masterAccount flag set to `@@@@@@@@`. Notice that the master account is set to `loaded.potato` from the validator_key.json file.

Screenshot 2019-08-06 10 52 55

Expected:
Same flow, except that perhaps step (2) loads the most recently logged in account and step (3) uses whatever flag is explicitly set.

Money in the shell should be denominated in "Near"

Currently they are denominates in attoNEAR, which means that staking 10 NEARs is large number with 19 zeros which is hard to keep track.
All the amounts, including provided by user and printed out should display amount in NEAR (and use mantissa like 0.001 โ“ƒ if it's smaller than one)

Staging environment

We have now 2 testnets - "TestNet" and "Staging". Would be good to be able to specify via NODE_ENV=staging

Bring back pynear features

  • send_money
  • view_account
  • view_state
  • stake (this will be more complex, because people will be able to stake in several different ways: as validators and verifiers)
  • swap_key
  • view latest block
  • get block by hash

Note, that some of these functions are or will be special cases of more generic functions. For instance, we discussed with @evgenykuzyakov and @ilblackdragon that we want all our transactions to look like function calls for consistency and forward compatibility. For instance, send_money will be a short cut for near call <my_account> send_money "{"receiver": <other_account>}", or somesuch.

Originally posted by @nearmax in near/docs#36 (comment)

Remove confusing failed to load master key message

This message shows up even if we are on envs that do not have a keypath configured

Failed to load master account key from /Users/evgueniadegtiareva/.near/validator_key.json: Error: ENOENT: no such file or directory, open '/Users/evgueniadegtiareva/.near/validator_key.json'

near build doesn't work if gulp is not installed globally

{
networkId: 'default',
nodeUrl: 'https://rpc.nearprotocol.com',
contractName: 'near-hello-devnet',
walletUrl: 'https://wallet.nearprotocol.com',
initialBalance: 100000000
}
events.js:173
throw er; // Unhandled 'error' event
^

Error: spawn gulp ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:248:19)
at onErrorNT (internal/child_process.js:431:16)
at processTicksAndRejections (internal/process/task_queues.js:84:17)
Emitted 'error' event at:
at Process.ChildProcess._handle.onexit (internal/child_process.js:254:12)
at onErrorNT (internal/child_process.js:431:16)
at processTicksAndRejections (internal/process/task_queues.js:84:17)

Create a separate repo for blank_project

This gives the option to also fork the project. If we make it a dependency for this than we can still just copy the files as we currently do. Ideally it would be nice to have a selection of starting projects similar to NEARStudio.

'near send' is broken

What should happen:

near send loaded.potato 1000000000
# All good. You sent a bunch o money

What's happening:
Screenshot 2019-08-01 12 24 38

Login fails if the neardev folder is missing

near login --walletUrl https://wallet.nearprotocol.com                                         Fri Jul 19 19:50:09 2019
[WARNING] Didn't find config at /Users/cypress/projects/nearprotocol/src/config

Please navigate to this url and follow the instructions to log in:
https://wallet.nearprotocol.com/login/?title=NEAR+Shell&public_key=2AuZoEzNToANowe1zZpfq29KUptwvvaXfopq8LmbuPSD
Please enter the accountId that you logged in with:illia.china
Logged in with illia.china
(node:12745) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, mkdir './neardev/default'
(node:12745) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12745) [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.

Generate project from template with a given contract name

Generated template would generally have unique contract name, I'm thinking of following workflow.

Create app in my-awesome-app folder with my-awesome-app contract name:

npx create-near-app my-awesome-app

npm install done behind the scenes (like with create-react-app), contract account also created immediately.
This should also eventually have option for different stater templates, etc.

Run generated app:

cd my-awesome-app
npm start

Originally posted by @vgrichina in https://github.com/nearprotocol/near-shell/pull/24/files

Cover all `nearcore` features (missing from pynear)

Note, there is also other stuff that was not in pynear but we will very likely have:

  • expiration_date Returns date and time of contract or access key expiration due to rent payments;
  • add_access_key
  • delete_access_key
  • delete_account (Both delete_access_key and delete_account can be called by non-account owner if they are about to run out of balance due to rent)
  • async_call (for contract calls the incur a long chain of cross-contract calls)
  • async_status

Note, that some of these functions are or will be special cases of more generic functions. For instance, we discussed with @evgenykuzyakov and @ilblackdragon that we want all our transactions to look like function calls for consistency and forward compatibility. For instance, send_money will be a short cut for near call <my_account> send_money "

{"receiver": <other_account>}

", or somesuch.

_Originally posted by @nearmax in near/docs#36 (comment)

Support using multiple accounts

Right now it looks like I can only use one account at once which has keys stored in neardev/devkey.json.

This cannot support normal deploy pattern where developer deploys to local node and shared devnet using different accounts.

There should be some straightforward option to either use different accounts/key pairs or to use same key pair on both local node and shared devnet.

Near Login doesn't work outside of project directory

I need to run near login in a near project to login. Not doing so will result in a message like:

[WARNING] Didn't find config at /Users/shei/Desktop/code/nearcore/src/config
Log in is not needed on this environment. Please use appropriate master account for shell operations.

New_project requires out dir

If we create a project using near new_project . and then run npm i && near build it would give the following error Error: ENOENT: no such file or directory, open 'out/model.near.ts' and can be resolved by manually creating the out directory.

If there is a validator key, it is used always even when connecting to a diff network

steps to repro:
start local node e.g. via nearcore/scripts/start_local

near login to testnet
near new_project and deploy
near view contractId whoSaidHi fails with

rror: Error: [-32000] Server error: account {localaccount} does not exist while viewing
at JsonRpcProvider.sendJsonRpc (/Users/evgueniadegtiareva/near/near-shell/node_modules/nearlib/lib/providers/json-rpc-provider.js:50:19)
at processTicksAndRejections (internal/process/task_queues.js:85:5)
at async JsonRpcProvider.query (/Users/evgueniadegtiareva/near/near-shell/node_modules/nearlib/lib/providers/json-rpc-provider.js:32:24)
at async Account.fetchState (/Users/evgueniadegtiareva/near/near-shell/node_modules/nearlib/lib/account.js:33:23)
at async Account.state (/Users/evgueniadegtiareva/near/near-shell/node_modules/nearlib/lib/account.js:39:9)
at async Near.account (/Users/evgueniadegtiareva/near/near-shell/node_modules/nearlib/lib/near.js:35:9)
at async Object.exports.callViewFunction (/Users/evgueniadegtiareva/near/near-shell/index.js:110:21)
at async exitOnError (/Users/evgueniadegtiareva/near/near-shell/bin/near:8:5)

Regression: new project is broken

At least one dev flow is broken.
run after new_project, npm install, npm run-script test - this should run tests in a sandbox environment (i.e. separate instance of contract deployed and used). local_test_environment is supposed to be used for that, and it's being ignored right now.

Deploying generic wasm contracts from near-shell

Near shell cannot be used for users working with Rust contracts:

  • It requires config.js;
  • It requires contract helper. near shell is supposed to supersede pynear, by pynear was able to work without locally running contract helper.

To reproduce:

near create_account --useDevAccount --account_id "francis"         ๎‚ฒ โœ” ๎‚ฒ 10014 ๎‚ฒ 10:01:20
[WARNING] Didn't find config at /Users/zaver/Projects/near-shell/src/config
near deploy --useDevAccount --account_id "francis" --wasmFile /Users/zaver/Projects/nearcore/runtime/rust-api/test-contract/pkg/test_contract_bg.wasm
[WARNING] Didn't find config at /Users/zaver/Projects/near-shell/src/config

Starting deployment. Account id: francis, node: http://localhost:3030, helper: undefined, file: /Users/zaver/Projects/nearcore/runtime/rust-api/test-contract/pkg/test_contract_bg.wasm
Error:  Error: [1] Error calling abci_query(account/francis,,0,false)
Message: undefined
account francis does not exist while viewing
    at NearClient.jsonRpcRequest (/usr/local/lib/node_modules/near-shell/node_modules/nearlib/nearclient.js:108:27)
    at processTicksAndRejections (internal/process/task_queues.js:89:5)
    at async NearClient.viewAccount (/usr/local/lib/node_modules/near-shell/node_modules/nearlib/nearclient.js:23:26)
    at async NearClient.getNonce (/usr/local/lib/node_modules/near-shell/node_modules/nearlib/nearclient.js:87:17)
    at async Near.deployContract (/usr/local/lib/node_modules/near-shell/node_modules/nearlib/near.js:128:23)
    at async Object.exports.deploy (/usr/local/lib/node_modules/near-shell/index.js:78:9)
    at async exitOnError (/usr/local/lib/node_modules/near-shell/bin/near:8:5) {
  log: 'account francis does not exist while viewing'

Returning u64 prevents compilation

export function broken_function(): u64[] {
    return [1, 2];
}

Trying to compile this results in the following error:

ERROR TS2339: Property 'toString' does not exist on type 'u64'.
    encoder.setString(null, value[i].toString());
    in ../out/main.near.ts(42,33)

call function fails

Steps to reproduce:

  • Start a node Navigate to nearcore folder. Switch to staging branch. Pull it. Start a node with:
rm -rf testdir; ./scripts/start_unittest.py --local
  • Get most recent near-shell Navigate to near-shell folder. Switch to staging. Install it:
rm -rf node_modules; npm install
  • Create new account Where /Users/zaver/Projects/nearcore should be replaced to your path to nearcore folder.
./bin/near create_account status_message --masterAccount=test.near --homeDir=/Users/zaver/Projects/nearcore/testdir --nodeUrl=http://localhost:3030
/bin/near deploy --accountId=status_message --wasmFile=/Users/zaver/Projects/near-runtime-rs/examples/status-message/res/status_message.wasm --homeDir=/Users/zaver/Projects/nearcore/testdir --nodeUrl=http://localhost:3030
  • Call a function on it
./bin/near call status_message set_status "{\"message\": \"Hello\"}" --accountId=test.near --wasmFile=/Users/zaver/Projects/near-runtime-rs/examples/status-message/res/status_message.wasm --homeDir=/Users/zaver/Projects/nearcore/testdir --nodeUrl=http://localhost:3030

EXPECTED:

To get a meaningful output.

ACTUAL:

near-shell returns an error:

WARNING] Didn't find config at /Users/zaver/Projects/near-shell/src/config, using default shell config
Scheduling a call: status_message.set_status({"message": "Hello"}) with attached 1000000000 NEAR
Loaded master account test.near key from /Users/zaver/Projects/nearcore/testdir/validator_key.json with public key = 22skMptHjFWNyuEWY22ftn2AbLPSYpmYwGJRGwpNHbTV
Error:  TypeError: Cannot read property 'length' of undefined
    at Object.getTransactionLastResult (/Users/zaver/Projects/near-shell/node_modules/nearlib/lib/providers/provider.js:14:32)
    at Object.exports.scheduleFunctionCall (/Users/zaver/Projects/near-shell/index.js:98:37)
    at processTicksAndRejections (internal/process/task_queues.js:89:5)
    at async exitOnError (/Users/zaver/Projects/near-shell/bin/near:8:5)
  • Confirm that the state changed. We want to make sure that the above error is about transaction status not being read correctly, while the contract call was actually correctly executed.
./bin/near view status_message get_status "{\"account_id\": \"test.near\"}" --accountId=test.near --wasmFile=/Users/zaver/Projects/near-runtime-rs/examples/status-message/res/status_message.wasm --homeDir=/Users/zaver/Projects/nearcore/testdir --nodeUrl=http://localhost:3030

OBSERVE:

Result: Hello

Error: URL is undefined on Node versions 9.x and before when running near login command

Running near login with node version 9.0 gives error:

{ networkId: 'default',
nodeUrl: 'http://34.94.33.164:3030',
contractName: 'near-hello-devnet',
walletUrl: 'https://wallet.nearprotocol.com' }
Error: ReferenceError: URL is not defined
at Object.exports.login (/usr/local/lib/node_modules/near-shell/index.js:122:24)
at Object.handler (/usr/local/lib/node_modules/near-shell/bin/near:90:39)
at Object.runCommand (/usr/local/lib/node_modules/near-shell/node_modules/yargs/lib/command.js:242:26)
at Object.parseArgs [as _parseArgs] (/usr/local/lib/node_modules/near-shell/node_modules/yargs/yargs.js:1078:30)
at Object.get [as argv] (/usr/local/lib/node_modules/near-shell/node_modules/yargs/yargs.js:1012:21)
at Object. (/usr/local/lib/node_modules/near-shell/bin/near:216:3)
at Module._compile (internal/modules/cjs/loader.js:654:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
at Module.load (internal/modules/cjs/loader.js:566:32)
at tryModuleLoad (internal/modules/cjs/loader.js:506:12)

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.