Skip to content

Commit

Permalink
merge diff into master
Browse files Browse the repository at this point in the history
  • Loading branch information
behaviary committed Mar 23, 2019
2 parents 1d68b7b + 02bc82c commit 8a118f3
Show file tree
Hide file tree
Showing 12 changed files with 315 additions and 9 deletions.
25 changes: 25 additions & 0 deletions blank_project/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Greeter example in AssemblyScript

## Description

The contract implements a single function to return a greeting.

## To Run


## To Test

*In NEAR Studio (https://studio.nearprotocol.com)*

```
npm install
npm run-script build
npm test
```

## To Explore

- `assembly/main.ts` for the contract code
- `src/main.html` for the front-end HTML
- `src/main.js` for the JavaScript front-end code and how to integrate contracts
- `src/test.js` for the JS tests for the contract
18 changes: 18 additions & 0 deletions blank_project/assembly/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import "allocator/arena";
export { memory };

import { context, storage, near } from "./near";

import { Greeter } from "./model.near";

// --- contract code goes below

// >> hello-snippet
// To be able to call this function in the contract we need to export it
// using `export` keyword.

export function hello(): string {
let greeter = new Greeter("Hello");
return greeter.greet("world");
}
// << hello-snippet
12 changes: 12 additions & 0 deletions blank_project/assembly/model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Basic data model
export class Greeter {
text: string;

constructor(text: string) {
this.text = text;
}

greet(userId: string): string {
return "Hello, " + userId;
}
}
6 changes: 6 additions & 0 deletions blank_project/assembly/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"extends": "../node_modules/assemblyscript/std/assembly.json",
"include": [
"./**/*.ts"
]
}
82 changes: 82 additions & 0 deletions blank_project/local_test_environment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
const NodeEnvironment = require('jest-environment-node');
const dev = require('nearlib/dev');
const fs = require('fs');
const nearlib = require('nearlib');


class LocalTestEnvironment extends NodeEnvironment {
constructor(config) {
super(config);
}

async setup() {
this.global.ArrayBuffer = ArrayBuffer;
this.global.DataView = DataView;

this.global.Uint8Array = Uint8Array;
this.global.Uint8ClampedArray = Uint8ClampedArray;
this.global.Uint16Array = Uint16Array;
this.global.Uint32Array = Uint32Array;
this.global.Int8Array = Int8Array;
this.global.Int16Array = Int16Array;
this.global.Int32Array = Int32Array;
this.global.Float32Array = Float32Array;
this.global.Float64Array = Float64Array;
this.global.Map = Map;
this.global.Set = Set;
this.global.Promise = Promise;
this.global.nearlib = require('nearlib');
this.global.nearlib.dev = require('nearlib/dev');
this.global.window = {};
this.global.testSettings = {
contractName: "test" + Date.now(),
accountId: "test" + Date.now(),
nodeUrl: "http://localhost:3030",
deps: {
storage: this.createFakeStorage(),
keyStore: new nearlib.InMemoryKeyStore(),
createAccount: dev.createAccountWithLocalNodeConnection
}
};
const near = await dev.connect(this.global.testSettings);

const keyWithRandomSeed = await nearlib.KeyPair.fromRandomSeed();
await dev.createAccountWithLocalNodeConnection(this.global.testSettings.contractName, keyWithRandomSeed.getPublicKey());
this.global.testSettings.deps.keyStore.setKey(this.global.testSettings.contractName, keyWithRandomSeed);

// deploy contract
const data = [...fs.readFileSync('./out/main.wasm')];
await near.waitForTransactionResult(
await near.deployContract(this.global.testSettings.contractName, data));

await super.setup();
}

async teardown() {
await super.teardown();
}

runScript(script) {
return super.runScript(script);
}

createFakeStorage() {
let store = {};
return {
getItem: function(key) {
return store[key];
},
setItem: function(key, value) {
store[key] = value.toString();
},
clear: function() {
store = {};
},
removeItem: function(key) {
delete store[key];
}
};
};
}

module.exports = LocalTestEnvironment
23 changes: 23 additions & 0 deletions blank_project/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "@wasm/hello_world_ts",
"description": "",
"version": "1.0.0",
"scripts": {
"build": "node_modules/near-shell/near build",
"test": "jest test --env=./local_test_environment.js"
},
"devDependencies": {
"assemblyscript": "github:nearprotocol/assemblyscript.git",
"gulp": "^3",
"assemblyscript-json": "github:nearprotocol/assemblyscript-json",
"jest-environment-node": "^24.5.0",
"near-runtime-ts": "github:nearprotocol/near-runtime-ts",
"near-shell": "0.0.10"
},
"wasmStudio": {
"name": "Hello World Example",
"description": "The contract implements a single function to return \"Hello, World!\" using AssemblyScript",
"icon": "typescript-lang-file-icon"
},
"dependencies": {}
}
17 changes: 17 additions & 0 deletions blank_project/src/main.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!-- >> markup-snippet -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
</head>
<body style="background: #fff">
<div class="container">
Contract says:
<h1 id="contract-message"></h1>
</div>
<script src="https://cdn.jsdelivr.net/npm/nearlib@0.3.3/dist/nearlib.js"></script>
<script src="./main.js"></script>
</body>
</html>
<!-- << markup-snippet -->
43 changes: 43 additions & 0 deletions blank_project/src/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Initializing contract

// >> frontend-snippet

