Skip to content

Commit

Permalink
Finished all CLI, tested all methods
Browse files Browse the repository at this point in the history
  • Loading branch information
TrevorJTClarke committed Apr 10, 2021
1 parent 76dc8be commit b0f2c96
Show file tree
Hide file tree
Showing 9 changed files with 168 additions and 74 deletions.
26 changes: 13 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,27 @@ Crond CLI is a Node.js application that relies on [`near-api-js`](https://github

> note that **Node.js version 10+** is required to run Crond CLI
## Installation
## Docker Installation & Setup

```bash
npm install -g crond-js
```
TBD

## Usage

In command line, from the directory with your project:
## CLI Installation

```bash
crond <command>
npm install -g crond-js
```

### Commands

For a list of up-to-date commands, run `crond` in your terminal with no arguments.
For a list of up-to-date commands, run `crond --help` in your terminal.

#### For account:
```bash
crond login # logging in through NEAR protocol wallet
crond init # create a cron Agent account
crond run # run the crond agent
Usage: crond <command> [options]

Commands:
crond register <accountId> <payableAccountId> Add your agent to cron known agents
crond update <accountId> <payableAccountId> Update your agent to cron known agents
crond unregister <accountId> Account to remove from list of active agents.
crond withdraw <accountId> Withdraw all rewards earned for this account
crond status <accountId> Check agent status and balance for this account
```
7 changes: 4 additions & 3 deletions bin/crond
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#!/usr/bin/env node
const flaggedRespawn = require('flagged-respawn');
const flaggedRespawn = require('flagged-respawn')
require = require('esm')(module /*, options*/);
require('v8flags')((e, flags) => {
if (e) {
throw e;
Expand All @@ -10,8 +11,8 @@ require('v8flags')((e, flags) => {
ready => {
if (ready) {
// Need to filter out '--no-respawning' to avoid yargs complaining about it
process.argv = process.argv.filter(arg => arg != '--no-respawning');
require('./crond.js');
process.argv = process.argv.filter(arg => arg != '--no-respawning')
require('./crond.js')
}
});
})
102 changes: 69 additions & 33 deletions bin/crond.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
require('dotenv').config()
const chalk = require('chalk')
const yargs = require('yargs')
import { agentFunction } from '../src/actions'

const chalk = require('chalk');
import getConfig from '../src/config'
const { agentFunction } = require('../src/actions')

const registerAgent = {
command: 'register <accountId>',
command: 'register <accountId> <payableAccountId>',
desc: 'Add your agent to cron known agents',
builder: (yargs) => yargs
.option('accountId', {
Expand All @@ -19,13 +18,13 @@ const registerAgent = {
type: 'string',
required: false
}),
handler: async function (options) {
handler: async options => {
await agentFunction('register_agent', options);
}
};

const updateAgent = {
command: 'update <accountId>',
command: 'update <accountId> <payableAccountId>',
desc: 'Update your agent to cron known agents',
builder: (yargs) => yargs
.option('accountId', {
Expand All @@ -38,7 +37,7 @@ const updateAgent = {
type: 'string',
required: false
}),
handler: async function (options) {
handler: async options => {
await agentFunction('update_agent', options);
}
};
Expand All @@ -52,46 +51,83 @@ const unregisterAgent = {
type: 'string',
required: true
}),
handler: async function (options) {
handler: async options => {
await agentFunction('unregister_agent', options)
}
};

const withdrawBalance = {
command: 'update <accountId>',
command: 'withdraw <accountId>',
desc: 'Withdraw all rewards earned for this account',
builder: (yargs) => yargs
.option('accountId', {
desc: 'Account that earned rewards.',
type: 'string',
required: true
}),
handler: async function (options) {
handler: async options => {
await agentFunction('withdraw_task_balance', options);
}
};

let config = require('../src/config').getConfig(process.env.NODE_ENV || 'development');
const status = {
command: 'status <accountId>',
desc: 'Check agent status and balance for this account',
builder: (yargs) => yargs
.option('accountId', {
desc: 'Account to check',
type: 'string',
required: true
}),
handler: async options => {
await agentFunction('get_agent', options, true);
}
};
const config = getConfig(process.env.NODE_ENV || 'development')
yargs // eslint-disable-line
.strict()
.middleware(require('../cli/check-version'))
.scriptName('crond')
.option('verbose', {
desc: 'Prints out verbose output',
type: 'boolean',
alias: 'v',
default: false
})
.middleware(require('../src/print-options'))
.command(registerAgent)
.command(updateAgent)
.command(unregisterAgent)
.command(withdrawBalance)
.config(config)
.showHelpOnFail(true)
.recommendCommands()
.demandCommand(1, chalk`Pass {bold --help} to see all available commands and options.`)
.usage(chalk`Usage: {bold $0 <command> [options]}`)
.epilogue(chalk`More info: {bold https://cron.cat}`)
.wrap(null)
.argv;
.strict()
.scriptName('crond')
.middleware(require('../cli/check-version'))
.middleware(require('../cli/print-options'))
.option('verbose', {
desc: 'Prints out verbose output',
type: 'boolean',
alias: 'v',
default: false
})
.option('nodeUrl', {
desc: 'NEAR node URL',
type: 'string',
default: config.nodeUrl
})
.option('networkId', {
desc: 'NEAR network ID, allows using different keys based on network',
type: 'string',
default: config.networkId
})
.option('helperUrl', {
desc: 'NEAR contract helper URL',
type: 'string',
})
.option('walletUrl', {
desc: 'Website for NEAR Wallet',
type: 'string'
})
.option('explorerUrl', {
hidden: true,
desc: 'Base url for explorer',
type: 'string',
})
.command(registerAgent)
.command(updateAgent)
.command(unregisterAgent)
.command(withdrawBalance)
.command(status)
.config(config)
.showHelpOnFail(true)
.recommendCommands()
.demandCommand(1, chalk`Pass {bold --help} to see all available commands and options.`)
.usage(chalk`Usage: {bold $0 <command> [options]}`)
.epilogue(chalk`More info: {bold https://cron.cat}`)
.wrap(null)
.argv;
17 changes: 0 additions & 17 deletions cli/index.js

This file was deleted.

6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
"dev": "nodemon --exec npm run restart",
"test": "echo \"Error: no test specified\" && exit 1"
},
"bin": {
"crond": "bin/crond"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Cron-Near/crond-js.git"
Expand All @@ -30,8 +33,11 @@
"chalk": "^4.1.0",
"core-js": "^3.10.1",
"dotenv": "^8.2.0",
"esm": "^3.2.25",
"flagged-respawn": "^1.0.1",
"near-api-js": "^0.39.0",
"regenerator-runtime": "^0.13.7",
"v8flags": "^3.2.0",
"yargs": "^16.2.0"
},
"devDependencies": {
Expand Down
Binary file added public/running.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
53 changes: 46 additions & 7 deletions src/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ export const AGENT_ACCOUNT_ID = process.env.AGENT_ACCOUNT_ID || 'crond-agent'
export const BASE_GAS_FEE = 300000000000000
export const BASE_ATTACHED_PAYMENT = 0

function removeUneededArgs(obj) {
const allowed = ['pk', 'payable_account_id']
const fin = {}

Object.keys(obj).forEach(k => {
if (allowed.includes(k)) fin[k] = obj[k]
})

return fin
}

export const Near = new NearProvider({
networkId: env === 'production' ? 'mainnet' : 'testnet',
accountId: AGENT_ACCOUNT_ID,
Expand All @@ -23,11 +34,12 @@ export async function connect() {
await Near.getNearConnection()
}

export async function getCronManager() {
export async function getCronManager(nearInstance) {
if (cronManager) return cronManager
const _n = nearInstance || Near
const abi = contractAbi.abis.manager
const contractId = contractAbi[env].manager
cronManager = await Near.getContractInstance(contractId, abi)
cronManager = await _n.getContractInstance(contractId, abi)
return cronManager
}

Expand Down Expand Up @@ -91,13 +103,40 @@ export async function runAgentTick() {
setTimeout(runAgentTick, WAIT_INTERVAL_MS)
}

export async function agentFunction(method, args) {
const manager = await getCronManager()
export async function agentFunction(method, args, isView) {
const _n = new NearProvider(args)
await _n.getNearConnection()
agentAccount = await _n.getAccountCredentials(args.accountId)
const manager = await getCronManager(_n)
const params = method === 'get_agent' ? { pk: agentAccount.toString() } : removeUneededArgs(args)
let res

try {
const res = await manager[method](args, BASE_GAS_FEE, BASE_ATTACHED_PAYMENT)
console.log('agentFunction res', method, res);
res = isView
? await manager[method](params)
: await manager[method](params, BASE_GAS_FEE, BASE_ATTACHED_PAYMENT)
} catch (e) {
console.log(e)
if (e && e.panic_msg) {
log('\n')
log('\t' + chalk.red(e.panic_msg.split(',')[0].replace('panicked at ', '').replace(/\'/g, '')))
log('\n')
}
}

if (!res && !isView) log('\n\t' + chalk.green(`${method} Success!`) + '\n')
if (!res && isView) log(chalk.green(`No response data`))

if (isView && res) {
try {
const payload = JSON.parse(res)
log('\n')
Object.keys(payload).forEach(k => {
log(`${chalk.bold.white(k.replace(/\_/g, ' '))}: ${chalk.white(payload[k])}`)
})
log('\n')
} catch (ee) {
// No need to do anything
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/near.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class NearProvider {

const existingKey = await keyStore.getKey(this.config.networkId, accountId)
if (existingKey) {
console.log(`AGENT: "${accountId}", Public Key ${existingKey.publicKey}`)
// console.log(`AGENT: "${accountId}", Public Key ${existingKey.publicKey}`)
this.accountId = accountId
return existingKey.publicKey
}
Expand Down
Loading

0 comments on commit b0f2c96

Please sign in to comment.