async function doInitContract() {
// Getting config from cookies that are provided by the NEAR Studio.
const config = await nearlib.dev.getConfig();
console.log("nearConfig", config);

// Initializing connection to the NEAR DevNet.
window.near = await nearlib.dev.connect();

// Initializing our contract APIs by contract name and configuration.
window.contract = await near.loadContract(config.contractName, {
// NOTE: This configuration only needed while NEAR is still in development
// View methods are read only. They don't modify the state, but usually return some value.
viewMethods: ["hello"],
// Change methods can modify the state. But you don't receive the returned value when called.
changeMethods: [],
// Sender is the account ID to initialize transactions.
// For devnet we create accounts on demand. See other examples on how to authorize accounts.
sender: nearlib.dev.myAccountId
});

// Once everything is ready, we can start using contract
return doWork();
}

// Using initialized contract
async function doWork() {
// Calling method hello on the blockchain for our contract.
// .hello() returns a promise which we awaiting.
const message = await contract.hello();
// Displaying the message once we have it.
document.getElementById('contract-message').innerText = message;
}

// COMMON CODE BELOW:
// Loads nearlib and this contract into window scope.

window.nearInitPromise = doInitContract().catch(console.error);

// << frontend-snippet
41 changes: 41 additions & 0 deletions blank_project/src/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// >> tests-snippet
describe("Greeter", function() {
let near;
let contract;
let accountId;

jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;

// Common setup below
beforeAll(async function() {
if (window.testSettings === undefined) {
window.testSettings = {};
}
near = await nearlib.dev.connect(testSettings);
accountId = testSettings.accountId ? testSettings.accountId : nearlib.dev.myAccountId;
const contractName = testSettings.contractName ?
testSettings.contractName :
(new URL(window.location.href)).searchParams.get("contractName");
contract = await near.loadContract(contractName, {
// NOTE: This configuration only needed while NEAR is still in development
// View methods are read only. They don't modify the state, but usually return some value.
viewMethods: ["hello"],
// Change methods can modify the state. But you don't receive the returned value when called.
changeMethods: [],
sender: accountId
});
});

// Multiple tests can be described below. Search Jasmine JS for documentation.
describe("simple", function() {
beforeAll(async function() {
// There can be some common setup for each test.
});

it("get hello message", async function() {
const result = await contract.hello();
expect(result).toBe("Hello, world");
});
});
});
// << tests-snippet
26 changes: 19 additions & 7 deletions gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ ncp.limit = 16;
gulp.task("build:model", async function (done) {
const asc = require("assemblyscript/bin/asc");
const buildModelFn = function(fileName) {
asc.main([
fileName,
"--baseDir", yargs.argv.out_dir,
"--nearFile", generateNearFileFullPath(fileName),
"--measure"
], done);
if (fs.existsSync(yargs.argv.out_dir + "/" + fileName)){
asc.main([
fileName,
"--baseDir", yargs.argv.out_dir,
"--nearFile", generateNearFileFullPath(fileName),
"--measure"
], done);
}
};
yargs.argv.model_files.forEach(buildModelFn);
});
Expand Down Expand Up @@ -57,7 +59,7 @@ async function ensureDir (dirPath) {

gulp.task('copyfiles', async function(done) {
// Need to wait for the copy to finish, otherwise next tasks do not find files.
console.log("Copying files to build directory v2");
console.log("Copying files to build directory");
const copyDirFn = () => {
return new Promise(resolve => {
ncp (yargs.argv.src_dir, yargs.argv.out_dir, response => resolve(response));
Expand All @@ -76,6 +78,16 @@ gulp.task('copyfiles', async function(done) {
done();
});

gulp.task('newProject', async function(done) {
// Need to wait for the copy to finish, otherwise next tasks do not find files.
console.log("Copying files to new project directory");
const copyDirFn = () => {
return new Promise(resolve => {
ncp (__dirname + "/blank_project", yargs.argv.project_dir, response => resolve(response));
})};
await copyDirFn();
});

gulp.task('clean', async function(done) {
const rmDirFn = () => {
return new Promise(resolve => {
Expand Down
25 changes: 25 additions & 0 deletions near
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,36 @@ const clean = {
}
};

const newProject = {
command: 'new_project',
desc: 'create a new blank project',
builder: (yargs) => yargs
.option('project_dir', {
desc: 'project directory',
type: 'string',
default: '.'
})
,
handler: (argv) => {
console.log(__dirname);
gulp.on('error', function(e) {
console.log("Create new project failed. Error:")
console.log(e.error);
});
if (gulp.task('newProject')) {
const result = gulp.task('newProject')(argv).catch(console.log);
} else {
throw "Unexpected error: clean task not found in gulpfile."
}
}
};

yargs // eslint-disable-line
.command(createAccount)
.command(build)
.command(deploy)
.command(clean)
.command(newProject)
.demandCommand(1, 'Please enter a command')
.argv;

6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "near-shell",
"version": "0.0.9",
"description": "Command line utilities to interact with near blockchain. NEAR cli.",
"version": "0.0.11",
"description": "Command line utilities to interact with near blockchain",
"main": "index.js",
"scripts": {
"build": "echo \"Error: not implemented\" && exit 1",
Expand All @@ -24,6 +24,8 @@
"devDependencies": {},
"dependencies": {
"assemblyscript": "github:nearprotocol/assemblyscript",
"assemblyscript-json": "github:nearprotocol/assemblyscript-json",
"near-runtime-ts": "github:nearprotocol/near-runtime-ts",
"fs": "0.0.1-security",
"gulp": "^4.0.0",
"ncp": "^2.0.0",
Expand Down

0 comments on commit 8a118f3

Please sign in to comment.