repoName
stringlengths
7
77
tree
stringlengths
0
2.85M
readme
stringlengths
0
4.9M
nghiattbss_near-crust-ipfs
README.md index.js package.json src crust.js pin.js upload.js
## Near Crust IPFS Implementation A node JS package to upload file using Crust dStorage Solution (IPFS, pinning service) for NFT marketplace on NEAR. ## Install Package `npm i near-crust-ipfs` ## Functions - `upload(authHeader, content)`: to upload a file using Crust IPFS gateway - `pin(authHeader, cid, fileName)`: to pin a file using Crust IPFS pinning service - `uploadToCrust(file)`: to upload & pin a file using Crust IPFS. For NEAR, authHeader can be created by this code block: ``` // 1. get authheader const keyPair = KeyPair.fromRandom('ed25519'); // get address const addressRaw = keyPair.getPublicKey().toString(); const address = addressRaw.substring(8); // get singature const {signature} = keyPair.sign(Buffer.from(address)); const sig = u8aToHex(signature).substring(2); // Authorization: Bear <base64(ChainType-PubKey:SignedMsg)> // compile a authHeader const authHeaderRaw = `near-${address}:${sig}`; const authHeader = Buffer.from(authHeaderRaw).toString('base64'); ``` ## How to use ### Using React Dropzone Component - [React Dropzone](https://react-dropzone.js.org/) - [Sample Code](https://github.com/BSSCommerce/picasarts.io---Near/blob/master/src/components/common/ImageUpload.jsx) ### Using html file upload Import library to your js file. - `import { uploadToCrust } from "near-crust-ipfs"` Create a html file upload - `<input type="file" onChange={(e) => handleInputChange("file", e.target.files[0])} />` Create a function handleInputChange to handle state, and use uploadToCrustFunction to upload - `await uploadToCrust(file)`
near_sandbox
.github workflows docker-image.yml release.yml rust.yml tests.yml Cargo.toml README.md crate CHANGELOG.md Cargo.toml build.rs src lib.rs sync.rs npm .changeset README.md config.json __tests__ path.test.ts test.ts dist getBinary.d.ts getBinary.js index.d.ts index.js install.d.ts install.js run.d.ts run.js test.d.ts uninstall.d.ts uninstall.js utils.d.ts utils.js getBinary.js install.js package.json run.js src getBinary.ts index.ts install.ts run.ts uninstall.ts utils.ts tsconfig.json uninstall.js
# Changesets Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it [in our repository](https://github.com/changesets/changesets) We have a quick list of common questions to get you started engaging with this project in [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) # NEAR Sandbox NEAR Sandbox lets you easily run a local NEAR blockchain. NEAR Sandbox is a [custom build](https://github.com/near/nearcore/blob/9f5e20b29f1a15a00fc50d6051b3b44bb6db60b6/Makefile#L67-L69) of the NEAR blockchain optimized for local development and testing. If you're familiar with [Ganache for Ethereum](https://www.trufflesuite.com/ganache), this is similar. This repository contains code to quickly install pre-built binaries of NEAR Sandbox for multiple programming languages (currently just NodeJS; Rust coming soon) and operating systems (currently just Intel-based Macs and Debian/Ubuntu-flavored Linux distros using Intel processors). # Using NEAR Sandbox If you just want to run tests against a NEAR Sandbox instance, check out [near-workspaces](https://github.com/near/workspaces) for your favorite language: - [JavaScript](https://github.com/near/workspaces-js) - [Rust](https://github.com/near/workspaces-rs) Tip: `near-runner` includes `near-sandbox` as a dependency, so you will not need to install or run `near-sandbox` on its own. If you want to run NEAR Sandbox on its own, continue reading. ## Install ### With [npm](https://www.npmjs.com/) npm i -g near-sandbox Note: If you have trouble downloading binary from IPFS gateway, you can upload a pre-built near-sandbox tar file to any file storage service and use `SANDBOX_ARTIFACT_URL` environment variable to specify it's base URL. e.g. `> SANDBOX_ARTIFACT_URL=https://s3.aws.com/my-binary npm i near-sandbox` ### With Rust Coming soon ### From Source * Install [Rust with correct build target](https://docs.near.org/develop/prerequisites) * Clone [nearcore](https://github.com/near/nearcore) git clone https://github.com/near/nearcore * `cd` into your `nearcore` folder and run `make sandbox` cd nearcore make sandbox * For ease-of-use, you can copy (or [symlink](https://kb.iu.edu/d/abbe)) the binary to somewhere in your [PATH](https://www.cloudsavvyit.com/1933/what-is-the-unix-path-and-how-do-you-add-programs-to-it/). For example, if you have a `~/bin` folder: cp target/debug/near-sandbox ~/bin/ ## Use * Initialize the Sandbox node near-sandbox --home /tmp/near-sandbox init * Run it near-sandbox --home /tmp/near-sandbox run To find out other things you can do: near-sandbox --help ## Stop Once you're finished using the sandbox node you can stop it by using <kbd>Ctrl</kbd><kbd>C</kbd>. To clean up the data it generates: rm -rf /tmp/near-sandbox # What's special about NEAR Sandbox NEAR Sandbox includes custom features to make tweaking local and test environments easier. * `sandbox_patch_state` RPC call, used by [`patchState` in runner-js](https://github.com/near/runner-js#patch-state-on-the-fly), useful for making arbitrary state mutations on any contract or account
html1704_challenge-1
.gitpod.yml README.md babel.config.js contract Cargo.toml README.md compile.js src lib.rs target .rustc_info.json debug .fingerprint Inflector-9e3c62115074b9cf lib-inflector.json autocfg-cd255646c4ed3339 lib-autocfg.json borsh-derive-5ae16aa117c7f399 lib-borsh-derive.json borsh-derive-internal-d0a21fc13ecc1b98 lib-borsh-derive-internal.json borsh-schema-derive-internal-ab395ab8b11e5be3 lib-borsh-schema-derive-internal.json byteorder-f262064c186a8c75 build-script-build-script-build.json convert_case-95e284bc56c12eb5 lib-convert_case.json derive_more-69cde6e327ff0a85 lib-derive_more.json generic-array-092d57466d24febe build-script-build-script-build.json hashbrown-23b6f330e2a36dbb run-build-script-build-script-build.json hashbrown-cdcf863ec2cdd3e4 build-script-build-script-build.json hashbrown-d487e72206b07264 lib-hashbrown.json indexmap-1e685d288818a816 lib-indexmap.json indexmap-8c9f9453652d0887 run-build-script-build-script-build.json indexmap-c3ac49ead90ef7d0 build-script-build-script-build.json itoa-b06d4cff304254a3 lib-itoa.json memchr-035c4269a6233099 build-script-build-script-build.json near-rpc-error-core-b63ef2006bff2a54 lib-near-rpc-error-core.json near-rpc-error-macro-379a6a754086af95 lib-near-rpc-error-macro.json near-sdk-core-f46d7222a619c60b lib-near-sdk-core.json near-sdk-macros-67a465e716adb526 lib-near-sdk-macros.json num-bigint-d69df36f763339d9 build-script-build-script-build.json num-integer-733a54d88eb397d7 build-script-build-script-build.json num-rational-ae7f1682837cfa6a build-script-build-script-build.json num-traits-4b4399d154f5b10c build-script-build-script-build.json proc-macro-crate-12334d71f27edc5f lib-proc-macro-crate.json proc-macro2-3fad645d9b421e8e run-build-script-build-script-build.json proc-macro2-5fcfb2a46c5df79c build-script-build-script-build.json proc-macro2-c9e8a8bd316f311f lib-proc-macro2.json quote-577c40b40ecd60bd lib-quote.json ryu-218129458e3751da run-build-script-build-script-build.json ryu-a617547c15767d1a build-script-build-script-build.json ryu-b54e014f019506d7 lib-ryu.json serde-283b18786897374f lib-serde.json serde-552ea552149e1a4d build-script-build-script-build.json serde-b99429f97a9b8ecc run-build-script-build-script-build.json serde_derive-4f31ad7a0e5ec105 build-script-build-script-build.json serde_derive-9dbff8f6028e8a2c run-build-script-build-script-build.json serde_derive-ea52ca527bcbc75e lib-serde_derive.json serde_json-bf5b0064d1b45776 run-build-script-build-script-build.json serde_json-c83f8bc67b0f9037 lib-serde_json.json serde_json-e9017e2e6ab453c7 build-script-build-script-build.json syn-0359a400ed92222f build-script-build-script-build.json syn-60a21e1eff858db6 lib-syn.json syn-84879f3141fd595e run-build-script-build-script-build.json toml-dc98d37f2aab96c5 lib-toml.json typenum-b487004bf7bc9a32 build-script-build-script-main.json unicode-xid-1ccf9a8622388d0a lib-unicode-xid.json version_check-c02be86861b3fab0 lib-version_check.json wee_alloc-4c1d5fc69208e232 build-script-build-script-build.json wasm32-unknown-unknown debug .fingerprint ahash-31500eed5b448aad lib-ahash.json aho-corasick-b89132b0381c749e lib-aho_corasick.json base64-646109cef868d84f lib-base64.json block-buffer-5f9d9d8b55f1d3b1 lib-block-buffer.json block-buffer-bc99728b4d693dcc lib-block-buffer.json block-padding-13821e343f46f753 lib-block-padding.json borsh-6fb510f42155d666 lib-borsh.json bs58-7212f4faed67cdbf lib-bs58.json byte-tools-a6cd60c7ea46575a lib-byte-tools.json byteorder-425eab9cce122222 lib-byteorder.json byteorder-b1278529b57a037f run-build-script-build-script-build.json cfg-if-53998aee5392ec20 lib-cfg-if.json cfg-if-f1de31271fe8376a lib-cfg-if.json digest-02b66ce3a4c78c1c lib-digest.json digest-5bb936ed42c05efb lib-digest.json generic-array-30cd0a03156a9b87 lib-generic_array.json generic-array-6802468a8a36c271 run-build-script-build-script-build.json generic-array-845551d223c666ba lib-generic_array.json greeter-98ace302c5fafa12 lib-greeter.json hashbrown-483ac2a52167ff2a lib-hashbrown.json hashbrown-51d3921aceef5ebb run-build-script-build-script-build.json hashbrown-9e21cf3d1d28819b lib-hashbrown.json hex-261cfc3fcecaa4ef lib-hex.json indexmap-33441b070f70d190 run-build-script-build-script-build.json indexmap-549d81fd1b4aaa1a lib-indexmap.json itoa-4c06a779eef25af4 lib-itoa.json keccak-b0c9ccd044944503 lib-keccak.json lazy_static-b79bf709c5f09987 lib-lazy_static.json memchr-8974d6d0eea4ab03 lib-memchr.json memchr-f922bd3de584c24c run-build-script-build-script-build.json memory_units-3804df6a88cda429 lib-memory_units.json near-primitives-core-22512a59771af8d0 lib-near-primitives-core.json near-runtime-utils-3357838d53825c1b lib-near-runtime-utils.json near-sdk-b965d2f0da3bed34 lib-near-sdk.json near-vm-errors-20e6f8caa2eb3f21 lib-near-vm-errors.json near-vm-logic-afd430776e895057 lib-near-vm-logic.json num-bigint-7e7d1d90c83f30cc lib-num-bigint.json num-bigint-a699a4a251dccc5e run-build-script-build-script-build.json num-integer-8d01ee791cd20c62 lib-num-integer.json num-integer-e00df3a90a9271c0 run-build-script-build-script-build.json num-rational-abf9bfbe7cbd8dd6 lib-num-rational.json num-rational-e5b980680ebaaecb run-build-script-build-script-build.json num-traits-c1660e0226ce670c run-build-script-build-script-build.json num-traits-e0f409119940623e lib-num-traits.json opaque-debug-20397d3162c70a7a lib-opaque-debug.json opaque-debug-67e11037907b0a62 lib-opaque-debug.json regex-e489d254d1e7e12d lib-regex.json regex-syntax-bcaa825332c5ba50 lib-regex-syntax.json ryu-52a388757c15c1a6 run-build-script-build-script-build.json ryu-a7a81e23b9bcb06b lib-ryu.json serde-6d59abfee35ae43b run-build-script-build-script-build.json serde-ebe94b1241f5047e lib-serde.json serde_json-1da7a0c73c632567 lib-serde_json.json serde_json-c3b71e6248b2b8a1 run-build-script-build-script-build.json sha2-bdebeba22d9faa70 lib-sha2.json sha3-4cf15448deb657a1 lib-sha3.json typenum-4976863587ad7c9e run-build-script-build-script-main.json typenum-eee99a2ed0f1494e lib-typenum.json wee_alloc-1aec1ccd611d0139 run-build-script-build-script-build.json wee_alloc-6b415af9b59e77f3 lib-wee_alloc.json build num-bigint-a699a4a251dccc5e out radix_bases.rs typenum-4976863587ad7c9e out consts.rs op.rs tests.rs wee_alloc-1aec1ccd611d0139 out wee_alloc_static_array_backend_size_bytes.txt package-lock.json package.json src App.js __mocks__ fileMock.js assets logo-black.svg logo-white.svg config.js global.css index.html index.js jest.init.js main.test.js utils.js wallet login index.html
HelloWorldNear ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `HelloWorldNear.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `HelloWorldNear.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account HelloWorldNear.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'HelloWorldNear.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages HelloWorldNear Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html
here-wallet_herewallet-connect
README.md dist index.d.ts index.js selector.d.ts selector.js index.css package-lock.json package.json src index.ts selector.ts tsconfig.json
# @herewallet/connect ```bash npm i @here-wallet/connect --save ``` > Make sure your near-api-js is version ^1.0.0 ## Usage ```ts import * as near from "near-api-js" import runHereWallet from "@here-wallet/connect" import "@here-wallet/connect/index.css" // Initialize here wallet bridge runHereWallet({ near, onlyHere: true }) // Just keep using the near api just like you did before! const initialize = async () => { const near = await connect({ ... }) const wallet = new WalletConnection(near, "app"); wallet.requestSignIn({ contractId: "contract", methodNames: ["method"], }); } ``` ## Options * `near`<br/> By default Here use global near package * `onlyHere`<br/> By default here show popup with choose between near wallet and here wallet, but with this flag all methods will be redirects to herewallet ## Dispose You can enable and disable herewallet patching at any time, for example: ```ts let dispose; const enableHereWallet = () => { dispose = runHereWallet({ near, onlyHere: true }) } const disableHereWallet = () => { if (dispose == null) return dispose() } ``` ## Patching Herewallet bridge absolutely safe, code of this lib just wrap few prototypes methods of WalletConnection and Account: ```ts // add balance of liquidity stake from here account acount.getBalance() // Resolve redirects to herewallet wallet.requestSignIn() wallet.requestSignTransactions() ``` ## Networks At the moment here wallet only supports mainnet and testnet networks. If you specify some other network in the near-api initialization, `@here-wallet/connect` will be ignored and all signatures will go through your near-api settings. Our endpoints: ```ts mainnet: { hereWallet: "https://web.herewallet.app", hereContract: "storage.herewallet.near", }, testnet: { hereWallet: "https://web.testnet.herewallet.app", hereContract: "storage.herewallet.testnet", } ```
near_StackOverflowBot
.github FUNDING.yml ISSUE_TEMPLATE BOUNTY.yml workflows PostToTwitter.yml RePostSlackIntegration.yml SlackIntegration.yml Manifest.toml Project.toml README.md
# Stack Overflow, Twitter, and Slack Integration between Stackoverflow, Twitter, and Slack for the JuliaLang.slack.com workspace. Every 30 minutes, a GitHub Action will run, which pings the StackOverflow API for new [Julia tagged questions](https://stackoverflow.com/questions/tagged/julia). If there are new questions, it posts them in the `#stackoverflow-feed` channel on the [JuliaLang Slack](https://julialang.org/slack/) and on [Twitter](https://twitter.com/JuliaOverflow). Every even numbered day of the month at 11 AM UTC time, un-answered questions will be re-posted. This project is built in pure Julia and uses [Slack.jl](https://github.com/logankilpatrick/Slack.jl) as well as [StackOverflow.jl](https://github.com/logankilpatrick/StackOverflow.jl). ## Current state The code for this repo should now be in a static state and 100% Julia (yay). The only change on the near horizon is that Re-posted questions will be sent as a threaded message. This integration will happen in Slack.jl and then be utilized here. All feeedback / suggestions / feature requests are welcome! Just open an issue on this repo. ## Env Secrets `JULIALANGSLACKENDPOINT` should be in the form or `/services/TQVJBU534/BR8C1LMPS/42thawJz34SWSgZCpniyLBSE`. See https://github.com/JuliaLangSlack/Slack.jl#usage for more details. ## Resources [YML Check](https://yamlchecker.com) [Slack App settings page](https://api.slack.com/apps/AN12MEVDH/general?) [Slack Message formatting check](https://api.slack.com/docs/messages/builder?msg=%7B%22text%22%3A%20%22This%20is%20a%20line%20of%20text.%5CnAnd%20this%20is%20another%20one.%22%7D) [GitHub Action Scheduling Docs](https://help.github.com/en/articles/events-that-trigger-workflows#scheduled-events-schedule) [Slack.jl](https://github.com/logankilpatrick/Slack.jl) [StackOverflow.jl](https://github.com/logankilpatrick/StackOverflow.jl)
frobenius7_frobenius7.github.io
Near3.html NearvemberEx3.html _config.yml index.md near4 App.js config.js index.html index.js tests integration App-integration.test.js ui App-ui.test.js test.html
NEARFoundation_transaction-tracking-app
.eslintrc.json README.md db AvailableTokens.ts export.ts queries all.ts query.ts row.ts helpers RateLimiter.ts currency.ts datetime.ts lockup.ts nearConnection.ts next.config.js package.json pages api csv.ts public vercel.svg styles Home.module.css globals.css tsconfig.json
# 🛑 IMPORTANT! Please see the newer repo at https://github.com/NEARFoundation/transaction-tracking-app instead of this repo, which is legacy. # NEAR Transaction Tracker App (also known as "Transactions Accounting Report") Transaction Tracker App (TTA) produces a report that helps teams across the ecosystem to see a simplified view of all transactions over a certain period (e.g. the Finance/Legal/Operations team uses it to reconcile their transactions and stay compliant). ## What it does Ledgers like https://explorer.near.org don't always provide a simple view of when money changes hands (i.e. NEAR tokens or fungible tokens from one NEAR account to another). TTA allows you to specify a NEAR mainnet account ID and see a table of all transactions involding the transfer of NEAR tokens or fungible tokens into or out of that account. You can export the table as CSV. When you specify one or more NEAR acccount IDs, those account IDs get saved to your browser's localStorage. Additionally, the server starts downloading all transactions (from the private indexer) for those account IDs and processes them and saves the data into TTA's Mongo database, which is what powers the table you see in your browser. The downloads can take a while (because the tables are huge), and a cron job keeps track of their progress. --- # Overview - The frontend is a React app in the "frontend" folder. - `/frontend/src/index.html` is a great place to start exploring. Note that it loads in `/frontend/src/index.tsx`, where you can learn how the frontend connects to the NEAR blockchain. - The backend is an Express app (with cron jobs and a Mongo database) in the "backend" folder. - The backend relies on a private [clone](https://github.com/near/near-indexer-for-explorer/) of the [NEAR Explorer](https://explorer.near.org) indexer, a large PostgreSQL database (certain tables are ~1 TB). We use our own clone of NEAR Explorer (on a bare metal Hetzner server) instead of using the public credentials of the actual NEAR Explorer because the complicated queries take too long and time out. - There is also a folder called "shared" for code that both apps use. - Tests use [jest](https://jestjs.io/docs/getting-started#using-typescript). You can run via `yarn test`. --- # Getting Started To run this project locally (as an operations engineer, or a developer looking to deliver code): - Get a Nix-based development environment (Linux, Mac, WSL). - Get and setup Docker for your environment. - Clone this repo and get into the project. - run `docker-compose up` - App will be available at: http://localhost:8085/ (frontend) and http://localhost:8086/ (backend) To run this project locally (as a developer running a fully local development environment) 1. Make sure you've installed [Node.js](https://nodejs.org/en/download/package-manager/) ≥ 18. `nvm use 18`. 1. Install and start [Mongo](https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-os-x/) using the instructions in its own section below. 1. `cp frontend/.env.development frontend/.env.development.local && cp backend/.env.development backend/.env.development.local` 1. Edit the values for each of those local env files. If you set REACT_APP_ALLOW_DELETING_FROM_DATABASE to "true" in `frontend/.env.development.local` and ALLOW_DELETING_FROM_DATABASE to "true" in `backend/.env.development.local`, you will see a button in the frontend that allows you to delete records from the database, which is useful when you are manually testing whether transaction processing is working after editing the SQL queries. - Similarly, if you ever want to nuke your local Mongo cache, you can run `yarn drop_actions_and_tasks_and_types`. 1. Install PostreSQL: ```bash brew install postgresql brew services start postgresql psql postgres \du CREATE ROLE testuser WITH LOGIN PASSWORD 'secret'; ALTER ROLE testuser CREATEDB; CREATE ROLE dev WITH LOGIN PASSWORD 'public'; ALTER ROLE dev CREATEDB; \q psql postgres -U testuser CREATE DATABASE tta_test_db; GRANT ALL PRIVILEGES ON DATABASE tta_test_db TO testuser; \list \q psql postgres -U dev CREATE DATABASE local_explorer; GRANT ALL PRIVILEGES ON DATABASE local_explorer TO dev; \list \q ``` 1. Install dependencies for frontend and backend: `yarn install_all` 1. Seed the local dev database via `yarn seed`. 1. (optional) `POSTGRESQL_CONNECTION_STRING=___ ./backend/test_helpers/updateTestData.sh` (where `___` is the mainnet Postgres credentials string) 1. `yarn test` 1. Start the backend: `yarn backend_dev` 1. In a second terminal, start the frontend: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`). TODO: Check whether https://www.npmjs.com/package/concurrently would help. 1. Visit http://localhost:1234/ in the browser. Go ahead and play with the app and the code. As you make frontend code changes, the app will automatically reload. ## Setting up Mongo and MongoDB Shell ``` brew tap mongodb/brew brew update -v brew install [email protected] brew services start [email protected] brew install mongosh mongosh use admin show databases db.createUser( { user: "MongoTestDbUser", pwd: "MongoTestDbSecretPhrase", roles: [ { role: "readWrite", db: "test" } ] } ) db.createUser( { user: "MongoDbUser", pwd: "MongoDbSecretPhrase", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } ) show users exit ``` https://medium.com/@haxzie/getting-started-with-mongodb-setting-up-admin-and-user-accounts-4fdd33687741 was useful. # Tests `*.test.ts` files live right next to whatever file they are testing. `backend/src/helpers/updateTransactions.test.ts` contains tests about the complicated SQL queries that process each of the ~40 transaction types. To test that `updateTransactions` works correctly, first ensure that `backend/test_helpers/expectedOutput.csv` contains the values that you want. (Ideally we will have more than 1 row per transaction type.) Then run `yarn update_test_data`. This command will download all of the real-world data from the mainnet indexer Postgres database into SQL files that the automated tests will use when seeing your local database (the mock indexer). (See https://stackoverflow.com/a/20909045/ for how the update_test_data script works.) To avoid downloading terabytes of data from the remote database (private indexer), the scripts look in `expectedOutput.csv` to see exactly which transaction hashes matter. The output of `updateTestData.sh` is `backend/test_helpers/internal/testData.sql`, which is how tests can see the local PostgreSQL test database (mock indexer). The inputs for `backend/src/helpers/updateTransactions.test.ts` come from `expectedOutput.csv` (its transaction hashes and account IDs), and of course so do the expected outputs. Then run `yarn test` to run the tests. # Updating seed files for local database and test database 1. Visit https://docs.google.com/spreadsheets/d/1g3yymiHP2QJqwLrJdwma8gu-J92XCbZR-DDpObmu_2o/edit#gid=726351924 - The FLO team has decided that this is the official list of transaction types. 1. Sort the rows by "keep" descending, "phase" ascending, "txType" ascending. - (We can't try to skip this step by creating a sorted "filter view" in Google Sheets because the "Download" step doesn't honor filter views.) 1. For rows where "keep" === 1, search for occurrences of "E+". If any numeric values are using this kind of (exponential) notation, you need to correct the cell (write out the full number instead). - You might need to prepend the value with a single quote ('). 1. File > Download > .ods (choose a temporary folder somewhere). - (We need this extra step before CSV because Google Sheets doesn't save the double-quotes correctly.) 1. Open the .ods file in LibreOffice. 1. Delete the rows where "keep" is not "1". 1. Delete these columns: "keep", "errors", "phase". 1. File > Save As > Text CSV (.csv) 1. Choose to save to `backend/test_helpers/expectedOutput.csv` 1. Check the boxes for "Save cell content as shown" and "Quote all text cells" # TODO: Explain how to get permissions. # Other Helpful Docs - [react](https://reactjs.org/) - [create-near-app](https://github.com/near/create-near-app) - [near accounts](https://docs.near.org/docs/concepts/account) - [near wallet](https://wallet.testnet.near.org/) - [near-cli](https://github.com/near/near-cli) - [gh-pages](https://github.com/tschaub/gh-pages) # Intro This is a temporary app while https://github.com/NEARFoundation/tx-tracking-app is being improved. # Framework This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). # Deployments It automatically deploys each commit of the `main` branch to https://tta-basic.onrender.com/ See https://dashboard.render.com/ ## Getting Started `cp .env.development.local.example .env.development.local` Then edit the values. Run the development server: ```bash npm run dev # or yarn dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file. [API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`. The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
gacarg_wish
Cargo.toml README.md build.sh src lib.rs main.rs
# wish write your wishes on near contract! using this rebo u can send me wish(wish.gacar.testnet) with tip! or someone send can wish _____ #### for build and deploy(use helper): ``` run build.sh ``` ## commands: #### add wish: ``` near call U_CONTRACT --accountId=U_ACCOUNT_UD add_wish '{"wish":"(U_WISH)"}' --deposit TIPS ``` #### get wish: ``` near call U_CONTRACT --accountId=U_ACCOUNT_UD '{"account_id":"SEARCH_ACCOUNT_ID"}' ``` #### get list wish: ``` near view U_CONTRACT --accountId=U_ACCOUNT_UD get_list_wish ``` ## [Loom video](https://www.loom.com/share/91c0ff1b13474c9e82ef85c0a71a3562 )
georgesimon640_event-arena
README.md package.json public index.html manifest.json robots.txt smartcontract README.md asconfig.json assembly as_types.d.ts index.ts model.ts tsconfig.json package-lock.json package.json src App.css App.js App.test.js components Wallet.js marketplace AddEvent.js Event.js Events.js utils Cover.js Loader.js Notifications.js index.css index.js logo.svg reportWebVitals.js setupTests.js utils config.js marketplace.js near.js
# Prerequsities Install the next tools: * `node` * `yarn` * `near-cli` Also, you'd need a code editor of choice. In this course we are going to use Visual Studio Code. ## Create project structure The next directories and files must be created to proceed with smart contracts: * assembly/ - this directory contains smart contracts source code * asconfig.json - contains most of configuration properties * assembly/tsconfig.json ### `assembly/asconfig.json` By default it's needed to add the next content to the file. By adding this, we just extend the configuration provided by `near-sdk-as`. ``` { "extends": "near-sdk-as/asconfig.json" } ``` ### `assembly/tsconfig.json` The purpose of this file is to specify compiler options and root level files that are necessary for a TypeScript project to be compiled. Also, this file implies that the directory where `tsconfig.json` is located is the root of the TypeScript project. ``` { "extends": "../node_modules/assemblyscript/std/assembly.json", "include": [ "./**/*.ts" ] } ``` ### `as_types.d.ts` This files declares that some type names must be included in the compilation. In this case, names are imported from `near-sdk-as` ``` /// <reference types="near-sdk-as/assembly/as_types" /> ``` ## Initialize project Run the next commands in a terminal window (in the project's root): ``` yarn init ``` It will create a `package.json` file where development dependencies can be added. Run the next command to add `near-sdk-as` to the project: ``` yarn add -D near-sdk-as ``` The next step is to create an entry file for the smart contract - create `index.ts` file in the `assembly` directory. The resulting project structure should be like this: ``` ├── asconfig.json ├── assembly │   ├── as_types.d.ts │   ├── index.ts │   └── tsconfig.json ├── package.json └── yarn.lock ``` # Compile, build and deployt the smart contract ## Compile & build a smart contract Before a smart contract can be deployed, it must be built as `.wasm`. To do that, the next command should be run from the project's root: ``` yarn asb ``` The output of this command is a `.wasm` file that is placed into `${PROJECT_ROOT}/build/release` directory. ## Login to an account in a shell In order to deploy a contract from via terminal, account's credentials are needed. To get the credentials, run the next command in a terminal window: ``` near login ``` It opens a wallet url in a browser where you can login to your account (or selected one of the existing accounts if you have one). As the result the session in the terminal window is authenticated and you can start deploying contracts and view/call functions. ## Deploy a smart contract To deploy a smart contract, run the next command from in a terminal window: ``` near deploy ${PATH_TO_WASM} --accountId=${ACCOUNT_NAME} ``` where: * `${ACCOUNT_NAME}` - an account name that should be used to deploy a smart contract * `${CONTRACT_NAME}` - an account name that should be used for the contract (we will use the same value as for `${ACCOUNT_NAME}`) * `${PATH_TO_WASM}` - a path to the `.wasm` file issued by the `yarn asb` command - `${PROJECT_ROOT}/build/release/some_name.wasm` ## Contract interaction There are two types of functions in `near`: * `view` functions are used to read state hence they are free. Nothing is modified/persisted when a `view` function is called. * `call` functions are used to modify state of the data stored in the blockchain. # Event-Arena Event Arena is a platform that hosts can create event and other users can register to attend these events by paying the registration fee set by the event creator. # Demo link https://voluble-crepe-731ef0.netlify.app
mikenevermindng_Token-factory
factory Cargo.toml build.sh src lib.rs ft-token Cargo.toml build.sh src lib.rs
connesus ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `connesus.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `connesus.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account connesus.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'connesus.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages
mohammeddr1_blockvotee
.gitpod.yml README.md babel.config.js package.json
blockvote ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `blockvote.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `blockvote.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account blockvote.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'blockvote.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # blockvotetutorial2
near_workspaces-js
.github ISSUE_TEMPLATE BOUNTY.yml workflows lint.yml tests-sandbox.yml typedoc-generator.yml .near-credentials workspaces testnet ro3evqruqecmi7q4uwux1651245117258.json .vscode extensions.json settings.json README.md __tests__ 01.basic-transactions.ava.ts 03.single-use-access-keys-with-linkdrop.ava.ts 04.cross-contract-calls-with-fungible-token.ava.ts 05.spoon-contract-to-sandbox.ava.ts 06.init-config.ava.ts 07.resue-worker.ava.ts 08.custom-network.ava.ts 08.fast-forward.ava.ts ci-ignore-02.patch-state.ava.ts examples simple-project README.md __tests__ test-simple-project.ava.js test-status-message.ava.js package.json lerna.json package.json packages js README.md __tests__ account-manager.ava.ts account.ava.ts jsonrpc.ava.js record-builder.ava.ts dist account account-manager.d.ts account-manager.js account.d.ts account.js index.d.ts index.js near-account-manager.d.ts near-account-manager.js near-account.d.ts near-account.js utils.d.ts utils.js contract-state.d.ts contract-state.js index.d.ts index.js internal-utils.d.ts internal-utils.js jsonrpc.d.ts jsonrpc.js record builder.d.ts builder.js index.d.ts index.js types.d.ts types.js server index.d.ts index.js server.d.ts server.js transaction-result.d.ts transaction-result.js transaction.d.ts transaction.js types.d.ts types.js utils.d.ts utils.js worker.d.ts worker.js package.json scripts delete-accounts.ts install.js src account account-manager.ts account.ts index.ts near-account-manager.ts near-account.ts utils.ts contract-state.ts index.ts internal-utils.ts jsonrpc.ts record builder.ts index.ts types.ts server index.ts node-port-check.d.ts server.ts transaction-result.ts transaction.ts types.ts utils.ts worker.ts tsconfig.json typedoc.json tsconfig.json typedoc.json
<div align="center"> <h1>NEAR Workspaces (TypeScript/JavaScript Edition)</h1> [![Project license](https://img.shields.io/badge/license-Apache2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Project license](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![Discord](https://img.shields.io/discord/490367152054992913?label=discord)](https://discord.gg/Vyp7ETM) [![NPM version](https://img.shields.io/npm/v/near-workspaces.svg?style=flat-square)](https://npmjs.com/near-workspaces) [![Size on NPM](https://img.shields.io/bundlephobia/minzip/near-workspaces.svg?style=flat-square)](https://npmjs.com/near-workspaces) </div> `NEAR Workspaces` is a library for automating workflows and writing tests for NEAR smart contracts. You can use it as is or integrate with test runner of your choise (AVA, Jest, Mocha, etc.). If you don't have a preference, we suggest you to use AVA. Quick Start (without testing frameworks) =========== To get started with `Near Workspaces` you need to do only two things: 1. Initialize a `Worker`. ```ts const worker = await Worker.init(); const root = worker.rootAccount; const alice = await root.createSubAccount('alice'); const contract = await root.devDeploy('path/to/compiled.wasm'); ``` 2. Writing tests. `near-workspaces` is designed for concurrency. Here's a simple way to get concurrent runs using plain JS: ```ts import {strict as assert} from 'assert'; await Promise.all([ async () => { await alice.call( contract, 'some_update_function', {some_string_argument: 'cool', some_number_argument: 42} ); const result = await contract.view( 'some_view_function', {account_id: alice} ); assert.equal(result, 'whatever'); }, async () => { const result = await contract.view( 'some_view_function', {account_id: alice} ); /* Note that we expect the value returned from `some_view_function` to be a default here, because this `fork` runs *at the same time* as the previous, in a separate local blockchain */ assert.equal(result, 'some default'); } ]); ``` ``` More info in our main README: https://github.com/near/workspaces-js # Simple project This is the simplest project setup example with workspaces-js. You can copy it as the starting point when setup your project. ## Usage ``` yarn yarn test ``` ## Setup your project Assume you have written your smart contract. Setup and write workspaces-js test as this project is easy: 1. Build the contract to `.wasm` as place it in `contracts/`. 2. Install the `near-workspaces` and `ava` with `npm` or `yarn`. 3. Copy the ava.config.cjs to you project root directory. 4. Write test, place in `__tests__/`, end with `.ava.js`. You can refer to `__tests__/test-status-message.ava.js` as an example. 5. We're done! Run test with `yarn test` and continue adding more tests! <div align="center"> <h1>NEAR Workspaces (TypeScript/JavaScript Edition)</h1> [![Project license](https://img.shields.io/badge/license-Apache2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Project license](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![Discord](https://img.shields.io/discord/490367152054992913?label=discord)](https://discord.gg/Vyp7ETM) [![NPM version](https://img.shields.io/npm/v/near-workspaces.svg?style=flat-square)](https://npmjs.com/near-workspaces) [![Size on NPM](https://img.shields.io/bundlephobia/minzip/near-workspaces.svg?style=flat-square)](https://npmjs.com/near-workspaces) </div> `NEAR Workspaces` is a library for automating workflows and writing tests for NEAR smart contracts. You can use it as is or integrate with test runner of your choise (AVA, Jest, Mocha, etc.). If you don't have a preference, we suggest you to use AVA. Quick Start (without testing frameworks) =========== To get started with `Near Workspaces` you need to do only two things: 1. Initialize a `Worker`. ```ts const worker = await Worker.init(); const root = worker.rootAccount; const alice = await root.createSubAccount('alice'); const contract = await root.devDeploy('path/to/compiled.wasm'); ``` Let's step through this. 1. `Worker.init` initializes a new `SandboxWorker` or `TestnetWorker` depending on the config. `SandboxWorker` contains [NEAR Sandbox](https://github.com/near/sandbox), which is essentially a local mini-NEAR blockchain. You can create one `Worker` per test to get its own data directory and port (for Sandbox) or root account (for Testnet), so that tests can run in parallel without race conditions in accessing states. If there's no state intervention. you can also reuse the `Worker` to speedup the tests. 2. The worker has a `root` account. For `SandboxWorker`, it's `test.near`. For `TestnetWorker`, it creates a unique account. The following accounts are created as subaccounts of the root account. The name of the account will change from different runs, so you should not refer to them by hard coded account name. You can access them via the account object, such as `root`, `alice` and `contract` above. 3. `root.createSubAccount` creates a new subaccount of `root` with the given name, for example `alice.<root-account-name>`. 4. `root.devDeploy` creates an account with random name, then deploys the specified Wasm file to it. 5. `path/to/compiled.wasm` will resolve relative to your project root. That is, the nearest directory with a `package.json` file, or your current working directory if no `package.json` is found. To construct a path relative to your test file, you can use `path.join(__dirname, '../etc/etc.wasm')` ([more info](https://nodejs.org/api/path.html#path_path_join_paths)). 6. `worker` contains a reference to this data directory, so that multiple tests can use it as a starting point. 7. If you're using a test framework, you can save the `worker` object and account objects `root`, `alice`, `contract` to test context to reuse them in subsequent tests. 8. At the end of test, call `await worker.tearDown()` to shuts down the Worker. It gracefully shuts down the Sandbox instance it ran in the background. However, it keeps the data directory around. That's what stores the state of the two accounts that were created (`alice` and `contract-account-name` with its deployed contract). 2. Writing tests. `near-workspaces` is designed for concurrency. Here's a simple way to get concurrent runs using plain JS: ```ts import {strict as assert} from 'assert'; await Promise.all([ async () => { await alice.call( contract, 'some_update_function', {some_string_argument: 'cool', some_number_argument: 42} ); const result = await contract.view( 'some_view_function', {account_id: alice} ); assert.equal(result, 'whatever'); }, async () => { const result = await contract.view( 'some_view_function', {account_id: alice} ); /* Note that we expect the value returned from `some_view_function` to be a default here, because this `fork` runs *at the same time* as the previous, in a separate local blockchain */ assert.equal(result, 'some default'); } ]); ``` Let's step through this. 1. `worker` and accounts such as `alice` are created before. 2. `call` syntax mirrors [near-cli](https://github.com/near/near-cli) and either returns the successful return value of the given function or throws the encountered error. If you want to inspect a full transaction and/or avoid the `throw` behavior, you can use `callRaw` instead. 3. While `call` is invoked on the account _doing the call_ (`alice.call(contract, …)`), `view` is invoked on the account _being viewed_ (`contract.view(…)`). This is because the caller of a view is irrelevant and ignored. See the [tests](https://github.com/near/workspaces-js/tree/main/__tests__) directory in this project for more examples. Quick Start with AVA =========== Since `near-workspaces` is designed for concurrency, AVA is a great fit, because it runs tests concurrently by default. To use`NEAR Workspaces` with AVA: 1. Start with the basic setup described [here](https://github.com/avajs/ava). 2. Add custom script for running tests on Testnet (if needed). Check instructions in `Running on Testnet` section. 3. Add your tests following these example: ```ts import {Worker} from 'near-workspaces'; import anyTest, {TestFn} from 'ava' const test = anyTest as TestFn<{ worker: Worker; accounts: Record<string, NearAccount>; }>; /* If using `test.before`, each test is reusing the same worker; If you'd like to make a copy of the worker, use `beforeEach` after `afterEach`, which allows you to isolate the state for each test */ test.before(async t => { const worker = await Worker.init(); const root = worker.rootAccount; const contract = await root.devDeploy('path/to/contract/file.wasm'); /* Account that you will be able to use in your tests */ const ali = await root.createSubAccount('ali'); t.context.worker = worker; t.context.accounts = {root, contract, ali}; }) test('Test name', async t => { const {ali, contract} = t.context.accounts; await ali.call(contract, 'set_status', {message: 'hello'}); const result: string = await contract.view('get_status', {account_id: ali}); t.is(result, 'hello'); }); test.after(async t => { // Stop Sandbox server await t.context.worker.tearDown().catch(error => { console.log('Failed to tear down the worker:', error); }); }); ``` "Spooning" Contracts from Testnet and Mainnet ============================================= [Spooning a blockchain](https://coinmarketcap.com/alexandria/glossary/spoon-blockchain) is copying the data from one network into a different network. near-workspaces makes it easy to copy data from Mainnet or Testnet contracts into your local Sandbox environment: ```ts const refFinance = await root.importContract({ mainnetContract: 'v2.ref-finance.near', blockId: 50_000_000, withData: true, }); ``` This would copy the Wasm bytes and contract state from [v2.ref-finance.near](https://explorer.near.org/accounts/v2.ref-finance.near) to your local blockchain as it existed at block `50_000_000`. This makes use of Sandbox's special [patch state](#patch-state-on-the-fly) feature to keep the contract name the same, even though the top level account might not exist locally (note that this means it only works in Sandbox testing mode). You can then interact with the contract in a deterministic way the same way you interact with all other accounts created with near-workspaces. Gotcha: `withData` will only work out-of-the-box if the contract's data is 50kB or less. This is due to the default configuration of RPC servers; see [the "Heads Up" note here](https://docs.near.org/api/rpc/contracts#view-contract-state). Some teams at NEAR are hard at work giving you an easy way to run your own RPC server, at which point you can point tests at your custom RPC endpoint and get around the 50kB limit. See an [example of spooning](https://github.com/near/workspaces-js/blob/main/__tests__/05.spoon-contract-to-sandbox.ava.ts) contracts. Running on Testnet ================== near-workspaces is set up so that you can write tests once and run them against a local Sandbox node (the default behavior) or against [NEAR TestNet](https://docs.near.org/concepts/basics/networks). Some reasons this might be helpful: * Gives higher confidence that your contracts work as expected * You can test against deployed testnet contracts * If something seems off in Sandbox mode, you can compare it to testnet In order to use Workspaces JS in testnet mode you will need to have a testnet account. You can create one [here](https://wallet.testnet.near.org/). You can switch to testnet mode in three ways. 1. When creating Worker set network to `testnet` and pass your master account: ```ts const worker = await Worker.init({ network: 'testnet', testnetMasterAccountId: '<yourAccountName>', }) ``` 2. Set the `NEAR_WORKSPACES_NETWORK` and `TESTNET_MASTER_ACCOUNT_ID` environment variables when running your tests: ```bash NEAR_WORKSPACES_NETWORK=testnet TESTNET_MASTER_ACCOUNT_ID=<your master account Id> node test.js ``` If you set this environment variables and pass `{network: 'testnet', testnetMasterAccountId: <masterAccountId>}` to `Worker.init`, the config object takes precedence. 3. If using `near-workspaces` with AVA, you can use a custom config file. Other test runners allow similar config files; adjust the following instructions for your situation. Create a file in the same directory as your `package.json` called `ava.testnet.config.cjs` with the following contents: ```js module.exports = { ...require('near-workspaces/ava.testnet.config.cjs'), ...require('./ava.config.cjs'), }; module.exports.environmentVariables = { TESTNET_MASTER_ACCOUNT_ID: '<masterAccountId>', }; ``` The [near-workspaces/ava.testnet.config.cjs](https://github.com/near/workspaces-js/blob/main/ava.testnet.config.cjs) import sets the `NEAR_WORKSPACES_NETWORK` environment variable for you. A benefit of this approach is that you can then easily ignore files that should only run in Sandbox mode. Now you'll also want to add a `test:testnet` script to your `package.json`'s `scripts` section: ```diff "scripts": { "test": "ava", + "test:testnet": "ava --config ./ava.testnet.config.cjs" } ``` Stepping through a testnet example ---------------------------------- Let's revisit a shortened version of the example from How It Works above, describing what will happen in Testnet. 1. Create a `Worker`. ```ts const worker = await Worker.init(); ``` `Worker.init` creates a unique testnet account as root account. 2. Write tests. ```ts await Promise.all([ async () => { await alice.call( contract, 'some_update_function', {some_string_argument: 'cool', some_number_argument: 42} ); const result = await contract.view( 'some_view_function', {account_id: alice} ); assert.equal(result, 'whatever'); }, async () => { const result = await contract.view( 'some_view_function', {account_id: alice} ); assert.equal(result, 'some default'); } ]); ``` Note: Sometimes account creation rate limits are reached on testnet, simply wait a little while and try again. Running tests only in Sandbox ------------------------------- If some of your runs take advantage of Sandbox-specific features, you can skip these on testnet in two ways: 1. You can skip entire sections of your files by checking `getNetworkFromEnv() === 'sandbox'`. ```ts let worker = Worker.init(); // things make sense to any network const root = worker.rootAccount; const alice = await root.createSubAccount('alice'); if (getNetworkFromEnv() === 'sandbox') { // thing that only makes sense with sandbox } ``` 2. Use a separate testnet config file, as described under the "Running on Testnet" heading above. Specify test files to include and exclude in config file. Patch State on the Fly ====================== In Sandbox-mode, you can add or modify any contract state, contract code, account or access key with `patchState`. You cannot perform arbitrary mutation on contract state with transactions since transactions can only include contract calls that mutate state in a contract-programmed way. For example, with an NFT contract, you can perform some operation with NFTs you have ownership of, but you cannot manipulate NFTs that are owned by other accounts since the smart contract is coded with checks to reject that. This is the expected behavior of the NFT contract. However, you may want to change another person's NFT for a test setup. This is called "arbitrary mutation on contract state" and can be done with `patchState`. Alternatively you can stop the node, dump state at genesis, edit genesis, and restart the node. The later approach is more complicated to do and also cannot be performed without restarting the node. It is true that you can alter contract code, accounts, and access keys using normal transactions via the `DeployContract`, `CreateAccount`, and `AddKey` [actions](https://nomicon.io/RuntimeSpec/Actions.html?highlight=actions#actions). But this limits you to altering your own account or sub-account. `patchState` allows you to perform these operations on any account. To see an example of how to do this, see the [patch-state test](https://github.com/near/workspaces-js/blob/main/__tests__/02.patch-state.ava.ts). Time Traveling =============== In Sandbox-mode, you can forward time-related state (the block height, timestamp and epoch height) with `fastForward`. This means contracts which require time sensitive data do not need to sit and wait the same amount of time for blocks on the sandbox to be produced. We can simply just call the api to get us further in time. For an example, see the [fast-forward test](./__tests__/08.fast-forward.ava.ts) Note: `fastForward` does not speed up an in-flight transactions. Pro Tips ======== * `NEAR_WORKSPACES_DEBUG=true` – run tests with this environment variable set to get copious debug output and a full log file for each Sandbox instance. * `Worker.init` [config](https://github.com/near/workspaces-js/blob/main/packages/js/src/interfaces.ts) – you can pass a config object as the first argument to `Worker.init`. This lets you do things like: * skip initialization if specified data directory already exists (the default behavior) ```ts Worker.init( { rm: false, homeDir: './test-data/alice-owns-an-nft' }, ) ``` * always recreate such data directory instead with `rm: true` * specify which port to run on * and more! Env variables ======== ```text NEAR_CLI_MAINNET_RPC_SERVER_URL NEAR_CLI_TESTNET_RPC_SERVER_URL ``` Clear them in case you want to get back to the default RPC server. Example: ```shell export NEAR_CLI_MAINNET_RPC_SERVER_URL=<put_your_rpc_server_url_here> ``` here is a testcase: [jsonrpc.ava.js](./packages/js/__tests__/jsonrpc.ava.js)
josefophe_nearmock-rs
Cargo.toml README.md build.bat build.sh src lib.rs test.sh
# Rust Smart Contract Template ## Getting started To get started with this template: 1. Click the "Use this template" button to create a new repo based on this template 2. Update line 2 of `Cargo.toml` with your project name 3. Update line 4 of `Cargo.toml` with your project author names 4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites) 5. Begin writing your smart contract in `src/lib.rs` 6. Test the contract `cargo test -- --nocapture` 8. Build the contract `RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release` **Get more info at:** * [Rust Smart Contract Quick Start](https://docs.near.org/docs/develop/contracts/rust/intro) * [Rust SDK Book](https://www.near-sdk.io/)
LeeWayner_jackpot-near-demo
.eslintrc.js README.md contracts Cargo.toml README.md build.sh src lib.rs trust-contract lib.rs package.json server app.js middleware near.js package.json utils near-utils.js src App.css App.js components Contract.js Keys.js Wallet.js config.js index.html index.js state app.js near.js utils near-utils.js state.js storage.js test app.test.js near-utils.js server.test.js test-utils.js trust.test.js utils patch-config.js
# Near Certificate Level 1 Demo Demo Jackpot contract name: dev-1638960081273-25835481325504 Deploy transaction id: C93mFeVLF4RqoVjM3HLustiR4DeJkhcELdaM9SWp9Aq5 Minimal NEP#4 Implementation ============================ This contract implements bare-minimum functionality to satisfy the [NEP#4](https://github.com/nearprotocol/NEPs/pull/4) specification Notable limitations of this implementation ========================================== * Only the token owner can mint tokens. * You cannot give another account escrow access to a limited set of your tokens; an escrow must be trusted with all of your tokens or none at all * No functions to return the maximum or current supply of tokens * No functions to return metadata such as the name or symbol of this NFT * No functions (or storage primitives) to find all tokens belonging to a given account * Usability issues: some functions (e.g. `revoke_access`, `transfer`, `get_token_owner`) do not verify that they were given sensible inputs; if given non-existent keys, the errors they throw will not be very useful Still, if you track some of this information in an off-chain database, these limitations may be acceptable for your needs. In that case, this implementation may help reduce gas and storage costs. Notable additions that go beyond the specification of NEP#4 =========================================================== `mint_token`: the spec gives no guidance or requirements on how tokens are minted/created/assigned. This specific implementation only allows the contract owner to mint new tokens. If this implementation of `mint_token` is close to matching your needs, feel free to ship your NFT with only minor modifications. If you'd rather go with a strategy such as minting the whole supply of tokens upon deploy of the contract, or something else entirely, you may want to drastically change this behavior.
Java-para-todos_smart-contract-metztli
README.md as-pect.config.js asconfig.json aseembly as.types.d.ts index.ts model.ts tsconfig.json package.json
# Smart Contract Metztli ## INTRODUCCIÓN A medida que las criptomonedas y la tecnología blockchain se hicieron más populares, Bitcoin, Ethereum y otras redes empezaron a enfrentar desafíos de escalabilidad debido a una mayor demanda. El creciente interés por las aplicaciones descentralizadas y los tokens no fungibles (NFT) hace que dichos desafíos sean particularmente notorios en la blockchain Ethereum. La red a menudo sufre elevados precios del gas y costos de transacción debido al gran tráfico, lo que puede resultar desalentador para muchos usuarios y desarrolladores. A pesar de que hay varios equipos que exploran distintas soluciones de escalabilidad para redes blockchain, el equipo de NEAR Protocol (NEAR) está centrado en solventar las limitaciones a través del sharding.
marija-mijailovic_mint_fungible_token
.gitpod.yml README.md contract Cargo.toml README.md src external.rs lib.rs integration-tests Cargo.toml src tests.rs target .rustc_info.json debug .fingerprint actix-f890f546970199f0 lib-actix.json actix-rt-93bacc8e09691b80 lib-actix_rt.json actix_derive-e207052baed9f2d1 lib-actix_derive.json addr2line-28b4814b343fe24a lib-addr2line.json addr2line-f63a43c59b18431e lib-addr2line.json adler-858bd64f4c31c0d1 lib-adler.json adler-f82fbff19b442ad8 lib-adler.json ahash-c719d6b2bde37366 run-build-script-build-script-build.json ahash-d886da6223e35546 build-script-build-script-build.json ahash-f573443ba7b149e3 lib-ahash.json aho-corasick-23b781de6f346cd7 lib-aho_corasick.json aho-corasick-7b0be70019cce818 lib-aho_corasick.json ansi_term-2c04eb7e5356e169 lib-ansi_term.json anyhow-1e6850e3be735397 lib-anyhow.json anyhow-540879b1ea8699c5 run-build-script-build-script-build.json anyhow-a7a4a56fe6922aa0 lib-anyhow.json anyhow-f3419b6bbc3e5ef7 build-script-build-script-build.json arrayref-24708cf1ba2eebb4 lib-arrayref.json arrayvec-29ab9de30bf8315f lib-arrayvec.json arrayvec-9467d1dec571ca8e run-build-script-build-script-build.json arrayvec-bf2189e320a74cd7 lib-arrayvec.json arrayvec-cc8c6898c975e805 build-script-build-script-build.json arrayvec-e47cd96fcdceaa10 lib-arrayvec.json arrayvec-f80d3e01dd83f122 lib-arrayvec.json async-io-3ebd119a7842d52c lib-async-io.json async-io-558b260b1637666c run-build-script-build-script-build.json async-io-d220f8987ab88722 lib-async-io.json async-io-f031dc95f86d0c04 build-script-build-script-build.json async-process-60dd3c2efcc0dcf2 lib-async-process.json async-process-6cdfa456369938a1 run-build-script-build-script-build.json async-process-8223a97ba5a8913f build-script-build-script-build.json async-process-ab724364835fbf5d lib-async-process.json async-trait-0bd8d56ea1281134 run-build-script-build-script-build.json async-trait-1745214ce415bb1c lib-async-trait.json async-trait-9affaf76d2bc3c34 build-script-build-script-build.json autocfg-e7ca05903964afbb lib-autocfg.json backtrace-133b3618e84048b9 build-script-build-script-build.json backtrace-add8417f770fdc9b lib-backtrace.json backtrace-d05a23b62abccd23 lib-backtrace.json backtrace-ffff84cb7c58f2ce run-build-script-build-script-build.json base64-31929adc05d844be lib-base64.json base64-998b29efe5d13773 lib-base64.json binary-install-cbcd80e8019115a3 lib-binary-install.json binary-install-edec766c63aa32d9 lib-binary-install.json bitflags-19fcf5a03b1d5132 lib-bitflags.json bitvec-b3b7b689a2192e22 lib-bitvec.json blake2-14a28bfe2b49caf3 lib-blake2.json block-buffer-0414d8affa7c5dcb lib-block-buffer.json block-buffer-58d787918be07569 lib-block-buffer.json borsh-5173ffa967c4f08e lib-borsh.json borsh-derive-03a31efe7d14cc89 lib-borsh-derive.json borsh-derive-internal-712214a3f03b651a lib-borsh-derive-internal.json borsh-schema-derive-internal-dd4dbe351b5f6c13 lib-borsh-schema-derive-internal.json bs58-aa108e3711e25659 lib-bs58.json byte-slice-cast-d973ebc659558655 lib-byte-slice-cast.json byteorder-0d9133d4213b7819 lib-byteorder.json byteorder-827e1da5be11fd60 lib-byteorder.json bytes-017ce34b2adf53c5 lib-bytes.json bytesize-31eb192a669b8773 lib-bytesize.json bzip2-bd6488044a397d99 lib-bzip2.json bzip2-f75dd27700960621 lib-bzip2.json bzip2-sys-0792448352a876bf build-script-build-script-build.json bzip2-sys-5a7f1166f2b66bfe run-build-script-build-script-build.json bzip2-sys-9b71b94f3eaf50be lib-bzip2_sys.json bzip2-sys-f496dbf06c6d9b85 lib-bzip2_sys.json c2-chacha-6ab729a2291ab98f lib-c2-chacha.json cache-padded-12d85df2b525981f lib-cache-padded.json cache-padded-ccbf56638ba106e7 lib-cache-padded.json cc-cbfd2c7a8f88c135 lib-cc.json cfg-if-113393695a919ceb lib-cfg-if.json cfg-if-547ae41a7204f788 lib-cfg-if.json cfg-if-c4179dfb752cca64 lib-cfg-if.json chrono-69c4e46c69218c8f lib-chrono.json chrono-e9239c69523c0ee9 lib-chrono.json cipher-03f51c676ad78b2d lib-cipher.json concurrent-queue-58a55d5ab2283920 lib-concurrent-queue.json concurrent-queue-b6e779a7be9b4e41 lib-concurrent-queue.json convert_case-053a30fffa0bd654 lib-convert_case.json core-foundation-d43dbf4379df9b00 lib-core-foundation.json core-foundation-sys-5642fd3e0992d1f0 lib-core-foundation-sys.json core-foundation-sys-8c44c85026457c39 build-script-build-script-build.json core-foundation-sys-a151c41c5cb8bbc8 run-build-script-build-script-build.json core-foundation-sys-f1b49b7cf3743646 lib-core-foundation-sys.json cpufeatures-4d20fd3aea5a9780 lib-cpufeatures.json crc32fast-0697d6949ba5e35b run-build-script-build-script-build.json crc32fast-151b2d19d9086e77 build-script-build-script-build.json crc32fast-2178b82d4c4c0004 lib-crc32fast.json crc32fast-c17214a40ce5b58d lib-crc32fast.json crossbeam-channel-d6d875fcbc82e784 lib-crossbeam-channel.json crossbeam-utils-b1f92f474fbcc16a build-script-build-script-build.json crossbeam-utils-c07bbe1d0344ed8b lib-crossbeam-utils.json crossbeam-utils-c721bae91c09b272 run-build-script-build-script-build.json crunchy-3b484ed7d48e9d8b run-build-script-build-script-build.json crunchy-9fe51b59834b1742 lib-crunchy.json crunchy-fc138d4b0ca01606 build-script-build-script-build.json crypto-common-5dc6d4aa5e392436 lib-crypto-common.json crypto-mac-e205d122ce2cfb38 lib-crypto-mac.json curl-2abf866255d0cca0 run-build-script-build-script-build.json curl-4069b5b8dca0f770 lib-curl.json curl-97b25a43613cb0cc build-script-build-script-build.json curl-b15df2c5f226de2b lib-curl.json curl-sys-1ec5093ed55a955e build-script-build-script-build.json curl-sys-6d3f22e87cce9ff7 lib-curl_sys.json curl-sys-8093620058633d95 lib-curl_sys.json curl-sys-ba43b4ce1be072e1 run-build-script-build-script-build.json curve25519-dalek-a0aa23bef47b8f0b lib-curve25519-dalek.json derive_more-1ecc1589a37ea908 lib-derive_more.json digest-b7fa6cbcda5a9c7c lib-digest.json digest-edc1cfd18177894e lib-digest.json dirs-6fab4c16c0566696 lib-dirs.json dirs-813a21799684b355 lib-dirs.json dirs-a88b220dd0db1ed4 lib-dirs.json dirs-sys-e65dec71822e3819 lib-dirs-sys.json easy-ext-4d32359cfe53bd66 lib-easy-ext.json ed25519-66ebc913c3c4697a lib-ed25519.json ed25519-dalek-6e7ebb7f00fa5276 lib-ed25519-dalek.json encoding_rs-53f92f5c782770c2 run-build-script-build-script-build.json encoding_rs-b3bc7be564a24fb0 build-script-build-script-build.json encoding_rs-d51dfd1699a186bb lib-encoding_rs.json event-listener-432f68ae54f5680f lib-event-listener.json event-listener-46e7d851289b23ae lib-event-listener.json failure-69a6122c476b72ac lib-failure.json failure-9151a188db9ebfef lib-failure.json failure_derive-48ec8ed4e26c5262 lib-failure_derive.json failure_derive-8d449cc38c1204f4 build-script-build-script-build.json failure_derive-a17c3d579f3b46f8 run-build-script-build-script-build.json fastrand-850549886f09cfd1 lib-fastrand.json fastrand-b69faec9d03e70c5 lib-fastrand.json filetime-554e963447318529 lib-filetime.json filetime-5762ce789902b2cf lib-filetime.json fixed-hash-2b69dfd0dd68964d lib-fixed-hash.json flate2-87c7e6b1edf94689 lib-flate2.json flate2-dc3b0b81300910c7 lib-flate2.json fnv-042b15ce25807ae9 lib-fnv.json form_urlencoded-c91630427a1506ca lib-form_urlencoded.json funty-b43799034261d164 lib-funty.json futures-channel-594a85b836887dc8 lib-futures-channel.json futures-channel-880e42d2fcdc54c3 build-script-build-script-build.json futures-channel-b4afcc72d067ebd9 run-build-script-build-script-build.json futures-core-128e7e59b540e78c build-script-build-script-build.json futures-core-587fb2523666145a lib-futures-core.json futures-core-6cec8b73064a7686 run-build-script-build-script-build.json futures-core-d4c2725df18243ce lib-futures-core.json futures-io-9a9072e8541e0728 lib-futures-io.json futures-io-9eb5b2d58a7b18d4 lib-futures-io.json futures-lite-4dce6c2db3f7807b lib-futures-lite.json futures-lite-cbe330082ccc0c51 lib-futures-lite.json futures-sink-6c5122824dd0dc30 lib-futures-sink.json futures-task-251235f4ab784011 build-script-build-script-build.json futures-task-9a4aa0dc59052e28 run-build-script-build-script-build.json futures-task-b18e4d0a3cc80b59 lib-futures-task.json futures-util-0174425ac8bb3e7b lib-futures-util.json futures-util-903afeb25e82eb68 run-build-script-build-script-build.json futures-util-b8054936f6c283dd build-script-build-script-build.json generic-array-a34e01579584ec49 run-build-script-build-script-build.json generic-array-ab611ae170f369a2 lib-generic_array.json generic-array-adb4b6e383096b14 build-script-build-script-build.json getrandom-26930420c5259460 run-build-script-build-script-build.json getrandom-6a7f0f9eb48228ab lib-getrandom.json getrandom-e94786bb0afa87a6 lib-getrandom.json getrandom-fb6054d7d97d8b7e build-script-build-script-build.json gimli-5d347ac38bd1aa3a lib-gimli.json gimli-7a56051f07054dc2 lib-gimli.json h2-c618a266a965308f lib-h2.json hashbrown-3e63a8264f259d5a lib-hashbrown.json hashbrown-57bc24ac6a011c8e lib-hashbrown.json heck-ad869977884323ce lib-heck.json hex-33254ce7b700798d lib-hex.json hex-8324c6b1ae72528b lib-hex.json hex-fc577482bbf4185b lib-hex.json home-43c4948612dc683d lib-home.json home-a65e196a4df8a3c4 lib-home.json http-body-1dec4ed5554929bd lib-http-body.json http-c3a1902f17bd6e03 lib-http.json httparse-1cb3e5703152be60 lib-httparse.json httparse-89be7a880eb12d17 run-build-script-build-script-build.json httparse-9cc2f7ec54254607 build-script-build-script-build.json httpdate-88b4a09ee64fe848 lib-httpdate.json hyper-919c9dc19ed77921 lib-hyper.json hyper-tls-8c8b2214b30b3bc5 lib-hyper-tls.json iana-time-zone-0d9f9f53b82c92ab lib-iana-time-zone.json iana-time-zone-386386403972bf62 lib-iana-time-zone.json idna-0de77f8b91df489f lib-idna.json impl-codec-02058c7cfbfca7cf lib-impl-codec.json impl-trait-for-tuples-8e4f7c129529d332 lib-impl-trait-for-tuples.json indexmap-2726bac38f553a5a run-build-script-build-script-build.json indexmap-c80ea7f0220a5fc1 lib-indexmap.json indexmap-d536383993201657 build-script-build-script-build.json integration-tests-1c842d5d6ebe71b8 example-integration-tests.json ipnet-795fbd3143af12d8 lib-ipnet.json is_executable-23e333b863bd4756 lib-is_executable.json is_executable-cf8cb8c3637bf58d lib-is_executable.json itoa-4d337ffcf2f1ea8d lib-itoa.json itoa-b8b17daece5bce6e lib-itoa.json itoa-d0c4dc98e5d62d2e lib-itoa.json lazy_static-1b186a0ce60fb41b lib-lazy_static.json libc-08171c39d1a63164 build-script-build-script-build.json libc-5667c0dd53c397bb run-build-script-build-script-build.json libc-a0b8a5feeff581f6 lib-libc.json libc-c46eea223e5a8cd5 lib-libc.json libz-sys-0a2fe3614d8ec8b8 lib-libz-sys.json libz-sys-4e3ceb64f31f2381 build-script-build-script-build.json libz-sys-6a44bef63774d10c lib-libz-sys.json libz-sys-d653c7a5dc80ea26 run-build-script-build-script-build.json lock_api-0be72b10590dd0be lib-lock_api.json lock_api-b76766cc1b77ba27 run-build-script-build-script-build.json lock_api-cd97695aeb704b59 build-script-build-script-build.json log-4398adebe8a3a8ca lib-log.json log-754c6038801dd6ba lib-log.json log-ae530ee81c355859 build-script-build-script-build.json log-fdee3daf9bec996a run-build-script-build-script-build.json maplit-4cbf590f4a2c9745 lib-maplit.json matchers-f6a845e5556076b4 lib-matchers.json matches-e7274a65bd76115f lib-matches.json memchr-387fbab2cdb5dbe3 lib-memchr.json memchr-a23b671cde0167d1 lib-memchr.json memchr-ddd25960255b1ad7 build-script-build-script-build.json memchr-ed8e6df6adb19d6a run-build-script-build-script-build.json mime-28aaa047b2606a88 lib-mime.json miniz_oxide-87db1efad8fb94c4 lib-miniz_oxide.json miniz_oxide-9e36fb11c8b013df lib-miniz_oxide.json mio-e949a58fe1650c2a lib-mio.json native-tls-9562109ef03a7162 run-build-script-build-script-build.json native-tls-b02718d3baa8dd50 build-script-build-script-build.json native-tls-c22624e3e80f7a6b lib-native-tls.json near-account-id-369e79eb6373b7e2 lib-near-account-id.json near-chain-configs-facdfae4ae12de73 lib-near-chain-configs.json near-chain-primitives-7ea1d27166d12efd lib-near-chain-primitives.json near-chunks-primitives-de8adff7b8a0fe0a lib-near-chunks-primitives.json near-client-primitives-d5da1f36a815159e lib-near-client-primitives.json near-crypto-5e5b44f402dc5185 lib-near-crypto.json near-jsonrpc-client-acd490b47c1f4be0 lib-near-jsonrpc-client.json near-jsonrpc-primitives-bbef33f85c07cfea lib-near-jsonrpc-primitives.json near-network-primitives-ee1f224c3dd57c66 lib-near-network-primitives.json near-primitives-160f92a64b66689d lib-near-primitives.json near-primitives-core-14220ceaa15b86f9 lib-near-primitives-core.json near-rpc-error-core-2e13ff95a9e31631 lib-near-rpc-error-core.json near-rpc-error-macro-d15ffb2a04922cd9 lib-near-rpc-error-macro.json near-sandbox-utils-0702cdcf9ff48ebd build-script-build-script-build.json near-sandbox-utils-1a723bd9e420255a run-build-script-build-script-build.json near-sandbox-utils-b83f4f2b1e263984 lib-near-sandbox-utils.json near-sandbox-utils-df379858cec587a1 lib-near-sandbox-utils.json near-units-99e11912296d6b26 lib-near-units.json near-units-core-40c7805fedbf2db1 lib-near-units-core.json near-units-core-5124feb298be0096 lib-near-units-core.json near-units-macro-33dcb46eec20aaf1 lib-near-units-macro.json near-vm-errors-f82cb0042829469d lib-near-vm-errors.json nodrop-3e9f93bee1818ac0 lib-nodrop.json nodrop-7b09a371bc25dad5 lib-nodrop.json num-bigint-a09216aa085e8721 build-script-build-script-build.json num-bigint-b93920fdde2df200 run-build-script-build-script-build.json num-bigint-ff3c8d3d5aff95f9 lib-num-bigint.json num-format-2f10646c7472467d lib-num-format.json num-format-3ed7f38be3499d3d lib-num-format.json num-integer-22dd03690c42cbc3 lib-num-integer.json num-integer-4176fb3632f97f58 lib-num-integer.json num-integer-9dd3d98371acfea4 build-script-build-script-build.json num-integer-f15fef2cfef3304a run-build-script-build-script-build.json num-rational-bc15ecbadb3d62d3 build-script-build-script-build.json num-rational-f5382f979564f095 run-build-script-build-script-build.json num-rational-f6069cbc745a041c lib-num-rational.json num-traits-0ebdd4f377be87a8 run-build-script-build-script-build.json num-traits-18a457225f75c980 lib-num-traits.json num-traits-354734e324a62f96 lib-num-traits.json num-traits-c92e850257918cf4 build-script-build-script-build.json num_cpus-1b530f63119cb9ed lib-num_cpus.json object-35cb4c157d4178d1 lib-object.json object-ba621f88604d1482 lib-object.json once_cell-96bf5c4886155156 lib-once_cell.json once_cell-fa4395168e72e066 lib-once_cell.json opaque-debug-d02774f9be40d760 lib-opaque-debug.json parity-scale-codec-52a39adadbb28799 lib-parity-scale-codec.json parity-scale-codec-derive-3aad3244cdf0f815 lib-parity-scale-codec-derive.json parity-secp256k1-19f1dd1eae175fc9 run-build-script-build-script-build.json parity-secp256k1-6ae034410dc6cd86 build-script-build-script-build.json parity-secp256k1-e0b77022ef6981f3 lib-secp256k1.json parking-c9cc267f17e72820 lib-parking.json parking-dc63c943c0e9d0cc lib-parking.json parking_lot-d6046aaebda2fe44 lib-parking_lot.json parking_lot_core-2d7c3ad9d70dc188 build-script-build-script-build.json parking_lot_core-3ec4dfe056df8174 lib-parking_lot_core.json parking_lot_core-f8037e32cb3132f4 run-build-script-build-script-build.json percent-encoding-79211a885f44c3cb lib-percent-encoding.json pin-project-05ddf5529cfe6b03 lib-pin-project.json pin-project-internal-1517bc4fc6cebf61 lib-pin-project-internal.json pin-project-lite-8818766aa8e91039 lib-pin-project-lite.json pin-project-lite-cee2c2450ec13f8f lib-pin-project-lite.json pin-utils-6b2f1ec8c257d447 lib-pin-utils.json pkg-config-4abd8efe544e99c7 lib-pkg-config.json pkg-config-59c29e99c9c69270 lib-pkg-config.json polling-10da06af8925981b lib-polling.json polling-65003646a4f02bcb run-build-script-build-script-build.json polling-c1b4697b27623c1c lib-polling.json polling-d1097a9ecd50f89c build-script-build-script-build.json portpicker-f6b1dd31170cb398 lib-portpicker.json ppv-lite86-935cd2204261b2bb lib-ppv-lite86.json primitive-types-8eac0c195a9aaad8 lib-primitive-types.json proc-macro-crate-743c8c7d8e64b345 lib-proc-macro-crate.json proc-macro-crate-a4412baac2094b4b lib-proc-macro-crate.json proc-macro2-0aaaf97b61cf2b85 run-build-script-build-script-build.json proc-macro2-cda26b7e2159c02f lib-proc-macro2.json proc-macro2-da85fb38197b06f9 build-script-build-script-build.json quote-667ff666576ceb5a build-script-build-script-build.json quote-9e449efd26161204 run-build-script-build-script-build.json quote-e972fb8ca6573e81 lib-quote.json radium-25ed7c5379e5f630 run-build-script-build-script-build.json radium-ac11fe0919f57b20 lib-radium.json radium-b3c7d926f34665a5 build-script-build-script-build.json rand-87c9ab1567f0ab73 lib-rand.json rand-b3a7ef523560011f lib-rand.json rand_chacha-ed673a03188e9aef lib-rand_chacha.json rand_chacha-feb21732a19c0c0d lib-rand_chacha.json rand_core-102aa32d3ff707fc lib-rand_core.json rand_core-729dcc2560e8cbca lib-rand_core.json reed-solomon-erasure-54c1058c0579e036 build-script-build-script-build.json reed-solomon-erasure-62aebc1b2ad19216 lib-reed-solomon-erasure.json reed-solomon-erasure-d725c4c5e8a0afc0 run-build-script-build-script-build.json regex-9014ca75aaf8204e lib-regex.json regex-automata-9f8cbfc438666901 lib-regex-automata.json regex-c0438920e1bab30d lib-regex.json regex-syntax-5ef26c782b982fff lib-regex-syntax.json regex-syntax-b5f71f3631350283 lib-regex-syntax.json remove_dir_all-d4eed08308896d39 lib-remove_dir_all.json reqwest-66eb02d107133d62 lib-reqwest.json rustc-demangle-5f07c398a0f33316 lib-rustc-demangle.json rustc-demangle-e942706306c8fe7a lib-rustc-demangle.json rustc-hex-65496bfa335265f6 lib-rustc-hex.json rustversion-6f81e8ce7a512df8 build-script-build-script-build.json rustversion-b4aa0ff606bacdad run-build-script-build-script-build.json rustversion-c5ab0b0656e75860 lib-rustversion.json ryu-4500a746ffcf4120 lib-ryu.json scopeguard-82221405f4e5bfb0 lib-scopeguard.json security-framework-f77b8b446cf046fb lib-security-framework.json security-framework-sys-acef3cd4e39c3458 lib-security-framework-sys.json serde-0065f847d0e7fabb run-build-script-build-script-build.json serde-b99065c98db926ae lib-serde.json serde-c4c0623b34a9e7a7 build-script-build-script-build.json serde-f6e57893baa9da9b lib-serde.json serde_derive-241c8720f1487d22 run-build-script-build-script-build.json serde_derive-583a81c365be497d lib-serde_derive.json serde_derive-e283c1d67cde26bd build-script-build-script-build.json serde_json-0e0455191c0b5419 build-script-build-script-build.json serde_json-1ee8850e37dc095c run-build-script-build-script-build.json serde_json-8b5eb1d8e30f05f3 lib-serde_json.json serde_urlencoded-46c699ebaead7760 lib-serde_urlencoded.json sha2-8d8ee07fa7e4903c lib-sha2.json sha2-f9c94b6f29841dd4 lib-sha2.json sharded-slab-4e94177e51c6dbd9 lib-sharded-slab.json signal-hook-6d1eabadec56b877 build-script-build-script-build.json signal-hook-77b7f0cd9bdbc33f run-build-script-build-script-build.json signal-hook-c55817754af295b2 lib-signal-hook.json signal-hook-cf1dc956076f02c5 lib-signal-hook.json signal-hook-registry-d5235e3dc773a249 lib-signal-hook-registry.json signal-hook-registry-df0284ce96d8c190 lib-signal-hook-registry.json signature-b46605707e1efc03 lib-signature.json siphasher-44fcdfc594ab4e0d lib-siphasher.json siphasher-afe40217f94c0570 lib-siphasher.json slab-40a2b1fcb6f68ddb build-script-build-script-build.json slab-5a68fd730cd44bb3 lib-slab.json slab-62471c1f40261746 lib-slab.json slab-775a598d3efe1cac run-build-script-build-script-build.json smallvec-f1317cdc49311d70 lib-smallvec.json smart-default-27d73f3c04eaf51c lib-smart-default.json socket2-6fef3ac7fb05b703 lib-socket2.json socket2-d8d763d3d918ac23 lib-socket2.json static_assertions-30487efa69385dc8 lib-static_assertions.json strum-2032a3db36676ce2 lib-strum.json strum_macros-5da0df82ba159f56 lib-strum_macros.json subtle-eadc68db0d1ecf25 lib-subtle.json syn-7cd19a5104efa16d build-script-build-script-build.json syn-a8b3af7ae3da46cd run-build-script-build-script-build.json syn-b082b1d4ac03447f lib-syn.json synstructure-2cf58e8aeba3e604 lib-synstructure.json tap-de7b16960074974f lib-tap.json tar-5e1fd6e91fe91d06 lib-tar.json tar-c2e1b2d4a062e19f lib-tar.json tempfile-f935d2dc893216e1 lib-tempfile.json thiserror-4ab708992fc7549b lib-thiserror.json thiserror-e7df4c0bf2f47629 lib-thiserror.json thiserror-impl-f69f95c5389673ca lib-thiserror-impl.json thread_local-840232a535450fff lib-thread_local.json time-584ea93ca0dc64c0 lib-time.json time-702020bfcdaee3f9 lib-time.json tinyvec-23a2ef2cb2174c17 lib-tinyvec.json tinyvec_macros-8eafa7d5cf947455 lib-tinyvec_macros.json tokio-04714a377f8c3d50 run-build-script-build-script-build.json tokio-4c6757875de6df44 lib-tokio.json tokio-d0dfd52c6d8881a3 build-script-build-script-build.json tokio-macros-a8ceb77aadff5571 lib-tokio-macros.json tokio-native-tls-f02c4e245ceeb33e lib-tokio-native-tls.json tokio-retry-82f76f3a73f3fdee lib-tokio-retry.json tokio-util-8763378dd005f27b lib-tokio-util.json toml-4f53d23c0f925d28 lib-toml.json tower-service-e4e80a6d2e149895 lib-tower-service.json tracing-73a67ae1cead564f lib-tracing.json tracing-attributes-721154761a1187b1 lib-tracing-attributes.json tracing-core-7744f80ac182819c lib-tracing-core.json tracing-log-6947d08c9631368b lib-tracing-log.json tracing-subscriber-533a19121cf5d74d lib-tracing-subscriber.json try-lock-37c5216782e6957f lib-try-lock.json typenum-33ac51f90ca6c532 lib-typenum.json typenum-5f00231cc8b28fea run-build-script-build-script-main.json typenum-fc662d92fd984d02 build-script-build-script-main.json uint-c4237b45a64869d3 lib-uint.json unicode-bidi-3681eb209bd36b50 lib-unicode_bidi.json unicode-ident-273f8e69308c371e lib-unicode-ident.json unicode-normalization-da9ecef199b96d8a lib-unicode-normalization.json unicode-xid-d77a5930a524c502 lib-unicode-xid.json url-55664b2afef42538 lib-url.json uuid-42796ddc8133b6a9 lib-uuid.json version_check-ebe8ed00620ced58 lib-version_check.json waker-fn-1c9799f61acecb6d lib-waker-fn.json waker-fn-88653edf2b6367dd lib-waker-fn.json want-63fdaffe2b837592 lib-want.json workspaces-14d7ea16cfa48cac lib-workspaces.json workspaces-b9d3af6a481e9bae run-build-script-build-script-build.json workspaces-cffd335d4ecde160 build-script-build-script-build.json wyz-001c4546d04e38a1 lib-wyz.json xattr-2d3ad8dca97cefd1 lib-xattr.json xattr-8e46eb65d554aa79 lib-xattr.json zeroize-7bd0ba93f0e092f2 lib-zeroize.json zeroize_derive-b82e7e8268211f83 lib-zeroize_derive.json zip-7bbdb431d33b9baa lib-zip.json zip-a387b0afed3b33ae lib-zip.json build anyhow-540879b1ea8699c5 out probe.rs bzip2-sys-5a7f1166f2b66bfe out include bzlib.h crunchy-3b484ed7d48e9d8b out lib.rs num-bigint-b93920fdde2df200 out radix_bases.rs parity-secp256k1-19f1dd1eae175fc9 out flag_check.c reed-solomon-erasure-d725c4c5e8a0afc0 out table.rs typenum-5f00231cc8b28fea out consts.rs op.rs tests.rs Public header file for the library. bzlib.h end bzlib.h package-lock.json package.json
Hello NEAR! ================================= A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. 2. There are two functions to the smart contract: `get_greeting` and `set_greeting`. 3. Tests: You can run smart contract tests with the `cargo test`. [smart contract]: https://docs.near.org/develop/welcome [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://docs.near.org/develop/prerequisites#rust-and-wasm [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html near-min-fungible_token
necmigunduz_web3-necm
README.md as-pect.config.js asconfig.json package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts simple __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
## Setting up your terminal The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project. It uses the following setup: ```sh # set your terminal up to have 2 windows, A and B like this: ┌─────────────────────────────────┬─────────────────────────────────┐ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands _helper scripts_ ```sh 1.dev-deploy.sh # helper: build and deploy contracts 2.use-contract.sh # helper: call methods on ContractPromise 3.cleanup.sh # helper: delete build and deploy artifacts ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068) # Web3 Near Course on `https://app.patika.dev/courses/web3-fundamentals-and-near/` # `near-sdk-as` Starter Kit This is a good project to use as a starting point for your AssemblyScript project. ## Samples This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage There are 2 AssemblyScript contracts in this project, each in their own folder: - **simple** in the `src/simple` folder - **singleton** in the `src/singleton` folder ### Simple We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions. In this case, all exported functions become public contract methods. ```ts // return the string 'hello world' export function helloWorld(): string {} // read the given key from account (contract) storage export function read(key: string): string {} // write the given value at the given key to account (contract) storage export function write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} ``` ### Singleton We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`. In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh). ```ts @nearBindgen export class Contract { // return the string 'hello world' helloWorld(): string {} // read the given key from account (contract) storage read(key: string): string {} // write the given value at the given key to account (contract) storage @mutateState() write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} } ``` ## Usage ### Getting started (see below for video recordings of each of the following steps) INSTALL `NEAR CLI` first like this: `npm i -g near-cli` 1. clone this repo to a local folder 2. run `yarn` 3. run `./scripts/1.dev-deploy.sh` 3. run `./scripts/2.use-contract.sh` 4. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 5. run `./scripts/3.cleanup.sh` ### Videos **`1.dev-deploy.sh`** This video shows the build and deployment of the contract. [![asciicast](https://asciinema.org/a/409575.svg)](https://asciinema.org/a/409575) **`2.use-contract.sh`** This video shows contract methods being called. You should run the script twice to see the effect it has on contract state. [![asciicast](https://asciinema.org/a/409577.svg)](https://asciinema.org/a/409577) **`3.cleanup.sh`** This video shows the cleanup script running. Make sure you add the `BENEFICIARY` environment variable. The script will remind you if you forget. ```sh export BENEFICIARY=<your-account-here> # this account receives contract account balance ``` [![asciicast](https://asciinema.org/a/409580.svg)](https://asciinema.org/a/409580) ### Other documentation - See `./scripts/README.md` for documentation about the scripts - Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` ## The file system ```sh ├── README.md # this file ├── as-pect.config.js # configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts) ├── package.json # NodeJS project manifest ├── scripts │   ├── 1.dev-deploy.sh # helper: build and deploy contracts │   ├── 2.use-contract.sh # helper: call methods on ContractPromise │   ├── 3.cleanup.sh # helper: delete build and deploy artifacts │   └── README.md # documentation for helper scripts ├── src │   ├── as_types.d.ts # AssemblyScript headers for type hints │   ├── simple # Contract 1: "Simple example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 1 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 1 │   ├── singleton # Contract 2: "Singleton-style example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 2 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 2 │   ├── tsconfig.json # Typescript configuration │   └── utils.ts # common contract utility functions └── yarn.lock # project manifest version lock ``` You may clone this repo to get started OR create everything from scratch. Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files: ``` ./assembly/ ./assembly/tests/ ./assembly/tests/example.spec.ts ./assembly/tests/as-pect.d.ts ```
near-everything_market-contract
Cargo.toml README.md build.sh src external.rs internal.rs lib.rs nft_callbacks.rs sale.rs sale_views.rs
<div id="top"></div> <!-- PROJECT SHIELDS --> [![Contributors][contributors-shield]][contributors-url] [![Forks][forks-shield]][forks-url] [![Stargazers][stars-shield]][stars-url] [![Issues][issues-shield]][issues-url] [![MIT License][license-shield]][license-url] <!-- PROJECT LOGO --> <br /> <div align="center"> <a href="https://github.com/near-everything/market-contract"> <img src="docs/everything.png" alt="Logo" width="80" height="80"> </a> <h2 align="center">everything market-contract</h3> <p align="center"> The Market Smart Contract for the inventory of everything. <br /> <!-- <a href="https://documentation.everything.dev"><strong>Explore the docs »</strong></a> --> <!-- <br /> --> <br /> <a href="https://everything.dev">Use App</a> · <a href="https://github.com/near-everything/market-contract/issues">Report Bug</a> · <a href="https://github.com/near-everything/market-contract/issues">Request Feature</a> </p> </div> <!-- TABLE OF CONTENTS --> <details> <summary>Table of Contents</summary> <ol> <li> <a href="#about-the-project">About The Project</a> </li> <li> <a href="#getting-started">Getting Started</a> <ul> <li><a href="#prerequisites">Prerequisites</a></li> <li><a href="#installation">Installation</a></li> </ul> </li> <li><a href="#usage">Usage</a></li> <li><a href="#roadmap">Roadmap</a></li> <li><a href="#contributing">Contributing</a></li> <li><a href="#license">License</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#acknowledgments">Acknowledgments</a></li> </ol> </details> <!-- ABOUT THE PROJECT --> ## About The Project <!-- [![Product Name Screen Shot][product-screenshot]](https://example.com) --> The everything market-contract is an implementation for transfering tokens and facilitating transactions regarding [NEAR](https://nomicon.io) Protocol's [Non-Fungible-Tokens](https://nomicon.io/Standards/NonFungibleToken/). It interacts with the NFTs created by the [nft-contract](https://github.com/near-everything/nft-contract). <p align="right">(<a href="#top">back to top</a>)</p> ### Built With - [![Rust][rust]][rust-url] - [NEAR][near-url] <p align="right">(<a href="#top">back to top</a>)</p> <!-- GETTING STARTED --> ## Getting Started ### Prerequisites - Rust per the prerequisites in [near-sdk-rs](https://github.com/near/near-sdk-rs) - [near-cli](https://github.com/near/near-cli) ### Installation 1. Clone the repo ```sh git clone https://github.com/near-everything/market-contract.git ``` 2. Build the contract (this will create a market.wasm in /out) ```sh sh ./build.sh ``` <p align="right">(<a href="#top">back to top</a>)</p> <!-- ROADMAP --> ## Roadmap - [ ] TBD... See the [open issues](https://github.com/near-everything/market-contract/issues) for a full list of proposed features (and known issues). <p align="right">(<a href="#top">back to top</a>)</p> <!-- CONTRIBUTING --> ## Contributing Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**. If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again! 1. Fork the Project 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the Branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request <p align="right">(<a href="#top">back to top</a>)</p> <!-- LICENSE --> ## License Distributed under the MIT License. See `LICENSE.txt` for more information. <p align="right">(<a href="#top">back to top</a>)</p> <!-- CONTACT --> ## Contact Elliot Braem - [email protected] <p align="right">(<a href="#top">back to top</a>)</p> <!-- ACKNOWLEDGMENTS --> ## Acknowledgments - Contract mostly derived from [near-examples/NFT](https://github.com/near-examples/NFT) - README adapted from [Best-README-Template](https://github.com/othneildrew/Best-README-Template/blob/master/BLANK_README.md) <p align="right">(<a href="#top">back to top</a>)</p> <!-- MARKDOWN LINKS & IMAGES --> <!-- https://www.markdownguide.org/basic-syntax/#reference-style-links --> [contributors-shield]: https://img.shields.io/github/contributors/near-everything/market-contract.svg?style=for-the-badge [contributors-url]: https://github.com/near-everything/market-contract/graphs/contributors [forks-shield]: https://img.shields.io/github/forks/near-everything/market-contract.svg?style=for-the-badge [forks-url]: https://github.com/near-everything/market-contract/network/members [stars-shield]: https://img.shields.io/github/stars/near-everything/market-contract.svg?style=for-the-badge [stars-url]: https://github.com/near-everything/market-contract/stargazers [issues-shield]: https://img.shields.io/github/issues/near-everything/market-contract.svg?style=for-the-badge [issues-url]: https://github.com/near-everything/market-contract/issues [license-shield]: https://img.shields.io/github/license/near-everything/market-contract.svg?style=for-the-badge [license-url]: https://github.com/near-everything/market-contract/blob/main/LICENSE.txt [logging-in-tutorial]: docs/logging-in.gif [rust]: https://img.shields.io/badge/Rust-000?logo=rust&logoColor=fff&style=for-the-badge [rust-url]: http://rust-lang.org [near-url]: http://near.org
marco-sundsk_findsatoshi
README.md contracts nft Cargo.toml README.md build.sh src custom.rs internal.rs lib.rs mining.rs mining_internal.rs mint.rs nft_core.rs nft_metadata.rs test.sh vbtc Cargo.toml README.md build.sh src lib.rs v_btc.rs
# findsatoshi # TBD ```shell export OWNERID=findsatoshi-owner.testnet export NFTID=findsatoshi-nft.testnet ``` ### mint token ```shell near call $NFTID nft_mint '{"token_id": "testtoken01", "metadata": {"title": "熊猫-T80S", "description": "nft-description", "media": null, "media_hash": null, "copies": "500", "issued_at": "2021-04-01T14:00:01Z", "expires_at": null, "starts_at": "2021-04-01T14:00:01Z", "updated_at": "2021-04-01T14:00:01Z", "extra": "{\"id\": \"miner001\", \"type\": \"熊猫-T80S\", \"Thash\": 110, \"W\": 3250}", "reference": null, "reference_hash": null}}' --account_id=$OWNERID --amount=1 ``` ### build and deploy ```shell source build.sh near deploy $NFTID res/nft.wasm --account_id=$NFTID near call $NFTID new '{"owner_id": "findsatoshi-owner.testnet"}' --account_id=$NFTID near view $NFTID nft_metadata ``` # TBD
jonathanLozaiza_near_program
Cargo.toml src lib.rs
jorgeantonio21_MetaStage
README.md contracts CHANGELOG.md Cargo.toml README.md build.sh deploy.md src consts.rs error.rs fund_creators.rs lib.rs nft.rs registry.rs tests.rs token_receiver.rs views.rs test.sh
On a high level the contract API boils down to the following: 1. Check the epoch timeline of creator registration, followed by posterior funding by users. More explicitly, the contract operates per `Epoch`. Each time a new epoch starts, there is a period of creator registration, where creators can register their work/projects, and establish all the metadata related to this. During this period, all the data necessary for NFT minting is provided. After creator registration ends, the funding period starts. In this case, users are incentivized to come to the platform and fund the projects they consider to have more potential. The epoch changing and inner-epoch dynamics is orchestrated by an admin. This is the sole role of the admin in the entire protocol. 2. Creator registration process. The creator registration process is done via the platform by means of an RPC call to the contract. The relevant method is `creator_registration`. It receives as input a `Metadata` type. Notice, that each project has `3` tiers of NFTs. Each tier represents the scarcity of the NFT associated to the project (namely `Common`, `Uncommon`, `Rare`) Internally it consists of the following parameters - An array of size `3` of type `u128` (big integer) with the price of each NFT, for each tier; - An array of size `3` of type `String` with the Token/Project title, for each tier; - An array of size `3` of type `String` with the Token/Project description, for each tier; - An array of size `3` of type `String` with the Token/Project media link (either IPFS, or own cloud storage), for each tier; - An array of size `3` of type `u32` (integer) with the number of copies for each NFT, for each tier; - An array of size `3` of type `String` with extra metadata associated with the Creator project, for each tier; - An array of size `3` of type `String` with references associated with the Creator project, for each tier. The above input data, must be retrieved directly from the Creator, via the platform. 3. User funding. After creators have registered their projects, a new phase begins (in the current epoch). Namely, users are incentivized to fund their favorite projects, via the platform. If done via the platform, users are promp to connect their wallets and make a transfer call to a fungible contract (e.g., `USDT` or `wNear`). The fungible contract call has to be provided with the following data: - A `receiver_id`, in this case the `AccountId` of the `MetaDao` contract; - An `amount`, a `u128` value of the number of tokens the user is willing to provide to the creator. In exchange, it shall receive a NFT, corresponding to the tier in which `amount` fits in. Notice that, if the user funds a value inferior to the least tier, it will not receive a NFT back. - A `msg`, a plain `String` which specifies what is the actual creator project the user is funding and what is the tier to choose. # MetaStage MetaStage is a web3 platform for NFT creation and crowd funding. Using the highly scalable Near blockchain, we implement code that allows creators to: 1. Register and request funds from community (per epoch); 2. Build their portfolios and share their reputation. At the funding level, users can use our platform to: 1. Support and funding any project a user sees fit; 2. Build their community status as creative art ventures. Our main goal is to improve the content creation, in the digital era. This is only possible if the majority of the revenues of content creation is allocated to the actual creators, and not big corporations. For this reason, we welcome inclusiveness of ideas, creative thinking and passion for decentralization.
iOchando_Artemis-Contract
Cargo.toml README.md build.sh src lib.rs
# Artemis - Backend Artemis - Backend
philoniare_rust-code-samples
external.rs internal.rs lib.rs nft_callbacks.rs sale.rs sale_views.rs
near_indexers-docs
.github ISSUE_TEMPLATE BOUNTY.yml workflows build.yml spellcheck.yml README.md babel.config.js blog 2022-02-04-updates.md 2022-02-18-updates.md 2022-03-25-updates.md 2022-04-01-updates.md 2022-04-08-updates.md 2022-04-15-updates.md 2022-04-22-updates.md authors.yml docs data-flow-and-structures _category_.json flow _category_.json structures _category_.json intro.md projects _category_.json overview.md docusaurus.config.js package.json sidebars.js src components HomepageFeatures index.js styles.module.css ProgrammingLanguage index.js styles.module.css css custom.css monokai-sublime.css pages index.js index.module.css markdown-page.md remark rehype-highlight-word.js static img logo.svg logo_dark.svg index.html js mixpanel.js
# Website This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator. ### Installation ``` $ yarn ``` ### Local Development ``` $ yarn start ``` This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. ### Build ``` $ yarn build ``` This command generates static content into the `build` directory and can be served using any static contents hosting service. ### Deployment Using SSH: ``` $ USE_SSH=true yarn deploy ``` Not using SSH: ``` $ GIT_USER=<Your GitHub username> yarn deploy ``` If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.
Learn-NEAR-Hispano_NCD1--beyond-NEAR
README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts models Campaing.ts tsconfig.json neardev dev-account.env package-lock.json package.json
# :earth_americas: BeyondNear BeyondNear es un smart contract bajo el Near protocol, el cual permite crear campañas para la recaudacion de fondos en nears dedicados a una causa especifica. Este smart contract permite: - Crear una campaña. - Conseguir informacion de una campaña. - Conseguir lista de campañas. - Donar a una campaña. - Eliminar una campaña. # :gear: Instalación Para la instalación local de este projecto: ## Pre - requisitos - Asegúrese de haber instalado Node.js ≥ 12 (recomendamos usar nvm). - Asegúrese de haber instalado yarn: npm install -g yarn. - Instalar dependencias: yarn install. - Crear un test near account NEAR test account. - Instalar el NEAR CLI globally: near-cli es una interfaz de linea de comando (CLI) para interacturar con NEAR blockchain. # :key: Configurar NEAR CLI Configura tu near-cli para autorizar tu cuenta de prueba creada recientemente: ```html near login ``` # :page_facing_up: Clonar el repositorio ```html git clone https://github.com/JoseGabriel-web/beyondNearContract.git ``` ```html cd beyondNearContract ``` # :hammer_and_wrench: Build del proyecto y despliegue en development mode. Instalar las dependencias necesarias con npm. ```html npm install ``` Hacer el build y deployment en development mode. ```html yarn devdeploy ``` ## Comando para crear una campaña: ```html near call <your deployed contract> createCampaing "{\"categorie\": \"string\", \"objectives\": \"string\", \"location\":\"string\", \"goal\": number}" --account-id <your test account> ``` ## Comando para conseguir informacion de una campaña: ```html near call <your deployed contract> getCampaing "{\"id\": number}" --account-id <your test account> ``` ## Comando para conseguir lista de campañas: ```html near call <your deployed contract> getCampaings "{}" --account-id <your test account> ``` ## Comando para hacer donacion a una campaña: ```html near call <your deployed contract> donate "{\"campaingID\": number, \"cuantity\": number}" --account-id <your test account> ``` ## Comando para eliminar una campaña: ```html near call <your deployed contract> deleteCampaing "{\"id\": number}" --account-id <your test account> ``` # :world_map: Explora el codigo: BeyondNear smart contract file system. ```bash ├── assembly │ ├── __tests__ │ │ ├── as-pect.d.ts # As-pect unit testing headers for type hints │ │ └── main.spec.ts # Unit test for the contract │ ├── as_types.d.ts # AssemblyScript headers for type hint │ ├── index.ts # Contains the smart contract code │ ├── models.ts # Contains models accesible to the smart contract │ │ └── Campaing.ts # Contains Campaing model. │ └── tsconfig.json # Typescript configuration file ├── neardev │ ├── dev-account # In this file the provisional deploy smart contract account is saved │ └── dev-account.env # In this file the provisional deploy smart contract account is saved like a environment variable ├── out │ └── main.wasm # Compiled smart contract code using to deploy ├── as-pect.config.js # Configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # Configuration file for Assemblyscript compiler ├── package-lock.json # Project manifest lock version ├── package.json # Node.js project manifest (scripts and dependencies) ├── README.md # This file └── yarn.lock # Project manifest lock version ``` # Gracias por visitar nuestro proyecto. :wave: Aqui les dejamos nuestro diseño - [UI/UX](https://www.figma.com/file/768sgTudgZJ4B8I0MOA7f8/BeyondNear?node-id=0%3A1). ## License MIT License Copyright (c) [2021] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
jon-lewis_giant-potato
.github ISSUE_TEMPLATE 01_BUG_REPORT.md 02_FEATURE_REQUEST.md 03_CODEBASE_IMPROVEMENT.md 04_SUPPORT_QUESTION.md config.yml PULL_REQUEST_TEMPLATE.md workflows build.yml deploy-to-console.yml lock.yml stale.yml README.md contract README.md babel.config.json build.sh check-deploy.sh deploy.sh package-lock.json package.json src contract.ts tsconfig.json docs CODE_OF_CONDUCT.md CONTRIBUTING.md SECURITY.md frontend .env .eslintrc.json .prettierrc.json contracts contract.ts greeting-contract.ts next-env.d.ts next.config.js package-lock.json package.json pages api hello.ts postcss.config.js public next.svg thirteen.svg vercel.svg styles globals.css tailwind.config.js tsconfig.json integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json
<h1 align="center"> <a href="https://github.com/near/boilerplate-template"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/near/boilerplate-template/main/docs/images/pagoda_logo_light.png"> <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/near/boilerplate-template/main/docs/images/pagoda_logo_dark.png"> <img alt="" src="https://raw.githubusercontent.com/near/boilerplate-template/main/docs/images/pagoda_logo_dark.png"> </picture> </a> </h1> <div align="center"> Boilerplate Template React <br /> <br /> <a href="https://github.com/near/boilerplate-template/issues/new?assignees=&labels=bug&template=01_BUG_REPORT.md&title=bug%3A+">Report a Bug</a> · <a href="https://github.com/near/boilerplate-template/issues/new?assignees=&labels=enhancement&template=02_FEATURE_REQUEST.md&title=feat%3A+">Request a Feature</a> . <a href="https://github.com/near/boilerplate-template/issues/new?assignees=&labels=question&template=04_SUPPORT_QUESTION.md&title=support%3A+">Ask a Question</a> </div> <div align="center"> <br /> [![Pull Requests welcome](https://img.shields.io/badge/PRs-welcome-ff69b4.svg?style=flat-square)](https://github.com/near/boilerplate-template/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) [![code with love by near](https://img.shields.io/badge/%3C%2F%3E%20with%20%E2%99%A5%20by-near-ff1414.svg?style=flat-square)](https://github.com/near) </div> <details open="open"> <summary>Table of Contents</summary> - [Getting Started](#getting-started) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Usage](#usage) - [Exploring The Code](#exploring-the-code) - [Deploy](#deploy) - [Step 0: Install near-cli (optional)](#step-0-install-near-cli-optional) - [Step 1: Create an account for the contract](#step-1-create-an-account-for-the-contract) - [Step 2: deploy the contract](#step-2-deploy-the-contract) - [Step 3: set contract name in your frontend code](#step-3-set-contract-name-in-your-frontend-code) - [Troubleshooting](#troubleshooting) - [Deploy on Vercel](#deploy-on-vercel) - [Roadmap](#roadmap) - [Support](#support) - [Project assistance](#project-assistance) - [Contributing](#contributing) - [Authors \& contributors](#authors--contributors) - [Security](#security) </details> --- ## About This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) and [`tailwindcss`](https://tailwindcss.com/docs/guides/nextjs) created for easy-to-start as a React skeleton template in the Pagoda Gallery. Smart-contract was initialized with [create-near-app]. Use this template and start to build your own gallery project! ### Built With [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app), [`tailwindcss`](https://tailwindcss.com/docs/guides/nextjs), [`tailwindui`](https://tailwindui.com/), [`@headlessui/react`](https://headlessui.com/), [`@heroicons/react`](https://heroicons.com/), [create-near-app], [`amazing-github-template`](https://github.com/dec0dOS/amazing-github-template) Getting Started ================== ### Prerequisites Make sure you have a [current version of Node.js](https://nodejs.org/en/about/releases/) installed – we are targeting versions `18>`. Read about other [prerequisites](https://docs.near.org/develop/prerequisites) in our docs. ### Installation Install all dependencies: npm install Build your contract: npm run build Deploy your contract to TestNet with a temporary dev account: npm run deploy Usage ===== Start your frontend in development mode: npm run dev Start your frontend in production mode: npm run start Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. Test your contract: npm run test Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. You can start editing the page by modifying `frontend/pages/index.tsx`. The page auto-updates as you edit the file. This is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract (must use node v16): `npm test`, this will run the tests in `integration-tests` directory. 4. [API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `frontend/pages/api/hello.ts`. 5. The `frontend/pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages. 6. This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify `NEXT_PUBLIC_CONTRACT_NAME` in `frontend/.env.local` that sets the account name of the contract. Set it to the account id you used above. NEXT_PUBLIC_CONTRACT_NAME=near-blank-project.YOUR-NAME.testnet Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-next-app]: https://github.com/vercel/next.js/tree/canary/packages/create-next-app [Node.js]: https://nodejs.org/en/download/package-manager [tailwindcss]: https://tailwindcss.com/docs/guides/nextjs [create-near-app]: https://github.com/near/create-near-app [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. ## Roadmap See the [open issues](https://github.com/near/boilerplate-template/issues) for a list of proposed features (and known issues). - [Top Feature Requests](https://github.com/near/boilerplate-template/issues?q=label%3Aenhancement+is%3Aopen+sort%3Areactions-%2B1-desc) (Add your votes using the 👍 reaction) - [Top Bugs](https://github.com/near/boilerplate-template/issues?q=is%3Aissue+is%3Aopen+label%3Abug+sort%3Areactions-%2B1-desc) (Add your votes using the 👍 reaction) - [Newest Bugs](https://github.com/near/boilerplate-template/issues?q=is%3Aopen+is%3Aissue+label%3Abug) ## Support Reach out to the maintainer: - [GitHub issues](https://github.com/near/boilerplate-template/issues/new?assignees=&labels=question&template=04_SUPPORT_QUESTION.md&title=support%3A+) ## Project assistance If you want to say **thank you** or/and support active development of Boilerplate Template React: - Add a [GitHub Star](https://github.com/near/boilerplate-template) to the project. - Tweet about the Boilerplate Template React. - Write interesting articles about the project on [Dev.to](https://dev.to/), [Medium](https://medium.com/) or your personal blog. Together, we can make Boilerplate Template React **better**! ## Contributing First off, thanks for taking the time to contribute! Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make will benefit everybody else and are **greatly appreciated**. Please read [our contribution guidelines](docs/CONTRIBUTING.md), and thank you for being involved! ## Authors & contributors The original setup of this repository is by [Dmitriy Sheleg](https://github.com/shelegdmitriy). For a full list of all authors and contributors, see [the contributors page](https://github.com/near/boilerplate-template/contributors). ## Security Boilerplate Template React follows good practices of security, but 100% security cannot be assured. Boilerplate Template React is provided **"as is"** without any **warranty**. Use at your own risk. _For more information and to report security issues, please refer to our [security documentation](docs/SECURITY.md)._ # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```ts @NearBindgen({}) class HelloNear { greeting: string = "Hello"; @view // This method is read-only and can be called for free get_greeting(): string { return this.greeting; } @call // This method changes the state, for which it cost gas set_greeting({ greeting }: { greeting: string }): void { // Record a log permanently to the blockchain! near.log(`Saving greeting ${greeting}`); this.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash npm run deploy ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `call` method. `Call` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"greeting":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`.
opact-protocol_tickets
.eslintrc.js .github ISSUE_TEMPLATE bug-report.yml feature-creation.yml PULL_REQUEST_TEMPLATE.md workflows CI.yml deploy-command.yml dispatcher.yml near_bigint.yml near_groth16_verifier.yml near_mimc.yml prod_deploy.yml .husky commit-msg.sh LICENSE.md commitlint.config.js cypress.config.ts cypress e2e base.cy.ts fixtures example.json support commands.ts e2e.ts format_rust.sh package.json packages circuits ci_sample_compile_groth16 verification_key.json withdraw_js generate_witness.js witness_calculator.js package.json contract-libraries ff_wasm_unknown_unknown CHANGELOG.md Cargo.toml README.md ff_derive_wasm_unknown_unknown Cargo.toml src lib.rs pow_fixed.rs src batch.rs lib.rs tests derive.rs groth_verifier Cargo.toml near_groth16_verifier Cargo.toml README.md changelog.md src lib.rs pairing.rs package.json sample_circuit circuit_cpp calcwit.cpp circuit.cpp fr.asm fr.cpp main.cpp circuit_js generate_witness.js input0.json input1.json input2.json witness_calculator.js temp_proofs 0proof.json 0public.json 1proof.json 1public.json 2proof.json 2public.json verification_key.json tests-rs Cargo.toml src main.rs methods mod.rs share_token.rs storage.rs token.rs tests_verifier mod.rs verifier_test Cargo.toml src lib.rs hyc_events Cargo.toml README.md src lib.rs near_bigint Cargo.toml README.md changelog.md src lib.rs near_mimc Cargo.toml README.md changelog.md src fp.rs lib.rs round_constants.rs tests index.js package.json package.json plonk_verifier Cargo.toml near_plonk_verifier Cargo.toml README.md changelog.md src calculate_challanges.rs calculate_lagrange.rs calculate_pl.rs calculate_points.rs calculate_t.rs lib.rs modinverse.rs pairing.rs signed_u256.rs package.json sample_circuit circuit_cpp calcwit.cpp circuit.cpp fr.asm fr.cpp main.cpp circuit_js generate_witness.js witness_calculator.js input input.json input1.json input2.json input3.json input4_wrong.json proof.json proof1.json proof2.json proof3.json proof4_wrong.json public.json public1.json public2.json public3.json public4_wrong.json solidity_example package.json test index.test.js verification_key.json tests-rs Cargo.toml src main.rs methods mod.rs share_token.rs storage.rs token.rs tests_verifier mod.rs verifier_test Cargo.toml src lib.rs contracts .rustfmt.toml Cargo.toml README.md compile.js instance Cargo.toml README.md src actions mod.rs owner.rs transactions.rs view.rs commitment_tree.rs currency.rs ext_interface.rs lib.rs jest.config.js package.json registry Cargo.toml README.md src actions allowlist.rs mod.rs owner.rs view.rs allowlist_tree_v2.rs ext_interface.rs hapi_connector.rs lib.rs migrations allowlist_tree_v1.rs mod.rs relayer_setup index.js package.json prepareCommitments.js setup.js test_contracts fungible_token Cargo.toml README.md src errors.rs lib.rs testnet_seeder package.json src deployTestnet.ts index.ts utils.ts tsconfig.json tests-rs Cargo.toml package.json prepare_commitments.js src main.rs methods hyc.rs mod.rs storage.rs token.rs tests_core mod.rs test_near_flow.rs test_nep_141_flow.rs test_registry_records.rs test_wrong_coin_deposits.rs tests-ts package.json src actions account.ts connection.ts contracts.ts registry.ts token.ts constants index.ts merkle-tree.ts near.ts index.ts prepare_commitments.ts utils file.ts near.ts number.ts secrets.ts tsconfig.json denylist-bot build.js jest.config.js package.json scripts package.json src populateEnvs.ts secrets.ts tsconfig.json src dos pagination.ts index.ts services consumer.ts request.ts types env.ts pagination.ts utils.ts test consumer.test.ts tsconfig.json tsconfig.json wrangler.toml front api geoloc.ts package.json index.html package.json postcss.config.js public check_circle.svg copied-icon.svg copy-icon.svg error.svg hideyourcash.svg logo-opact.svg logo.svg near-icon.svg phone-frame.svg shield-check.svg success.svg warning.svg src components form index.ts index.ts layout index.ts modals index.ts hooks deposit.types.ts index.css store index.ts sw worker.ts utils actions.ts artifact-store.ts artifacts.ts debounce.ts graphql-queries.ts near.ts number.ts poolScores.ts proof-worker.ts reloadPage.ts returnMessages.ts sdk.ts sdk.types.ts set-storages.ts verify-storage.ts vite-env.d.ts tailwind.config.js tsconfig.json tsconfig.node.json vercel-dev.json vercel.json vite.config.ts vite.config.ts.js relayer build.js jest.config.js package.json scripts package.json src populateEnvs.ts secrets.ts tsconfig.json src constants index.ts near.ts ref.ts helpers index.ts numbers.ts pools.ts swap index.ts parallelSwapLogic.ts stable-swap.ts index.ts interfaces env.ts fee.ts index.ts ref.ts relayer.ts services fee.ts index.ts near.ts relay.ts test relayer.test.ts tsconfig.json util index.ts near.ts tsconfig.json wrangler.toml sdk jest.config.ts package.json src actions compliance.ts connection.ts index.ts merkle-tree.ts relayer.ts snark-proof.ts ticket.ts constants index.ts merkle-tree.ts near.ts relayer.ts graphql index.ts merkle-tree.ts helpers date.ts index.ts merkle-tree.ts near.ts number.ts web3.ts index.ts interfaces currencies.ts index.ts merkle-tree.ts near.ts relayer.ts snark-proof.ts services hideyourcash actions.ts index.ts service.ts views.ts index.ts merkle-tree.ts mimc.ts views account.ts currencies.ts fungible-token.ts index.ts relayer.ts snark-proof.ts ticket.ts test sdk.test.ts utils index.ts logger.ts near.ts tsconfig-base.json tsconfig-cjs.json tsconfig.json tsup.config.ts subgraph assembly hapiOne.ts mappings.ts merkle.ts withdraw.ts generated schema.ts make-yaml.js networks.json package.json readme.md tsconfig.json tsconfig.json
<div align="center"> <h1><code>near-groth16-verifier</code></h1> <p> <strong>Rust library to use verify groth16 zero knowledge proofs inside a NEAR Protocol smart contract.</strong> </p> </div> ## Use cases Applying zero knowledge cryptography inside blockchain smart contracts has been one of the most widely praised uses of this new technology. In the Ethereum ecosystem, there are many applications using zero-knowledge proofs to ensure data privacy and computational efficiency in a permissionless blockchain context. Developing this kind of applications became accessible to a normal (read not a cryptography expert) developer with libraries such as [snarky.js](https://github.com/o1-labs/snarkyjs) and [circom](https://docs.circom.io/), which simplify the construction of algorithms by abstracting away all cryptography implementation and allowing developers to only focus on business logic. This tooling, however, is only compatible with EVM based blockchains. For developers looking to build zk-based applications on the NEAR protocol the tool was not enough. With this in mind, we developed this library as a generic proof verifier utilizing the [groth16 algorithm](https://www.zeroknowledgeblog.com/index.php/groth16). This can be utilized together with snarky.js and circom to generate a full fledged application running zk proofs. You can use this library as a substitute for the `Verifying from a Smart Contract` section in the [circom tutorial](https://docs.circom.io/getting-started/proving-circuits/#verifying-from-a-smart-contract). ## How to use it To implement this Verifier in your Smart Contract you must first have setup your logical circuit and produced a trusted setup using snarky.js. This library will allow you to verify if a proof is valid or not inside the Smart Contract. To do so you must: 1. Initialize the Verifier in the Smart Contract's state by passing the setup values generated by snarky.js to it 2. Submit proofs generated by the prover binary (created by snarky.js) to the smart contract The verifier can be implemented with a simple import: ```rust use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::json_types::U128; use near_sdk::{env, near_bindgen, PanicOnDefault, AccountId, BorshStorageKey}; use near_sdk::collections::{LookupSet}; use near_groth16_verifier::{self, Verifier}; #[near_bindgen] #[derive(PanicOnDefault, BorshDeserialize, BorshSerialize)] pub struct Contract { pub verifier: Verifier, } impl Contract { #[init] pub fn new( verifier: Verifier ) -> Self { assert!(!env::state_exists(), "Already initialized"); Self { verifier } } } ``` The `Verifier` struct can be represented as a series of elliptic curve points: ```rust #[derive(Serialize, Deserialize, BorshSerialize, BorshDeserialize, Clone, Debug)] #[serde(crate = "near_sdk::serde")] pub struct G1Point { pub x: U256, pub y: U256, } #[derive(Serialize, Deserialize, BorshSerialize, BorshDeserialize, Clone)] #[serde(crate = "near_sdk::serde")] pub struct G2Point { pub x: [U256; 2], pub y: [U256; 2], } #[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)] #[serde(crate = "near_sdk::serde")] pub struct Verifier { pub alfa1: G1Point, pub beta2: G2Point, pub gamma2: G2Point, pub delta2: G2Point, pub ic: Vec<G1Point>, pub snark_scalar_field: U256, } ``` To fill out this values, refer to the verification_key.json file generated by snarky.js, it will provide all the parameters to initialize the `Verifier`, except for `snark_scalar_field`. `snark_scalar_field` is the size of the scalar field used in the construction of your circuit. The standard value for this variable in snarky.js is `21888242871839275222246405745257275088548364400416034343698204186575808495617`. To better understand this parameter, please refer to the [circom documentation](https://docs.circom.io/circom-language/basic-operators/). After initializing the verifier, it can be used to evaluate any proof in your circuit and check whether it is valid or not with the verify method. ```rust pub fn verify(&self, input: Vec<U256>, proof: Proof) -> bool #[derive(Serialize, Deserialize)] #[serde(crate = "near_sdk::serde")] pub struct Proof { pub a: G1Point, pub b: G2Point, pub c: G1Point, } ``` Proofs always follow the same structure and are generated by snarky.js when running the prover algorithm. the `input` parameter refers to the public inputs provided to the circuit. Those must be provided as a Vec of big integers. Snarky.js generates 2 files whenever it creates a proof: 1. public -> contains an array of values that should be passed to `input` 2. proof -> contains the `Proof` struct in json format ## Supported near-sdk versions near-groth16-verifier is built on top of near-sdk 4.0.0 and will be updated periodically to reflect updates on near-sdk. Previous near-sdk versions are not compatible with this library. # HYC events This lib is used to make event formats uniform across registry and instance contracts for HYC. <div align="center"> <h1><code>near-plonk-verifier</code></h1> <p> <strong>Rust library to use verify plonk zero knowledge proofs inside a NEAR Protocol smart contract.</strong> </p> </div> ## Use cases Applying zero knowledge cryptography inside blockchain smart contracts has been one of the most widely praised uses of this new technology. In the Ethereum ecosystem, there are many applications using zero-knowledge proofs to ensure data privacy and computational efficiency in a permissionless blockchain context. Developing this kind of applications became accessible to a normal (read not a cryptography expert) developer with libraries such as [snark.js](https://github.com/iden3/snarkjs) and [circom](https://docs.circom.io/), which simplify the construction of algorithms by abstracting away all cryptography implementation and allowing developers to only focus on business logic. This tooling, however, is only compatible with EVM based blockchains. For developers looking to build zk-based applications on the NEAR protocol the tool was not enough. With this in mind, we developed this library as a generic proof verifier utilizing the [plonk algorithm](https://blog.iden3.io/circom-snarkjs-plonk.html). This can be utilized together with snark.js and circom to generate a full fledged application running zk proofs. You can use this library as a substitute for the `Verifying from a Smart Contract` section in the [circom tutorial](https://docs.circom.io/getting-started/proving-circuits/#verifying-from-a-smart-contract). ## How to use it To implement this Verifier in your Smart Contract you must first have setup your logical circuit and produced a trusted setup using snark.js. This library will allow you to verify if a proof is valid or not inside the Smart Contract. To do so you must: 1. Initialize the Verifier in the Smart Contract's state by passing the setup values generated by snark.js to it 2. Submit proofs generated by the prover binary (created by snark.js) to the smart contract The verifier can be implemented with a simple import: ```rust use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::json_types::U128; use near_sdk::{env, near_bindgen, PanicOnDefault, AccountId, BorshStorageKey}; use near_sdk::collections::{LookupSet}; use near_plonk_verifier::{self, Verifier, U256, G1Point, G2Point}; #[near_bindgen] #[derive(PanicOnDefault, BorshDeserialize, BorshSerialize)] pub struct Contract { pub verifier: Verifier, } impl Contract { #[init] pub fn new( power: U256, n_public: U256, q_m: G1Point, q_l: G1Point, q_r: G1Point, q_o: G1Point, q_c: G1Point, s_1: G1Point, s_2: G1Point, s_3: G1Point, k_1: U256, k_2: U256, x_2: G2Point, q: U256, qf: U256, w1: U256, ) -> Self { assert!(!env::state_exists(), "Already initialized"); Self { verifier: Verifier::new( power n_public, q_m, q_l, q_r, q_o, q_c, s_1, s_2, s_3, k_1, k_2, x_2, q, qf, w1, ) } } } ``` The `Verifier` struct can be represented as a series of elliptic curve points and scalar values: ```rust #[derive(Serialize, Deserialize, BorshSerialize, BorshDeserialize, Clone, Debug)] #[serde(crate = "near_sdk::serde")] pub struct G1Point { pub x: U256, pub y: U256, } #[derive(Serialize, Deserialize, BorshSerialize, BorshDeserialize, Clone)] #[serde(crate = "near_sdk::serde")] pub struct G2Point { pub x: [U256; 2], pub y: [U256; 2], } #[derive(BorshSerialize, BorshDeserialize, Serialize, Deserialize)] #[serde(crate = "near_sdk::serde")] pub struct Verifier { pub struct Verifier { // n values power: U256, n: U256, n_public: U256, n_lagrange: U256, // Q values q_m: G1Point, q_l: G1Point, q_r: G1Point, q_o: G1Point, q_c: G1Point, // S values s_1: G1Point, s_2: G1Point, s_3: G1Point, // k values k_1: U256, k_2: U256, // X2 values x_2: G2Point, // Field size constants q: U256, qf: U256, // omega value w1: U256, } } ``` To fill out this values, refer to the verification_key.json file generated by snarkjs.js, it will provide all the parameters to initialize the `Verifier`. After initializing the verifier, it can be used to evaluate any proof in your circuit and check whether it is valid or not with the verify method. ```rust pub fn verify(&self, input: Vec<U256>, proof: Proof) -> bool #[derive(Serialize, Deserialize)] #[serde(crate = "near_sdk::serde")] pub struct Proof { // public values public_values: Vec<U256>, // proof values a: G1Point, b: G1Point, c: G1Point, z: G1Point, t_1: G1Point, t_2: G1Point, t_3: G1Point, eval_a: U256, eval_b: U256, eval_c: U256, eval_s1: U256, eval_s2: U256, eval_zw: U256, eval_r: U256, wxi: G1Point, wxi_w: G1Point, } ``` Proofs always follow the same structure and are generated by snark.js when running the prover algorithm. They have `public_values` added to it as a vec, in snark.js public values are generated as a separate json file containing a single array. snark.js generates 2 files whenever it creates a proof: 1. public -> contains an array of values that should be passed to `public_values` 2. proof -> contains the rest of the params to be added to `Proof` ## Supported near-sdk versions near-plonk-verifier is built on top of near-sdk 4.0.0 and will be updated periodically to reflect updates on near-sdk. Previous near-sdk versions are not compatible with this library. ## ff_wasm_unknown_unknown `ff_wasm_unknown_unknown` is an independent adaptation of the open-sourced `ff` library that removes features incompatible with wasm32-unknown-unknown architecture, specially methods that require pseudorandom number generation. # ff `ff` is a finite field library written in pure Rust, with no `unsafe{}` code. ## Disclaimers * This library does not provide constant-time guarantees. The traits enable downstream users to expose constant-time logic, but `#[derive(PrimeField)]` in particular does not generate constant-time code (even for trait methods that return constant-time-compatible values). ## Usage Add the `ff` crate to your `Cargo.toml`: ```toml [dependencies] ff = "0.12" ``` The `ff` crate contains the `Field` and `PrimeField` traits. See the **[documentation](https://docs.rs/ff/)** for more. ### #![derive(PrimeField)] If you need an implementation of a prime field, this library also provides a procedural macro that will expand into an efficient implementation of a prime field when supplied with the modulus. `PrimeFieldGenerator` must be an element of Fp of p-1 order, that is also quadratic nonresidue. First, enable the `derive` crate feature: ```toml [dependencies] ff = { version = "0.12", features = ["derive"] } ``` And then use the macro like so: ```rust #[macro_use] extern crate ff; #[derive(PrimeField)] #[PrimeFieldModulus = "52435875175126190479447740508185965837690552500527637822603658699938581184513"] #[PrimeFieldGenerator = "7"] #[PrimeFieldReprEndianness = "little"] struct Fp([u64; 4]); ``` And that's it! `Fp` now implements `Field` and `PrimeField`. ## Minimum Supported Rust Version Requires Rust **1.56** or higher. Minimum supported Rust version can be changed in the future, but it will be done with a minor version bump. ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. # Opact Tickets Instance Smart Contract Instance Smart contract is responsible for receiving deposits and issuing withdrawals. Each instance can only receive deposits of a single token type at a fixed amount. The contract references the registry in its initialization and trusts the registry for all allowlist related data. ## API ### Anonymity methods 1. `deposit` params: - secrets_hash: U256 -> hash value of (secret | nullifier) according to circuit docs. Must be formatted as decimal number in string format User calling this method must attach the NEAR amount corresponding to the contract's value. This only works if contract has been initialized using NEAR as its currency. Deposit value must be exactly the initialized value. Panics if contract kill_switch is activated Panics if user is not in allowlist Inserts the commitment in the contract so that a withdraw can be made using the secrets 2. `ft_on_transfer` params: - sender_id: AccountId -> Account that originally sent funds - amount: U128 -> Quantity of tokens sent. Must be exactly the value used when initializing the contract - msg: String -> hash value of secret | nullifier according to circuit docs. Must be formatted as decimal number in string format This method will be called when using `ft_transfer_call` on the NEP-141 contract. For more information on `ft_transfer_call` mechanims (read the docs)[https://nomicon.io/Standards/Tokens/FungibleToken/Core#nep-141]. This method can only be called from the NEP-141 contract address passed when initializing the HYC contract. If you try to transfer any other token the call will panic. Panics if contract kill_switch is activated Panics if user is not in allowlist Inserts the commitment in the contract so that a withdraw can be made using the secrets 3. `withdraw` params: - root: U256 -> root value of commitment merkle tree used to build proof - nullifier_hash: U256 -> value of nullifier hash used to build proof - recipient: AccountId -> account that will receive withdrawn tokens - relayer: Option<AccountId> -> account of the relayer of the transaction - if used - fee: U256 -> quantity of tokens that will be sent to relayer as a fee - refund: U256 -> quantity of tokens that will be sent to relayer as refund for gas - allowlist_root: U256 -> root value of allowlist merkle tree used to build proof - a: G1Point -> A point component of proof, - b: G1Point -> B point component of proof, - c: G1Point -> C point component of proof, - z: G1Point -> Z point component of proof, - t_1: G1Point -> T1 point component of proof, - t_2: G1Point -> T2 point component of proof, - t_3: G1Point -> T3 point component of proof, - eval_a: U256 -> eval_a value component of proof, - eval_b: U256 -> eval_b value component of proof, - eval_c: U256 -> eval_c value component of proof, - eval_s1: U256 -> eval_s1 value component of proof, - eval_s2: U256 -> eval_s2 value component of proof, - eval_zw: U256 -> eval_zw value component of proof, - eval_r: U256 -> eval_r value component of proof, - wxi: G1Point -> Wxi point component of proof, - wxi_w: G1Point -> Wxiw point component of proof, Panics if proof is invalid Panics if nullifier has already been withdrawn Panics if roots used are too old or invalid Panics if fee > withdraw value Sends tokens to recipient and registers nullifier_hash as already used, so that it cannot be double spent. ### View methods 1. `view_account_hash` (Will be deprecated in favor of off chain computation) -> `U256` params: - account_id: AccountId -> account whose MiMC hash value you want to calculate Calculates MiMC hash of an account id. Necessary to build proofs 2. `view_nullifier_hash` (Will be deprecated in favor of off chain computation) -> `U256` params: - nullifier: U256 -> nullifier used to build commitment Calculates MiMC hash of nullifier. Necessary to build proofs and commitments 3. `view_commitments_root` -> `U256` returns last know commitment merkle tree root in the cotnract. Necessary to build proofs 4. `view_was_nullifier_spent` -> `bool` params: - nullifier: U256 -> nullifier you want to check true if nullifier was already spent, false otherwise 5. `view_kill_switch` -> `bool` Returns current value of kill_switch variable 6. `view_contract_params` -> `ContractParams` Returns object containing all setup parameters in place for the contract 7. `view_is_withdraw_valid` -> `bool` params: - root: U256 -> root value of commitment merkle tree used to build proof - nullifier_hash: U256 -> value of nullifier hash used to build proof - recipient: AccountId -> account that will receive withdrawn tokens - relayer: Option<AccountId> -> account of the relayer of the transaction - if used - fee: U256 -> quantity of tokens that will be sent to relayer as a fee - refund: U256 -> quantity of tokens that will be sent to relayer as refund for gas - allowlist_root: U256 -> root value of allowlist merkle tree used to build proof - a: G1Point -> A point component of proof, - b: G1Point -> B point component of proof, - c: G1Point -> C point component of proof, - z: G1Point -> Z point component of proof, - t_1: G1Point -> T1 point component of proof, - t_2: G1Point -> T2 point component of proof, - t_3: G1Point -> T3 point component of proof, - eval_a: U256 -> eval_a value component of proof, - eval_b: U256 -> eval_b value component of proof, - eval_c: U256 -> eval_c value component of proof, - eval_s1: U256 -> eval_s1 value component of proof, - eval_s2: U256 -> eval_s2 value component of proof, - eval_zw: U256 -> eval_zw value component of proof, - eval_r: U256 -> eval_r value component of proof, - wxi: G1Point -> Wxi point component of proof, - wxi_w: G1Point -> Wxiw point component of proof, Panics if proof and public params submitted are invalid, returns `true` otherwise. Performs the exact same evaluation as `withdraw` method. ** This evaluation does not include a validation of the allowlist_root value. This must be validated within the registry contract using `view_is_allowlist_root_valid`. ### Owner methods 1. `toggle_kill_switch` Can only be called by owner upon depositing 1 yoctoNEAR. Toggles value of kill_switch. Default is false. When true, disallows all deposits. <div align="center"> <h1><code>near-mimc</code></h1> <p> <strong>Rust library to use MiMC Hash function in NEAR Protocol Smart Contract development.</strong> </p> </div> ## Use cases This library was created as an implementation of the MiMC Hash function that can run within a NEAR Protocol Smart Cotnract. It is fully compatible (i.e. implemented in the exact same way) as in circom2 sample circuits. This allows the hash function to be used within zkSNARK schemes based on [snarky.js](https://github.com/o1-labs/snarkyjs) and [circom](https://docs.circom.io/). ## Supported near-sdk versions near-bigint is built on top of near-sdk 4.0.0 and will be updated periodically to reflect updates on near-sdk. Previous near-sdk versions are not compatible with this library. Additionally, the function interfaces utilize big integer types from the near-bigint library version 1.0.0. ## How to use it The lbrary exposes 2 different hash functions, one taking 2 input values and the other taking a single value. ```rust pub fn u256_mimc_sponge(k: U256, inputs: [U256; INPUTS]) -> [U256; OUTPUTS] pub fn u256_mimc_sponge_single(k: U256, inputs: [U256; 1]) -> [U256; 1] ``` <div align="center"> <h1><code>near-bigint</code></h1> <p> <strong>Rust library to use Big Integer types in NEAR Protocol Smart Contract development.</strong> </p> </div> ## Use cases Smart contracts in the NEAR Blockchain are limited by the native rust data type. This means developers can represent integer numbers up to 128 bits using the `u128` type. However, when dealing with blockchain financial applications, it is often possible that larger numbers might need to be represented. For instance, the solidity language in the Ethereum ecosystem supports up to 256 bits nativelly, translating solidity apps to NEAR naively can easily lead to integer overflow errors. A common solution to the problem has been to use well known rust packages that implement big integer arithmetics as dependencies to implement bigger integer types, such as [uint](https://crates.io/crates/uint). These libraries work well and allow developers to safely use big integer arithmetics within NEAR smart contract applications, however, they lack the ergonomics necessary to work within the NEAR environment. Such required features are: 1. Borsh serialization and deserialization -> Allows values to be stored directly into the blockchain's state without needing to convert it to a binary representation 2. Serde serialization and deserialization -> Allows values to be passed as function arguments when calling public methods in the smart contract 3. StorageKey serialization -> Allows values to be used as keys within th blockchain's trie We chose to implement these features on top of the [uint](https://crates.io/crates/uint) library, which is used by top NEAR projects such as [ref.finance](https://www.ref.finance/). Besides implementing the aforementioned features, we also added a more ergonomic API to: 1. Convert big integer format to u128 and panic if number does not fit 2. Convert big integer format to little or big endian bytes 3. Generate empty buffer values for big integer initialization ## How to use There are 2 ways to use the library: 1. Import pre constructed types 2. Import macro to build Big Integer types of any size The library nativelly exports types for big integers of 256, 384, 512, 640, 768, 896 and 1024 bits. ```rust use near_bigint::{U256, U384, U512, /* ... */}; ``` If you need a type with a different bit size, you can construct your own using the `construct_near_bigint` macro. This allows you to build types of any size that is a multiple of 64 bits. ```rust use near_bigint::construct_near_bigint; /// You need to declare a name for the type you're creating - U{bit size} is recommended /// You also need to declare the intended bit size (as a multiple of 64) /// construct_near_bigint!(pub struct {type name}({multiple of 64 bitsize});); construct_near_bigint!(pub struct U2048(32);); construct_near_bigint!(pub struct U192(3);); let u2048_var = U2048::from_dec_str("100").unwrap(); let u192_var = U192::from_dec_str("100").unwrap(); ``` ## API and examples All types contructed with this library inherit the API from the [uint](https://crates.io/crates/uint) library. This can be found in their documentation and will not be reproduced here. All near-bigint types are borsh serializable and deserializable, which means you can store them directly into the contract's state: ```rust use near_sdk::{env, near_bindgen, PanicOnDefault, AccountId, BorshStorageKey, Promise}; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::{LookupSet}; use near_bigint::U256; #[near_bindgen] #[derive(PanicOnDefault, BorshDeserialize, BorshSerialize)] pub struct Contract { pub owner: AccountId, pub guardian: LookupSet<AccountId>, pub deposit_value: U256, pub deposited_valeus: LookupSet<U256>, } ``` Types are also serde serializable/deserializable, meaning they can be used as argument or return types in public methods. The end users must then pass the values as strings in their front-end application (the same way that near_sdk::json_types::{U128, U64} work). ```rust use near_sdk::{env, near_bindgen, PanicOnDefault, AccountId, BorshStorageKey, Promise}; use near_bigint::U256; use crate::Contract; #[near_bindgen] impl Contract { pub fn public_method(&mut self, number: U256) { self.deposit_value = number; } } ``` Finally, types can also be used as storage keys in the trie: ```rust use near_sdk::{env, near_bindgen, PanicOnDefault, AccountId, BorshStorageKey, Promise}; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::{LookupMap}; use near_bigint::U256; #[near_bindgen] #[derive(PanicOnDefault, BorshDeserialize, BorshSerialize)] pub struct Contract { pub owner: AccountId, /// Bigint used as storage key here pub map: LookupMap<U256, AccountId>, } #[near_bindgen] impl Contract { #[init] pub fn new( owner: AccountId, initial_key: U256 ) -> Self { assert!(!env::state_exists(), "Already initialized"); assert!( env::is_valid_account_id(owner.as_bytes()), "Invalid owner account" ); /// Bigint used as storage key here let mut map = LookupMap::new(initial_key); /// Bigint used as storage key here map.insert(&U256::from_dec_str("0").unwrap(), &owner); Self { owner, map, }; } } ``` Some utilities are also implemented to improve ergonomy: ```rust use near_bigint::U256; let sample_var = U256::from_dec_str("5165164138").unwrap(); /// Convert to big endian bytes let big_endian: [u8; 256] = sample_var.to_be_bytes(); /// Convert to little endian bytes let little_endian: [u8; 256] = sample_var.to_le_bytes(); /// Get bytes equivalent to 0 value let 0_bytes: [u8; 256] = U256::empty_buffer(); /// Convert to u128 (panics in case big number overflows 128 bits) let 128_bits: u128 = sample_var.as_u128(); ``` ## Supported near-sdk versions near-bigint is built on top of near-sdk 4.0.0 and will be updated periodically to reflect updates on near-sdk. Previous near-sdk versions are not compatible with this library. # Opact Tickets Registry Smart Contract The smart contract implements a NEAR protocol compatible Registry to allow multiple different amounts and currencies to be used with Opact Tickets. The goal is for end users to be able to: 1. Discover all token and amount options available in HYC; 2. Discover the correct addresses for every available currency and amount option within HYC; 3. Allow the seamless replacement of deprecated contracts for their updated versions without compromising users ability to withdraw deposited funds; 4. Allow relayers to check whether specific contracts should be trusted; The ideal logic would be for this to be the single point of contact for every interaction with HYC. However, given NEAR protocol's asynchronous nature, it is not possible to implement a router or proxy as we would for a different blockchain, such as Ethereum. ## Contract logic The contract stores an `UnorderedMap` mapping each currency to a `HashMap` of deposit amounts accepted and the contract address for that amount. The contract also stores an `UnorderedSet` containing all HYC contracts ever deployed, to allow relayers and users to validate the addresses of deprecated contracts in case there are still funds to withdraw on them. Only the owner can insert new currencies and amounts. Every time a contract is added to the registry it is added both to the map and the allowlist set. If the contract is removed from the map - be it because HYC frontend doesn't want to support it anymore or because it has been deprecated in an upgrade - it is still going to be available in the allowlist, to allow users to withdraw funds they had previously deposited to them. In case a contract ever needs to be removed from the allowlist, this operation should be explicitly done after removing from the map, using `remove_from_allowlist`. ## Security assumptions This contract does not handle user funds directly, it is only an on-chain information registry. Therefore, this contract has no intention of being run as a fully decentralized application. It is going to be controlled by the development team during project's early phases and handled over to the DAO structure later on. If a hacker ever compromises this contract, the main consequence would be the possibility to insert malicious contract into the registry, which would be trusted by frontends and relayers running the protocol - and by its end users in extension. This could carry great consequences, allowing phishing scams to effectivelly attack users. However, there would be no risk for already deposited funds. To keep maximum security, owner's private keys should be stored in a hardware wallet and later on transferred to a DAO structure. ## Contract interface ### Initialize 1. `new` params: - owner: AccountId -> account that will be able to edit the registry - authorizer: AccountId -> Account of hapi.one protocol contract - risk_params: Vec<CategoryRisk> -> Risk parameters for contract allowlist - height: u64 -> height of allowlist merkle tree - last_roots_len: u8 -> quantity of previous allowlist roots to be stored in contract - q: U256 -> Field size for ZK calculations - zero_value: U256 -> Zero value for ZK calculations Method to initialize the contract with a specified owner. The owner is going to be the only account able to alter the registry. Current implementation does not allow future changes in owner. ### Change methods (owner restricted) 1. `add_entry` params: - currency: Currency -> The currency of the contract address you want to add - amount: U256 -> Amount value of deposits for HYC contract you want to add - account_id: AccountId -> Address of the HYC contract that you're adding to the registry This method can only be called by the contract owner. It adds a specific entry to the registry (adds a contract address for the (currency, amount) pair). If there was a previous contract stored in the location it will be overwritten. 2. `remove_entry` params: - currency: Currency -> The currency of the contract address you want to remove - amount: U256 -> Amount value of deposits for HYC contract you want to remove This method removes one entry from the registry, according to the (currnecy, amount) pair specified in args. Panics if currency or amount is not registered. 3. `remove_from_allowlist` params: - account_id: AccountId -> Address of the HYC contract that you're removing from the allowlist This method removes one entry from the allowlist. ### Allowlist methods 1. `allowlist` params: - account_id: AccountId -> account that you want to add to allowlist Panics if risk is too high, Panics if account is already registered, Adds account to allowlist otherwise 2. `denylist` params: - account_id: AccountId -> account that you want to add to denylist Panics if account risk is acceptable Adds account to denylist otherwise ### View methods 1. `view_all_currencies` -> `Vec<Currency>` Returns a Vec with all supported currencies in HYC. 2. `view_currency_contracts` -> `HashMap<U256, AccountId>` params: - currency: Currency -> Currency for which you want to query all available contracts Returns a HashMap mapping each available deposit amount in the currency to the corresponding HYC contract address 3. `view_is_contract_allowed` -> `bool` params: - account_id: AccountId -> Address of the contract whose allowlist membership you want to check Returns `true` if contract is in allowlist, `false` otherwise. 4. `view_contract_allowlist` -> `Vec<AccountId>` Returns a Vec containing all contract addresses in the allowlist. There is a know limitation to retrive large lists, however allowlist is not expected to ever exceed 100 elements 5. `view_allowlist_root` -> `U256` returns last know allowlist merkle tree root in the cotnract. Necessary to build proofs 6. `view_is_in_allowlist` -> `bool` params: - account_id: AccountId -> account you want to checks true if account is in allowlist, false otherwise # Opact Tickets Smart Contracts This suite of smart contracts implements a zk transaction mixer on NEAR protocol that is nativelly integrated into [hapi.one's anti money laundering software](https://hapi.one/). The contract support both NEAR native token and NEP-141 tokens. ## Mixing logic The contract provides anonimicity to users by leveraging a transaction mixer. Users can deposit funds with the deposit method and withdraw them from another account with the withdraw method by prociding a zk Proof of deposit. The mechanism is based on tornado.cash's zk scheme with a twist that allows it to perform anti money laundery compliance. ## Anti money laundery The anti money laundery scheme is powered by [hapi.one](https://hapi.one/). Upon setting up the contract a max tolerated risk level is selected by the deployer for each different risk category. Accounts can only interact with the protocol if they present a risk level smaller than the max tolerated level. To interact with the protocol for the first time, an account must be added to the allowlist. To require inclusion in the allowlist, a user must call `allowlist` and pass in their account id - the address will then be queried by hapi.one and, if it present a risk level below or equal to the threshold, the user will be included in the allowlist. Once a user has been added to the allowlist, they may deposit funds into the protocol and other users may withdraw them. However, it is always possible for anyone (this will be done by robots in production and rewarded) to challange addresses that are in the allowlist, by performing new queries to hapi.one. This is done through the `denylist` method. It will query the account passed into hapi.one and, should the risk be greater than the threshold the account will be added to the denylist and will not be able to deposit new funds nor withdraw previously deposited funds. ## Protocol fees The contract implements a protocol fee, which is a percentage taken from every deposit and transferred to the owner account. This fee is variable and is set during initialization of each instance contract. To protect users from fee changes that would affect their deposits, once the fee is set it can never be reset. ## NEP-141 storage According to NEP-141 documentation, tokens should implement storage registration for anyone that wants to hold a token balance. This has implications for this contract when using a NEP-141 token. Whenever a user tries to withdraw to an account that is not registered in the contract for the token, the transaction is going to be reverted so that the user does not lose their funds. Relayers and front end apps should check registration and pay for storage in case the accounts are not registered. However, if owner or relayer are not registered in the NEP-141 contract, the fees that are transferred to them on each withdraw are going to fail and the funds will be locked in the HYC contract forever. So make sure that owner and relayers are registered in the contract. ## Contract ownership The contract implements an ownership model, where a priviledged `owner` account has access to methods that regular users do not. However, since the intent of the contract is to be totally decentralized, `owner` does not have access to any funds stored in the contract, cannot alter any preset parameters and if `owner` is ever compromised, it represents no risk for the contract whatsoever. The only method that owner has access to is `toggle_kill_switch`. This method toggles the value of `kill_switch` which is used to lock new deposits to the protocol. This has 2 main use cases: 1. Upgrading the contract -> new deposits will be forbidden and users will only be able to withdraw. A new contract will be deployed with updated version. 2. AML failures -> in case the AML system is currepted somehow either by corruption of third party data providors or by attacks on HYC's security model, the owner can stop the contract to prevent further damage while the team works in improving the protocol to upgrade to a new version. The account that deploys the HYC contract should burn all it access keys to ensure users that the protocol is fully decentralized and - given a secure source code - their funds cannot be tampered with. ## Architecture The system is designed around a single REGISTRY smart contract and multiple INSTANCE smart contracts. The registry is responsible for the setup of all AML parameters and for keeeping track of all different currencies and amounts supported by the protocol. Instace smart contracts are where funds are actually mixed. Each instance only accepts one token type and deposits and withdraws can only be made in a fixed amount. That ensures external observers cannot differentiate between withdraws, guaranteeing more anonymity to users. # NEP-141 Standard token contract for NEAR protocol This smart contract creates a token on the NEAR blockchain. This token follows the [NEP-141 and NEP-148 standards](https://nomicon.io/Standards/Tokens/FungibleToken/). ## Authors - [@hack-a-chain-software](https://github.com/hack-a-chain-software) ## Appendix In order to deploy and create a token, there are a few prerequisites necessary: - Install near CLI (Command Line Interface) - (Please ensure you [have NodeJS](https://nodejs.org/en/download/package-manager/) > 12.) - Install RUST - Add Wasm toolchain ### NEAR CLI To Install the near CLI, open your terminal: - On Mac open Terminal using Spotlight with these steps: Press Command + Space Bar on your Mac Keyboard. Type in “Terminal” When you see Terminal in the Spotlight search list, click it to open the app - On Windows, click Start and search for "Command Prompt." Alternatively, you can also access the command prompt by pressing Ctrl + r on your keyboard, type "cmd" and then click OK. and run the following command: ```bash npm install -g near-cli ``` Now, you can run: ```bash near ``` After that, you can log in on the NEAR account that you would like to be the **address where the contract will be deployed** - Please note that this is **not the owner of the contract**. To log in, type: ```bash near login ``` This will bring you to NEAR Wallet again where you can confirm the creation of a full-access key. ### RUST Rust is the programming language used to program the smart contract. In order to use this contract, you must have rust installed on your computer. To install Rust we will be using ```rustup``` an installer for rust. Please see the directions from the [Rustup](https://rustup.rs/#) site. For OS X or Unix, you may use (type on command line): ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` Pro tip: to keep your command line clean, type ```clear``` and hit enter. ### Wasm toolchain Smart contracts compile to WebAssembly (Wasm) so we'll add the toolchain for Rust: ```bash rustup target add wasm32-unknown-unknown ``` More info about it can be found [here](https://rustwasm.github.io/docs/book/). If you followed correctly the steps above, you are now ready to go. You can read more about the NEAR CLI and the deployment of rust codes [here](https://www.near-sdk.io/zero-to-hero/basics/set-up-skeleton) If the contract is not compiled (it should be), you can compile it using: ```bash RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release ``` ## Deployment Assuming that you already have the ```NEAR CLI```, ```Rust``` and the ```Wasm Toolchain``` installed, and is logged in into the account that you want to deploy the project, we can now deploy it. Now, we are going to deploy this project to the nar blockchain mainnet. Frist, make sure you are on the project folder. You can change yout folder by typing: ```bash cd your-project-folder-path ``` Now, check if your project folders have a folder called ``` out ``` and a file called ``` main.wasm ``` if not, [check near-sdk git](https://github.com/near/near-sdk-rs) on how to compile the code. To make it easier to deploy the project, lets create an enviroment variable with the **address that we want for our contract** (you must be logged into this wallet) ```bash export CONTRACT_ID="YOUR_ACCOUNT_NAME.near" ``` Now, finally, we are going to run the following command to deploy the code: ```bash near deploy --wasmFile out/main.wasm --accountId $CONTRACT_ID ``` At this point, the contract should have been deployed to your account and you're ready to move onto configuring the token specifications and setting the contract owner. ### CONFIGURING THE CONTRACT Now, are contract is deployed. The next step is to configure it, according to your tokenomics. If we check the code, will see that we have the following parameters used to define a token: ```bash owner_id: AccountId, metadata: FungibleTokenMetadata, ``` The ```owner_id ``` is the account that will own the contract. This account will be able perform actions that are restricted Since this contract has a minting function, the owner will not get any tokens on the contract start. At last, the ``` FungibleTokenMetadata ``` ([reference](https://nomicon.io/Standards/Tokens/FungibleToken/Metadata)) is all the token metadata, wich means its all the extra token information , that describes it. This metadata has the following format: ```bash pub struct FungibleTokenMetadata { pub spec: String, pub name: String, pub symbol: String, pub icon: Option<String>, pub reference: Option<String>, pub reference_hash: Option<Base64VecU8>, pub decimals: u8, ``` An implementing contract **MUST** include the following fields on-chain: - ```spec```: a string. Should be ```ft-1.0.0``` to indicate that a Fungible Token contract adheres to the current versions of this Metadata and the Fungible Token Core specs. This will allow consumers of the Fungible Token to know if they support the features of a given contract - ```name```: the human-readable name of the token, E.g.: Bitcoin - ```symbol```: the abbreviation, E.g.: BTC - ```decimals```: used in frontends to show the proper significant digits of a token. This concept is explained well in this [OpenZeppelin](https://docs.openzeppelin.com/contracts/3.x/erc20#a-note-on-decimals) post - NEAR NEP-141 standard is to have 24 decimals. An implementing contract **MAY** include the following fields on-chain - ```icon```: a small image associated with this token. Must be a data URL, to help consumers display it quickly while protecting <br> user data [more information](https://nomicon.io/Standards/Tokens/FungibleToken/Metadata). - ```reference```: a link to a valid JSON file containing various keys offering supplementary details on the token. <br>Example: /ipfs/QmdmQXB2mzChmMeKY47C43LxUdg1NDJ5MWcKMKxDu7RgQm, https://example.com/token.json, etc. If the information given in this document conflicts with the on-chain attributes, the values in reference shall be considered the source of truth. - ```reference_hash```:the base64-encoded sha256 hash of the JSON file contained in the reference field. This is to guard against off-chain tampering. Although it is note necessary, we **strongly recommend** that you that you implement the fields mentioned above. Also, we recommend that your logo is an SVG. Now that we have everything covered, we can call the ```new``` function and set our token parameters. Below is the command that we are going to use to set the token parameters. Note that the ```owner_id``` is the owner account for that contract, and that cannot be changed. The owner of the contract is going to receive all of the tokens once you call the function. You are going to be able to check your NEAR Wallet and the tokens should be there. Copy the code below, change all of the paramters and run the command on your terminal. ```bash near call $FT_CONTRACT_ID new '{ "owner_id": "owner.near", "metadata": { "spec": "ft-1.0.0", "name": "Bitcoin", "symbol": "BTC", "icon": "data:image/svg+xml,%3C…", "reference": "https://example.com/wbtc.json", "reference_hash": "AK3YRHqKhCJNmKfV6SrutnlWW/icN5J8NUPtKsNXR1M=", "decimals": 24 } }' --accountId owner.near ``` **If you do not want to set an icon, a reference and a reference hash, you must pass this parameters with the value ```null```** E.g.: ```bash "icon": null, ``` With these steps concluded, you'll have sucessfully deployed and configured your token contract. ## REGISTER AN USER In order to register a user on the contract, you must use the function ```storage_deposit```. Here's how to use this function: ```bash near call $FT_CONTRACT_ID storage_deposit '{"account_id": "any_account.near"}' \ --accountId owner_account.near --amount 0.00235 ``` The ```amount``` is the initial deposit to register the user. The ```account_id``` is the user account you want to register. For further information you can check [this link](https://nomicon.io/Standards/StorageManagement). That's all the information you need to use the contract. For further reference on other functions that the contract has, you can always check the [Contract Standards](https://nomicon.io/Standards/Tokens/FungibleToken/Core).
L-tech_NEAR-DApp-Marketplace
asconfig.json assembly as_types.d.ts index.ts model.ts tsconfig.json package.json
Learn-NEAR_NCD--pokemon
README.md as-pect.config.js asconfig.js assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts constants.ts helpers.ts main.ts models.ts tsconfig.json package.json
<!-- @format --> # Near Pokemon ## Set Up `yarn` : installs all the relevant node modules \ `yarn build` : creates the out/main.wasm file \ `yarn test` : runs the main.spec.ts file in assembly/\_\_tests\_\_ ## NEAR `near dev-deploy out/main.wasm` : deploys the contract ### View Methods `near view $CONTRACT getAllPokemon` : returns a list of all pokemon\ `near view $CONTRACT getPokemonById '{"id": $POKEMON_ID}'` : gets a pokemon by id\ `near view $CONTRACT getPokemonByOwner '{"owner": $OWNER_NAME}'` : gets all pokemon for a specific account ### Change Methods `near call $CONTRACT createPokemon '{"name": $POKEMON_NAME}' --account_id $YOUR_ACCOUNT` : creates a pokemon with the specified name and assigns the owner of the pokemon to $YOUR_ACCOUNT\ `near call $CONTRACT deletePokemon '{"id": $POKEMON_ID}' --account_id $YOUR_ACCOUNT` : deletes a pokemon with the specified id\ `near call $CONTRACT transferPokemon '{"newOwner": $OWNER_ACCOUNT, "id": $POKEMON_ID}' --account_id $YOUR_ACCOUNT` : transfers a pokemon from $YOUR_ACCOUNT to $OWNER_ACCOUNT\ `near call $CONTRACT trainPokemon '{"id": $POKEMON_ID, "cpuLevel": $CPU_LEVEL}' --account_id $YOUR_ACCOUNT` : trains a pokemon with id of $POKEMON_ID from $YOUR_ACCOUNT against a random cpu at level $CPU_LEVEL\ `near call $CONTRACT healPokemon '{"id": $POKEMON_ID}' --account_id $YOUR_ACCOUNT` : heals a pokemon with id of $POKEMON_ID from $YOUR_ACCOUNT to full health
jrapbit_yeji-swap-contract
Cargo.toml README.md deploy.sh flow.txt neardev dev-account.env src farm.rs farming.rs lib.rs pool.rs tranfer.rs
# YejiSwap smart contract Smart contract for decentralized exchange on NEAR protocol. Final project for bachelor of computer engineering. ## Tech Stack **Web:** [React](https://www.github.com/jrapbit) **Smart Contract:** Rust ## Authors - [@jrapbit](https://www.github.com/jrapbit) - [@narawitPtm](https://www.github.com/narawitPtm) ## How to deploy First build your rust project to .wasm ```bash cargo build --target wasm32-unknown-unknown --release ``` Then replace `YOUR_ACCOUNT_HERE` with your wallet address. ```bash near deploy --wasmFile target/wasm32-unknown-unknown/release/yeji_swap_contract.wasm --accountId YOUR_ACCOUNT_HERE ```
monocrowd_near-hello
.gitpod.yml README.md contract Cargo.toml README.md compile.js src lib.rs dist global.e37b531c.css global.e50bbfba.css global.e50bbfba.js global.eca22910.css index.html index.js logo-black.3916bf24.svg logo-black.eab7a939.svg logo-white.7fec831f.svg logo-white.c927fc35.svg src.37ed3139.js src.a71af5db.js src.c4364ca5.js src.e31bb0bc.js package.json src assets logo-black.svg logo-white.svg config.js global.css index.html index.js main.test.js utils.js wallet login index.html
hello-near ================== https://monocrowd.github.io/near-hello/ # credit - https://codemyui.com/text-reveal-animation-using-threejs/ hello-near Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html
netocaz_Crypto-Password-Manager
.eslintrc.yml .github dependabot.yml workflows deploy.yml tests.yml .gitpod.yml .travis.yml README-Gitpod.md README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts guestbook.spec.ts as_types.d.ts main.ts model.ts tsconfig.json babel.config.js neardev shared-test-staging test.near.json shared-test test.near.json package.json src App.js config.js index.html index.js services near.js tests integration App-integration.test.js ui App-ui.test.js
Guest Book ========== [![Build Status](https://travis-ci.com/near-examples/guest-book.svg?branch=master)](https://travis-ci.com/near-examples/guest-book) [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near-examples/guest-book) <!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page --> Sign in with [NEAR] and add a message to the guest book! A starter app built with an [AssemblyScript] backend and a [React] frontend. Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you have Node.js ≥ 12 installed (https://nodejs.org), then use it to install [yarn]: `npm install --global yarn` (or just `npm i -g yarn`) 2. Install dependencies: `yarn install --frozen-lockfile` (or just `yarn --frozen-lockfile`) 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Running `yarn dev` will tell you the URL you can visit in your browser to see the app. Exploring The Code ================== 1. The backend code lives in the `/assembly` folder. This code gets deployed to the NEAR blockchain when you run `yarn deploy:contract`. This sort of code-that-runs-on-a-blockchain is called a "smart contract" – [learn more about NEAR smart contracts][smart contract docs]. 2. The frontend code lives in the `/src` folder. [/src/index.html](/src/index.html) is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and backend. The backend code gets tested with the [asp] command for running the backend AssemblyScript tests, and [jest] for running frontend tests. You can run both of these at once with `yarn test`. Both contract and client-side code will auto-reload as you change source files. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contracts get deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli -------------------------- You need near-cli installed globally. Here's how: npm install --global near-cli This will give you the `near` [CLI] tool. Ensure that it's installed with: near --version Step 1: Create an account for the contract ------------------------------------------ Visit [NEAR Wallet] and make a new account. You'll be deploying these smart contracts to this new account. Now authorize NEAR CLI for this new account, and follow the instructions it gives you: near login Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'your-account-here!' Step 3: change remote URL if you cloned this repo ------------------------- Unless you forked this repository you will need to change the remote URL to a repo that you have commit access to. This will allow auto deployment to Github Pages from the command line. 1) go to GitHub and create a new repository for this project 2) open your terminal and in the root of this project enter the following: $ `git remote set-url origin https://github.com/YOUR_USERNAME/YOUR_REPOSITORY.git` Step 4: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contracts to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. [NEAR]: https://nearprotocol.com/ [yarn]: https://yarnpkg.com/ [AssemblyScript]: https://docs.assemblyscript.org/ [React]: https://reactjs.org [smart contract docs]: https://docs.nearprotocol.com/docs/roles/developer/contracts/assemblyscript [asp]: https://www.npmjs.com/package/@as-pect/cli [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.nearprotocol.com/docs/concepts/account [NEAR Wallet]: https://wallet.nearprotocol.com [near-cli]: https://github.com/nearprotocol/near-cli [CLI]: https://www.w3schools.com/whatis/whatis_cli.asp [create-near-app]: https://github.com/nearprotocol/create-near-app [gh-pages]: https://github.com/tschaub/gh-pages
josealfredo79_near-marketplace-dapp-nuevo
README.md asconfig.json assembly as_types.d.ts index.ts model.ts tsconfig.json package-lock.json package.json public index.html manifest.json robots.txt src App.css App.js App.test.js components Wallet.js marketplace AddProduct.js Product.js Products.js utils Cover.js Loader.js Notifications.js index.css index.js logo.svg reportWebVitals.js setupTests.js utils config.js marketplace.js near.js
# Prerequsities Install the next tools: * `node` * `yarn` * `near-cli` Also, you'd need a code editor of choice. In this course we are going to use Visual Studio Code. ## Create project structure The next directories and files must be created to proceed with smart contracts: * assembly/ - this directory contains smart contracts source code * asconfig.json - contains most of configuration properties * assembly/tsconfig.json ### `assembly/asconfig.json` By default it's needed to add the next content to the file. By adding this, we just extend the configuration provided by `near-sdk-as`. ``` { "extends": "near-sdk-as/asconfig.json" } ``` ### `assembly/tsconfig.json` The purpose of this file is to specify compiler options and root level files that are necessary for a TypeScript project to be compiled. Also, this file implies that the directory where `tsconfig.json` is located is the root of the TypeScript project. ``` { "extends": "../node_modules/assemblyscript/std/assembly.json", "include": [ "./**/*.ts" ] } ``` ### `as_types.d.ts` This files declares that some type names must be included in the compilation. In this case, names are imported from `near-sdk-as` ``` /// <reference types="near-sdk-as/assembly/as_types" /> ``` ## Initialize project Run the next commands in a terminal window (in the project's root): ``` yarn init ``` It will create a `package.json` file where development dependencies can be added. Run the next command to add `near-sdk-as` to the project: ``` yarn add -D near-sdk-as ``` The next step is to create an entry file for the smart contract - create `index.ts` file in the `assembly` directory. The resulting project structure should be like this: ``` ├── asconfig.json ├── assembly │   ├── as_types.d.ts │   ├── index.ts │   └── tsconfig.json ├── package.json └── yarn.lock ``` # Compile, build and deployt the smart contract ## Compile & build a smart contract Before a smart contract can be deployed, it must be built as `.wasm`. To do that, the next command should be run from the project's root: ``` yarn asb ``` The output of this command is a `.wasm` file that is placed into `${PROJECT_ROOT}/build/release` directory. ## Login to an account in a shell In order to deploy a contract from via terminal, account's credentials are needed. To get the credentials, run the next command in a terminal window: ``` near login ``` It opens a wallet url in a browser where you can login to your account (or selected one of the existing accounts if you have one). As the result the session in the terminal window is authenticated and you can start deploying contracts and view/call functions. ## Deploy a smart contract To deploy a smart contract, run the next command from in a terminal window: ``` near deploy ${PATH_TO_WASM} --accountId=${ACCOUNT_NAME} ``` where: * `${ACCOUNT_NAME}` - an account name that should be used to deploy a smart contract * `${CONTRACT_NAME}` - an account name that should be used for the contract (we will use the same value as for `${ACCOUNT_NAME}`) * `${PATH_TO_WASM}` - a path to the `.wasm` file issued by the `yarn asb` command - `${PROJECT_ROOT}/build/release/some_name.wasm` ## Contract interaction There are two types of functions in `near`: * `view` functions are used to read state hence they are free. Nothing is modified/persisted when a `view` function is called. * `call` functions are used to modify state of the data stored in the blockchain.
luciotato_vanilla-near-webwallet-typescript
.gitpod.yml .vscode tasks.json README.md contract README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts tsconfig.json compile.js node_modules .package-lock.json @as-pect assembly README.md assembly index.ts internal Actual.ts Expectation.ts Expected.ts RTrace.ts Reflect.ts ReflectedValueType.ts Test.ts assert.ts call.ts comparison toIncludeComparison.ts toIncludeEqualComparison.ts log.ts noOp.ts runtime.ts package.json types as-pect.d.ts as-pect.portable.d.ts env.d.ts cli README.md init as-pect.config.js env.d.ts example.spec.ts init-types.d.ts portable-types.d.ts lib as-pect.cli.amd.d.ts as-pect.cli.amd.js help.d.ts help.js index.d.ts index.js init.d.ts init.js portable.d.ts portable.js run.d.ts run.js test.d.ts test.js types.d.ts types.js util CommandLineArg.d.ts CommandLineArg.js IConfiguration.d.ts IConfiguration.js asciiArt.d.ts asciiArt.js collectReporter.d.ts collectReporter.js getTestEntryFiles.d.ts getTestEntryFiles.js removeFile.d.ts removeFile.js strings.d.ts strings.js writeFile.d.ts writeFile.js worklets ICommand.d.ts ICommand.js compiler.d.ts compiler.js package.json core README.md lib as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js reporter CombinationReporter.d.ts CombinationReporter.js EmptyReporter.d.ts EmptyReporter.js IReporter.d.ts IReporter.js SummaryReporter.d.ts SummaryReporter.js VerboseReporter.d.ts VerboseReporter.js test IWarning.d.ts IWarning.js TestContext.d.ts TestContext.js TestNode.d.ts TestNode.js transform assemblyscript.d.ts assemblyscript.js createAddReflectedValueKeyValuePairsMember.d.ts createAddReflectedValueKeyValuePairsMember.js createGenericTypeParameter.d.ts createGenericTypeParameter.js createStrictEqualsMember.d.ts createStrictEqualsMember.js emptyTransformer.d.ts emptyTransformer.js hash.d.ts hash.js index.d.ts index.js util IAspectExports.d.ts IAspectExports.js IWriteable.d.ts IWriteable.js ReflectedValue.d.ts ReflectedValue.js TestNodeType.d.ts TestNodeType.js rTrace.d.ts rTrace.js stringifyReflectedValue.d.ts stringifyReflectedValue.js timeDifference.d.ts timeDifference.js wasmTools.d.ts wasmTools.js package.json csv-reporter index.ts lib as-pect.csv-reporter.amd.d.ts as-pect.csv-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json json-reporter index.ts lib as-pect.json-reporter.amd.d.ts as-pect.json-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json snapshots __tests__ snapshot.spec.ts jest.config.js lib Snapshot.d.ts Snapshot.js SnapshotDiff.d.ts SnapshotDiff.js SnapshotDiffResult.d.ts SnapshotDiffResult.js as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js parser grammar.d.ts grammar.js package.json src Snapshot.ts SnapshotDiff.ts SnapshotDiffResult.ts index.ts parser grammar.ts tsconfig.json @assemblyscript loader README.md index.d.ts index.js package.json ansi-regex index.d.ts index.js package.json readme.md ansi-styles index.d.ts index.js package.json readme.md as-bignum .travis.yml README.md as-pect.config.js assembly __tests__ as-pect.d.ts safe_u128.spec.as.ts u128.spec.as.ts u256.spec.as.ts utils.ts fixed fp128.ts fp256.ts index.ts safe fp128.ts fp256.ts types.ts globals.ts index.ts integer i128.ts i256.ts index.ts safe i128.ts i256.ts i64.ts index.ts u128.ts u256.ts u64.ts u128.ts u256.ts tsconfig.json utils.ts index.js package.json tsconfig.json asbuild README.md dist cli.d.ts cli.js index.d.ts index.js main.d.ts main.js index.js package.json assemblyscript-json .travis.yml README.md as-pect.config.js assembly JSON.ts __tests__ as-pect.d.ts roundtrip.spec.ts decoder.ts encoder.ts index.ts tsconfig.json util index.ts index.js package.json assemblyscript README.md cli README.md asc.d.ts asc.js asc.json shim README.md fs.js path.js process.js transform.d.ts transform.js util colors.d.ts colors.js find.d.ts find.js mkdirp.d.ts mkdirp.js options.d.ts options.js utf8.d.ts utf8.js dist asc.js assemblyscript.d.ts assemblyscript.js sdk.js index.d.ts index.js lib loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json rtrace README.md index.d.ts index.js package.json umd index.d.ts index.js package.json package-lock.json package.json std README.md assembly.json assembly array.ts arraybuffer.ts atomics.ts bindings Date.ts Math.ts Reflect.ts asyncify.ts console.ts wasi.ts wasi_snapshot_preview1.ts wasi_unstable.ts builtins.ts compat.ts dataview.ts date.ts diagnostics.ts error.ts function.ts gc.ts index.d.ts iterator.ts map.ts math.ts memory.ts number.ts object.ts polyfills.ts reference.ts regexp.ts rt.ts rt README.md common.ts index-full.ts index-half.ts index-none.ts index-stub.ts index.d.ts pure.ts rtrace.ts stub.ts tlsf.ts set.ts shared feature.ts target.ts tsconfig.json typeinfo.ts staticarray.ts string.ts symbol.ts table.ts tsconfig.json typedarray.ts util casemap.ts error.ts hash.ts math.ts memory.ts number.ts sort.ts string.ts vector.ts wasi index.ts portable.json portable index.d.ts index.js types assembly index.d.ts package.json portable index.d.ts package.json tsconfig-base.json axios CHANGELOG.md README.md UPGRADE_GUIDE.md dist axios.js axios.min.js index.d.ts index.js lib adapters README.md http.js xhr.js axios.js cancel Cancel.js CancelToken.js isCancel.js core Axios.js InterceptorManager.js README.md buildFullPath.js createError.js dispatchRequest.js enhanceError.js mergeConfig.js settle.js transformData.js defaults.js helpers README.md bind.js buildURL.js combineURLs.js cookies.js deprecatedMethod.js isAbsoluteURL.js isURLSameOrigin.js normalizeHeaderName.js parseHeaders.js spread.js utils.js package.json balanced-match LICENSE.md README.md index.js package.json base-x LICENSE.md README.md package.json src index.d.ts index.js binary-install README.md example binary.js package.json run.js index.js package.json src binary.js binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts bn.js CHANGELOG.md README.md lib bn.js package.json brace-expansion README.md index.js package.json bs58 CHANGELOG.md README.md index.js package.json camelcase index.d.ts index.js package.json readme.md chalk index.d.ts package.json readme.md source index.js templates.js util.js chownr README.md chownr.js package.json cliui CHANGELOG.md LICENSE.txt README.md index.js package.json color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name README.md index.js package.json commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts concat-map .travis.yml example map.js index.js package.json test map.js debug .coveralls.yml .travis.yml CHANGELOG.md README.md karma.conf.js node.js package.json src browser.js debug.js index.js node.js decamelize index.js package.json readme.md diff CONTRIBUTING.md README.md dist diff.js lib convert dmp.js xml.js diff array.js base.js character.js css.js json.js line.js sentence.js word.js index.es6.js index.js patch apply.js create.js merge.js parse.js util array.js distance-iterator.js params.js package.json release-notes.md runtime.js discontinuous-range .travis.yml README.md index.js package.json test main-test.js emoji-regex LICENSE-MIT.txt README.md es2015 index.js text.js index.d.ts index.js package.json text.js env-paths index.d.ts index.js package.json readme.md find-up index.d.ts index.js package.json readme.md follow-redirects README.md http.js https.js index.js package.json fs-minipass README.md index.js package.json fs.realpath README.md index.js old.js package.json function-bind .jscs.json .travis.yml README.md implementation.js index.js package.json test index.js get-caller-file LICENSE.md README.md index.d.ts index.js package.json glob README.md changelog.md common.js glob.js package.json sync.js has-flag index.d.ts index.js package.json readme.md has README.md package.json src index.js test index.js hasurl README.md index.js package.json inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json interpret README.md index.js mjs-stub.js package.json is-core-module .github FUNDING.yml workflows node-4+.yml node-iojs.yml node-pretest.yml node-zero.yml rebase.yml require-allow-edits.yml CHANGELOG.md README.md core.json index.js package.json test index.js is-fullwidth-code-point index.d.ts index.js package.json readme.md js-base64 LICENSE.md README.md base64.d.ts base64.js package.json locate-path index.d.ts index.js package.json readme.md lodash.clonedeep README.md index.js package.json lodash.sortby README.md index.js package.json long README.md dist long.js index.js package.json src long.js minimatch README.md minimatch.js package.json minimist .travis.yml example parse.js index.js package.json test all_bool.js bool.js dash.js default_bool.js dotted.js kv_short.js long.js num.js parse.js parse_modified.js proto.js short.js stop_early.js unknown.js whitespace.js minipass README.md index.js package.json minizlib README.md constants.js index.js package.json mkdirp bin cmd.js usage.txt index.js package.json moo README.md moo.js package.json ms index.js license.md package.json readme.md near-mock-vm assembly __tests__ main.ts context.ts index.ts outcome.ts vm.ts bin bin.js package.json pkg near_mock_vm.d.ts near_mock_vm.js package.json vm dist cli.d.ts cli.js context.d.ts context.js index.d.ts index.js memory.d.ts memory.js runner.d.ts runner.js utils.d.ts utils.js index.js near-sdk-as as-pect.config.js as_types.d.ts asconfig.json asp.asconfig.json assembly __tests__ as-pect.d.ts assert.spec.ts avl-tree.spec.ts bignum.spec.ts contract.spec.ts contract.ts data.txt empty.ts generic.ts includeBytes.spec.ts main.ts model.ts near.spec.ts persistent-set.spec.ts rollback.spec.ts roundtrip.spec.ts runtime.spec.ts unordered-map.spec.ts util.ts utils.spec.ts as_types.d.ts bindgen.ts index.ts tsconfig.json vm __tests__ vm.include.ts index.ts compiler.js imports.js package.json near-sdk-bindgen README.md assembly index.ts compiler.js dist JSONBuilder.d.ts JSONBuilder.js classExporter.d.ts classExporter.js index.d.ts index.js transformer.d.ts transformer.js typeChecker.d.ts typeChecker.js utils.d.ts utils.js index.js package.json near-sdk-core README.md asconfig.json assembly as_types.d.ts base58.ts base64.ts bignum.ts collections avlTree.ts index.ts persistentDeque.ts persistentMap.ts persistentSet.ts persistentUnorderedMap.ts persistentVector.ts util.ts contract.ts env env.ts index.ts runtime_api.ts index.ts logging.ts math.ts promise.ts storage.ts tsconfig.json util.ts docs assets css main.css js main.js search.json classes _sdk_core_assembly_collections_avltree_.avltree.html _sdk_core_assembly_collections_avltree_.avltreenode.html _sdk_core_assembly_collections_avltree_.childparentpair.html _sdk_core_assembly_collections_avltree_.nullable.html _sdk_core_assembly_collections_persistentdeque_.persistentdeque.html _sdk_core_assembly_collections_persistentmap_.persistentmap.html _sdk_core_assembly_collections_persistentset_.persistentset.html _sdk_core_assembly_collections_persistentunorderedmap_.persistentunorderedmap.html _sdk_core_assembly_collections_persistentvector_.persistentvector.html _sdk_core_assembly_contract_.context-1.html _sdk_core_assembly_contract_.contractpromise.html _sdk_core_assembly_contract_.contractpromiseresult.html _sdk_core_assembly_math_.rng.html _sdk_core_assembly_promise_.contractpromisebatch.html _sdk_core_assembly_storage_.storage-1.html globals.html index.html modules _sdk_core_assembly_base58_.base58.html _sdk_core_assembly_base58_.html _sdk_core_assembly_base64_.base64.html _sdk_core_assembly_base64_.html _sdk_core_assembly_collections_avltree_.html _sdk_core_assembly_collections_index_.collections.html _sdk_core_assembly_collections_index_.html _sdk_core_assembly_collections_persistentdeque_.html _sdk_core_assembly_collections_persistentmap_.html _sdk_core_assembly_collections_persistentset_.html _sdk_core_assembly_collections_persistentunorderedmap_.html _sdk_core_assembly_collections_persistentvector_.html _sdk_core_assembly_collections_util_.html _sdk_core_assembly_contract_.html _sdk_core_assembly_env_env_.env.html _sdk_core_assembly_env_env_.html _sdk_core_assembly_env_index_.html _sdk_core_assembly_env_runtime_api_.html _sdk_core_assembly_index_.html _sdk_core_assembly_logging_.html _sdk_core_assembly_logging_.logging.html _sdk_core_assembly_math_.html _sdk_core_assembly_math_.math.html _sdk_core_assembly_promise_.html _sdk_core_assembly_storage_.html _sdk_core_assembly_util_.html _sdk_core_assembly_util_.util.html package.json near-sdk-simulator __tests__ avl-tree-contract.spec.ts cross.spec.ts empty.spec.ts exportAs.spec.ts singleton-no-constructor.spec.ts singleton.spec.ts asconfig.js asconfig.json assembly __tests__ avlTreeContract.ts empty.ts exportAs.ts model.ts sentences.ts singleton-fail.ts singleton-no-constructor.ts singleton.ts words.ts as_types.d.ts tsconfig.json dist bin.d.ts bin.js context.d.ts context.js index.d.ts index.js runtime.d.ts runtime.js types.d.ts types.js utils.d.ts utils.js jest.config.js out assembly __tests__ exportAs.ts model.ts sentences.ts singleton-no-constructor.ts singleton.ts package.json src context.ts index.ts runtime.ts types.ts utils.ts tsconfig.json near-vm getBinary.js install.js package.json run.js uninstall.js nearley LICENSE.txt README.md bin nearley-railroad.js nearley-test.js nearley-unparse.js nearleyc.js lib compile.js generate.js lint.js nearley-language-bootstrapped.js nearley.js stream.js unparse.js package.json once README.md once.js package.json p-limit index.d.ts index.js package.json readme.md p-locate index.d.ts index.js package.json readme.md p-try index.d.ts index.js package.json readme.md path-exists index.d.ts index.js package.json readme.md path-is-absolute index.js package.json readme.md path-parse .travis.yml README.md index.js package.json test.js punycode LICENSE-MIT.txt README.md package.json punycode.es6.js punycode.js railroad-diagrams README.md example.html generator.html package.json railroad-diagrams.css railroad-diagrams.js railroad_diagrams.py randexp README.md lib randexp.js package.json rechoir .travis.yml README.md index.js lib extension.js normalize.js register.js package.json require-directory .travis.yml index.js package.json require-main-filename CHANGELOG.md LICENSE.txt README.md index.js package.json resolve SECURITY.md appveyor.yml example async.js sync.js index.js lib async.js caller.js core.js core.json is-core.js node-modules-paths.js normalize-options.js sync.js package.json test core.js dotdot.js dotdot abc index.js index.js faulty_basedir.js filter.js filter_sync.js mock.js mock_sync.js module_dir.js module_dir xmodules aaa index.js ymodules aaa index.js zmodules bbb main.js package.json node-modules-paths.js node_path.js node_path x aaa index.js ccc index.js y bbb index.js ccc index.js nonstring.js pathfilter.js pathfilter deep_ref main.js precedence.js precedence aaa.js aaa index.js main.js bbb.js bbb main.js resolver.js resolver baz doom.js package.json quux.js browser_field a.js b.js package.json cup.coffee dot_main index.js package.json dot_slash_main index.js package.json foo.js incorrect_main index.js package.json invalid_main package.json mug.coffee mug.js multirepo lerna.json package.json packages package-a index.js package.json package-b index.js package.json nested_symlinks mylib async.js package.json sync.js other_path lib other-lib.js root.js quux foo index.js same_names foo.js foo index.js symlinked _ node_modules foo.js package bar.js package.json without_basedir main.js resolver_sync.js shadowed_core.js shadowed_core node_modules util index.js subdirs.js symlinks.js ret README.md lib index.js positions.js sets.js types.js util.js package.json rimraf CHANGELOG.md README.md bin.js package.json rimraf.js safe-buffer README.md index.d.ts index.js package.json set-blocking CHANGELOG.md LICENSE.txt README.md index.js package.json shelljs CHANGELOG.md README.md commands.js global.js make.js package.json plugin.js shell.js src cat.js cd.js chmod.js common.js cp.js dirs.js echo.js error.js exec-child.js exec.js find.js grep.js head.js ln.js ls.js mkdir.js mv.js popd.js pushd.js pwd.js rm.js sed.js set.js sort.js tail.js tempdir.js test.js to.js toEnd.js touch.js uniq.js which.js string-width index.d.ts index.js package.json readme.md strip-ansi index.d.ts index.js package.json readme.md supports-color browser.js index.js package.json readme.md tar README.md index.js lib create.js extract.js get-write-flag.js header.js high-level-opt.js large-numbers.js list.js mkdir.js mode-fix.js pack.js parse.js path-reservations.js pax.js read-entry.js replace.js types.js unpack.js update.js warn-mixin.js winchars.js write-entry.js package.json tr46 LICENSE.md README.md index.js lib mappingTable.json regexes.js package.json ts-mixer CHANGELOG.md README.md dist decorator.d.ts decorator.js index.d.ts index.js mixin-tracking.d.ts mixin-tracking.js mixins.d.ts mixins.js proxy.d.ts proxy.js settings.d.ts settings.js types.d.ts types.js util.d.ts util.js package.json universal-url README.md browser.js index.js package.json visitor-as .travis.yml README.md as index.d.ts index.js asconfig.json dist astBuilder.d.ts astBuilder.js base.d.ts base.js baseTransform.d.ts baseTransform.js decorator.d.ts decorator.js examples capitalize.d.ts capitalize.js exportAs.d.ts exportAs.js functionCallTransform.d.ts functionCallTransform.js includeBytesTransform.d.ts includeBytesTransform.js list.d.ts list.js index.d.ts index.js path.d.ts path.js simpleParser.d.ts simpleParser.js transformer.d.ts transformer.js utils.d.ts utils.js visitor.d.ts visitor.js package.json tsconfig.json webidl-conversions LICENSE.md README.md lib index.js package.json whatwg-url LICENSE.txt README.md lib URL-impl.js URL.js URLSearchParams-impl.js URLSearchParams.js infra.js public-api.js url-state-machine.js urlencoded.js utils.js package.json which-module CHANGELOG.md README.md index.js package.json wrap-ansi index.js package.json readme.md wrappy README.md package.json wrappy.js y18n CHANGELOG.md README.md index.js package.json yallist README.md iterator.js package.json yallist.js yargs-parser CHANGELOG.md LICENSE.txt README.md index.js lib tokenize-arg-string.js package.json yargs CHANGELOG.md README.md build lib apply-extends.d.ts apply-extends.js argsert.d.ts argsert.js command.d.ts command.js common-types.d.ts common-types.js completion-templates.d.ts completion-templates.js completion.d.ts completion.js is-promise.d.ts is-promise.js levenshtein.d.ts levenshtein.js middleware.d.ts middleware.js obj-filter.d.ts obj-filter.js parse-command.d.ts parse-command.js process-argv.d.ts process-argv.js usage.d.ts usage.js validation.d.ts validation.js yargs.d.ts yargs.js yerror.d.ts yerror.js index.js locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json yargs.js package-lock.json package.json | package.json src assets logo-black.svg logo-white.svg narwallets.svg config.ts contracts GreetingContract.ts global.css index.html index.ts main.test.js wallet-api base-sc.ts batch-transaction.ts disconnected-wallet.ts narwallets narwallets.ts near-web-wallet near-web-wallet.ts wallet-interface.ts wallet login index.html tsconfig.json
vanilla Smart Contract ================== A [smart contract] written in [AssemblyScript] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install [Node.js] ≥ 12 Exploring The Code ================== 1. The main smart contract code lives in `assembly/index.ts`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard AssemblyScript tests using [as-pect]. [smart contract]: https://docs.near.org/docs/roles/developer/contracts/intro [AssemblyScript]: https://www.assemblyscript.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [as-pect]: https://www.npmjs.com/package/@as-pect/cli # rechoir [![Build Status](https://secure.travis-ci.org/tkellen/js-rechoir.png)](http://travis-ci.org/tkellen/js-rechoir) > Require any supported file as a node module. [![NPM](https://nodei.co/npm/rechoir.png)](https://nodei.co/npm/rechoir/) ## What is it? This module, in conjunction with [interpret]-like objects can register any file type the npm ecosystem has a module loader for. This library is a dependency of [Liftoff]. ## API ### prepare(config, filepath, requireFrom) Look for a module loader associated with the provided file and attempt require it. If necessary, run any setup required to inject it into [require.extensions](http://nodejs.org/api/globals.html#globals_require_extensions). `config` An [interpret]-like configuration object. `filepath` A file whose type you'd like to register a module loader for. `requireFrom` An optional path to start searching for the module required to load the requested file. Defaults to the directory of `filepath`. If calling this method is successful (aka: it doesn't throw), you can now require files of the type you requested natively. An error with a `failures` property will be thrown if the module loader(s) configured for a given extension cannot be registered. If a loader is already registered, this will simply return `true`. **Note:** While rechoir will automatically load and register transpilers like `coffee-script`, you must provide a local installation. The transpilers are **not** bundled with this module. #### Usage ```js const config = require('interpret').extensions; const rechoir = require('rechoir'); rechoir.prepare(config, './test/fixtures/test.coffee'); rechoir.prepare(config, './test/fixtures/test.csv'); rechoir.prepare(config, './test/fixtures/test.toml'); console.log(require('./test/fixtures/test.coffee')); console.log(require('./test/fixtures/test.csv')); console.log(require('./test/fixtures/test.toml')); ``` [interpret]: http://github.com/tkellen/js-interpret [Liftoff]: http://github.com/tkellen/js-liftoff # once Only call a function once. ## usage ```javascript var once = require('once') function load (file, cb) { cb = once(cb) loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Or add to the Function.prototype in a responsible way: ```javascript // only has to be done once require('once').proto() function load (file, cb) { cb = cb.once() loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Ironically, the prototype feature makes this module twice as complicated as necessary. To check whether you function has been called, use `fn.called`. Once the function is called for the first time the return value of the original function is saved in `fn.value` and subsequent calls will continue to return this value. ```javascript var once = require('once') function load (cb) { cb = once(cb) var stream = createStream() stream.once('data', cb) stream.once('end', function () { if (!cb.called) cb(new Error('not found')) }) } ``` ## `once.strict(func)` Throw an error if the function is called twice. Some functions are expected to be called only once. Using `once` for them would potentially hide logical errors. In the example below, the `greet` function has to call the callback only once: ```javascript function greet (name, cb) { // return is missing from the if statement // when no name is passed, the callback is called twice if (!name) cb('Hello anonymous') cb('Hello ' + name) } function log (msg) { console.log(msg) } // this will print 'Hello anonymous' but the logical error will be missed greet(null, once(msg)) // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time greet(null, once.strict(msg)) ``` # lodash.clonedeep v4.5.0 The [lodash](https://lodash.com/) method `_.cloneDeep` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.clonedeep ``` In Node.js: ```js var cloneDeep = require('lodash.clonedeep'); ``` See the [documentation](https://lodash.com/docs#cloneDeep) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.clonedeep) for more details. # set-blocking [![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) [![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) [![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. ```js const setBlocking = require('set-blocking') setBlocking(true) console.log(someLargeStringToOutput) ``` ## Historical Context/Word of Warning This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on newer versions of Node.js (`0.12+`), truncating terminal output. You should be mindful of the side-effects caused by using `set-blocking`: * if your module sets blocking to `true`, it will effect other modules consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call `setBlocking(true)` once we already know we are about to call `process.exit(code)`. * this patch will not apply to subprocesses spawned with `isTTY = true`, this is the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). ## License ISC # [nearley](http://nearley.js.org) ↗️ [![JS.ORG](https://img.shields.io/badge/js.org-nearley-ffb400.svg?style=flat-square)](http://js.org) [![npm version](https://badge.fury.io/js/nearley.svg)](https://badge.fury.io/js/nearley) nearley is a simple, fast and powerful parsing toolkit. It consists of: 1. [A powerful, modular DSL for describing languages](https://nearley.js.org/docs/grammar) 2. [An efficient, lightweight Earley parser](https://nearley.js.org/docs/parser) 3. [Loads of tools, editor plug-ins, and other goodies!](https://nearley.js.org/docs/tooling) nearley is a **streaming** parser with support for catching **errors** gracefully and providing _all_ parsings for **ambiguous** grammars. It is compatible with a variety of **lexers** (we recommend [moo](http://github.com/tjvr/moo)). It comes with tools for creating **tests**, **railroad diagrams** and **fuzzers** from your grammars, and has support for a variety of editors and platforms. It works in both node and the browser. Unlike most other parser generators, nearley can handle *any* grammar you can define in BNF (and more!). In particular, while most existing JS parsers such as PEGjs and Jison choke on certain grammars (e.g. [left recursive ones](http://en.wikipedia.org/wiki/Left_recursion)), nearley handles them easily and efficiently by using the [Earley parsing algorithm](https://en.wikipedia.org/wiki/Earley_parser). nearley is used by a wide variety of projects: - [artificial intelligence](https://github.com/ChalmersGU-AI-course/shrdlite-course-project) and - [computational linguistics](https://wiki.eecs.yorku.ca/course_archive/2014-15/W/6339/useful_handouts) classes at universities; - [file format parsers](https://github.com/raymond-h/node-dmi); - [data-driven markup languages](https://github.com/idyll-lang/idyll-compiler); - [compilers for real-world programming languages](https://github.com/sizigi/lp5562); - and nearley itself! The nearley compiler is bootstrapped. nearley is an npm [staff pick](https://www.npmjs.com/package/npm-collection-staff-picks). ## Documentation Please visit our website https://nearley.js.org to get started! You will find a tutorial, detailed reference documents, and links to several real-world examples to get inspired. ## Contributing Please read [this document](.github/CONTRIBUTING.md) *before* working on nearley. If you are interested in contributing but unsure where to start, take a look at the issues labeled "up for grabs" on the issue tracker, or message a maintainer (@kach or @tjvr on Github). nearley is MIT licensed. A big thanks to Nathan Dinsmore for teaching me how to Earley, Aria Stewart for helping structure nearley into a mature module, and Robin Windels for bootstrapping the grammar. Additionally, Jacob Edelman wrote an experimental JavaScript parser with nearley and contributed ideas for EBNF support. Joshua T. Corbin refactored the compiler to be much, much prettier. Bojidar Marinov implemented postprocessors-in-other-languages. Shachar Itzhaky fixed a subtle bug with nullables. ## Citing nearley If you are citing nearley in academic work, please use the following BibTeX entry. ```bibtex @misc{nearley, author = "Kartik Chandra and Tim Radvan", title = "{nearley}: a parsing toolkit for {JavaScript}", year = {2014}, doi = {10.5281/zenodo.3897993}, url = {https://github.com/kach/nearley} } ``` discontinuous-range =================== ``` DiscontinuousRange(1, 10).subtract(4, 6); // [ 1-3, 7-10 ] ``` [![Build Status](https://travis-ci.org/dtudury/discontinuous-range.png)](https://travis-ci.org/dtudury/discontinuous-range) this is a pretty simple module, but it exists to service another project so this'll be pretty lacking documentation. reading the test to see how this works may help. otherwise, here's an example that I think pretty much sums it up ###Example ``` var all_numbers = new DiscontinuousRange(1, 100); var bad_numbers = DiscontinuousRange(13).add(8).add(60,80); var good_numbers = all_numbers.clone().subtract(bad_numbers); console.log(good_numbers.toString()); //[ 1-7, 9-12, 14-59, 81-100 ] var random_good_number = good_numbers.index(Math.floor(Math.random() * good_numbers.length)); ``` # AssemblyScript Loader A convenient loader for [AssemblyScript](https://assemblyscript.org) modules. Demangles module exports to a friendly object structure compatible with TypeScript definitions and provides useful utility to read/write data from/to memory. [Documentation](https://assemblyscript.org/loader.html) [![NPM registry](https://img.shields.io/npm/v/as-bignum.svg?style=for-the-badge)](https://www.npmjs.com/package/as-bignum)[![Build Status](https://img.shields.io/travis/com/MaxGraey/as-bignum/master?style=for-the-badge)](https://travis-ci.com/MaxGraey/as-bignum)[![NPM license](https://img.shields.io/badge/license-Apache%202.0-ba68c8.svg?style=for-the-badge)](LICENSE.md) ## Work in progress --- ### WebAssembly fixed length big numbers written on [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) Provide wide numeric types such as `u128`, `u256`, `i128`, `i256` and fixed points and also its arithmetic operations. Namespace `safe` contain equivalents with overflow/underflow traps. All kind of types pretty useful for economical and cryptographic usages and provide deterministic behavior. ### Install > yarn add as-bignum or > npm i as-bignum ### Usage via AssemblyScript ```ts import { u128 } from "as-bignum"; declare function logF64(value: f64): void; declare function logU128(hi: u64, lo: u64): void; var a = u128.One; var b = u128.from(-32); // same as u128.from<i32>(-32) var c = new u128(0x1, -0xF); var d = u128.from(0x0123456789ABCDEF); // same as u128.from<i64>(0x0123456789ABCDEF) var e = u128.from('0x0123456789ABCDEF01234567'); var f = u128.fromString('11100010101100101', 2); // same as u128.from('0b11100010101100101') var r = d / c + (b << 5) + e; logF64(r.as<f64>()); logU128(r.hi, r.lo); ``` ### Usage via JavaScript/Typescript ```ts TODO ``` ### List of types - [x] [`u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u128.ts) unsigned type (tested) - [ ] [`u256`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u256.ts) unsigned type (very basic) - [ ] `i128` signed type - [ ] `i256` signed type --- - [x] [`safe.u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/safe/u128.ts) unsigned type (tested) - [ ] `safe.u256` unsigned type - [ ] `safe.i128` signed type - [ ] `safe.i256` signed type --- - [ ] [`fp128<Q>`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/fixed/fp128.ts) generic fixed point signed type٭ (very basic for now) - [ ] `fp256<Q>` generic fixed point signed type٭ --- - [ ] `safe.fp128<Q>` generic fixed point signed type٭ - [ ] `safe.fp256<Q>` generic fixed point signed type٭ ٭ _typename_ `Q` _is a type representing count of fractional bits_ # axios [![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) [![build status](https://img.shields.io/travis/axios/axios/master.svg?style=flat-square)](https://travis-ci.org/axios/axios) [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) [![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios) [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios) [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios) [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) Promise based HTTP client for the browser and node.js ## Features - Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser - Make [http](http://nodejs.org/api/http.html) requests from node.js - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API - Intercept request and response - Transform request and response data - Cancel requests - Automatic transforms for JSON data - Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) ## Browser Support ![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) | --- | --- | --- | --- | --- | --- | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ | [![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios) ## Installing Using npm: ```bash $ npm install axios ``` Using bower: ```bash $ bower install axios ``` Using yarn: ```bash $ yarn add axios ``` Using cdn: ```html <script src="https://unpkg.com/axios/dist/axios.min.js"></script> ``` ## Example ### note: CommonJS usage In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: ```js const axios = require('axios').default; // axios.<method> will now provide autocomplete and parameter typings ``` Performing a `GET` request ```js const axios = require('axios'); // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .finally(function () { // always executed }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .finally(function () { // always executed }); // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } ``` > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet > Explorer and older browsers, so use with caution. Performing a `POST` request ```js axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` Performing multiple concurrent requests ```js function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete })); ``` ## axios API Requests can be made by passing the relevant config to `axios`. ##### axios(config) ```js // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); ``` ```js // GET request for remote image axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); ``` ##### axios(url[, config]) ```js // Send a GET request (default method) axios('/user/12345'); ``` ### Request method aliases For convenience aliases have been provided for all supported request methods. ##### axios.request(config) ##### axios.get(url[, config]) ##### axios.delete(url[, config]) ##### axios.head(url[, config]) ##### axios.options(url[, config]) ##### axios.post(url[, data[, config]]) ##### axios.put(url[, data[, config]]) ##### axios.patch(url[, data[, config]]) ###### NOTE When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. ### Concurrency Helper functions for dealing with concurrent requests. ##### axios.all(iterable) ##### axios.spread(callback) ### Creating an instance You can create a new instance of axios with a custom config. ##### axios.create([config]) ```js const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); ``` ### Instance methods The available instance methods are listed below. The specified config will be merged with the instance config. ##### axios#request(config) ##### axios#get(url[, config]) ##### axios#delete(url[, config]) ##### axios#head(url[, config]) ##### axios#options(url[, config]) ##### axios#post(url[, data[, config]]) ##### axios#put(url[, data[, config]]) ##### axios#patch(url[, data[, config]]) ##### axios#getUri([config]) ## Request Config These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. ```js { // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // syntax alternative to send data into the body // method post // only the value is sent, not the key data: 'Country=Brasil&City=Belo Horizonte', // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. // Please note that only HTTP Basic auth is configurable through this parameter. // For Bearer tokens and such, use `Authorization` custom headers instead. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content in bytes allowed maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' defines the hostname and port of the proxy server. // You can also define your proxy using the conventional `http_proxy` and // `https_proxy` environment variables. If you are using environment variables // for your proxy configuration, you can also define a `no_proxy` environment // variable as a comma-separated list of domains that should not be proxied. // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }) } ``` ## Response Schema The response for a request contains the following information. ```js { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with // All header names are lower cased headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} } ``` When using `then`, you will receive the response as follows: ```js axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); ``` When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section. ## Config Defaults You can specify config defaults that will be applied to every request. ### Global axios defaults ```js axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; ``` ### Custom instance defaults ```js // Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; ``` ### Config order of precedence Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. ```js // Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); ``` ## Interceptors You can intercept requests or responses before they are handled by `then` or `catch`. ```js // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); }); ``` If you need to remove an interceptor later you can. ```js const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); ``` You can add interceptors to a custom instance of axios. ```js const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); ``` ## Handling Errors ```js axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); ``` Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. ```js axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } }) ``` Using `toJSON` you get an object with more information about the HTTP error. ```js axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); }); ``` ## Cancellation You can cancel a request using a *cancel token*. > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises). You can create a cancel token using the `CancelToken.source` factory as shown below: ```js const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.'); ``` You can also create a cancel token by passing an executor function to the `CancelToken` constructor: ```js const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }); // cancel the request cancel(); ``` > Note: you can cancel several requests with the same cancel token. ## Using application/x-www-form-urlencoded format By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options. ### Browser In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows: ```js const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params); ``` > Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: ```js const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 })); ``` Or in another way (ES6), ```js import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options); ``` ### Node.js In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: ```js const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' })); ``` You can also use the [`qs`](https://github.com/ljharb/qs) library. ###### NOTE The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665). ## Semver Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. ## Promises axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). ## TypeScript axios includes [TypeScript](http://typescriptlang.org) definitions. ```typescript import axios from 'axios'; axios.get('/user?ID=12345'); ``` ## Resources * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) ## Credits axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular. ## License [MIT](LICENSE) Shims used when bundling asc for browser usage. # base-x [![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x) [![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Fast base encoding / decoding of any given alphabet using bitcoin style leading zero compression. **WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. ## Example Base58 ``` javascript var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' var bs58 = require('base-x')(BASE58) var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') console.log(decoded) // => <Buffer 80 ed db dc 11 68 f1 da ea db d3 e4 4c 1e 3f 8f 5a 28 4c 20 29 f7 8a d2 6a f9 85 83 a4 99 de 5b 19> console.log(bs58.encode(decoded)) // => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr ``` ### Alphabets See below for a list of commonly recognized alphabets, and their respective base. Base | Alphabet ------------- | ------------- 2 | `01` 8 | `01234567` 11 | `0123456789a` 16 | `0123456789abcdef` 32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ` 32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32) 36 | `0123456789abcdefghijklmnopqrstuvwxyz` 58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` 62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` 64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` 66 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~` ## How it works It encodes octet arrays by doing long divisions on all significant digits in the array, creating a representation of that number in the new base. Then for every leading zero in the input (not significant as a number) it will encode as a single leader character. This is the first in the alphabet and will decode as 8 bits. The other characters depend upon the base. For example, a base58 alphabet packs roughly 5.858 bits per character. This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each character. While unusual, this does mean that no padding is required and it works for bases like 43. ## LICENSE [MIT](LICENSE) A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets. # Glob Match files using the patterns the shell uses, like stars and stuff. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. ![](logo/glob.png) ## Usage Install with npm ``` npm i glob ``` ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ## Glob Primer "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with any number of comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion: * `*` Matches 0 or more characters in a single path portion * `?` Matches 1 character * `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. * `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided * `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: $ echo a*s*d*f a*s*d*f To get the bash-style behavior, set the `nonull:true` in the options. ### See Also: * `man sh` * `man bash` (Search for "Pattern Matching") * `man 3 fnmatch` * `man 5 gitignore` * [minimatch documentation](https://github.com/isaacs/minimatch) ## glob.hasMagic(pattern, [options]) Returns `true` if there are any special characters in the pattern, and `false` otherwise. Note that the options affect the results. If `noext:true` is set in the options object, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` then that is considered magical, unless `nobrace:true` is set in the options. ## glob(pattern, [options], cb) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * `cb` `{Function}` * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Perform an asynchronous glob search. ## glob.sync(pattern, [options]) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * return: `{Array<String>}` filenames found matching the pattern Perform a synchronous glob search. ## Class: glob.Glob Create a Glob object by instantiating the `glob.Glob` class. ```javascript var Glob = require("glob").Glob var mg = new Glob(pattern, options, cb) ``` It's an EventEmitter, and starts walking the filesystem to find matches immediately. ### new glob.Glob(pattern, [options], [cb]) * `pattern` `{String}` pattern to search for * `options` `{Object}` * `cb` `{Function}` Called when an error occurs, or matches are found * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Note that if the `sync` flag is set in the options, then matches will be immediately available on the `g.found` member. ### Properties * `minimatch` The minimatch object that the glob uses. * `options` The options object passed in. * `aborted` Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * `cache` Convenience object. Each field has the following possible values: * `false` - Path does not exist * `true` - Path exists * `'FILE'` - Path exists, and is not a directory * `'DIR'` - Path exists, and is a directory * `[file, entries, ...]` - Path exists, is a directory, and the array value is the results of `fs.readdir` * `statCache` Cache of `fs.stat` results, to prevent statting the same path multiple times. * `symlinks` A record of which paths are symbolic links, which is relevant in resolving `**` patterns. * `realpathCache` An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. ### Events * `end` When the matching is finished, this is emitted with all the matches found. If the `nonull` option is set, and no match was found, then the `matches` list contains the original pattern. The matches are sorted, unless the `nosort` flag is set. * `match` Every time a match is found, this is emitted with the specific thing that matched. It is not deduplicated or resolved to a realpath. * `error` Emitted when an unexpected error is encountered, or whenever any fs error occurs if `options.strict` is set. * `abort` When `abort()` is called, this event is raised. ### Methods * `pause` Temporarily stop the search * `resume` Resume the search * `abort` Stop the search forever ### Options All the options that can be passed to Minimatch can also be passed to Glob to change pattern matching behavior. Also, some have been added, or have glob-specific ramifications. All options are false by default, unless otherwise noted. All options are added to the Glob object, as well. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to shortcut some `stat` and `readdir` calls. At the very least, you may pass in shared `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults to `process.cwd()`. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. * `nomount` By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. * `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. * `nosort` Don't sort the results. * `stat` Set to true to stat *all* results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. * `silent` When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. * `strict` When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. * `cache` See `cache` property above. Pass in a previously generated cache object to save some fs calls. * `statCache` A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See "Race Conditions" below.) * `symlinks` A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save `lstat` calls when resolving `**` matches. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. * `nounique` In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. * `nonull` Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). * `debug` Set to enable debug logging in minimatch and glob. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. * `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) * `noext` Do not match `+(a|b)` "extglob" patterns. * `nocase` Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. * `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. * `nodir` Do not match directories, only files. (Note: to match *only* directories, simply put a `/` at the end of the pattern.) * `ignore` Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are *always* in `dot:true` mode, regardless of any other settings. * `follow` Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. * `realpath` Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.3, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not crawled as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. If an escaped pattern has no matches, and the `nonull` flag is set, then glob returns the pattern as-provided, rather than interpreting the character escapes. For example, `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking and such. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. As part of its internal implementation, this program caches all stat and readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache or statCache objects are reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ## Glob Logo Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ``` # to run tests npm test # to re-generate test fixtures npm run test-regen # to benchmark against bash/zsh npm run bench # to profile javascript npm run prof ``` ![](oh-my-glob.gif) vanilla ================== This app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `vanilla.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `vanilla.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account vanilla.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'vanilla.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # wrappy Callback wrapping utility ## USAGE ```javascript var wrappy = require("wrappy") // var wrapper = wrappy(wrapperFunction) // make sure a cb is called only once // See also: http://npm.im/once for this specific use case var once = wrappy(function (cb) { var called = false return function () { if (called) return called = true return cb.apply(this, arguments) } }) function printBoo () { console.log('boo') } // has some rando property printBoo.iAmBooPrinter = true var onlyPrintOnce = once(printBoo) onlyPrintOnce() // prints 'boo' onlyPrintOnce() // does nothing // random property is retained! assert.equal(onlyPrintOnce.iAmBooPrinter, true) ``` # require-main-filename [![Build Status](https://travis-ci.org/yargs/require-main-filename.png)](https://travis-ci.org/yargs/require-main-filename) [![Coverage Status](https://coveralls.io/repos/yargs/require-main-filename/badge.svg?branch=master)](https://coveralls.io/r/yargs/require-main-filename?branch=master) [![NPM version](https://img.shields.io/npm/v/require-main-filename.svg)](https://www.npmjs.com/package/require-main-filename) `require.main.filename` is great for figuring out the entry point for the current application. This can be combined with a module like [pkg-conf](https://www.npmjs.com/package/pkg-conf) to, _as if by magic_, load top-level configuration. Unfortunately, `require.main.filename` sometimes fails when an application is executed with an alternative process manager, e.g., [iisnode](https://github.com/tjanczuk/iisnode). `require-main-filename` is a shim that addresses this problem. ## Usage ```js var main = require('require-main-filename')() // use main as an alternative to require.main.filename. ``` ## License ISC # assemblyscript-json JSON encoder / decoder for AssemblyScript. Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing infra for AssemblyScript. # Limitations This is developed for use in smart contracts written in AssemblyScript for https://github.com/nearprotocol/nearcore. This imposes such limitations: - Float numbers not supported - We assume that memory never needs to be deallocated (cause these contracts are short-lived). Note that this mostly just defines the way it's currently implemented. Contributors are welcome to fix limitations. # Usage ## Encoding JSON ```ts // Make sure memory allocator is available import "allocator/arena"; // Import encoder import { JSONEncoder } from "path/to/module"; // Create encoder let encoder = new JSONEncoder(); // Construct necessary object encoder.pushObject("obj"); encoder.setInteger("int", 10); encoder.setString("str", ""); encoder.popObject(); // Get serialized data let json: Uint8Array = encoder.serialize(); // Or get serialized data as string let jsonString: String = encoder.toString(); ``` ## Parsing JSON ```ts // Make sure memory allocator is available import "allocator/arena"; // Import decoder import { JSONDecoder, JSONHandler } from "path/to/module"; // Events need to be received by custom object extending JSONHandler. // NOTE: All methods are optional to implement. class MyJSONEventsHandler extends JSONHandler { setString(name: string, value: string): void { // Handle field } setBoolean(name: string, value: bool): void { // Handle field } setNull(name: string): void { // Handle field } setInteger(name: string, value: i32): void { // Handle field } pushArray(name: string): bool { // Handle array start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popArray(): void { // Handle array end } pushObject(name: string): bool { // Handle object start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popObject(): void { // Handle object end } } // Create decoder let decoder = new JSONDecoder<MyJSONEventsHandler>(new MyJSONEventsHandler()); // Let's assume JSON data is available in this variable let json: Uint8Array = ...; // Parse JSON decoder.deserialize(json); // This will send events to MyJSONEventsHandler ``` ## JSON namespace ```ts import { JSON } from "path/to/module"; // Can use JS parse api let jsonObj: JSON.Object = JSON.parse(`{"hello": "world"}`); // Can then use a key to read from the object if you know it's type let world = jsonObj.getString("hello"); // If you don't know what the type of the value let unknown = jsonObj.getValue("hello") unknown.isString // true; ``` # cliui [![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui) [![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) easily create complex multi-column command-line-interfaces. ## Example ```js var ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 2, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. [![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## options * unlink, chmod, stat, lstat, rmdir, readdir, unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync In order to use a custom file system library, you can override specific fs functions on the options object. If any of these functions are present on the options object, then the supplied function will be used instead of the default fs method. Sync methods are only relevant for `rimraf.sync()`, of course. For example: ```javascript var myCustomFS = require('some-custom-fs') rimraf('some-thing', myCustomFS, callback) ``` * maxBusyTries If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered on Windows systems, then rimraf will retry with a linear backoff wait of 100ms longer on each try. The default maxBusyTries is 3. Only relevant for async usage. * emfileWait If an `EMFILE` error is encountered, then rimraf will retry repeatedly with a linear backoff of 1ms longer on each try, until the timeout counter hits this max. The default limit is 1000. If you repeatedly encounter `EMFILE` errors, then consider using [graceful-fs](http://npm.im/graceful-fs) in your program. Only relevant for async usage. * glob Set to `false` to disable [glob](http://npm.im/glob) pattern matching. Set to an object to pass options to the glob module. The default glob options are `{ nosort: true, silent: true }`. Glob version 6 is used in this module. Relevant for both sync and async usage. * disableGlob Set to any non-falsey value to disable globbing entirely. (Equivalent to setting `glob: false`.) ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp). # minipass A _very_ minimal implementation of a [PassThrough stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) [It's very fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0) for objects, strings, and buffers. Supports pipe()ing (including multi-pipe() and backpressure transmission), buffering data until either a `data` event handler or `pipe()` is added (so you don't lose the first chunk), and most other cases where PassThrough is a good idea. There is a `read()` method, but it's much more efficient to consume data from this stream via `'data'` events or by calling `pipe()` into some other stream. Calling `read()` requires the buffer to be flattened in some cases, which requires copying memory. There is also no `unpipe()` method. Once you start piping, there is no stopping it! If you set `objectMode: true` in the options, then whatever is written will be emitted. Otherwise, it'll do a minimal amount of Buffer copying to ensure proper Streams semantics when `read(n)` is called. `objectMode` can also be set by doing `stream.objectMode = true`, or by writing any non-string/non-buffer data. `objectMode` cannot be set to false once it is set. This is not a `through` or `through2` stream. It doesn't transform the data, it just passes it right through. If you want to transform the data, extend the class, and override the `write()` method. Once you're done transforming the data however you want, call `super.write()` with the transform output. For some examples of streams that extend Minipass in various ways, check out: - [minizlib](http://npm.im/minizlib) - [fs-minipass](http://npm.im/fs-minipass) - [tar](http://npm.im/tar) - [minipass-collect](http://npm.im/minipass-collect) - [minipass-flush](http://npm.im/minipass-flush) - [minipass-pipeline](http://npm.im/minipass-pipeline) - [tap](http://npm.im/tap) - [tap-parser](http://npm.im/tap) - [treport](http://npm.im/tap) - [minipass-fetch](http://npm.im/minipass-fetch) - [pacote](http://npm.im/pacote) - [make-fetch-happen](http://npm.im/make-fetch-happen) - [cacache](http://npm.im/cacache) - [ssri](http://npm.im/ssri) - [npm-registry-fetch](http://npm.im/npm-registry-fetch) - [minipass-json-stream](http://npm.im/minipass-json-stream) - [minipass-sized](http://npm.im/minipass-sized) ## Differences from Node.js Streams There are several things that make Minipass streams different from (and in some ways superior to) Node.js core streams. Please read these caveats if you are familiar with noode-core streams and intend to use Minipass streams in your programs. ### Timing Minipass streams are designed to support synchronous use-cases. Thus, data is emitted as soon as it is available, always. It is buffered until read, but no longer. Another way to look at it is that Minipass streams are exactly as synchronous as the logic that writes into them. This can be surprising if your code relies on `PassThrough.write()` always providing data on the next tick rather than the current one, or being able to call `resume()` and not have the entire buffer disappear immediately. However, without this synchronicity guarantee, there would be no way for Minipass to achieve the speeds it does, or support the synchronous use cases that it does. Simply put, waiting takes time. This non-deferring approach makes Minipass streams much easier to reason about, especially in the context of Promises and other flow-control mechanisms. ### No High/Low Water Marks Node.js core streams will optimistically fill up a buffer, returning `true` on all writes until the limit is hit, even if the data has nowhere to go. Then, they will not attempt to draw more data in until the buffer size dips below a minimum value. Minipass streams are much simpler. The `write()` method will return `true` if the data has somewhere to go (which is to say, given the timing guarantees, that the data is already there by the time `write()` returns). If the data has nowhere to go, then `write()` returns false, and the data sits in a buffer, to be drained out immediately as soon as anyone consumes it. ### Hazards of Buffering (or: Why Minipass Is So Fast) Since data written to a Minipass stream is immediately written all the way through the pipeline, and `write()` always returns true/false based on whether the data was fully flushed, backpressure is communicated immediately to the upstream caller. This minimizes buffering. Consider this case: ```js const {PassThrough} = require('stream') const p1 = new PassThrough({ highWaterMark: 1024 }) const p2 = new PassThrough({ highWaterMark: 1024 }) const p3 = new PassThrough({ highWaterMark: 1024 }) const p4 = new PassThrough({ highWaterMark: 1024 }) p1.pipe(p2).pipe(p3).pipe(p4) p4.on('data', () => console.log('made it through')) // this returns false and buffers, then writes to p2 on next tick (1) // p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) // p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) // p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' // on next tick (4) // p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and // 'drain' on next tick (5) // p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) // p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next // tick (7) p1.write(Buffer.alloc(2048)) // returns false ``` Along the way, the data was buffered and deferred at each stage, and multiple event deferrals happened, for an unblocked pipeline where it was perfectly safe to write all the way through! Furthermore, setting a `highWaterMark` of `1024` might lead someone reading the code to think an advisory maximum of 1KiB is being set for the pipeline. However, the actual advisory buffering level is the _sum_ of `highWaterMark` values, since each one has its own bucket. Consider the Minipass case: ```js const m1 = new Minipass() const m2 = new Minipass() const m3 = new Minipass() const m4 = new Minipass() m1.pipe(m2).pipe(m3).pipe(m4) m4.on('data', () => console.log('made it through')) // m1 is flowing, so it writes the data to m2 immediately // m2 is flowing, so it writes the data to m3 immediately // m3 is flowing, so it writes the data to m4 immediately // m4 is flowing, so it fires the 'data' event immediately, returns true // m4's write returned true, so m3 is still flowing, returns true // m3's write returned true, so m2 is still flowing, returns true // m2's write returned true, so m1 is still flowing, returns true // No event deferrals or buffering along the way! m1.write(Buffer.alloc(2048)) // returns true ``` It is extremely unlikely that you _don't_ want to buffer any data written, or _ever_ buffer data that can be flushed all the way through. Neither node-core streams nor Minipass ever fail to buffer written data, but node-core streams do a lot of unnecessary buffering and pausing. As always, the faster implementation is the one that does less stuff and waits less time to do it. ### Immediately emit `end` for empty streams (when not paused) If a stream is not paused, and `end()` is called before writing any data into it, then it will emit `end` immediately. If you have logic that occurs on the `end` event which you don't want to potentially happen immediately (for example, closing file descriptors, moving on to the next entry in an archive parse stream, etc.) then be sure to call `stream.pause()` on creation, and then `stream.resume()` once you are ready to respond to the `end` event. ### Emit `end` When Asked One hazard of immediately emitting `'end'` is that you may not yet have had a chance to add a listener. In order to avoid this hazard, Minipass streams safely re-emit the `'end'` event if a new listener is added after `'end'` has been emitted. Ie, if you do `stream.on('end', someFunction)`, and the stream has already emitted `end`, then it will call the handler right away. (You can think of this somewhat like attaching a new `.then(fn)` to a previously-resolved Promise.) To prevent calling handlers multiple times who would not expect multiple ends to occur, all listeners are removed from the `'end'` event whenever it is emitted. ### Impact of "immediate flow" on Tee-streams A "tee stream" is a stream piping to multiple destinations: ```js const tee = new Minipass() t.pipe(dest1) t.pipe(dest2) t.write('foo') // goes to both destinations ``` Since Minipass streams _immediately_ process any pending data through the pipeline when a new pipe destination is added, this can have surprising effects, especially when a stream comes in from some other function and may or may not have data in its buffer. ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone src.pipe(dest2) // gets nothing! ``` The solution is to create a dedicated tee-stream junction that pipes to both locations, and then pipe to _that_ instead. ```js // Safe example: tee to both places const src = new Minipass() src.write('foo') const tee = new Minipass() tee.pipe(dest1) tee.pipe(dest2) src.pipe(tee) // tee gets 'foo', pipes to both locations ``` The same caveat applies to `on('data')` event listeners. The first one added will _immediately_ receive all of the data, leaving nothing for the second: ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.on('data', handler1) // receives 'foo' right away src.on('data', handler2) // nothing to see here! ``` Using a dedicated tee-stream can be used in this case as well: ```js // Safe example: tee to both data handlers const src = new Minipass() src.write('foo') const tee = new Minipass() tee.on('data', handler1) tee.on('data', handler2) src.pipe(tee) ``` ## USAGE It's a stream! Use it like a stream and it'll most likely do what you want. ```js const Minipass = require('minipass') const mp = new Minipass(options) // optional: { encoding, objectMode } mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` ### OPTIONS * `encoding` How would you like the data coming _out_ of the stream to be encoded? Accepts any values that can be passed to `Buffer.toString()`. * `objectMode` Emit data exactly as it comes in. This will be flipped on by default if you write() something other than a string or Buffer at any point. Setting `objectMode: true` will prevent setting any encoding value. ### API Implements the user-facing portions of Node.js's `Readable` and `Writable` streams. ### Methods * `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the base Minipass class, the same data will come out.) Returns `false` if the stream will buffer the next write, or true if it's still in "flowing" mode. * `end([chunk, [encoding]], [callback])` - Signal that you have no more data to write. This will queue an `end` event to be fired when all the data has been consumed. * `setEncoding(encoding)` - Set the encoding for data coming of the stream. This can only be done once. * `pause()` - No more data for a while, please. This also prevents `end` from being emitted for empty streams until the stream is resumed. * `resume()` - Resume the stream. If there's data in the buffer, it is all discarded. Any buffered events are immediately emitted. * `pipe(dest)` - Send all output to the stream provided. There is no way to unpipe. When data is emitted, it is immediately written to any and all pipe destinations. * `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some events are given special treatment, however. (See below under "events".) * `promise()` - Returns a Promise that resolves when the stream emits `end`, or rejects if the stream emits `error`. * `collect()` - Return a Promise that resolves on `end` with an array containing each chunk of data that was emitted, or rejects if the stream emits `error`. Note that this consumes the stream data. * `concat()` - Same as `collect()`, but concatenates the data into a single Buffer object. Will reject the returned promise if the stream is in objectMode, or if it goes into objectMode by the end of the data. * `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not provided, then consume all of it. If `n` bytes are not available, then it returns null. **Note** consuming streams in this way is less efficient, and can lead to unnecessary Buffer copying. * `destroy([er])` - Destroy the stream. If an error is provided, then an `'error'` event is emitted. If the stream has a `close()` method, and has not emitted a `'close'` event yet, then `stream.close()` will be called. Any Promises returned by `.promise()`, `.collect()` or `.concat()` will be rejected. After being destroyed, writing to the stream will emit an error. No more data will be emitted if the stream is destroyed, even if it was previously buffered. ### Properties * `bufferLength` Read-only. Total number of bytes buffered, or in the case of objectMode, the total number of objects. * `encoding` The encoding that has been set. (Setting this is equivalent to calling `setEncoding(enc)` and has the same prohibition against setting multiple times.) * `flowing` Read-only. Boolean indicating whether a chunk written to the stream will be immediately emitted. * `emittedEnd` Read-only. Boolean indicating whether the end-ish events (ie, `end`, `prefinish`, `finish`) have been emitted. Note that listening on any end-ish event will immediateyl re-emit it if it has already been emitted. * `writable` Whether the stream is writable. Default `true`. Set to `false` when `end()` * `readable` Whether the stream is readable. Default `true`. * `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written to the stream that have not yet been emitted. (It's probably a bad idea to mess with this.) * `pipes` A [yallist](http://npm.im/yallist) linked list of streams that this stream is piping into. (It's probably a bad idea to mess with this.) * `destroyed` A getter that indicates whether the stream was destroyed. * `paused` True if the stream has been explicitly paused, otherwise false. * `objectMode` Indicates whether the stream is in `objectMode`. Once set to `true`, it cannot be set to `false`. ### Events * `data` Emitted when there's data to read. Argument is the data to read. This is never emitted while not flowing. If a listener is attached, that will resume the stream. * `end` Emitted when there's no more data to read. This will be emitted immediately for empty streams when `end()` is called. If a listener is attached, and `end` was already emitted, then it will be emitted again. All listeners are removed when `end` is emitted. * `prefinish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'end'`. * `finish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'prefinish'`. * `close` An indication that an underlying resource has been released. Minipass does not emit this event, but will defer it until after `end` has been emitted, since it throws off some stream libraries otherwise. * `drain` Emitted when the internal buffer empties, and it is again suitable to `write()` into the stream. * `readable` Emitted when data is buffered and ready to be read by a consumer. * `resume` Emitted when stream changes state from buffering to flowing mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event listener is added.) ### Static Methods * `Minipass.isStream(stream)` Returns `true` if the argument is a stream, and false otherwise. To be considered a stream, the object must be either an instance of Minipass, or an EventEmitter that has either a `pipe()` method, or both `write()` and `end()` methods. (Pretty much any stream in node-land will return `true` for this.) ## EXAMPLES Here are some examples of things you can do with Minipass streams. ### simple "are you done yet" promise ```js mp.promise().then(() => { // stream is finished }, er => { // stream emitted an error }) ``` ### collecting ```js mp.collect().then(all => { // all is an array of all the data emitted // encoding is supported in this case, so // so the result will be a collection of strings if // an encoding is specified, or buffers/objects if not. // // In an async function, you may do // const data = await stream.collect() }) ``` ### collecting into a single blob This is a bit slower because it concatenates the data into one chunk for you, but if you're going to do it yourself anyway, it's convenient this way: ```js mp.concat().then(onebigchunk => { // onebigchunk is a string if the stream // had an encoding set, or a buffer otherwise. }) ``` ### iteration You can iterate over streams synchronously or asynchronously in platforms that support it. Synchronous iteration will end when the currently available data is consumed, even if the `end` event has not been reached. In string and buffer mode, the data is concatenated, so unless multiple writes are occurring in the same tick as the `read()`, sync iteration loops will generally only have a single iteration. To consume chunks in this way exactly as they have been written, with no flattening, create the stream with the `{ objectMode: true }` option. ```js const mp = new Minipass({ objectMode: true }) mp.write('a') mp.write('b') for (let letter of mp) { console.log(letter) // a, b } mp.write('c') mp.write('d') for (let letter of mp) { console.log(letter) // c, d } mp.write('e') mp.end() for (let letter of mp) { console.log(letter) // e } for (let letter of mp) { console.log(letter) // nothing } ``` Asynchronous iteration will continue until the end event is reached, consuming all of the data. ```js const mp = new Minipass({ encoding: 'utf8' }) // some source of some data let i = 5 const inter = setInterval(() => { if (i --> 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // consume the data with asynchronous iteration async function consume () { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // logs `foo\n` 5 times, and then `ok` ``` ### subclass that `console.log()`s everything written into it ```js class Logger extends Minipass { write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } } someSource.pipe(new Logger()).pipe(someDest) ``` ### same thing, but using an inline anonymous class ```js // js classes are fun someSource .pipe(new (class extends Minipass { emit (ev, ...data) { // let's also log events, because debugging some weird thing console.log('EMIT', ev) return super.emit(ev, ...data) } write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } })) .pipe(someDest) ``` ### subclass that defers 'end' for some reason ```js class SlowEnd extends Minipass { emit (ev, ...args) { if (ev === 'end') { console.log('going to end, hold on a sec') setTimeout(() => { console.log('ok, ready to end now') super.emit('end', ...args) }, 100) } else { return super.emit(ev, ...args) } } } ``` ### transform that creates newline-delimited JSON ```js class NDJSONEncode extends Minipass { write (obj, cb) { try { // JSON.stringify can throw, emit an error on that return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) } catch (er) { this.emit('error', er) } } end (obj, cb) { if (typeof obj === 'function') { cb = obj obj = undefined } if (obj !== undefined) { this.write(obj) } return super.end(cb) } } ``` ### transform that parses newline-delimited JSON ```js class NDJSONDecode extends Minipass { constructor (options) { // always be in object mode, as far as Minipass is concerned super({ objectMode: true }) this._jsonBuffer = '' } write (chunk, encoding, cb) { if (typeof chunk === 'string' && typeof encoding === 'string' && encoding !== 'utf8') { chunk = Buffer.from(chunk, encoding).toString() } else if (Buffer.isBuffer(chunk)) chunk = chunk.toString() } if (typeof encoding === 'function') { cb = encoding } const jsonData = (this._jsonBuffer + chunk).split('\n') this._jsonBuffer = jsonData.pop() for (let i = 0; i < jsonData.length; i++) { let parsed try { super.write(parsed) } catch (er) { this.emit('error', er) continue } } if (cb) cb() } } ``` Compiler frontend for node.js ============================= Usage ----- For an up to date list of available command line options, see: ``` $> asc --help ``` API --- The API accepts the same options as the CLI but also lets you override stdout and stderr and/or provide a callback. Example: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { asc.main([ "myModule.ts", "--binaryFile", "myModule.wasm", "--optimize", "--sourceMap", "--measure" ], { stdout: process.stdout, stderr: process.stderr }, function(err) { if (err) throw err; ... }); }); ``` Available command line options can also be obtained programmatically: ```js const options = require("assemblyscript/cli/asc.json"); ... ``` You can also compile a source string directly, for example in a browser environment: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { const { binary, text, stdout, stderr } = asc.compileString(`...`, { optimize: 2 }); }); ... ``` [![build status](https://secure.travis-ci.org/dankogai/js-base64.png)](http://travis-ci.org/dankogai/js-base64) # base64.js Yet another [Base64] transcoder. [Base64]: http://en.wikipedia.org/wiki/Base64 ## HEADS UP In version 3.0 `js-base64` switch to ES2015 module so it is no longer compatible with legacy browsers like IE (see below). And since version 3.3 it is written in TypeScript. Now `base64.mjs` is compiled from `base64.ts` then `base64.js` is generated from `base64.mjs`. ## Install ```shell $ npm install --save js-base64 ``` ## Usage ### In Browser Locally… ```html <script src="base64.js"></script> ``` … or Directly from CDN. In which case you don't even need to install. ```html <script src="https://cdn.jsdelivr.net/npm/[email protected]/base64.min.js"></script> ``` This good old way loads `Base64` in the global context (`window`). Though `Base64.noConflict()` is made available, you should consider using ES6 Module to avoid tainting `window`. ### As an ES6 Module locally… ```javascript import { Base64 } from 'js-base64'; ``` ```javascript // or if you prefer no Base64 namespace import { encode, decode } from 'js-base64'; ``` or even remotely. ```html <script type="module"> // note jsdelivr.net does not automatically minify .mjs import { Base64 } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ```html <script type="module"> // or if you prefer no Base64 namespace import { encode, decode } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ### node.js (commonjs) ```javascript const {Base64} = require('js-base64'); ``` Unlike the case above, the global context is no longer modified. You can also use [esm] to `import` instead of `require`. [esm]: https://github.com/standard-things/esm ```javascript require=require('esm')(module); import {Base64} from 'js-base64'; ``` ## SYNOPSIS ```javascript let latin = 'dankogai'; let utf8 = '小飼弾' let u8s = new Uint8Array([100,97,110,107,111,103,97,105]); Base64.encode(latin); // ZGFua29nYWk= Base64.btoa(latin); // ZGFua29nYWk= Base64.btoa(utf8); // raises exception Base64.fromUint8Array(u8s); // ZGFua29nYWk= Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe Base64.encode(utf8); // 5bCP6aO85by+ Base64.encode(utf8, true) // 5bCP6aO85by- Base64.encodeURI(utf8); // 5bCP6aO85by- ``` ```javascript Base64.decode( 'ZGFua29nYWk=');// dankogai Base64.atob( 'ZGFua29nYWk=');// dankogai Base64.atob( '5bCP6aO85by+');// '小飼弾' which is nonsense Base64.toUint8Array('ZGFua29nYWk=');// u8s above Base64.decode( '5bCP6aO85by+');// 小飼弾 // note .decodeURI() is unnecessary since it accepts both flavors Base64.decode( '5bCP6aO85by-');// 小飼弾 ``` ```javascript Base64.isValid(0); // false: 0 is not string Base64.isValid(''); // true: a valid Base64-encoded empty byte Base64.isValid('ZA=='); // true: a valid Base64-encoded 'd' Base64.isValid('Z A='); // true: whitespaces are okay Base64.isValid('ZA'); // true: padding ='s can be omitted Base64.isValid('++'); // true: can be non URL-safe Base64.isValid('--'); // true: or URL-safe Base64.isValid('+-'); // false: can't mix both ``` ### Built-in Extensions By default `Base64` leaves built-in prototypes untouched. But you can extend them as below. ```javascript // you have to explicitly extend String.prototype Base64.extendString(); // once extended, you can do the following 'dankogai'.toBase64(); // ZGFua29nYWk= '小飼弾'.toBase64(); // 5bCP6aO85by+ '小飼弾'.toBase64(true); // 5bCP6aO85by- '小飼弾'.toBase64URI(); // 5bCP6aO85by- ab alias of .toBase64(true) '小飼弾'.toBase64URL(); // 5bCP6aO85by- an alias of .toBase64URI() 'ZGFua29nYWk='.fromBase64(); // dankogai '5bCP6aO85by+'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.toUint8Array();// u8s above ``` ```javascript // you have to explicitly extend String.prototype Base64.extendString(); // once extended, you can do the following u8s.toBase64(); // 'ZGFua29nYWk=' u8s.toBase64URI(); // 'ZGFua29nYWk' u8s.toBase64URL(); // 'ZGFua29nYWk' an alias of .toBase64URI() ``` ```javascript // extend all at once Base64.extendBuiltins() ``` ## `.decode()` vs `.atob` (and `.encode()` vs `btoa()`) Suppose you have: ``` var pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; ``` Which is a Base64-encoded 1x1 transparent PNG, **DO NOT USE** `Base64.decode(pngBase64)`.  Use `Base64.atob(pngBase64)` instead.  `Base64.decode()` decodes to UTF-8 string while `Base64.atob()` decodes to bytes, which is compatible to browser built-in `atob()` (Which is absent in node.js).  The same rule applies to the opposite direction. Or even better, `Base64.toUint8Array(pngBase64)`. ### If you really, really need an ES5 version You can transpiles to an ES5 that runs on IE11. Do the following in your shell. ```shell $ make base64.es5.js ``` # jsdiff [![Build Status](https://secure.travis-ci.org/kpdecker/jsdiff.svg)](http://travis-ci.org/kpdecker/jsdiff) [![Sauce Test Status](https://saucelabs.com/buildstatus/jsdiff)](https://saucelabs.com/u/jsdiff) A javascript text differencing implementation. Based on the algorithm proposed in ["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927). ## Installation ```bash npm install diff --save ``` ## API * `Diff.diffChars(oldStr, newStr[, options])` - diffs two blocks of text, comparing character by character. Returns a list of change objects (See below). Options * `ignoreCase`: `true` to ignore casing difference. Defaults to `false`. * `Diff.diffWords(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, ignoring whitespace. Returns a list of change objects (See below). Options * `ignoreCase`: Same as in `diffChars`. * `Diff.diffWordsWithSpace(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, treating whitespace as significant. Returns a list of change objects (See below). * `Diff.diffLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line. Options * `ignoreWhitespace`: `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines` * `newlineIsToken`: `true` to treat newline characters as separate tokens. This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of `diffLines` and `diffLines` is better suited for patches and other computer friendly output. Returns a list of change objects (See below). * `Diff.diffTrimmedLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. Returns a list of change objects (See below). * `Diff.diffSentences(oldStr, newStr[, options])` - diffs two blocks of text, comparing sentence by sentence. Returns a list of change objects (See below). * `Diff.diffCss(oldStr, newStr[, options])` - diffs two blocks of text, comparing CSS tokens. Returns a list of change objects (See below). * `Diff.diffJson(oldObj, newObj[, options])` - diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter in this comparison. Returns a list of change objects (See below). * `Diff.diffArrays(oldArr, newArr[, options])` - diffs two arrays, comparing each item for strict equality (===). Options * `comparator`: `function(left, right)` for custom equality checks Returns a list of change objects (See below). * `Diff.createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Parameters: * `oldFileName` : String to be output in the filename section of the patch for the removals * `newFileName` : String to be output in the filename section of the patch for the additions * `oldStr` : Original string value * `newStr` : New string value * `oldHeader` : Additional information to include in the old file header * `newHeader` : Additional information to include in the new file header * `options` : An object with options. Currently, only `context` is supported and describes how many lines of context should be included. * `Diff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Just like Diff.createTwoFilesPatch, but with oldFileName being equal to newFileName. * `Diff.structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)` - returns an object with an array of hunk objects. This method is similar to createTwoFilesPatch, but returns a data structure suitable for further processing. Parameters are the same as createTwoFilesPatch. The data structure returned may look like this: ```js { oldFileName: 'oldfile', newFileName: 'newfile', oldHeader: 'header1', newHeader: 'header2', hunks: [{ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [' line2', ' line3', '-line4', '+line5', '\\ No newline at end of file'], }] } ``` * `Diff.applyPatch(source, patch[, options])` - applies a unified diff patch. Return a string containing new version of provided data. `patch` may be a string diff or the output from the `parsePatch` or `structuredPatch` methods. The optional `options` object may have the following keys: - `fuzzFactor`: Number of lines that are allowed to differ before rejecting a patch. Defaults to 0. - `compareLine(lineNumber, line, operation, patchContent)`: Callback used to compare to given lines to determine if they should be considered equal when patching. Defaults to strict equality but may be overridden to provide fuzzier comparison. Should return false if the lines should be rejected. * `Diff.applyPatches(patch, options)` - applies one or more patches. This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is: - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. * `Diff.parsePatch(diffStr)` - Parses a patch into structured data Return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. This parses to the same structure returned by `Diff.structuredPatch`. * `convertChangesToXML(changes)` - converts a list of changes to a serialized XML format All methods above which accept the optional `callback` method will run in sync mode when that parameter is omitted and in async mode when supplied. This allows for larger diffs without blocking the event loop. This may be passed either directly as the final parameter or as the `callback` field in the `options` object. ### Change Objects Many of the methods above return change objects. These objects consist of the following fields: * `value`: Text content * `added`: True if the value was inserted into the new string * `removed`: True if the value was removed from the old string Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner. ## Examples Basic example in Node ```js require('colors'); const Diff = require('diff'); const one = 'beep boop'; const other = 'beep boob blah'; const diff = Diff.diffChars(one, other); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; process.stderr.write(part.value[color]); }); console.log(); ``` Running the above program should yield <img src="images/node_example.png" alt="Node Example"> Basic example in a web page ```html <pre id="display"></pre> <script src="diff.js"></script> <script> const one = 'beep boop', other = 'beep boob blah', color = ''; let span = null; const diff = Diff.diffChars(one, other), display = document.getElementById('display'), fragment = document.createDocumentFragment(); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; span = document.createElement('span'); span.style.color = color; span.appendChild(document .createTextNode(part.value)); fragment.appendChild(span); }); display.appendChild(fragment); </script> ``` Open the above .html file in a browser and you should see <img src="images/web_example.png" alt="Node Example"> **[Full online demo](http://kpdecker.github.com/jsdiff)** ## Compatibility [![Sauce Test Status](https://saucelabs.com/browser-matrix/jsdiff.svg)](https://saucelabs.com/u/jsdiff) jsdiff supports all ES3 environments with some known issues on IE8 and below. Under these browsers some diff algorithms such as word diff and others may fail due to lack of support for capturing groups in the `split` operation. ## License See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE). # balanced-match Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! [![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) [![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) ## Example Get the first matching pair of braces: ```js var balanced = require('balanced-match'); console.log(balanced('{', '}', 'pre{in{nested}}post')); console.log(balanced('{', '}', 'pre{first}between{second}post')); console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); ``` The matches are: ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` ## API ### var m = balanced(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an object with those keys: * **start** the index of the first match of `a` * **end** the index of the matching `b` * **pre** the preamble, `a` and `b` not included * **body** the match, `a` and `b` not included * **post** the postscript, `a` and `b` not included If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. ### var r = balanced.range(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an array with indexes: `[ <a index>, <b index> ]`. If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. ## Installation With [npm](https://npmjs.org) do: ```bash npm install balanced-match ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # axios // helpers The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: - Browser polyfills - Managing cookies - Parsing HTTP headers Railroad-diagram Generator ========================== This is a small js library for generating railroad diagrams (like what [JSON.org](http://json.org) uses) using SVG. Railroad diagrams are a way of visually representing a grammar in a form that is more readable than using regular expressions or BNF. I think (though I haven't given it a lot of thought yet) that if it's easy to write a context-free grammar for the language, the corresponding railroad diagram will be easy as well. There are several railroad-diagram generators out there, but none of them had the visual appeal I wanted. [Here's an example of how they look!](http://www.xanthir.com/etc/railroad-diagrams/example.html) And [here's an online generator for you to play with and get SVG code from!](http://www.xanthir.com/etc/railroad-diagrams/generator.html) The library now exists in a Python port as well! See the information further down. Details ------- To use the library, just include the js and css files, and then call the Diagram() function. Its arguments are the components of the diagram (Diagram is a special form of Sequence). An alternative to Diagram() is ComplexDiagram() which is used to describe a complex type diagram. Components are either leaves or containers. The leaves: * Terminal(text) or a bare string - represents literal text * NonTerminal(text) - represents an instruction or another production * Comment(text) - a comment * Skip() - an empty line The containers: * Sequence(children) - like simple concatenation in a regex * Choice(index, children) - like | in a regex. The index argument specifies which child is the "normal" choice and should go in the middle * Optional(child, skip) - like ? in a regex. A shorthand for `Choice(1, [Skip(), child])`. If the optional `skip` parameter has the value `"skip"`, it instead puts the Skip() in the straight-line path, for when the "normal" behavior is to omit the item. * OneOrMore(child, repeat) - like + in a regex. The 'repeat' argument is optional, and specifies something that must go between the repetitions. * ZeroOrMore(child, repeat, skip) - like * in a regex. A shorthand for `Optional(OneOrMore(child, repeat))`. The optional `skip` parameter is identical to Optional(). For convenience, each component can be called with or without `new`. If called without `new`, the container components become n-ary; that is, you can say either `new Sequence([A, B])` or just `Sequence(A,B)`. After constructing a Diagram, call `.format(...padding)` on it, specifying 0-4 padding values (just like CSS) for some additional "breathing space" around the diagram (the paddings default to 20px). The result can either be `.toString()`'d for the markup, or `.toSVG()`'d for an `<svg>` element, which can then be immediately inserted to the document. As a convenience, Diagram also has an `.addTo(element)` method, which immediately converts it to SVG and appends it to the referenced element with default paddings. `element` defaults to `document.body`. Options ------- There are a few options you can tweak, at the bottom of the file. Just tweak either until the diagram looks like what you want. You can also change the CSS file - feel free to tweak to your heart's content. Note, though, that if you change the text sizes in the CSS, you'll have to go adjust the metrics for the leaf nodes as well. * VERTICAL_SEPARATION - sets the minimum amount of vertical separation between two items. Note that the stroke width isn't counted when computing the separation; this shouldn't be relevant unless you have a very small separation or very large stroke width. * ARC_RADIUS - the radius of the arcs used in the branching containers like Choice. This has a relatively large effect on the size of non-trivial diagrams. Both tight and loose values look good, depending on what you're going for. * DIAGRAM_CLASS - the class set on the root `<svg>` element of each diagram, for use in the CSS stylesheet. * STROKE_ODD_PIXEL_LENGTH - the default stylesheet uses odd pixel lengths for 'stroke'. Due to rasterization artifacts, they look best when the item has been translated half a pixel in both directions. If you change the styling to use a stroke with even pixel lengths, you'll want to set this variable to `false`. * INTERNAL_ALIGNMENT - when some branches of a container are narrower than others, this determines how they're aligned in the extra space. Defaults to "center", but can be set to "left" or "right". Caveats ------- At this early stage, the generator is feature-complete and works as intended, but still has several TODOs: * The font-sizes are hard-coded right now, and the font handling in general is very dumb - I'm just guessing at some metrics that are probably "good enough" rather than measuring things properly. Python Port ----------- In addition to the canonical JS version, the library now exists as a Python library as well. Using it is basically identical. The config variables are globals in the file, and so may be adjusted either manually or via tweaking from inside your program. The main difference from the JS port is how you extract the string from the Diagram. You'll find a `writeSvg(writerFunc)` method on `Diagram`, which takes a callback of one argument and passes it the string form of the diagram. For example, it can be used like `Diagram(...).writeSvg(sys.stdout.write)` to write to stdout. **Note**: the callback will be called multiple times as it builds up the string, not just once with the whole thing. If you need it all at once, consider something like a `StringIO` as an easy way to collect it into a single string. License ------- This document and all associated files in the github project are licensed under [CC0](http://creativecommons.org/publicdomain/zero/1.0/) ![](http://i.creativecommons.org/p/zero/1.0/80x15.png). This means you can reuse, remix, or otherwise appropriate this project for your own use **without restriction**. (The actual legal meaning can be found at the above link.) Don't ask me for permission to use any part of this project, **just use it**. I would appreciate attribution, but that is not required by the license. # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # is-core-module <sup>[![Version Badge][2]][1]</sup> [![Build Status][3]][4] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] Is this specifier a node.js core module? Optionally provide a node version to check; defaults to the current node version. ## Example ```js var isCore = require('is-core-module'); var assert = require('assert'); assert(isCore('fs')); assert(!isCore('butts')); ``` ## Tests Clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/is-core-module [2]: https://versionbadg.es/inspect-js/is-core-module.svg [3]: https://travis-ci.com/inspect-js/is-core-module.svg [4]: https://travis-ci.com/inspect-js/is-core-module [5]: https://david-dm.org/inspect-js/is-core-module.svg [6]: https://david-dm.org/inspect-js/is-core-module [7]: https://david-dm.org/inspect-js/is-core-module/dev-status.svg [8]: https://david-dm.org/inspect-js/is-core-module#info=devDependencies [11]: https://nodei.co/npm/is-core-module.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/is-core-module.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/is-core-module.svg [downloads-url]: https://npm-stat.com/charts.html?package=is-core-module # minizlib A fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding. This module was created to serve the needs of [node-tar](http://npm.im/tar) and [minipass-fetch](http://npm.im/minipass-fetch). Brotli is supported in versions of node with a Brotli binding. ## How does this differ from the streams in `require('zlib')`? First, there are no convenience methods to compress or decompress a buffer. If you want those, use the built-in `zlib` module. This is only streams. That being said, Minipass streams to make it fairly easy to use as one-liners: `new zlib.Deflate().end(data).read()` will return the deflate compressed result. This module compresses and decompresses the data as fast as you feed it in. It is synchronous, and runs on the main process thread. Zlib and Brotli operations can be high CPU, but they're very fast, and doing it this way means much less bookkeeping and artificial deferral. Node's built in zlib streams are built on top of `stream.Transform`. They do the maximally safe thing with respect to consistent asynchrony, buffering, and backpressure. See [Minipass](http://npm.im/minipass) for more on the differences between Node.js core streams and Minipass streams, and the convenience methods provided by that class. ## Classes - Deflate - Inflate - Gzip - Gunzip - DeflateRaw - InflateRaw - Unzip - BrotliCompress (Node v10 and higher) - BrotliDecompress (Node v10 and higher) ## USAGE ```js const zlib = require('minizlib') const input = sourceOfCompressedData() const decode = new zlib.BrotliDecompress() const output = whereToWriteTheDecodedData() input.pipe(decode).pipe(output) ``` ## REPRODUCIBLE BUILDS To create reproducible gzip compressed files across different operating systems, set `portable: true` in the options. This causes minizlib to set the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for 'unknown'. # minimatch A minimal matching utility. [![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. It works by converting glob expressions into JavaScript `RegExp` objects. ## Usage ```javascript var minimatch = require("minimatch") minimatch("bar.foo", "*.foo") // true! minimatch("bar.foo", "*.bar") // false! minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! ``` ## Features Supports these glob features: * Brace Expansion * Extended glob matching * "Globstar" `**` matching See: * `man sh` * `man bash` * `man 3 fnmatch` * `man 5 gitignore` ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. ```javascript var Minimatch = require("minimatch").Minimatch var mm = new Minimatch(pattern, options) ``` ### Properties * `pattern` The original pattern the minimatch object represents. * `options` The options supplied to the constructor. * `set` A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern `{a,b/c}/d` would expand to a set of patterns like: [ [ a, d ] , [ b, c, d ] ] If a portion of the pattern doesn't have any "magic" in it (that is, it's something like `"foo"` rather than `fo*o?`), then it will be left as a string rather than converted to a regular expression. * `regexp` Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. * `negate` True if the pattern is negated. * `comment` True if the pattern is a comment. * `empty` True if the pattern is `""`. ### Methods * `makeRe` Generate the `regexp` member if necessary, and return it. Will return `false` if the pattern is invalid. * `match(fname)` Return true if the filename matches the pattern, or false otherwise. * `matchOne(fileArray, patternArray, partial)` Take a `/`-split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. All other methods are internal, and will be called as necessary. ### minimatch(path, pattern, options) Main export. Tests a path against the pattern using the options. ```javascript var isJS = minimatch(file, "*.js", { matchBase: true }) ``` ### minimatch.filter(pattern, options) Returns a function that tests its supplied argument, suitable for use with `Array.filter`. Example: ```javascript var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) ``` ### minimatch.match(list, pattern, options) Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself. ```javascript var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) ``` ### minimatch.makeRe(pattern, options) Make a regular expression object from the pattern. ## Options All options are `false` by default. ### debug Dump a ton of stuff to stderr. ### nobrace Do not expand `{a,b}` and `{1..3}` brace sets. ### noglobstar Disable `**` matching against multiple folder names. ### dot Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` is set. ### noext Disable "extglob" style patterns like `+(a|b)`. ### nocase Perform a case-insensitive match. ### nonull When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. ### matchBase If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. ### nocomment Suppress the behavior of treating `#` at the start of a pattern as a comment. ### nonegate Suppress the behavior of treating a leading `!` character as negation. ### flipNegate Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations, and are intentional. If the pattern starts with a `!` character, then it is negated. Set the `nonegate` flag to suppress this behavior, and treat leading `!` characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` characters at the start of a pattern will negate the pattern multiple times. If a pattern starts with `#`, then it is treated as a comment, and will not match anything. Use `\#` to match a literal `#` at the start of a line, or set the `nocomment` flag to suppress this behavior. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.1, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. # universal-url [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Monitor][greenkeeper-image]][greenkeeper-url] > WHATWG [`URL`](https://developer.mozilla.org/en/docs/Web/API/URL) for Node & Browser. * For Node.js versions `>= 8`, the native implementation will be used. * For Node.js versions `< 8`, a [shim](https://npmjs.com/whatwg-url) will be used. * For web browsers without a native implementation, the same shim will be used. ## Installation [Node.js](http://nodejs.org/) `>= 6` is required. To install, type this at the command line: ```shell npm install universal-url ``` ## Usage ```js const {URL, URLSearchParams} = require('universal-url'); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` Global shim: ```js require('universal-url').shim(); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` ## Browserify/etc The bundled file size of this library can be large for a web browser. If this is a problem, try using [universal-url-lite](https://npmjs.com/universal-url-lite) in your build as an alias for this module. [npm-image]: https://img.shields.io/npm/v/universal-url.svg [npm-url]: https://npmjs.org/package/universal-url [travis-image]: https://img.shields.io/travis/stevenvachon/universal-url.svg [travis-url]: https://travis-ci.org/stevenvachon/universal-url [greenkeeper-image]: https://badges.greenkeeper.io/stevenvachon/universal-url.svg [greenkeeper-url]: https://greenkeeper.io/ Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # yargs-parser [![Build Status](https://travis-ci.org/yargs/yargs-parser.svg)](https://travis-ci.org/yargs/yargs-parser) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js var argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```sh node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js var argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```sh { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js var parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## API ### require('yargs-parser')(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```sh node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```sh node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```sh node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```sh node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```sh node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```sh node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```sh node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```sh node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```sh node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```sh node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```sh node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```sh node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```sh node example --arr 1 2 { _[], arr: [1, 2] } ``` _if disabled:_ ```sh node example --arr 1 2 { _[2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```sh node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```sh node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```sh node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```sh node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```sh node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```sh node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) Standard library ================ Standard library components for use with `tsc` (portable) and `asc` (assembly). Base configurations (.json) and definition files (.d.ts) are relevant to `tsc` only and not used by `asc`. # get-caller-file [![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. Inspired by http://stackoverflow.com/questions/13227489 *note: this relies on Node/V8 specific APIs, as such other runtimes may not work* ## Installation ```bash yarn add get-caller-file ``` ## Usage Given: ```js // ./foo.js const getCallerFile = require('get-caller-file'); module.exports = function() { return getCallerFile(); // figures out who called it }; ``` ```js // index.js const foo = require('./foo'); foo() // => /full/path/to/this/file/index.js ``` ## Options: * `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. The AssemblyScript Runtime ========================== The runtime provides the functionality necessary to dynamically allocate and deallocate memory of objects, arrays and buffers, as well as keep track of references that are no longer used. Interface --------- ### Memory manager * **__alloc**(size: `usize`): `usize`<br /> Dynamically allocates a chunk of memory of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. * **__realloc**(ref: `usize`, size: `usize`): `usize`<br /> Dynamically changes the size of a chunk of memory, possibly moving it to a new address. * **__free**(ref: `usize`): `void`<br /> Frees a dynamically allocated chunk of memory by its address. ### Garbage collector * **__new**(size: `usize`, id: `u32` = 0): `usize`<br /> Dynamically allocates a GC object of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. GC-allocated objects cannot be used with `__realloc` and `__free`. * **__renew**(ptr: `usize`, size: `usize`): `usize`<br /> Like `__realloc`, but for `__new`ed GC objects. * **__retain**(ref: `usize`): `usize`<br /> Retains a reference to an object. The object doesn't become collected as long as there's at least one retained reference. Returns the retained reference. * **__release**(ref: `usize`): `void`<br /> Releases a reference to an object. The object is considered for collection once all references to it have been released. * **__collect**(): `void`<br /> Forces a full garbage collection cycle. By default this means that reference cycles are resolved and possibly collected. ### Internals * **__visit**(ref: `usize`, cookie: `u32`): `void`<br /> Concrete visitor implementation called during traversal. Cookie can be used to indicate one of multiple operations. ### Built-ins * **__typeinfo**(id: `u32`): `RTTIFlags`<br /> Obtains the runtime type information for objects with the specified runtime id. Runtime type information is a set of flags indicating whether a reference type is managed, an array or similar, and what the relevant alignments when creating an instance externally are etc. * **__instanceof** * **__visit_globals**(cookie: `u32`): `void`<br /> Calls `__visit` on each global that is of a reference type. Not used anymore (originally provided to support tracing GCs) but still here for possible future use. * **__visit_members**(ref: `usize`, cookie: `u32`): `void`<br /> Calls `__visit` on each member of the object pointed to by `ref`. ### Related * **idof**<`T`>(): `u32`<br /> Obtains the unique internal class id of a reference type. Full/half --------- The [full](./index-full.ts) runtime is based on [the TLSF memory manager](./tlsf.ts) and [a pure reference counting garbage collector](./pure.ts) and provides all the functionality necessary. The [half](./index-half.ts) alias is essentially the same, but doesn't expose the runtime API so unused runtime code can be DCE'ed. Stub/none --------- The [stub](./index-stub.ts) runtime, though fully functional, provides minimal dynamic memory allocation but no deallocation. Useful for prototyping or very short-lived programs with hardly any memory footprint. The [none](./index-none.ts) alias is the same, but doesn't expose the runtime API so unused runtime code can be DCE'ed. Integration notes ----------------- The underlying reference counting implementation works very similar to other implementations. When an object is stored in a local, global or field, its reference becomes retained (reference count is incremented by 1), respectively when it becomes deleted, it is released (reference count is decremented by 1). Once the reference count reaches zero, the object is considered for collection and the reference count of all contained objects (fields, array elements etc.) is decremented by 1. Now, if an object is inherently acyclic (most objects are), it is free'd right away, while otherwise it is added to a cycle pool and considered for cycle collection on the next `__collect`. Differences to other implementations include: * A new object from `__new` doesn't start with a reference count of 1, but 0. * When an object is returned from a function, it remains at RC + 1 and the caller is expected to release it. * Functions with reference type arguments retain each such argument when called, and release it again when exited. This can't be counted on, however, because the compiler may decide to eliminate these where unnecessary. * Getters, setters, operator overloads and constructors are function calls and behave like one. Even though the rules are simple, working with the runtime internals within standard library code can be tricky and requires knowledge of where the compiler will insert runtime calls automatically. For instance * `changetype`ing a pointer to a reference type or vice-versa has no side-effects. For example in a `changetype<Ref>(ptr)` the pointer is untracked before, and the reference becomes tracked afterwards, but there's nothing inserted in between. * `load`, `store` and similar built-ins aren't functions but intrinsics and as such have no side-effects. For example a `load<Ref>(...)` is equivalent to a `changetype<Ref>(load<usize>(...))` and a `store<Ref>(..., ref)` equivalent to a `store<usize>(..., changetype<usize>(ref))`. **GOOD:** In case of doubt, the following pattern is universal: ```ts var ref = changetype<Ref>(__new(SIZE, idof<Ref>())); // assignment retains, RC=1 // ... safe ... return ref; // knows `ref` is already retained and simply returns it ``` **BAD:** A pattern one shouldn't use is: ```ts var ptr = __new(SIZE, idof<Ref>()); // RC=0 // ... not safe while RC=0 ... e.g.: someFunc(changetype<Ref>(ptr)); // might, or might not, free the object! ``` **BONUS:** Beware of runtime calls in conditional expressions like a ternary IF, logical AND or OR. Each arm can be in either of two states: Either in-flight if immediately retained/returned or not if the expression or the target doesn't support it. Don't fight the compiler there. # color-convert [![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). # path-parse [![Build Status](https://travis-ci.org/jbgutierrez/path-parse.svg?branch=master)](https://travis-ci.org/jbgutierrez/path-parse) > Node.js [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) [ponyfill](https://ponyfill.com). ## Install ``` $ npm install --save path-parse ``` ## Usage ```js var pathParse = require('path-parse'); pathParse('/home/user/dir/file.txt'); //=> { // root : "/", // dir : "/home/user/dir", // base : "file.txt", // ext : ".txt", // name : "file" // } ``` ## API See [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) docs. ### pathParse(path) ### pathParse.posix(path) The Posix specific version. ### pathParse.win32(path) The Windows specific version. ## License MIT © [Javier Blanco](http://jbgutierrez.info) <p align="center"> <img width="250" src="/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> [![Build Status][travis-image]][travis-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description : Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments. > <img width="400" src="/screen.png"> * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage : ### Simple Example ```javascript #!/usr/bin/env node const {argv} = require('yargs') if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node require('yargs') // eslint-disable-line .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ## Webpack See usage examples of yargs with webpack in [docs](/docs/webpack.md). ## Community : Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation : ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Contributing](/contributing.md) [travis-url]: https://travis-ci.org/yargs/yargs [travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc # y18n [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js var __ = require('y18n').__ console.log(__('my awesome string %s', 'foo')) ``` output: `my awesome string foo` _using tagged template literals_ ```js var __ = require('y18n').__ var str = 'foo' console.log(__`my awesome string ${str}`) ``` output: `my awesome string foo` _pluralization support:_ ```js var __n = require('y18n').__n console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')) ``` output: `2 fishes foo` ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## License ISC [travis-url]: https://travis-ci.org/yargs/y18n [travis-image]: https://img.shields.io/travis/yargs/y18n.svg [coveralls-url]: https://coveralls.io/github/yargs/y18n [coveralls-image]: https://img.shields.io/coveralls/yargs/y18n.svg [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard ## Follow Redirects Drop-in replacement for Nodes `http` and `https` that automatically follows redirects. [![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) [![Build Status](https://travis-ci.org/follow-redirects/follow-redirects.svg?branch=master)](https://travis-ci.org/follow-redirects/follow-redirects) [![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master) [![Dependency Status](https://david-dm.org/follow-redirects/follow-redirects.svg)](https://david-dm.org/follow-redirects/follow-redirects) [![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) `follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback) methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback) modules, with the exception that they will seamlessly follow redirects. ```javascript var http = require('follow-redirects').http; var https = require('follow-redirects').https; http.get('http://bit.ly/900913', function (response) { response.on('data', function (chunk) { console.log(chunk); }); }).on('error', function (err) { console.error(err); }); ``` You can inspect the final redirected URL through the `responseUrl` property on the `response`. If no redirection happened, `responseUrl` is the original request URL. ```javascript https.request({ host: 'bitly.com', path: '/UHfDGO', }, function (response) { console.log(response.responseUrl); // 'http://duckduckgo.com/robots.txt' }); ``` ## Options ### Global options Global options are set directly on the `follow-redirects` module: ```javascript var followRedirects = require('follow-redirects'); followRedirects.maxRedirects = 10; followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB ``` The following global options are supported: - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. ### Per-request options Per-request options are set by passing an `options` object: ```javascript var url = require('url'); var followRedirects = require('follow-redirects'); var options = url.parse('http://bit.ly/900913'); options.maxRedirects = 10; http.request(options); ``` In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback), the following per-request options are supported: - `followRedirects` (default: `true`) – whether redirects should be followed. - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. - `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }` - `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object. ### Advanced usage By default, `follow-redirects` will use the Node.js default implementations of [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html). To enable features such as caching and/or intermediate request tracking, you might instead want to wrap `follow-redirects` around custom protocol implementations: ```javascript var followRedirects = require('follow-redirects').wrap({ http: require('your-custom-http'), https: require('your-custom-https'), }); ``` Such custom protocols only need an implementation of the `request` method. ## Browserify Usage Due to the way `XMLHttpRequest` works, the `browserify` versions of `http` and `https` already follow redirects. If you are *only* targeting the browser, then this library has little value for you. If you want to write cross platform code for node and the browser, `follow-redirects` provides a great solution for making the native node modules behave the same as they do in browserified builds in the browser. To avoid bundling unnecessary code you should tell browserify to swap out `follow-redirects` with the standard modules when bundling. To make this easier, you need to change how you require the modules: ```javascript var http = require('follow-redirects/http'); var https = require('follow-redirects/https'); ``` You can then replace `follow-redirects` in your browserify configuration like so: ```javascript "browser": { "follow-redirects/http" : "http", "follow-redirects/https" : "https" } ``` The `browserify-http` module has not kept pace with node development, and no long behaves identically to the native module when running in the browser. If you are experiencing problems, you may want to check out [browserify-http-2](https://www.npmjs.com/package/http-browserify-2). It is more actively maintained and attempts to address a few of the shortcomings of `browserify-http`. In that case, your browserify config should look something like this: ```javascript "browser": { "follow-redirects/http" : "browserify-http-2/http", "follow-redirects/https" : "browserify-http-2/https" } ``` ## Contributing Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues) detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied by tests. You can run the test suite locally with a simple `npm test` command. ## Debug Logging `follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well. ## Authors - Olivier Lalonde ([email protected]) - James Talmage ([email protected]) - [Ruben Verborgh](https://ruben.verborgh.org/) ## License [https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE](MIT License) binaryen.js =========== **binaryen.js** is a port of [Binaryen](https://github.com/WebAssembly/binaryen) to the Web, allowing you to generate [WebAssembly](https://webassembly.org) using a JavaScript API. <a href="https://github.com/AssemblyScript/binaryen.js/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/binaryen.js/Build/master?label=build&logo=github" alt="Build status" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen.svg?label=latest&color=007acc&logo=npm" alt="npm version" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen/nightly.svg?label=nightly&color=007acc&logo=npm" alt="npm nightly version" /></a> Usage ----- ``` $> npm install binaryen ``` ```js var binaryen = require("binaryen"); // Create a module with a single function var myModule = new binaryen.Module(); myModule.addFunction("add", binaryen.createType([ binaryen.i32, binaryen.i32 ]), binaryen.i32, [ binaryen.i32 ], myModule.block(null, [ myModule.local.set(2, myModule.i32.add( myModule.local.get(0, binaryen.i32), myModule.local.get(1, binaryen.i32) ) ), myModule.return( myModule.local.get(2, binaryen.i32) ) ]) ); myModule.addFunctionExport("add", "add"); // Optimize the module using default passes and levels myModule.optimize(); // Validate the module if (!myModule.validate()) throw new Error("validation error"); // Generate text format and binary var textData = myModule.emitText(); var wasmData = myModule.emitBinary(); // Example usage with the WebAssembly API var compiled = new WebAssembly.Module(wasmData); var instance = new WebAssembly.Instance(compiled, {}); console.log(instance.exports.add(41, 1)); ``` The buildbot also publishes nightly versions once a day if there have been changes. The latest nightly can be installed through ``` $> npm install binaryen@nightly ``` or you can use one of the [previous versions](https://github.com/AssemblyScript/binaryen.js/tags) instead if necessary. ### Usage with a CDN * From GitHub via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/gh/AssemblyScript/binaryen.js@VERSION/index.js` * From npm via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/npm/binaryen@VERSION/index.js` * From npm via [unpkg](https://unpkg.com):<br /> `https://unpkg.com/binaryen@VERSION/index.js` Replace `VERSION` with a [specific version](https://github.com/AssemblyScript/binaryen.js/releases) or omit it (not recommended in production) to use master/latest. API --- **Please note** that the Binaryen API is evolving fast and that definitions and documentation provided by the package tend to get out of sync despite our best efforts. It's a bot after all. If you rely on binaryen.js and spot an issue, please consider sending a PR our way by updating [index.d.ts](./index.d.ts) and [README.md](./README.md) to reflect the [current API](https://github.com/WebAssembly/binaryen/blob/master/src/js/binaryen.js-post.js). <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ### Contents - [Types](#types) - [Module construction](#module-construction) - [Module manipulation](#module-manipulation) - [Module validation](#module-validation) - [Module optimization](#module-optimization) - [Module creation](#module-creation) - [Expression construction](#expression-construction) - [Control flow](#control-flow) - [Variable accesses](#variable-accesses) - [Integer operations](#integer-operations) - [Floating point operations](#floating-point-operations) - [Datatype conversions](#datatype-conversions) - [Function calls](#function-calls) - [Linear memory accesses](#linear-memory-accesses) - [Host operations](#host-operations) - [Vector operations 🦄](#vector-operations-) - [Atomic memory accesses 🦄](#atomic-memory-accesses-) - [Atomic read-modify-write operations 🦄](#atomic-read-modify-write-operations-) - [Atomic wait and notify operations 🦄](#atomic-wait-and-notify-operations-) - [Sign extension operations 🦄](#sign-extension-operations-) - [Multi-value operations 🦄](#multi-value-operations-) - [Exception handling operations 🦄](#exception-handling-operations-) - [Reference types operations 🦄](#reference-types-operations-) - [Expression manipulation](#expression-manipulation) - [Relooper](#relooper) - [Source maps](#source-maps) - [Debugging](#debugging) <!-- END doctoc generated TOC please keep comment here to allow auto update --> [Future features](http://webassembly.org/docs/future-features/) 🦄 might not be supported by all runtimes. ### Types * **none**: `Type`<br /> The none type, e.g., `void`. * **i32**: `Type`<br /> 32-bit integer type. * **i64**: `Type`<br /> 64-bit integer type. * **f32**: `Type`<br /> 32-bit float type. * **f64**: `Type`<br /> 64-bit float (double) type. * **v128**: `Type`<br /> 128-bit vector type. 🦄 * **funcref**: `Type`<br /> A function reference. 🦄 * **anyref**: `Type`<br /> Any host reference. 🦄 * **nullref**: `Type`<br /> A null reference. 🦄 * **exnref**: `Type`<br /> An exception reference. 🦄 * **unreachable**: `Type`<br /> Special type indicating unreachable code when obtaining information about an expression. * **auto**: `Type`<br /> Special type used in **Module#block** exclusively. Lets the API figure out a block's result type automatically. * **createType**(types: `Type[]`): `Type`<br /> Creates a multi-value type from an array of types. * **expandType**(type: `Type`): `Type[]`<br /> Expands a multi-value type to an array of types. ### Module construction * new **Module**()<br /> Constructs a new module. * **parseText**(text: `string`): `Module`<br /> Creates a module from Binaryen's s-expression text format (not official stack-style text format). * **readBinary**(data: `Uint8Array`): `Module`<br /> Creates a module from binary data. ### Module manipulation * Module#**addFunction**(name: `string`, params: `Type`, results: `Type`, vars: `Type[]`, body: `ExpressionRef`): `FunctionRef`<br /> Adds a function. `vars` indicate additional locals, in the given order. * Module#**getFunction**(name: `string`): `FunctionRef`<br /> Gets a function, by name, * Module#**removeFunction**(name: `string`): `void`<br /> Removes a function, by name. * Module#**getNumFunctions**(): `number`<br /> Gets the number of functions within the module. * Module#**getFunctionByIndex**(index: `number`): `FunctionRef`<br /> Gets the function at the specified index. * Module#**addFunctionImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, params: `Type`, results: `Type`): `void`<br /> Adds a function import. * Module#**addTableImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a table import. There's just one table for now, using name `"0"`. * Module#**addMemoryImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a memory import. There's just one memory for now, using name `"0"`. * Module#**addGlobalImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, globalType: `Type`): `void`<br /> Adds a global variable import. Imported globals must be immutable. * Module#**addFunctionExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a function export. * Module#**addTableExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a table export. There's just one table for now, using name `"0"`. * Module#**addMemoryExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a memory export. There's just one memory for now, using name `"0"`. * Module#**addGlobalExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a global variable export. Exported globals must be immutable. * Module#**getNumExports**(): `number`<br /> Gets the number of exports witin the module. * Module#**getExportByIndex**(index: `number`): `ExportRef`<br /> Gets the export at the specified index. * Module#**removeExport**(externalName: `string`): `void`<br /> Removes an export, by external name. * Module#**addGlobal**(name: `string`, type: `Type`, mutable: `number`, value: `ExpressionRef`): `GlobalRef`<br /> Adds a global instance variable. * Module#**getGlobal**(name: `string`): `GlobalRef`<br /> Gets a global, by name, * Module#**removeGlobal**(name: `string`): `void`<br /> Removes a global, by name. * Module#**setFunctionTable**(initial: `number`, maximum: `number`, funcs: `string[]`, offset?: `ExpressionRef`): `void`<br /> Sets the contents of the function table. There's just one table for now, using name `"0"`. * Module#**getFunctionTable**(): `{ imported: boolean, segments: TableElement[] }`<br /> Gets the contents of the function table. * TableElement#**offset**: `ExpressionRef` * TableElement#**names**: `string[]` * Module#**setMemory**(initial: `number`, maximum: `number`, exportName: `string | null`, segments: `MemorySegment[]`, flags?: `number[]`, shared?: `boolean`): `void`<br /> Sets the memory. There's just one memory for now, using name `"0"`. Providing `exportName` also creates a memory export. * MemorySegment#**offset**: `ExpressionRef` * MemorySegment#**data**: `Uint8Array` * MemorySegment#**passive**: `boolean` * Module#**getNumMemorySegments**(): `number`<br /> Gets the number of memory segments within the module. * Module#**getMemorySegmentInfoByIndex**(index: `number`): `MemorySegmentInfo`<br /> Gets information about the memory segment at the specified index. * MemorySegmentInfo#**offset**: `number` * MemorySegmentInfo#**data**: `Uint8Array` * MemorySegmentInfo#**passive**: `boolean` * Module#**setStart**(start: `FunctionRef`): `void`<br /> Sets the start function. * Module#**getFeatures**(): `Features`<br /> Gets the WebAssembly features enabled for this module. Note that the return value may be a bitmask indicating multiple features. Possible feature flags are: * Features.**MVP**: `Features` * Features.**Atomics**: `Features` * Features.**BulkMemory**: `Features` * Features.**MutableGlobals**: `Features` * Features.**NontrappingFPToInt**: `Features` * Features.**SignExt**: `Features` * Features.**SIMD128**: `Features` * Features.**ExceptionHandling**: `Features` * Features.**TailCall**: `Features` * Features.**ReferenceTypes**: `Features` * Features.**Multivalue**: `Features` * Features.**All**: `Features` * Module#**setFeatures**(features: `Features`): `void`<br /> Sets the WebAssembly features enabled for this module. * Module#**addCustomSection**(name: `string`, contents: `Uint8Array`): `void`<br /> Adds a custom section to the binary. * Module#**autoDrop**(): `void`<br /> Enables automatic insertion of `drop` operations where needed. Lets you not worry about dropping when creating your code. * **getFunctionInfo**(ftype: `FunctionRef`: `FunctionInfo`<br /> Obtains information about a function. * FunctionInfo#**name**: `string` * FunctionInfo#**module**: `string | null` (if imported) * FunctionInfo#**base**: `string | null` (if imported) * FunctionInfo#**params**: `Type` * FunctionInfo#**results**: `Type` * FunctionInfo#**vars**: `Type` * FunctionInfo#**body**: `ExpressionRef` * **getGlobalInfo**(global: `GlobalRef`): `GlobalInfo`<br /> Obtains information about a global. * GlobalInfo#**name**: `string` * GlobalInfo#**module**: `string | null` (if imported) * GlobalInfo#**base**: `string | null` (if imported) * GlobalInfo#**type**: `Type` * GlobalInfo#**mutable**: `boolean` * GlobalInfo#**init**: `ExpressionRef` * **getExportInfo**(export_: `ExportRef`): `ExportInfo`<br /> Obtains information about an export. * ExportInfo#**kind**: `ExternalKind` * ExportInfo#**name**: `string` * ExportInfo#**value**: `string` Possible `ExternalKind` values are: * **ExternalFunction**: `ExternalKind` * **ExternalTable**: `ExternalKind` * **ExternalMemory**: `ExternalKind` * **ExternalGlobal**: `ExternalKind` * **ExternalEvent**: `ExternalKind` * **getEventInfo**(event: `EventRef`): `EventInfo`<br /> Obtains information about an event. * EventInfo#**name**: `string` * EventInfo#**module**: `string | null` (if imported) * EventInfo#**base**: `string | null` (if imported) * EventInfo#**attribute**: `number` * EventInfo#**params**: `Type` * EventInfo#**results**: `Type` * **getSideEffects**(expr: `ExpressionRef`, features: `FeatureFlags`): `SideEffects`<br /> Gets the side effects of the specified expression. * SideEffects.**None**: `SideEffects` * SideEffects.**Branches**: `SideEffects` * SideEffects.**Calls**: `SideEffects` * SideEffects.**ReadsLocal**: `SideEffects` * SideEffects.**WritesLocal**: `SideEffects` * SideEffects.**ReadsGlobal**: `SideEffects` * SideEffects.**WritesGlobal**: `SideEffects` * SideEffects.**ReadsMemory**: `SideEffects` * SideEffects.**WritesMemory**: `SideEffects` * SideEffects.**ImplicitTrap**: `SideEffects` * SideEffects.**IsAtomic**: `SideEffects` * SideEffects.**Throws**: `SideEffects` * SideEffects.**Any**: `SideEffects` ### Module validation * Module#**validate**(): `boolean`<br /> Validates the module. Returns `true` if valid, otherwise prints validation errors and returns `false`. ### Module optimization * Module#**optimize**(): `void`<br /> Optimizes the module using the default optimization passes. * Module#**optimizeFunction**(func: `FunctionRef | string`): `void`<br /> Optimizes a single function using the default optimization passes. * Module#**runPasses**(passes: `string[]`): `void`<br /> Runs the specified passes on the module. * Module#**runPassesOnFunction**(func: `FunctionRef | string`, passes: `string[]`): `void`<br /> Runs the specified passes on a single function. * **getOptimizeLevel**(): `number`<br /> Gets the currently set optimize level. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **setOptimizeLevel**(level: `number`): `void`<br /> Sets the optimization level to use. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **getShrinkLevel**(): `number`<br /> Gets the currently set shrink level. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **setShrinkLevel**(level: `number`): `void`<br /> Sets the shrink level to use. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **getDebugInfo**(): `boolean`<br /> Gets whether generating debug information is currently enabled or not. * **setDebugInfo**(on: `boolean`): `void`<br /> Enables or disables debug information in emitted binaries. * **getLowMemoryUnused**(): `boolean`<br /> Gets whether the low 1K of memory can be considered unused when optimizing. * **setLowMemoryUnused**(on: `boolean`): `void`<br /> Enables or disables whether the low 1K of memory can be considered unused when optimizing. * **getPassArgument**(key: `string`): `string | null`<br /> Gets the value of the specified arbitrary pass argument. * **setPassArgument**(key: `string`, value: `string | null`): `void`<br /> Sets the value of the specified arbitrary pass argument. Removes the respective argument if `value` is `null`. * **clearPassArguments**(): `void`<br /> Clears all arbitrary pass arguments. * **getAlwaysInlineMaxSize**(): `number`<br /> Gets the function size at which we always inline. * **setAlwaysInlineMaxSize**(size: `number`): `void`<br /> Sets the function size at which we always inline. * **getFlexibleInlineMaxSize**(): `number`<br /> Gets the function size which we inline when functions are lightweight. * **setFlexibleInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when functions are lightweight. * **getOneCallerInlineMaxSize**(): `number`<br /> Gets the function size which we inline when there is only one caller. * **setOneCallerInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when there is only one caller. ### Module creation * Module#**emitBinary**(): `Uint8Array`<br /> Returns the module in binary format. * Module#**emitBinary**(sourceMapUrl: `string | null`): `BinaryWithSourceMap`<br /> Returns the module in binary format with its source map. If `sourceMapUrl` is `null`, source map generation is skipped. * BinaryWithSourceMap#**binary**: `Uint8Array` * BinaryWithSourceMap#**sourceMap**: `string | null` * Module#**emitText**(): `string`<br /> Returns the module in Binaryen's s-expression text format (not official stack-style text format). * Module#**emitAsmjs**(): `string`<br /> Returns the [asm.js](http://asmjs.org/) representation of the module. * Module#**dispose**(): `void`<br /> Releases the resources held by the module once it isn't needed anymore. ### Expression construction #### [Control flow](http://webassembly.org/docs/semantics/#control-constructs-and-instructions) * Module#**block**(label: `string | null`, children: `ExpressionRef[]`, resultType?: `Type`): `ExpressionRef`<br /> Creates a block. `resultType` defaults to `none`. * Module#**if**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse?: `ExpressionRef`): `ExpressionRef`<br /> Creates an if or if/else combination. * Module#**loop**(label: `string | null`, body: `ExpressionRef`): `ExpressionRef`<br /> Creates a loop. * Module#**br**(label: `string`, condition?: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a branch (br) to a label. * Module#**switch**(labels: `string[]`, defaultLabel: `string`, condition: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a switch (br_table). * Module#**nop**(): `ExpressionRef`<br /> Creates a no-operation (nop) instruction. * Module#**return**(value?: `ExpressionRef`): `ExpressionRef` Creates a return. * Module#**unreachable**(): `ExpressionRef`<br /> Creates an [unreachable](http://webassembly.org/docs/semantics/#unreachable) instruction that will always trap. * Module#**drop**(value: `ExpressionRef`): `ExpressionRef`<br /> Creates a [drop](http://webassembly.org/docs/semantics/#type-parametric-operators) of a value. * Module#**select**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse: `ExpressionRef`, type?: `Type`): `ExpressionRef`<br /> Creates a [select](http://webassembly.org/docs/semantics/#type-parametric-operators) of one of two values. #### [Variable accesses](http://webassembly.org/docs/semantics/#local-variables) * Module#**local.get**(index: `number`, type: `Type`): `ExpressionRef`<br /> Creates a local.get for the local at the specified index. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**local.set**(index: `number`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a local.set for the local at the specified index. * Module#**local.tee**(index: `number`, value: `ExpressionRef`, type: `Type`): `ExpressionRef`<br /> Creates a local.tee for the local at the specified index. A tee differs from a set in that the value remains on the stack. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**global.get**(name: `string`, type: `Type`): `ExpressionRef`<br /> Creates a global.get for the global with the specified name. Note that we must specify the type here as we may not have created the global being accessed yet. * Module#**global.set**(name: `string`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a global.set for the global with the specified name. #### [Integer operations](http://webassembly.org/docs/semantics/#32-bit-integer-operators) * Module#i32.**const**(value: `number`): `ExpressionRef` * Module#i32.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i64.**const**(value: `number`): `ExpressionRef` * Module#i64.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Floating point operations](http://webassembly.org/docs/semantics/#floating-point-operators) * Module#f32.**const**(value: `number`): `ExpressionRef` * Module#f32.**const_bits**(value: `number`): `ExpressionRef` * Module#f32.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#f64.**const**(value: `number`): `ExpressionRef` * Module#f64.**const_bits**(value: `number`): `ExpressionRef` * Module#f64.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Datatype conversions](http://webassembly.org/docs/semantics/#datatype-conversions-truncations-reinterpretations-promotions-and-demotions) * Module#i32.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**wrap**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**demote**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**promote**(value: `ExpressionRef`): `ExpressionRef` #### [Function calls](http://webassembly.org/docs/semantics/#calls) * Module#**call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef` Creates a call to a function. Note that we must specify the return type here as we may not have created the function being called yet. * Module#**return_call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef`<br /> Like **call**, but creates a tail-call. 🦄 * Module#**call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Similar to **call**, but calls indirectly, i.e., via a function pointer, so an expression replaces the name as the called value. * Module#**return_call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Like **call_indirect**, but creates a tail-call. 🦄 #### [Linear memory accesses](http://webassembly.org/docs/semantics/#linear-memory-accesses) * Module#i32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> > * Module#i64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store32**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Host operations](http://webassembly.org/docs/semantics/#resizing) * Module#**memory.size**(): `ExpressionRef` * Module#**memory.grow**(value: `number`): `ExpressionRef` #### [Vector operations](https://github.com/WebAssembly/simd/blob/master/proposals/simd/SIMD.md) 🦄 * Module#v128.**const**(bytes: `Uint8Array`): `ExpressionRef` * Module#v128.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#v128.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#v128.**not**(value: `ExpressionRef`): `ExpressionRef` * Module#v128.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**andnot**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**bitselect**(left: `ExpressionRef`, right: `ExpressionRef`, cond: `ExpressionRef`): `ExpressionRef` > * Module#i8x16.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i16x8.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**dot_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#f32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#v8x16.**shuffle**(left: `ExpressionRef`, right: `ExpressionRef`, mask: `Uint8Array`): `ExpressionRef` * Module#v8x16.**swizzle**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v8x16.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v16x8.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v32x4.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v64x2.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` #### [Atomic memory accesses](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#atomic-memory-accesses) 🦄 * Module#i32.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load32_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store32**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Atomic read-modify-write operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#read-modify-write) 🦄 * Module#i32.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` #### [Atomic wait and notify operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#wait-and-notify-operators) 🦄 * Module#i32.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#**atomic.notify**(ptr: `ExpressionRef`, notifyCount: `ExpressionRef`): `ExpressionRef` * Module#**atomic.fence**(): `ExpressionRef` #### [Sign extension operations](https://github.com/WebAssembly/sign-extension-ops/blob/master/proposals/sign-extension-ops/Overview.md) 🦄 * Module#i32.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend32_s**(value: `ExpressionRef`): `ExpressionRef` #### [Multi-value operations](https://github.com/WebAssembly/multi-value/blob/master/proposals/multi-value/Overview.md) 🦄 Note that these are pseudo instructions enabling Binaryen to reason about multiple values on the stack. * Module#**push**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**pop**(): `ExpressionRef` * Module#i64.**pop**(): `ExpressionRef` * Module#f32.**pop**(): `ExpressionRef` * Module#f64.**pop**(): `ExpressionRef` * Module#v128.**pop**(): `ExpressionRef` * Module#funcref.**pop**(): `ExpressionRef` * Module#anyref.**pop**(): `ExpressionRef` * Module#nullref.**pop**(): `ExpressionRef` * Module#exnref.**pop**(): `ExpressionRef` * Module#tuple.**make**(elements: `ExpressionRef[]`): `ExpressionRef` * Module#tuple.**extract**(tuple: `ExpressionRef`, index: `number`): `ExpressionRef` #### [Exception handling operations](https://github.com/WebAssembly/exception-handling/blob/master/proposals/Exceptions.md) 🦄 * Module#**try**(body: `ExpressionRef`, catchBody: `ExpressionRef`): `ExpressionRef` * Module#**throw**(event: `string`, operands: `ExpressionRef[]`): `ExpressionRef` * Module#**rethrow**(exnref: `ExpressionRef`): `ExpressionRef` * Module#**br_on_exn**(label: `string`, event: `string`, exnref: `ExpressionRef`): `ExpressionRef` > * Module#**addEvent**(name: `string`, attribute: `number`, params: `Type`, results: `Type`): `Event` * Module#**getEvent**(name: `string`): `Event` * Module#**removeEvent**(name: `stirng`): `void` * Module#**addEventImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, attribute: `number`, params: `Type`, results: `Type`): `void` * Module#**addEventExport**(internalName: `string`, externalName: `string`): `ExportRef` #### [Reference types operations](https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md) 🦄 * Module#ref.**null**(): `ExpressionRef` * Module#ref.**is_null**(value: `ExpressionRef`): `ExpressionRef` * Module#ref.**func**(name: `string`): `ExpressionRef` ### Expression manipulation * **getExpressionId**(expr: `ExpressionRef`): `ExpressionId`<br /> Gets the id (kind) of the specified expression. Possible values are: * **InvalidId**: `ExpressionId` * **BlockId**: `ExpressionId` * **IfId**: `ExpressionId` * **LoopId**: `ExpressionId` * **BreakId**: `ExpressionId` * **SwitchId**: `ExpressionId` * **CallId**: `ExpressionId` * **CallIndirectId**: `ExpressionId` * **LocalGetId**: `ExpressionId` * **LocalSetId**: `ExpressionId` * **GlobalGetId**: `ExpressionId` * **GlobalSetId**: `ExpressionId` * **LoadId**: `ExpressionId` * **StoreId**: `ExpressionId` * **ConstId**: `ExpressionId` * **UnaryId**: `ExpressionId` * **BinaryId**: `ExpressionId` * **SelectId**: `ExpressionId` * **DropId**: `ExpressionId` * **ReturnId**: `ExpressionId` * **HostId**: `ExpressionId` * **NopId**: `ExpressionId` * **UnreachableId**: `ExpressionId` * **AtomicCmpxchgId**: `ExpressionId` * **AtomicRMWId**: `ExpressionId` * **AtomicWaitId**: `ExpressionId` * **AtomicNotifyId**: `ExpressionId` * **AtomicFenceId**: `ExpressionId` * **SIMDExtractId**: `ExpressionId` * **SIMDReplaceId**: `ExpressionId` * **SIMDShuffleId**: `ExpressionId` * **SIMDTernaryId**: `ExpressionId` * **SIMDShiftId**: `ExpressionId` * **SIMDLoadId**: `ExpressionId` * **MemoryInitId**: `ExpressionId` * **DataDropId**: `ExpressionId` * **MemoryCopyId**: `ExpressionId` * **MemoryFillId**: `ExpressionId` * **RefNullId**: `ExpressionId` * **RefIsNullId**: `ExpressionId` * **RefFuncId**: `ExpressionId` * **TryId**: `ExpressionId` * **ThrowId**: `ExpressionId` * **RethrowId**: `ExpressionId` * **BrOnExnId**: `ExpressionId` * **PushId**: `ExpressionId` * **PopId**: `ExpressionId` * **getExpressionType**(expr: `ExpressionRef`): `Type`<br /> Gets the type of the specified expression. * **getExpressionInfo**(expr: `ExpressionRef`): `ExpressionInfo`<br /> Obtains information about an expression, always including: * Info#**id**: `ExpressionId` * Info#**type**: `Type` Additional properties depend on the expression's `id` and are usually equivalent to the respective parameters when creating such an expression: * BlockInfo#**name**: `string` * BlockInfo#**children**: `ExpressionRef[]` > * IfInfo#**condition**: `ExpressionRef` * IfInfo#**ifTrue**: `ExpressionRef` * IfInfo#**ifFalse**: `ExpressionRef | null` > * LoopInfo#**name**: `string` * LoopInfo#**body**: `ExpressionRef` > * BreakInfo#**name**: `string` * BreakInfo#**condition**: `ExpressionRef | null` * BreakInfo#**value**: `ExpressionRef | null` > * SwitchInfo#**names**: `string[]` * SwitchInfo#**defaultName**: `string | null` * SwitchInfo#**condition**: `ExpressionRef` * SwitchInfo#**value**: `ExpressionRef | null` > * CallInfo#**target**: `string` * CallInfo#**operands**: `ExpressionRef[]` > * CallImportInfo#**target**: `string` * CallImportInfo#**operands**: `ExpressionRef[]` > * CallIndirectInfo#**target**: `ExpressionRef` * CallIndirectInfo#**operands**: `ExpressionRef[]` > * LocalGetInfo#**index**: `number` > * LocalSetInfo#**isTee**: `boolean` * LocalSetInfo#**index**: `number` * LocalSetInfo#**value**: `ExpressionRef` > * GlobalGetInfo#**name**: `string` > * GlobalSetInfo#**name**: `string` * GlobalSetInfo#**value**: `ExpressionRef` > * LoadInfo#**isAtomic**: `boolean` * LoadInfo#**isSigned**: `boolean` * LoadInfo#**offset**: `number` * LoadInfo#**bytes**: `number` * LoadInfo#**align**: `number` * LoadInfo#**ptr**: `ExpressionRef` > * StoreInfo#**isAtomic**: `boolean` * StoreInfo#**offset**: `number` * StoreInfo#**bytes**: `number` * StoreInfo#**align**: `number` * StoreInfo#**ptr**: `ExpressionRef` * StoreInfo#**value**: `ExpressionRef` > * ConstInfo#**value**: `number | { low: number, high: number }` > * UnaryInfo#**op**: `number` * UnaryInfo#**value**: `ExpressionRef` > * BinaryInfo#**op**: `number` * BinaryInfo#**left**: `ExpressionRef` * BinaryInfo#**right**: `ExpressionRef` > * SelectInfo#**ifTrue**: `ExpressionRef` * SelectInfo#**ifFalse**: `ExpressionRef` * SelectInfo#**condition**: `ExpressionRef` > * DropInfo#**value**: `ExpressionRef` > * ReturnInfo#**value**: `ExpressionRef | null` > * NopInfo > * UnreachableInfo > * HostInfo#**op**: `number` * HostInfo#**nameOperand**: `string | null` * HostInfo#**operands**: `ExpressionRef[]` > * AtomicRMWInfo#**op**: `number` * AtomicRMWInfo#**bytes**: `number` * AtomicRMWInfo#**offset**: `number` * AtomicRMWInfo#**ptr**: `ExpressionRef` * AtomicRMWInfo#**value**: `ExpressionRef` > * AtomicCmpxchgInfo#**bytes**: `number` * AtomicCmpxchgInfo#**offset**: `number` * AtomicCmpxchgInfo#**ptr**: `ExpressionRef` * AtomicCmpxchgInfo#**expected**: `ExpressionRef` * AtomicCmpxchgInfo#**replacement**: `ExpressionRef` > * AtomicWaitInfo#**ptr**: `ExpressionRef` * AtomicWaitInfo#**expected**: `ExpressionRef` * AtomicWaitInfo#**timeout**: `ExpressionRef` * AtomicWaitInfo#**expectedType**: `Type` > * AtomicNotifyInfo#**ptr**: `ExpressionRef` * AtomicNotifyInfo#**notifyCount**: `ExpressionRef` > * AtomicFenceInfo > * SIMDExtractInfo#**op**: `Op` * SIMDExtractInfo#**vec**: `ExpressionRef` * SIMDExtractInfo#**index**: `ExpressionRef` > * SIMDReplaceInfo#**op**: `Op` * SIMDReplaceInfo#**vec**: `ExpressionRef` * SIMDReplaceInfo#**index**: `ExpressionRef` * SIMDReplaceInfo#**value**: `ExpressionRef` > * SIMDShuffleInfo#**left**: `ExpressionRef` * SIMDShuffleInfo#**right**: `ExpressionRef` * SIMDShuffleInfo#**mask**: `Uint8Array` > * SIMDTernaryInfo#**op**: `Op` * SIMDTernaryInfo#**a**: `ExpressionRef` * SIMDTernaryInfo#**b**: `ExpressionRef` * SIMDTernaryInfo#**c**: `ExpressionRef` > * SIMDShiftInfo#**op**: `Op` * SIMDShiftInfo#**vec**: `ExpressionRef` * SIMDShiftInfo#**shift**: `ExpressionRef` > * SIMDLoadInfo#**op**: `Op` * SIMDLoadInfo#**offset**: `number` * SIMDLoadInfo#**align**: `number` * SIMDLoadInfo#**ptr**: `ExpressionRef` > * MemoryInitInfo#**segment**: `number` * MemoryInitInfo#**dest**: `ExpressionRef` * MemoryInitInfo#**offset**: `ExpressionRef` * MemoryInitInfo#**size**: `ExpressionRef` > * MemoryDropInfo#**segment**: `number` > * MemoryCopyInfo#**dest**: `ExpressionRef` * MemoryCopyInfo#**source**: `ExpressionRef` * MemoryCopyInfo#**size**: `ExpressionRef` > * MemoryFillInfo#**dest**: `ExpressionRef` * MemoryFillInfo#**value**: `ExpressionRef` * MemoryFillInfo#**size**: `ExpressionRef` > * TryInfo#**body**: `ExpressionRef` * TryInfo#**catchBody**: `ExpressionRef` > * RefNullInfo > * RefIsNullInfo#**value**: `ExpressionRef` > * RefFuncInfo#**func**: `string` > * ThrowInfo#**event**: `string` * ThrowInfo#**operands**: `ExpressionRef[]` > * RethrowInfo#**exnref**: `ExpressionRef` > * BrOnExnInfo#**name**: `string` * BrOnExnInfo#**event**: `string` * BrOnExnInfo#**exnref**: `ExpressionRef` > * PopInfo > * PushInfo#**value**: `ExpressionRef` * **emitText**(expression: `ExpressionRef`): `string`<br /> Emits the expression in Binaryen's s-expression text format (not official stack-style text format). * **copyExpression**(expression: `ExpressionRef`): `ExpressionRef`<br /> Creates a deep copy of an expression. ### Relooper * new **Relooper**()<br /> Constructs a relooper instance. This lets you provide an arbitrary CFG, and the relooper will structure it for WebAssembly. * Relooper#**addBlock**(code: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block to the CFG, containing the provided code as its body. * Relooper#**addBranch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, condition: `ExpressionRef`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block to another block, with a condition (or nothing, if this is the default branch to take from the origin - each block must have one such branch), and optional code to execute on the branch (useful for phis). * Relooper#**addBlockWithSwitch**(code: `ExpressionRef`, condition: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block, which ends with a switch/br_table, with provided code and condition (that determines where we go in the switch). * Relooper#**addBranchForSwitch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, indexes: `number[]`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block ending in a switch, to another block, using an array of indexes that determine where to go, and optional code to execute on the branch. * Relooper#**renderAndDispose**(entry: `RelooperBlockRef`, labelHelper: `number`, module: `Module`): `ExpressionRef`<br /> Renders and cleans up the Relooper instance. Call this after you have created all the blocks and branches, giving it the entry block (where control flow begins), a label helper variable (an index of a local we can use, necessary for irreducible control flow), and the module. This returns an expression - normal WebAssembly code - that you can use normally anywhere. ### Source maps * Module#**addDebugInfoFileName**(filename: `string`): `number`<br /> Adds a debug info file name to the module and returns its index. * Module#**getDebugInfoFileName**(index: `number`): `string | null` <br /> Gets the name of the debug info file at the specified index. * Module#**setDebugLocation**(func: `FunctionRef`, expr: `ExpressionRef`, fileIndex: `number`, lineNumber: `number`, columnNumber: `number`): `void`<br /> Sets the debug location of the specified `ExpressionRef` within the specified `FunctionRef`. ### Debugging * Module#**interpret**(): `void`<br /> Runs the module in the interpreter, calling the start function. # axios // core The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are: - Dispatching requests - Managing interceptors - Handling config # randexp.js randexp will generate a random string that matches a given RegExp Javascript object. [![Build Status](https://secure.travis-ci.org/fent/randexp.js.svg)](http://travis-ci.org/fent/randexp.js) [![Dependency Status](https://david-dm.org/fent/randexp.js.svg)](https://david-dm.org/fent/randexp.js) [![codecov](https://codecov.io/gh/fent/randexp.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/randexp.js) # Usage ```js var RandExp = require('randexp'); // supports grouping and piping new RandExp(/hello+ (world|to you)/).gen(); // => hellooooooooooooooooooo world // sets and ranges and references new RandExp(/<([a-z]\w{0,20})>foo<\1>/).gen(); // => <m5xhdg>foo<m5xhdg> // wildcard new RandExp(/random stuff: .+/).gen(); // => random stuff: l3m;Hf9XYbI [YPaxV>U*4-_F!WXQh9>;rH3i l!8.zoh?[utt1OWFQrE ^~8zEQm]~tK // ignore case new RandExp(/xxx xtreme dragon warrior xxx/i).gen(); // => xxx xtReME dRAGON warRiOR xXX // dynamic regexp shortcut new RandExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i'); // is the same as new RandExp(new RegExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i')); ``` If you're only going to use `gen()` once with a regexp and want slightly shorter syntax for it ```js var randexp = require('randexp').randexp; randexp(/[1-6]/); // 4 randexp('great|good( job)?|excellent'); // great ``` If you miss the old syntax ```js require('randexp').sugar(); /yes|no|maybe|i don't know/.gen(); // maybe ``` # Motivation Regular expressions are used in every language, every programmer is familiar with them. Regex can be used to easily express complex strings. What better way to generate a random string than with a language you can use to express the string you want? Thanks to [String-Random](http://search.cpan.org/~steve/String-Random-0.22/lib/String/Random.pm) for giving me the idea to make this in the first place and [randexp](https://github.com/benburkert/randexp) for the sweet `.gen()` syntax. # Default Range The default generated character range includes printable ASCII. In order to add or remove characters, a `defaultRange` attribute is exposed. you can `subtract(from, to)` and `add(from, to)` ```js var randexp = new RandExp(/random stuff: .+/); randexp.defaultRange.subtract(32, 126); randexp.defaultRange.add(0, 65535); randexp.gen(); // => random stuff: 湐箻ໜ䫴␩⶛㳸長���邓蕲뤀쑡篷皇硬剈궦佔칗븛뀃匫鴔事좍ﯣ⭼ꝏ䭍詳蒂䥂뽭 ``` # Custom PRNG The default randomness is provided by `Math.random()`. If you need to use a seedable or cryptographic PRNG, you can override `RandExp.prototype.randInt` or `randexp.randInt` (where `randexp` is an instance of `RandExp`). `randInt(from, to)` accepts an inclusive range and returns a randomly selected number within that range. # Infinite Repetitionals Repetitional tokens such as `*`, `+`, and `{3,}` have an infinite max range. In this case, randexp looks at its min and adds 100 to it to get a useable max value. If you want to use another int other than 100 you can change the `max` property in `RandExp.prototype` or the RandExp instance. ```js var randexp = new RandExp(/no{1,}/); randexp.max = 1000000; ``` With `RandExp.sugar()` ```js var regexp = /(hi)*/; regexp.max = 1000000; ``` # Bad Regular Expressions There are some regular expressions which can never match any string. * Ones with badly placed positionals such as `/a^/` and `/$c/m`. Randexp will ignore positional tokens. * Back references to non-existing groups like `/(a)\1\2/`. Randexp will ignore those references, returning an empty string for them. If the group exists only after the reference is used such as in `/\1 (hey)/`, it will too be ignored. * Custom negated character sets with two sets inside that cancel each other out. Example: `/[^\w\W]/`. If you give this to randexp, it will return an empty string for this set since it can't match anything. # Projects based on randexp.js ## JSON-Schema Faker Use generators to populate JSON Schema samples. See: [jsf on github](https://github.com/json-schema-faker/json-schema-faker/) and [jsf demo page](http://json-schema-faker.js.org/). # Install ### Node.js npm install randexp ### Browser Download the [minified version](https://github.com/fent/randexp.js/releases) from the latest release. # Tests Tests are written with [mocha](https://mochajs.org) ```bash npm test ``` # License MIT # Regular Expression Tokenizer Tokenizes strings that represent a regular expressions. [![Build Status](https://secure.travis-ci.org/fent/ret.js.svg)](http://travis-ci.org/fent/ret.js) [![Dependency Status](https://david-dm.org/fent/ret.js.svg)](https://david-dm.org/fent/ret.js) [![codecov](https://codecov.io/gh/fent/ret.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/ret.js) # Usage ```js var ret = require('ret'); var tokens = ret(/foo|bar/.source); ``` `tokens` will contain the following object ```js { "type": ret.types.ROOT "options": [ [ { "type": ret.types.CHAR, "value", 102 }, { "type": ret.types.CHAR, "value", 111 }, { "type": ret.types.CHAR, "value", 111 } ], [ { "type": ret.types.CHAR, "value", 98 }, { "type": ret.types.CHAR, "value", 97 }, { "type": ret.types.CHAR, "value", 114 } ] ] } ``` # Token Types `ret.types` is a collection of the various token types exported by ret. ### ROOT Only used in the root of the regexp. This is needed due to the posibility of the root containing a pipe `|` character. In that case, the token will have an `options` key that will be an array of arrays of tokens. If not, it will contain a `stack` key that is an array of tokens. ```js { "type": ret.types.ROOT, "stack": [token1, token2...], } ``` ```js { "type": ret.types.ROOT, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### GROUP Groups contain tokens that are inside of a parenthesis. If the group begins with `?` followed by another character, it's a special type of group. A ':' tells the group not to be remembered when `exec` is used. '=' means the previous token matches only if followed by this group, and '!' means the previous token matches only if NOT followed. Like root, it can contain an `options` key instead of `stack` if there is a pipe. ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "stack": [token1, token2...], } ``` ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### POSITION `\b`, `\B`, `^`, and `$` specify positions in the regexp. ```js { "type": ret.types.POSITION, "value": "^", } ``` ### SET Contains a key `set` specifying what tokens are allowed and a key `not` specifying if the set should be negated. A set can contain other sets, ranges, and characters. ```js { "type": ret.types.SET, "set": [token1, token2...], "not": false, } ``` ### RANGE Used in set tokens to specify a character range. `from` and `to` are character codes. ```js { "type": ret.types.RANGE, "from": 97, "to": 122, } ``` ### REPETITION ```js { "type": ret.types.REPETITION, "min": 0, "max": Infinity, "value": token, } ``` ### REFERENCE References a group token. `value` is 1-9. ```js { "type": ret.types.REFERENCE, "value": 1, } ``` ### CHAR Represents a single character token. `value` is the character code. This might seem a bit cluttering instead of concatenating characters together. But since repetition tokens only repeat the last token and not the last clause like the pipe, it's simpler to do it this way. ```js { "type": ret.types.CHAR, "value": 123, } ``` ## Errors ret.js will throw errors if given a string with an invalid regular expression. All possible errors are * Invalid group. When a group with an immediate `?` character is followed by an invalid character. It can only be followed by `!`, `=`, or `:`. Example: `/(?_abc)/` * Nothing to repeat. Thrown when a repetitional token is used as the first token in the current clause, as in right in the beginning of the regexp or group, or right after a pipe. Example: `/foo|?bar/`, `/{1,3}foo|bar/`, `/foo(+bar)/` * Unmatched ). A group was not opened, but was closed. Example: `/hello)2u/` * Unterminated group. A group was not closed. Example: `/(1(23)4/` * Unterminated character class. A custom character set was not closed. Example: `/[abc/` # Install npm install ret # Tests Tests are written with [vows](http://vowsjs.org/) ```bash npm test ``` # License MIT # AssemblyScript Rtrace A tiny utility to sanitize the AssemblyScript runtime. Records allocations, retains, releases and frees performed by the runtime and emits an error if something is off. Also checks for leaks. Instructions ------------ Compile your module that uses the full or half runtime with `-use ASC_RTRACE=1 --explicitStart` and include an instance of this module as the import named `rtrace`. ```js var rtrace = new Rtrace({ onerror(err, info) { // handle error }, oninfo(msg) { // print message, optional }, getMemory() { // obtain the module's memory, // e.g. with --explicitStart: return instance.exports.memory; } }); var { module, instance } = await WebAssembly.instantiate(..., { rtrace, env: Object.assign({ // ... // only required when instrumenting memory }, rtrace.env), // ... }); instance.exports._start(); ... if (rtrace.active) { let leakCount = rtr.check(); if (leakCount) { // handle error } } ``` Note that references retained in globals which are not cleared before execution concludes appear as leaks, including their inner members. A TypedArray would leak itself and its backing ArrayBuffer in this case for example. This is perfectly normal and clearing all globals avoids this. # has > Object.prototype.hasOwnProperty.call shortcut ## Installation ```sh npm install --save has ``` ## Usage ```js var has = require('has'); has({}, 'hasOwnProperty'); // false has(Object.prototype, 'hasOwnProperty'); // true ``` # function-bind <!-- [![build status][travis-svg]][travis-url] [![NPM version][npm-badge-svg]][npm-url] [![Coverage Status][5]][6] [![gemnasium Dependency Status][7]][8] [![Dependency status][deps-svg]][deps-url] [![Dev Dependency status][dev-deps-svg]][dev-deps-url] --> <!-- [![browser support][11]][12] --> Implementation of function.prototype.bind ## Example I mainly do this for unit tests I run on phantomjs. PhantomJS does not have Function.prototype.bind :( ```js Function.prototype.bind = require("function-bind") ``` ## Installation `npm install function-bind` ## Contributors - Raynos ## MIT Licenced [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg [travis-url]: https://travis-ci.org/Raynos/function-bind [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg [npm-url]: https://npmjs.org/package/function-bind [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png [6]: https://coveralls.io/r/Raynos/function-bind [7]: https://gemnasium.com/Raynos/function-bind.png [8]: https://gemnasium.com/Raynos/function-bind [deps-svg]: https://david-dm.org/Raynos/function-bind.svg [deps-url]: https://david-dm.org/Raynos/function-bind [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies [11]: https://ci.testling.com/Raynos/function-bind.png [12]: https://ci.testling.com/Raynos/function-bind Like `chown -R`. Takes the same arguments as `fs.chown()` <p align="center"> <a href="https://assemblyscript.org" target="_blank" rel="noopener"><img width="100" src="https://avatars1.githubusercontent.com/u/28916798?s=200&v=4" alt="AssemblyScript logo"></a> </p> <p align="center"> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3ATest"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Test/master?label=test&logo=github" alt="Test status" /></a> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3APublish"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Publish/master?label=publish&logo=github" alt="Publish status" /></a> <a href="https://www.npmjs.com/package/assemblyscript"><img src="https://img.shields.io/npm/v/assemblyscript.svg?label=compiler&color=007acc&logo=npm" alt="npm compiler version" /></a> <a href="https://www.npmjs.com/package/@assemblyscript/loader"><img src="https://img.shields.io/npm/v/@assemblyscript/loader.svg?label=loader&color=007acc&logo=npm" alt="npm loader version" /></a> <a href="https://discord.gg/assemblyscript"><img src="https://img.shields.io/discord/721472913886281818.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2" alt="Discord online" /></a> </p> <p align="justify"><strong>AssemblyScript</strong> compiles a strict variant of <a href="http://www.typescriptlang.org">TypeScript</a> (basically JavaScript with types) to <a href="http://webassembly.org">WebAssembly</a> using <a href="https://github.com/WebAssembly/binaryen">Binaryen</a>. It generates lean and mean WebAssembly modules while being just an <code>npm install</code> away.</p> <h3 align="center"> <a href="https://assemblyscript.org">About</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/introduction.html">Introduction</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/quick-start.html">Quick&nbsp;start</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/examples.html">Examples</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/development.html">Development&nbsp;instructions</a> </h3> <br> <h2 align="center">Contributors</h2> <p align="center"> <a href="https://assemblyscript.org/#contributors"><img src="https://assemblyscript.org/contributors.svg" alt="Contributor logos" width="720" /></a> </p> <h2 align="center">Thanks to our sponsors!</h2> <p align="justify">Most of the core team members and most contributors do this open source work in their free time. If you use AssemblyScript for a serious task or plan to do so, and you'd like us to invest more time on it, <a href="https://opencollective.com/assemblyscript/donate" target="_blank" rel="noopener">please donate</a> to our <a href="https://opencollective.com/assemblyscript" target="_blank" rel="noopener">OpenCollective</a>. By sponsoring this project, your logo will show up below. Thank you so much for your support!</p> <p align="center"> <a href="https://assemblyscript.org/#sponsors"><img src="https://assemblyscript.org/sponsors.svg" alt="Sponsor logos" width="720" /></a> </p> # brace-expansion [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), as known from sh/bash, in JavaScript. [![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) [![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) [![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) [![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) ## Example ```js var expand = require('brace-expansion'); expand('file-{a,b,c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('-v{,,}') // => ['-v', '-v', '-v'] expand('file{0..2}.jpg') // => ['file0.jpg', 'file1.jpg', 'file2.jpg'] expand('file-{a..c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('file{2..0}.jpg') // => ['file2.jpg', 'file1.jpg', 'file0.jpg'] expand('file{0..4..2}.jpg') // => ['file0.jpg', 'file2.jpg', 'file4.jpg'] expand('file-{a..e..2}.jpg') // => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] expand('file{00..10..5}.jpg') // => ['file00.jpg', 'file05.jpg', 'file10.jpg'] expand('{{A..C},{a..c}}') // => ['A', 'B', 'C', 'a', 'b', 'c'] expand('ppp{,config,oe{,conf}}') // => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] ``` ## API ```js var expand = require('brace-expansion'); ``` ### var expanded = expand(str) Return an array of all possible and valid expansions of `str`. If none are found, `[str]` is returned. Valid expansions are: ```js /^(.*,)+(.+)?$/ // {a,b,...} ``` A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` A numeric sequence from `x` to `y` inclusive, with optional increment. If `x` or `y` start with a leading `0`, all the numbers will be padded to have equal length. Negative numbers and backwards iteration work too. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` An alphabetic sequence from `x` to `y` inclusive, with optional increment. `x` and `y` must be exactly one character, and if given, `incr` must be a number. For compatibility reasons, the string `${` is not eligible for brace expansion. ## Installation With [npm](https://npmjs.org) do: ```bash npm install brace-expansion ``` ## Contributors - [Julian Gruber](https://github.com/juliangruber) - [Isaac Z. Schlueter](https://github.com/isaacs) ## Sponsors This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # near-sdk-core This package contain a convenient interface for interacting with NEAR's host runtime. To see the functions that are provided by the host node see [`env.ts`](./assembly/env/env.ts). # ShellJS - Unix shell commands for Node.js [![Travis](https://img.shields.io/travis/shelljs/shelljs/master.svg?style=flat-square&label=unix)](https://travis-ci.org/shelljs/shelljs) [![AppVeyor](https://img.shields.io/appveyor/ci/shelljs/shelljs/master.svg?style=flat-square&label=windows)](https://ci.appveyor.com/project/shelljs/shelljs/branch/master) [![Codecov](https://img.shields.io/codecov/c/github/shelljs/shelljs/master.svg?style=flat-square&label=coverage)](https://codecov.io/gh/shelljs/shelljs) [![npm version](https://img.shields.io/npm/v/shelljs.svg?style=flat-square)](https://www.npmjs.com/package/shelljs) [![npm downloads](https://img.shields.io/npm/dm/shelljs.svg?style=flat-square)](https://www.npmjs.com/package/shelljs) ShellJS is a portable **(Windows/Linux/OS X)** implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts! ShellJS is proudly tested on every node release since `v4`! The project is [unit-tested](http://travis-ci.org/shelljs/shelljs) and battle-tested in projects like: + [Firebug](http://getfirebug.com/) - Firefox's infamous debugger + [JSHint](http://jshint.com) & [ESLint](http://eslint.org/) - popular JavaScript linters + [Zepto](http://zeptojs.com) - jQuery-compatible JavaScript library for modern browsers + [Yeoman](http://yeoman.io/) - Web application stack and development tool + [Deployd.com](http://deployd.com) - Open source PaaS for quick API backend generation + And [many more](https://npmjs.org/browse/depended/shelljs). If you have feedback, suggestions, or need help, feel free to post in our [issue tracker](https://github.com/shelljs/shelljs/issues). Think ShellJS is cool? Check out some related projects in our [Wiki page](https://github.com/shelljs/shelljs/wiki)! Upgrading from an older version? Check out our [breaking changes](https://github.com/shelljs/shelljs/wiki/Breaking-Changes) page to see what changes to watch out for while upgrading. ## Command line use If you just want cross platform UNIX commands, checkout our new project [shelljs/shx](https://github.com/shelljs/shx), a utility to expose `shelljs` to the command line. For example: ``` $ shx mkdir -p foo $ shx touch foo/bar.txt $ shx rm -rf foo ``` ## Plugin API ShellJS now supports third-party plugins! You can learn more about using plugins and writing your own ShellJS commands in [the wiki](https://github.com/shelljs/shelljs/wiki/Using-ShellJS-Plugins). ## A quick note about the docs For documentation on all the latest features, check out our [README](https://github.com/shelljs/shelljs). To read docs that are consistent with the latest release, check out [the npm page](https://www.npmjs.com/package/shelljs) or [shelljs.org](http://documentup.com/shelljs/shelljs). ## Installing Via npm: ```bash $ npm install [-g] shelljs ``` ## Examples ```javascript var shell = require('shelljs'); if (!shell.which('git')) { shell.echo('Sorry, this script requires git'); shell.exit(1); } // Copy files to release dir shell.rm('-rf', 'out/Release'); shell.cp('-R', 'stuff/', 'out/Release'); // Replace macros in each .js file shell.cd('lib'); shell.ls('*.js').forEach(function (file) { shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file); shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file); shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file); }); shell.cd('..'); // Run external tool synchronously if (shell.exec('git commit -am "Auto-commit"').code !== 0) { shell.echo('Error: Git commit failed'); shell.exit(1); } ``` ## Exclude options If you need to pass a parameter that looks like an option, you can do so like: ```js shell.grep('--', '-v', 'path/to/file'); // Search for "-v", no grep options shell.cp('-R', '-dir', 'outdir'); // If already using an option, you're done ``` ## Global vs. Local We no longer recommend using a global-import for ShellJS (i.e. `require('shelljs/global')`). While still supported for convenience, this pollutes the global namespace, and should therefore only be used with caution. Instead, we recommend a local import (standard for npm packages): ```javascript var shell = require('shelljs'); shell.echo('hello world'); ``` <!-- DO NOT MODIFY BEYOND THIS POINT - IT'S AUTOMATICALLY GENERATED --> ## Command reference All commands run synchronously, unless otherwise stated. All commands accept standard bash globbing characters (`*`, `?`, etc.), compatible with the [node `glob` module](https://github.com/isaacs/node-glob). For less-commonly used commands and features, please check out our [wiki page](https://github.com/shelljs/shelljs/wiki). ### cat([options,] file [, file ...]) ### cat([options,] file_array) Available options: + `-n`: number all output lines Examples: ```javascript var str = cat('file*.txt'); var str = cat('file1', 'file2'); var str = cat(['file1', 'file2']); // same as above ``` Returns a string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). ### cd([dir]) Changes to directory `dir` for the duration of the script. Changes to home directory if no argument is supplied. ### chmod([options,] octal_mode || octal_string, file) ### chmod([options,] symbolic_mode, file) Available options: + `-v`: output a diagnostic for every file processed + `-c`: like verbose, but report only when a change is made + `-R`: change files and directories recursively Examples: ```javascript chmod(755, '/Users/brandon'); chmod('755', '/Users/brandon'); // same as above chmod('u+x', '/Users/brandon'); chmod('-R', 'a-w', '/Users/brandon'); ``` Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions: + In symbolic modes, `a-r` and `-r` are identical. No consideration is given to the `umask`. + There is no "quiet" option, since default behavior is to run silent. ### cp([options,] source [, source ...], dest) ### cp([options,] source_array, dest) Available options: + `-f`: force (default behavior) + `-n`: no-clobber + `-u`: only copy if `source` is newer than `dest` + `-r`, `-R`: recursive + `-L`: follow symlinks + `-P`: don't follow symlinks Examples: ```javascript cp('file1', 'dir1'); cp('-R', 'path/to/dir/', '~/newCopy/'); cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above ``` Copies files. ### pushd([options,] [dir | '-N' | '+N']) Available options: + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. + `-q`: Supresses output to the console. Arguments: + `dir`: Sets the current working directory to the top of the stack, then executes the equivalent of `cd dir`. + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. Examples: ```javascript // process.cwd() === '/usr' pushd('/etc'); // Returns /etc /usr pushd('+1'); // Returns /usr /etc ``` Save the current directory on the top of the directory stack and then `cd` to `dir`. With no arguments, `pushd` exchanges the top two directories. Returns an array of paths in the stack. ### popd([options,] ['-N' | '+N']) Available options: + `-n`: Suppress the normal directory change when removing directories from the stack, so that only the stack is manipulated. + `-q`: Supresses output to the console. Arguments: + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. Examples: ```javascript echo(process.cwd()); // '/usr' pushd('/etc'); // '/etc /usr' echo(process.cwd()); // '/etc' popd(); // '/usr' echo(process.cwd()); // '/usr' ``` When no arguments are given, `popd` removes the top directory from the stack and performs a `cd` to the new top directory. The elements are numbered from 0, starting at the first directory listed with dirs (i.e., `popd` is equivalent to `popd +0`). Returns an array of paths in the stack. ### dirs([options | '+N' | '-N']) Available options: + `-c`: Clears the directory stack by deleting all of the elements. + `-q`: Supresses output to the console. Arguments: + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if `+N` or `-N` was specified. See also: `pushd`, `popd` ### echo([options,] string [, string ...]) Available options: + `-e`: interpret backslash escapes (default) + `-n`: remove trailing newline from output Examples: ```javascript echo('hello world'); var str = echo('hello world'); echo('-n', 'no newline at end'); ``` Prints `string` to stdout, and returns string with additional utility methods like `.to()`. ### exec(command [, options] [, callback]) Available options: + `async`: Asynchronous execution. If a callback is provided, it will be set to `true`, regardless of the passed value (default: `false`). + `silent`: Do not echo program output to console (default: `false`). + `encoding`: Character encoding to use. Affects the values returned to stdout and stderr, and what is written to stdout and stderr when not in silent mode (default: `'utf8'`). + and any option available to Node.js's [`child_process.exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) Examples: ```javascript var version = exec('node --version', {silent:true}).stdout; var child = exec('some_long_running_process', {async:true}); child.stdout.on('data', function(data) { /* ... do something with data ... */ }); exec('some_long_running_process', function(code, stdout, stderr) { console.log('Exit code:', code); console.log('Program output:', stdout); console.log('Program stderr:', stderr); }); ``` Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous mode, this returns a `ShellString` (compatible with ShellJS v0.6.x, which returns an object of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process object, and the `callback` receives the arguments `(code, stdout, stderr)`. Not seeing the behavior you want? `exec()` runs everything through `sh` by default (or `cmd.exe` on Windows), which differs from `bash`. If you need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. ### find(path [, path ...]) ### find(path_array) Examples: ```javascript find('src', 'lib'); find(['src', 'lib']); // same as above find('.').filter(function(file) { return file.match(/\.js$/); }); ``` Returns array of all files (however deep) in the given paths. The main difference from `ls('-R', path)` is that the resulting file names include the base directories (e.g., `lib/resources/file1` instead of just `file1`). ### grep([options,] regex_filter, file [, file ...]) ### grep([options,] regex_filter, file_array) Available options: + `-v`: Invert `regex_filter` (only print non-matching lines). + `-l`: Print only filenames of matching files. + `-i`: Ignore case. Examples: ```javascript grep('-v', 'GLOBAL_VARIABLE', '*.js'); grep('GLOBAL_VARIABLE', '*.js'); ``` Reads input string from given files and returns a string containing all lines of the file that match the given `regex_filter`. ### head([{'-n': \<num\>},] file [, file ...]) ### head([{'-n': \<num\>},] file_array) Available options: + `-n <num>`: Show the first `<num>` lines of the files Examples: ```javascript var str = head({'-n': 1}, 'file*.txt'); var str = head('file1', 'file2'); var str = head(['file1', 'file2']); // same as above ``` Read the start of a file. ### ln([options,] source, dest) Available options: + `-s`: symlink + `-f`: force Examples: ```javascript ln('file', 'newlink'); ln('-sf', 'file', 'existing'); ``` Links `source` to `dest`. Use `-f` to force the link, should `dest` already exist. ### ls([options,] [path, ...]) ### ls([options,] path_array) Available options: + `-R`: recursive + `-A`: all files (include files beginning with `.`, except for `.` and `..`) + `-L`: follow symlinks + `-d`: list directories themselves, not their contents + `-l`: list objects representing each file, each with fields containing `ls -l` output fields. See [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) for more info Examples: ```javascript ls('projs/*.js'); ls('-R', '/users/me', '/tmp'); ls('-R', ['/users/me', '/tmp']); // same as above ls('-l', 'file.txt'); // { name: 'file.txt', mode: 33188, nlink: 1, ...} ``` Returns array of files in the given `path`, or files in the current directory if no `path` is provided. ### mkdir([options,] dir [, dir ...]) ### mkdir([options,] dir_array) Available options: + `-p`: full path (and create intermediate directories, if necessary) Examples: ```javascript mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above ``` Creates directories. ### mv([options ,] source [, source ...], dest') ### mv([options ,] source_array, dest') Available options: + `-f`: force (default behavior) + `-n`: no-clobber Examples: ```javascript mv('-n', 'file', 'dir/'); mv('file1', 'file2', 'dir/'); mv(['file1', 'file2'], 'dir/'); // same as above ``` Moves `source` file(s) to `dest`. ### pwd() Returns the current directory. ### rm([options,] file [, file ...]) ### rm([options,] file_array) Available options: + `-f`: force + `-r, -R`: recursive Examples: ```javascript rm('-rf', '/tmp/*'); rm('some_file.txt', 'another_file.txt'); rm(['some_file.txt', 'another_file.txt']); // same as above ``` Removes files. ### sed([options,] search_regex, replacement, file [, file ...]) ### sed([options,] search_regex, replacement, file_array) Available options: + `-i`: Replace contents of `file` in-place. _Note that no backups will be created!_ Examples: ```javascript sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); ``` Reads an input string from `file`s, and performs a JavaScript `replace()` on the input using the given `search_regex` and `replacement` string or function. Returns the new string after replacement. Note: Like unix `sed`, ShellJS `sed` supports capture groups. Capture groups are specified using the `$n` syntax: ```javascript sed(/(\w+)\s(\w+)/, '$2, $1', 'file.txt'); ``` ### set(options) Available options: + `+/-e`: exit upon error (`config.fatal`) + `+/-v`: verbose: show all commands (`config.verbose`) + `+/-f`: disable filename expansion (globbing) Examples: ```javascript set('-e'); // exit upon first error set('+e'); // this undoes a "set('-e')" ``` Sets global configuration variables. ### sort([options,] file [, file ...]) ### sort([options,] file_array) Available options: + `-r`: Reverse the results + `-n`: Compare according to numerical value Examples: ```javascript sort('foo.txt', 'bar.txt'); sort('-r', 'foo.txt'); ``` Return the contents of the `file`s, sorted line-by-line. Sorting multiple files mixes their content (just as unix `sort` does). ### tail([{'-n': \<num\>},] file [, file ...]) ### tail([{'-n': \<num\>},] file_array) Available options: + `-n <num>`: Show the last `<num>` lines of `file`s Examples: ```javascript var str = tail({'-n': 1}, 'file*.txt'); var str = tail('file1', 'file2'); var str = tail(['file1', 'file2']); // same as above ``` Read the end of a `file`. ### tempdir() Examples: ```javascript var tmp = tempdir(); // "/tmp" for most *nix platforms ``` Searches and returns string containing a writeable, platform-dependent temporary directory. Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). ### test(expression) Available expression primaries: + `'-b', 'path'`: true if path is a block device + `'-c', 'path'`: true if path is a character device + `'-d', 'path'`: true if path is a directory + `'-e', 'path'`: true if path exists + `'-f', 'path'`: true if path is a regular file + `'-L', 'path'`: true if path is a symbolic link + `'-p', 'path'`: true if path is a pipe (FIFO) + `'-S', 'path'`: true if path is a socket Examples: ```javascript if (test('-d', path)) { /* do something with dir */ }; if (!test('-f', path)) continue; // skip if it's a regular file ``` Evaluates `expression` using the available primaries and returns corresponding value. ### ShellString.prototype.to(file) Examples: ```javascript cat('input.txt').to('output.txt'); ``` Analogous to the redirection operator `>` in Unix, but works with `ShellStrings` (such as those returned by `cat`, `grep`, etc.). _Like Unix redirections, `to()` will overwrite any existing file!_ ### ShellString.prototype.toEnd(file) Examples: ```javascript cat('input.txt').toEnd('output.txt'); ``` Analogous to the redirect-and-append operator `>>` in Unix, but works with `ShellStrings` (such as those returned by `cat`, `grep`, etc.). ### touch([options,] file [, file ...]) ### touch([options,] file_array) Available options: + `-a`: Change only the access time + `-c`: Do not create any files + `-m`: Change only the modification time + `-d DATE`: Parse `DATE` and use it instead of current time + `-r FILE`: Use `FILE`'s times instead of current time Examples: ```javascript touch('source.js'); touch('-c', '/path/to/some/dir/source.js'); touch({ '-r': FILE }, '/path/to/some/dir/source.js'); ``` Update the access and modification times of each `FILE` to the current time. A `FILE` argument that does not exist is created empty, unless `-c` is supplied. This is a partial implementation of [`touch(1)`](http://linux.die.net/man/1/touch). ### uniq([options,] [input, [output]]) Available options: + `-i`: Ignore case while comparing + `-c`: Prefix lines by the number of occurrences + `-d`: Only print duplicate lines, one for each group of identical lines Examples: ```javascript uniq('foo.txt'); uniq('-i', 'foo.txt'); uniq('-cd', 'foo.txt', 'bar.txt'); ``` Filter adjacent matching lines from `input`. ### which(command) Examples: ```javascript var nodeExec = which('node'); ``` Searches for `command` in the system's `PATH`. On Windows, this uses the `PATHEXT` variable to append the extension if it's not already executable. Returns string containing the absolute path to `command`. ### exit(code) Exits the current process with the given exit `code`. ### error() Tests if error occurred in the last command. Returns a truthy value if an error returned, or a falsy value otherwise. **Note**: do not rely on the return value to be an error message. If you need the last error message, use the `.stderr` attribute from the last command's return value instead. ### ShellString(str) Examples: ```javascript var foo = ShellString('hello world'); ``` Turns a regular string into a string-like object similar to what each command returns. This has special methods, like `.to()` and `.toEnd()`. ### env['VAR_NAME'] Object containing environment variables (both getter and setter). Shortcut to `process.env`. ### Pipes Examples: ```javascript grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); echo('files with o\'s in the name:\n' + ls().grep('o')); cat('test.js').exec('node'); // pipe to exec() call ``` Commands can send their output to another command in a pipe-like fashion. `sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand side of a pipe. Pipes can be chained. ## Configuration ### config.silent Example: ```javascript var sh = require('shelljs'); var silentState = sh.config.silent; // save old silent state sh.config.silent = true; /* ... */ sh.config.silent = silentState; // restore old silent state ``` Suppresses all command output if `true`, except for `echo()` calls. Default is `false`. ### config.fatal Example: ```javascript require('shelljs/global'); config.fatal = true; // or set('-e'); cp('this_file_does_not_exist', '/dev/null'); // throws Error here /* more commands... */ ``` If `true`, the script will throw a Javascript error when any shell.js command encounters an error. Default is `false`. This is analogous to Bash's `set -e`. ### config.verbose Example: ```javascript config.verbose = true; // or set('-v'); cd('dir/'); rm('-rf', 'foo.txt', 'bar.txt'); exec('echo hello'); ``` Will print each command as follows: ``` cd dir/ rm -rf foo.txt bar.txt exec echo hello ``` ### config.globOptions Example: ```javascript config.globOptions = {nodir: true}; ``` Use this value for calls to `glob.sync()` instead of the default options. ### config.reset() Example: ```javascript var shell = require('shelljs'); // Make changes to shell.config, and do stuff... /* ... */ shell.config.reset(); // reset to original state // Do more stuff, but with original settings /* ... */ ``` Reset `shell.config` to the defaults: ```javascript { fatal: false, globOptions: {}, maxdepth: 255, noglob: false, silent: false, verbose: false, } ``` ## Team | [![Nate Fischer](https://avatars.githubusercontent.com/u/5801521?s=130)](https://github.com/nfischer) | [![Brandon Freitag](https://avatars1.githubusercontent.com/u/5988055?v=3&s=130)](http://github.com/freitagbr) | |:---:|:---:| | [Nate Fischer](https://github.com/nfischer) | [Brandon Freitag](http://github.com/freitagbr) | # Visitor utilities for AssemblyScript Compiler transformers ## Example ### List Fields The transformer: ```ts import { ClassDeclaration, FieldDeclaration, MethodDeclaration, } from "../../as"; import { ClassDecorator, registerDecorator } from "../decorator"; import { toString } from "../utils"; class ListMembers extends ClassDecorator { visitFieldDeclaration(node: FieldDeclaration): void { if (!node.name) console.log(toString(node) + "\n"); const name = toString(node.name); const _type = toString(node.type!); this.stdout.write(name + ": " + _type + "\n"); } visitMethodDeclaration(node: MethodDeclaration): void { const name = toString(node.name); if (name == "constructor") { return; } const sig = toString(node.signature); this.stdout.write(name + ": " + sig + "\n"); } visitClassDeclaration(node: ClassDeclaration): void { this.visit(node.members); } get name(): string { return "list"; } } export = registerDecorator(new ListMembers()); ``` assembly/foo.ts: ```ts @list class Foo { a: u8; b: bool; i: i32; } ``` And then compile with `--transform` flag: ``` asc assembly/foo.ts --transform ./dist/examples/list --noEmit ``` Which prints the following to the console: ``` a: u8 b: bool i: i32 ``` # Web IDL Type Conversions on JavaScript Values This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). The goal is that you should be able to write code like ```js "use strict"; const conversions = require("webidl-conversions"); function doStuff(x, y) { x = conversions["boolean"](x); y = conversions["unsigned long"](y); // actual algorithm code here } ``` and your function `doStuff` will behave the same as a Web IDL operation declared as ```webidl void doStuff(boolean x, unsigned long y); ``` ## API This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`) Specific conversions may also accept other options, the details of which can be found below. ## Conversions implemented Conversions for all of the basic types from the Web IDL specification are implemented: - [`any`](https://heycam.github.io/webidl/#es-any) - [`void`](https://heycam.github.io/webidl/#es-void) - [`boolean`](https://heycam.github.io/webidl/#es-boolean) - [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter - [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float) - [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double) - [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter - [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString) - [`object`](https://heycam.github.io/webidl/#es-object) - [`Error`](https://heycam.github.io/webidl/#es-Error) - [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types) Additionally, for convenience, the following derived type definitions are implemented: - [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView) - [`BufferSource`](https://heycam.github.io/webidl/#BufferSource) - [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp) - [`Function`](https://heycam.github.io/webidl/#Function) - [`VoidFunction`](https://heycam.github.io/webidl/#VoidFunction) (although it will not censor the return type) Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project. ### A note on the `long long` types The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers, so the conversion is imperfect. For example, converting the JavaScript number `18446744073709552000` to a Web IDL `long long` is supposed to produce the Web IDL value `-18446744073709551232`. Since we are representing our Web IDL values in JavaScript, we can't represent `-18446744073709551232`, so we instead the best we could do is `-18446744073709552000` as the output. This library actually doesn't even get that far. Producing those results would require doing accurate modular arithmetic on 64-bit intermediate values, but JavaScript does not make this easy. We could pull in a big-integer library as a dependency, but in lieu of that, we for now have decided to just produce inaccurate results if you pass in numbers that are not strictly between `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER`. ## Background What's actually going on here, conceptually, is pretty weird. Let's try to explain. Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on. Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell. And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`. ## Don't use this Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript. The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/tmpvar/jsdom) project. A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Notation ### Prefixes There are several prefixes to instructions that affect the way the work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this tricks one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime # fs.realpath A backwards-compatible fs.realpath for Node v6 and above In Node v6, the JavaScript implementation of fs.realpath was replaced with a faster (but less resilient) native implementation. That raises new and platform-specific errors and cannot handle long or excessively symlink-looping paths. This module handles those cases by detecting the new errors and falling back to the JavaScript implementation. On versions of Node prior to v6, it has no effect. ## USAGE ```js var rp = require('fs.realpath') // async version rp.realpath(someLongAndLoopingPath, function (er, real) { // the ELOOP was handled, but it was a bit slower }) // sync version var real = rp.realpathSync(someLongAndLoopingPath) // monkeypatch at your own risk! // This replaces the fs.realpath/fs.realpathSync builtins rp.monkeypatch() // un-do the monkeypatching rp.unmonkeypatch() ``` bs58 ==== [![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58) JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin. **Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library. Install ------- npm i --save bs58 API --- ### encode(input) `input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`. **example**: ```js const bs58 = require('bs58') const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex') const address = bs58.encode(bytes) console.log(address) // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS ``` ### decode(input) `input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html). **example**: ```js const bs58 = require('bs58') const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS' const bytes = bs58.decode(address) console.log(out.toString('hex')) // => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187 ``` Hack / Test ----------- Uses JavaScript standard style. Read more: [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Credits ------- - [Mike Hearn](https://github.com/mikehearn) for original Java implementation - [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript - [Stephan Pair](https://github.com/gasteve) for buffer improvements - [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib - [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency License ------- MIT # which-module > Find the module object for something that was require()d [![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module) [![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) Find the `module` object in `require.cache` for something that was `require()`d or `import`ed - essentially a reverse `require()` lookup. Useful for libs that want to e.g. lookup a filename for a module or submodule that it did not `require()` itself. ## Install and Usage ``` npm install --save which-module ``` ```js const whichModule = require('which-module') console.log(whichModule(require('something'))) // Module { // id: '/path/to/project/node_modules/something/index.js', // exports: [Function], // parent: ..., // filename: '/path/to/project/node_modules/something/index.js', // loaded: true, // children: [], // paths: [ '/path/to/project/node_modules/something/node_modules', // '/path/to/project/node_modules', // '/path/to/node_modules', // '/path/node_modules', // '/node_modules' ] } ``` ## API ### `whichModule(exported)` Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object), if any, that represents the given argument in the `require.cache`. `exported` can be anything that was previously `require()`d or `import`ed as a module, submodule, or dependency - which means `exported` is identical to the `module.exports` returned by this method. If `exported` did not come from the `exports` of a `module` in `require.cache`, then this method returns `null`. ## License ISC © Contributors # Near Bindings Generator Transforms the Assembyscript AST to serialize exported functions and add `encode` and `decode` functions for generating and parsing JSON strings. ## Using via CLI After installling, `npm install nearprotocol/near-bindgen-as`, it can be added to the cli arguments of the assemblyscript compiler you must add the following: ```bash asc <file> --transform near-bindgen-as ... ``` This module also adds a binary `near-asc` which adds the default arguments required to build near contracts as well as the transformer. ```bash near-asc <input file> <output file> ``` ## Using a script to compile Another way is to add a file such as `asconfig.js` such as: ```js const compile = require("near-bindgen-as/compiler").compile; compile("assembly/index.ts", // input file "out/index.wasm", // output file [ // "-O1", // Optional arguments "--debug", "--measure" ], // Prints out the final cli arguments passed to compiler. {verbose: true} ); ``` It can then be built with `node asconfig.js`. There is an example of this in the test directory. # lodash.sortby v4.7.0 The [lodash](https://lodash.com/) method `_.sortBy` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.sortby ``` In Node.js: ```js var sortBy = require('lodash.sortby'); ``` See the [documentation](https://lodash.com/docs#sortBy) or [package source](https://github.com/lodash/lodash/blob/4.7.0-npm-packages/lodash.sortby) for more details. # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows note On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Note that PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Then, run the program to be debugged as usual. ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # inflight Add callbacks to requests in flight to avoid async duplication ## USAGE ```javascript var inflight = require('inflight') // some request that does some stuff function req(key, callback) { // key is any random string. like a url or filename or whatever. // // will return either a falsey value, indicating that the // request for this key is already in flight, or a new callback // which when called will call all callbacks passed to inflightk // with the same key callback = inflight(key, callback) // If we got a falsey value back, then there's already a req going if (!callback) return // this is where you'd fetch the url or whatever // callback is also once()-ified, so it can safely be assigned // to multiple events etc. First call wins. setTimeout(function() { callback(null, key) }, 100) } // only assigns a single setTimeout // when it dings, all cbs get called req('foo', cb1) req('foo', cb2) req('foo', cb3) req('foo', cb4) ``` long.js ======= A Long class for representing a 64 bit two's-complement integer value derived from the [Closure Library](https://github.com/google/closure-library) for stand-alone use and extended with unsigned support. [![Build Status](https://travis-ci.org/dcodeIO/long.js.svg)](https://travis-ci.org/dcodeIO/long.js) Background ---------- As of [ECMA-262 5th Edition](http://ecma262-5.com/ELS5_HTML.htm#Section_8.5), "all the positive and negative integers whose magnitude is no greater than 2<sup>53</sup> are representable in the Number type", which is "representing the doubleprecision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic". The [maximum safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) in JavaScript is 2<sup>53</sup>-1. Example: 2<sup>64</sup>-1 is 1844674407370955**1615** but in JavaScript it evaluates to 1844674407370955**2000**. Furthermore, bitwise operators in JavaScript "deal only with integers in the range −2<sup>31</sup> through 2<sup>31</sup>−1, inclusive, or in the range 0 through 2<sup>32</sup>−1, inclusive. These operators accept any value of the Number type but first convert each such value to one of 2<sup>32</sup> integer values." In some use cases, however, it is required to be able to reliably work with and perform bitwise operations on the full 64 bits. This is where long.js comes into play. Usage ----- The class is compatible with CommonJS and AMD loaders and is exposed globally as `Long` if neither is available. ```javascript var Long = require("long"); var longVal = new Long(0xFFFFFFFF, 0x7FFFFFFF); console.log(longVal.toString()); ... ``` API --- ### Constructor * new **Long**(low: `number`, high: `number`, unsigned?: `boolean`)<br /> Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. See the from* functions below for more convenient ways of constructing Longs. ### Fields * Long#**low**: `number`<br /> The low 32 bits as a signed value. * Long#**high**: `number`<br /> The high 32 bits as a signed value. * Long#**unsigned**: `boolean`<br /> Whether unsigned or not. ### Constants * Long.**ZERO**: `Long`<br /> Signed zero. * Long.**ONE**: `Long`<br /> Signed one. * Long.**NEG_ONE**: `Long`<br /> Signed negative one. * Long.**UZERO**: `Long`<br /> Unsigned zero. * Long.**UONE**: `Long`<br /> Unsigned one. * Long.**MAX_VALUE**: `Long`<br /> Maximum signed value. * Long.**MIN_VALUE**: `Long`<br /> Minimum signed value. * Long.**MAX_UNSIGNED_VALUE**: `Long`<br /> Maximum unsigned value. ### Utility * Long.**isLong**(obj: `*`): `boolean`<br /> Tests if the specified object is a Long. * Long.**fromBits**(lowBits: `number`, highBits: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. * Long.**fromBytes**(bytes: `number[]`, unsigned?: `boolean`, le?: `boolean`): `Long`<br /> Creates a Long from its byte representation. * Long.**fromBytesLE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its little endian byte representation. * Long.**fromBytesBE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its big endian byte representation. * Long.**fromInt**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given 32 bit integer value. * Long.**fromNumber**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. * Long.**fromString**(str: `string`, unsigned?: `boolean`, radix?: `number`)<br /> Long.**fromString**(str: `string`, radix: `number`)<br /> Returns a Long representation of the given string, written using the specified radix. * Long.**fromValue**(val: `*`, unsigned?: `boolean`): `Long`<br /> Converts the specified value to a Long using the appropriate from* function for its type. ### Methods * Long#**add**(addend: `Long | number | string`): `Long`<br /> Returns the sum of this and the specified Long. * Long#**and**(other: `Long | number | string`): `Long`<br /> Returns the bitwise AND of this Long and the specified. * Long#**compare**/**comp**(other: `Long | number | string`): `number`<br /> Compares this Long's value with the specified's. Returns `0` if they are the same, `1` if the this is greater and `-1` if the given one is greater. * Long#**divide**/**div**(divisor: `Long | number | string`): `Long`<br /> Returns this Long divided by the specified. * Long#**equals**/**eq**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value equals the specified's. * Long#**getHighBits**(): `number`<br /> Gets the high 32 bits as a signed integer. * Long#**getHighBitsUnsigned**(): `number`<br /> Gets the high 32 bits as an unsigned integer. * Long#**getLowBits**(): `number`<br /> Gets the low 32 bits as a signed integer. * Long#**getLowBitsUnsigned**(): `number`<br /> Gets the low 32 bits as an unsigned integer. * Long#**getNumBitsAbs**(): `number`<br /> Gets the number of bits needed to represent the absolute value of this Long. * Long#**greaterThan**/**gt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than the specified's. * Long#**greaterThanOrEqual**/**gte**/**ge**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than or equal the specified's. * Long#**isEven**(): `boolean`<br /> Tests if this Long's value is even. * Long#**isNegative**(): `boolean`<br /> Tests if this Long's value is negative. * Long#**isOdd**(): `boolean`<br /> Tests if this Long's value is odd. * Long#**isPositive**(): `boolean`<br /> Tests if this Long's value is positive. * Long#**isZero**/**eqz**(): `boolean`<br /> Tests if this Long's value equals zero. * Long#**lessThan**/**lt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than the specified's. * Long#**lessThanOrEqual**/**lte**/**le**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than or equal the specified's. * Long#**modulo**/**mod**/**rem**(divisor: `Long | number | string`): `Long`<br /> Returns this Long modulo the specified. * Long#**multiply**/**mul**(multiplier: `Long | number | string`): `Long`<br /> Returns the product of this and the specified Long. * Long#**negate**/**neg**(): `Long`<br /> Negates this Long's value. * Long#**not**(): `Long`<br /> Returns the bitwise NOT of this Long. * Long#**notEquals**/**neq**/**ne**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value differs from the specified's. * Long#**or**(other: `Long | number | string`): `Long`<br /> Returns the bitwise OR of this Long and the specified. * Long#**shiftLeft**/**shl**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits shifted to the left by the given amount. * Long#**shiftRight**/**shr**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits arithmetically shifted to the right by the given amount. * Long#**shiftRightUnsigned**/**shru**/**shr_u**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits logically shifted to the right by the given amount. * Long#**subtract**/**sub**(subtrahend: `Long | number | string`): `Long`<br /> Returns the difference of this and the specified Long. * Long#**toBytes**(le?: `boolean`): `number[]`<br /> Converts this Long to its byte representation. * Long#**toBytesLE**(): `number[]`<br /> Converts this Long to its little endian byte representation. * Long#**toBytesBE**(): `number[]`<br /> Converts this Long to its big endian byte representation. * Long#**toInt**(): `number`<br /> Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. * Long#**toNumber**(): `number`<br /> Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). * Long#**toSigned**(): `Long`<br /> Converts this Long to signed. * Long#**toString**(radix?: `number`): `string`<br /> Converts the Long to a string written in the specified radix. * Long#**toUnsigned**(): `Long`<br /> Converts this Long to unsigned. * Long#**xor**(other: `Long | number | string`): `Long`<br /> Returns the bitwise XOR of this Long and the given one. Building -------- To build an UMD bundle to `dist/long.js`, run: ``` $> npm install $> npm run build ``` Running the [tests](./tests): ``` $> npm test ``` # Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: * [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) * [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) * [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) * [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) * [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install punycode --save ``` In [Node.js](https://nodejs.org/): ```js const punycode = require('punycode'); ``` ## API ### `punycode.decode(string)` Converts a Punycode string of ASCII symbols to a string of Unicode symbols. ```js // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` ### `punycode.encode(string)` Converts a string of Unicode symbols to a Punycode string of ASCII symbols. ```js // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` ### `punycode.toUnicode(input)` Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. ```js // decode domain names punycode.toUnicode('xn--maana-pta.com'); // → 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // → '☃-⌘.com' // decode email addresses punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); // → 'джумла@джpумлатест.bрфa' ``` ### `punycode.toASCII(input)` Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. ```js // encode domain names punycode.toASCII('mañana.com'); // → 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // → 'xn----dqo34k.com' // encode email addresses punycode.toASCII('джумла@джpумлатест.bрфa'); // → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' ``` ### `punycode.ucs2` #### `punycode.ucs2.decode(string)` Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. ```js punycode.ucs2.decode('abc'); // → [0x61, 0x62, 0x63] // surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: punycode.ucs2.decode('\uD834\uDF06'); // → [0x1D306] ``` #### `punycode.ucs2.encode(codePoints)` Creates a string based on an array of numeric code point values. ```js punycode.ucs2.encode([0x61, 0x62, 0x63]); // → 'abc' punycode.ucs2.encode([0x1D306]); // → '\uD834\uDF06' ``` ### `punycode.version` A string representing the current Punycode.js version number. ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License Punycode.js is available under the [MIT](https://mths.be/mit) license. ![](cow.png) Moo! ==== Moo is a highly-optimised tokenizer/lexer generator. Use it to tokenize your strings, before parsing 'em with a parser like [nearley](https://github.com/hardmath123/nearley) or whatever else you're into. * [Fast](#is-it-fast) * [Convenient](#usage) * uses [Regular Expressions](#on-regular-expressions) * tracks [Line Numbers](#line-numbers) * handles [Keywords](#keywords) * supports [States](#states) * custom [Errors](#errors) * is even [Iterable](#iteration) * has no dependencies * 4KB minified + gzipped * Moo! Is it fast? ----------- Yup! Flying-cows-and-singed-steak fast. Moo is the fastest JS tokenizer around. It's **~2–10x** faster than most other tokenizers; it's a **couple orders of magnitude** faster than some of the slower ones. Define your tokens **using regular expressions**. Moo will compile 'em down to a **single RegExp for performance**. It uses the new ES6 **sticky flag** where possible to make things faster; otherwise it falls back to an almost-as-efficient workaround. (For more than you ever wanted to know about this, read [adventures in the land of substrings and RegExps](http://mrale.ph/blog/2016/11/23/making-less-dart-faster.html).) You _might_ be able to go faster still by writing your lexer by hand rather than using RegExps, but that's icky. Oh, and it [avoids parsing RegExps by itself](https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983#.2l8qu3l76). Because that would be horrible. Usage ----- First, you need to do the needful: `$ npm install moo`, or whatever will ship this code to your computer. Alternatively, grab the `moo.js` file by itself and slap it into your web page via a `<script>` tag; moo is completely standalone. Then you can start roasting your very own lexer/tokenizer: ```js const moo = require('moo') let lexer = moo.compile({ WS: /[ \t]+/, comment: /\/\/.*?$/, number: /0|[1-9][0-9]*/, string: /"(?:\\["\\]|[^\n"\\])*"/, lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], NL: { match: /\n/, lineBreaks: true }, }) ``` And now throw some text at it: ```js lexer.reset('while (10) cows\nmoo') lexer.next() // -> { type: 'keyword', value: 'while' } lexer.next() // -> { type: 'WS', value: ' ' } lexer.next() // -> { type: 'lparen', value: '(' } lexer.next() // -> { type: 'number', value: '10' } // ... ``` When you reach the end of Moo's internal buffer, next() will return `undefined`. You can always `reset()` it and feed it more data when that happens. On Regular Expressions ---------------------- RegExps are nifty for making tokenizers, but they can be a bit of a pain. Here are some things to be aware of: * You often want to use **non-greedy quantifiers**: e.g. `*?` instead of `*`. Otherwise your tokens will be longer than you expect: ```js let lexer = moo.compile({ string: /".*"/, // greedy quantifier * // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo" "bar' } ``` Better: ```js let lexer = moo.compile({ string: /".*?"/, // non-greedy quantifier *? // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo' } lexer.next() // -> { type: 'space', value: ' ' } lexer.next() // -> { type: 'string', value: 'bar' } ``` * The **order of your rules** matters. Earlier ones will take precedence. ```js moo.compile({ identifier: /[a-z0-9]+/, number: /[0-9]+/, }).reset('42').next() // -> { type: 'identifier', value: '42' } moo.compile({ number: /[0-9]+/, identifier: /[a-z0-9]+/, }).reset('42').next() // -> { type: 'number', value: '42' } ``` * Moo uses **multiline RegExps**. This has a few quirks: for example, the **dot `/./` doesn't include newlines**. Use `[^]` instead if you want to match newlines too. * Since an excluding character ranges like `/[^ ]/` (which matches anything but a space) _will_ include newlines, you have to be careful not to include them by accident! In particular, the whitespace metacharacter `\s` includes newlines. Line Numbers ------------ Moo tracks detailed information about the input for you. It will track line numbers, as long as you **apply the `lineBreaks: true` option to any rules which might contain newlines**. Moo will try to warn you if you forget to do this. Note that this is `false` by default, for performance reasons: counting the number of lines in a matched token has a small cost. For optimal performance, only match newlines inside a dedicated token: ```js newline: {match: '\n', lineBreaks: true}, ``` ### Token Info ### Token objects (returned from `next()`) have the following attributes: * **`type`**: the name of the group, as passed to compile. * **`text`**: the string that was matched. * **`value`**: the string that was matched, transformed by your `value` function (if any). * **`offset`**: the number of bytes from the start of the buffer where the match starts. * **`lineBreaks`**: the number of line breaks found in the match. (Always zero if this rule has `lineBreaks: false`.) * **`line`**: the line number of the beginning of the match, starting from 1. * **`col`**: the column where the match begins, starting from 1. ### Value vs. Text ### The `value` is the same as the `text`, unless you provide a [value transform](#transform). ```js const moo = require('moo') const lexer = moo.compile({ ws: /[ \t]+/, string: {match: /"(?:\\["\\]|[^\n"\\])*"/, value: s => s.slice(1, -1)}, }) lexer.reset('"test"') lexer.next() /* { value: 'test', text: '"test"', ... } */ ``` ### Reset ### Calling `reset()` on your lexer will empty its internal buffer, and set the line, column, and offset counts back to their initial value. If you don't want this, you can `save()` the state, and later pass it as the second argument to `reset()` to explicitly control the internal state of the lexer. ```js    lexer.reset('some line\n') let info = lexer.save() // -> { line: 10 } lexer.next() // -> { line: 10 } lexer.next() // -> { line: 11 } // ... lexer.reset('a different line\n', info) lexer.next() // -> { line: 10 } ``` Keywords -------- Moo makes it convenient to define literals. ```js moo.compile({ lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], }) ``` It'll automatically compile them into regular expressions, escaping them where necessary. **Keywords** should be written using the `keywords` transform. ```js moo.compile({ IDEN: {match: /[a-zA-Z]+/, type: moo.keywords({ KW: ['while', 'if', 'else', 'moo', 'cows'], })}, SPACE: {match: /\s+/, lineBreaks: true}, }) ``` ### Why? ### You need to do this to ensure the **longest match** principle applies, even in edge cases. Imagine trying to parse the input `className` with the following rules: ```js keyword: ['class'], identifier: /[a-zA-Z]+/, ``` You'll get _two_ tokens — `['class', 'Name']` -- which is _not_ what you want! If you swap the order of the rules, you'll fix this example; but now you'll lex `class` wrong (as an `identifier`). The keywords helper checks matches against the list of keywords; if any of them match, it uses the type `'keyword'` instead of `'identifier'` (for this example). ### Keyword Types ### Keywords can also have **individual types**. ```js let lexer = moo.compile({ name: {match: /[a-zA-Z]+/, type: moo.keywords({ 'kw-class': 'class', 'kw-def': 'def', 'kw-if': 'if', })}, // ... }) lexer.reset('def foo') lexer.next() // -> { type: 'kw-def', value: 'def' } lexer.next() // space lexer.next() // -> { type: 'name', value: 'foo' } ``` You can use [itt](https://github.com/nathan/itt)'s iterator adapters to make constructing keyword objects easier: ```js itt(['class', 'def', 'if']) .map(k => ['kw-' + k, k]) .toObject() ``` States ------ Moo allows you to define multiple lexer **states**. Each state defines its own separate set of token rules. Your lexer will start off in the first state given to `moo.states({})`. Rules can be annotated with `next`, `push`, and `pop`, to change the current state after that token is matched. A "stack" of past states is kept, which is used by `push` and `pop`. * **`next: 'bar'`** moves to the state named `bar`. (The stack is not changed.) * **`push: 'bar'`** moves to the state named `bar`, and pushes the old state onto the stack. * **`pop: 1`** removes one state from the top of the stack, and moves to that state. (Only `1` is supported.) Only rules from the current state can be matched. You need to copy your rule into all the states you want it to be matched in. For example, to tokenize JS-style string interpolation such as `a${{c: d}}e`, you might use: ```js let lexer = moo.states({ main: { strstart: {match: '`', push: 'lit'}, ident: /\w+/, lbrace: {match: '{', push: 'main'}, rbrace: {match: '}', pop: true}, colon: ':', space: {match: /\s+/, lineBreaks: true}, }, lit: { interp: {match: '${', push: 'main'}, escape: /\\./, strend: {match: '`', pop: true}, const: {match: /(?:[^$`]|\$(?!\{))+/, lineBreaks: true}, }, }) // <= `a${{c: d}}e` // => strstart const interp lbrace ident colon space ident rbrace rbrace const strend ``` The `rbrace` rule is annotated with `pop`, so it moves from the `main` state into either `lit` or `main`, depending on the stack. Errors ------ If none of your rules match, Moo will throw an Error; since it doesn't know what else to do. If you prefer, you can have moo return an error token instead of throwing an exception. The error token will contain the whole of the rest of the buffer. ```js moo.compile({ // ... myError: moo.error, }) moo.reset('invalid') moo.next() // -> { type: 'myError', value: 'invalid', text: 'invalid', offset: 0, lineBreaks: 0, line: 1, col: 1 } moo.next() // -> undefined ``` You can have a token type that both matches tokens _and_ contains error values. ```js moo.compile({ // ... myError: {match: /[\$?`]/, error: true}, }) ``` ### Formatting errors ### If you want to throw an error from your parser, you might find `formatError` helpful. Call it with the offending token: ```js throw new Error(lexer.formatError(token, "invalid syntax")) ``` It returns a string with a pretty error message. ``` Error: invalid syntax at line 2 col 15: totally valid `syntax` ^ ``` Iteration --------- Iterators: we got 'em. ```js for (let here of lexer) { // here = { type: 'number', value: '123', ... } } ``` Create an array of tokens. ```js let tokens = Array.from(lexer); ``` Use [itt](https://github.com/nathan/itt)'s iteration tools with Moo. ```js for (let [here, next] = itt(lexer).lookahead()) { // pass a number if you need more tokens // enjoy! } ``` Transform --------- Moo doesn't allow capturing groups, but you can supply a transform function, `value()`, which will be called on the value before storing it in the Token object. ```js moo.compile({ STRING: [ {match: /"""[^]*?"""/, lineBreaks: true, value: x => x.slice(3, -3)}, {match: /"(?:\\["\\rn]|[^"\\])*?"/, lineBreaks: true, value: x => x.slice(1, -1)}, {match: /'(?:\\['\\rn]|[^'\\])*?'/, lineBreaks: true, value: x => x.slice(1, -1)}, ], // ... }) ``` Contributing ------------ Do check the [FAQ](https://github.com/tjvr/moo/issues?q=label%3Aquestion). Before submitting an issue, [remember...](https://github.com/tjvr/moo/blob/master/.github/CONTRIBUTING.md) # whatwg-url whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). ## Specification conformance whatwg-url is currently up to date with the URL spec up to commit [7ae1c69](https://github.com/whatwg/url/commit/7ae1c691c96f0d82fafa24c33aa1e8df9ffbf2bc). For `file:` URLs, whose [origin is left unspecified](https://url.spec.whatwg.org/#concept-url-origin), whatwg-url chooses to use a new opaque origin (which serializes to `"null"`). ## API ### The `URL` and `URLSearchParams` classes The main API is provided by the [`URL`](https://url.spec.whatwg.org/#url-class) and [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) exports, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use these. ### Low-level URL Standard API The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They mostly operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. - [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` - [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` - [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` - [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` - [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` - [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin): `serializeURLOrigin(urlRecord)` - [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` - [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` - [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` - [Percent decode](https://url.spec.whatwg.org/#percent-decode): `percentDecode(buffer)` The `stateOverride` parameter is one of the following strings: - [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) - [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) - [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) - [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) - [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) - [`"relative"`](https://url.spec.whatwg.org/#relative-state) - [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) - [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) - [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) - [`"authority"`](https://url.spec.whatwg.org/#authority-state) - [`"host"`](https://url.spec.whatwg.org/#host-state) - [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) - [`"port"`](https://url.spec.whatwg.org/#port-state) - [`"file"`](https://url.spec.whatwg.org/#file-state) - [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) - [`"file host"`](https://url.spec.whatwg.org/#file-host-state) - [`"path start"`](https://url.spec.whatwg.org/#path-start-state) - [`"path"`](https://url.spec.whatwg.org/#path-state) - [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) - [`"query"`](https://url.spec.whatwg.org/#query-state) - [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) The URL record type has the following API: - [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) - [`username`](https://url.spec.whatwg.org/#concept-url-username) - [`password`](https://url.spec.whatwg.org/#concept-url-password) - [`host`](https://url.spec.whatwg.org/#concept-url-host) - [`port`](https://url.spec.whatwg.org/#concept-url-port) - [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) - [`query`](https://url.spec.whatwg.org/#concept-url-query) - [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) - [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. The return value of "failure" in the spec is represented by `null`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ `null`. ## Development instructions First, install [Node.js](https://nodejs.org/). Then, fetch the dependencies of whatwg-url, by running from this directory: npm install To run tests: npm test To generate a coverage report: npm run coverage To build and run the live viewer: npm run build npm run build-live-viewer Serve the contents of the `live-viewer` directory using any web server. ## Supporting whatwg-url The jsdom project (including whatwg-url) is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support us by: - [Getting professional support for whatwg-url](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&utm_medium=referral&utm_campaign=readme) as part of a Tidelift subscription. Tidelift helps making open source sustainable for us while giving teams assurances for maintenance, licensing, and security. - Contributing directly to the project. # axios // adapters The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received. ## Example ```js var settle = require('./../core/settle'); module.exports = function myAdapter(config) { // At this point: // - config has been merged with defaults // - request transformers have already run // - request interceptors have already run // Make the request using config provided // Upon response settle the Promise return new Promise(function(resolve, reject) { var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // From here: // - response transformers will run // - response interceptors will run }); } ``` # hasurl [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] > Determine whether Node.js' native [WHATWG `URL`](https://nodejs.org/api/url.html#url_the_whatwg_url_api) implementation is available. ## Installation [Node.js](http://nodejs.org/) `>= 4` is required. To install, type this at the command line: ```shell npm install hasurl ``` ## Usage ```js const hasURL = require('hasurl'); if (hasURL()) { // supported } else { // fallback } ``` [npm-image]: https://img.shields.io/npm/v/hasurl.svg [npm-url]: https://npmjs.org/package/hasurl [travis-image]: https://img.shields.io/travis/stevenvachon/hasurl.svg [travis-url]: https://travis-ci.org/stevenvachon/hasurl # binary-install Install .tar.gz binary applications via npm ## Usage This library provides a single class `Binary` that takes a download url and some optional arguments. You **must** provide either `name` or `installDirectory` when creating your `Binary`. | option | decription | | ---------------- | --------------------------------------------- | | name | The name of your binary | | installDirectory | A path to the directory to install the binary | If an `installDirectory` is not provided, the binary will be installed at your OS specific config directory. On MacOS it defaults to `~/Library/Preferences/${name}-nodejs` After your `Binary` has been created, you can run `.install()` to install the binary, and `.run()` to run it. ### Example This is meant to be used as a library - create your `Binary` with your desired options, then call `.install()` in the `postinstall` of your `package.json`, `.run()` in the `bin` section of your `package.json`, and `.uninstall()` in the `preuninstall` section of your `package.json`. See [this example project](/example) to see how to create an npm package that installs and runs a binary using the Github releases API. # fs-minipass Filesystem streams based on [minipass](http://npm.im/minipass). 4 classes are exported: - ReadStream - ReadStreamSync - WriteStream - WriteStreamSync When using `ReadStreamSync`, all of the data is made available immediately upon consuming the stream. Nothing is buffered in memory when the stream is constructed. If the stream is piped to a writer, then it will synchronously `read()` and emit data into the writer as fast as the writer can consume it. (That is, it will respect backpressure.) If you call `stream.read()` then it will read the entire file and return the contents. When using `WriteStreamSync`, every write is flushed to the file synchronously. If your writes all come in a single tick, then it'll write it all out in a single tick. It's as synchronous as you are. The async versions work much like their node builtin counterparts, with the exception of introducing significantly less Stream machinery overhead. ## USAGE It's just streams, you pipe them or read() them or write() to them. ```js const fsm = require('fs-minipass') const readStream = new fsm.ReadStream('file.txt') const writeStream = new fsm.WriteStream('output.txt') writeStream.write('some file header or whatever\n') readStream.pipe(writeStream) ``` ## ReadStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `readSize` The size of reads to do, defaults to 16MB - `size` The size of the file, if known. Prevents zero-byte read() call at the end. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the file is done being read. ## WriteStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `mode` The mode to create the file with. Defaults to `0o666`. - `start` The position in the file to start reading. If not specified, then the file will start writing at position zero, and be truncated by default. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the stream is ended. - `flags` Flags to use when opening the file. Irrelevant if `fd` is passed in, since file won't be opened in that case. Defaults to `'a'` if a `pos` is specified, or `'w'` otherwise. # node-tar [![Build Status](https://travis-ci.org/npm/node-tar.svg?branch=master)](https://travis-ci.org/npm/node-tar) [Fast](./benchmarks) and full-featured Tar for Node.js The API is designed to mimic the behavior of `tar(1)` on unix systems. If you are familiar with how tar works, most of this will hopefully be straightforward for you. If not, then hopefully this module can teach you useful unix skills that may come in handy someday :) ## Background A "tar file" or "tarball" is an archive of file system entries (directories, files, links, etc.) The name comes from "tape archive". If you run `man tar` on almost any Unix command line, you'll learn quite a bit about what it can do, and its history. Tar has 5 main top-level commands: * `c` Create an archive * `r` Replace entries within an archive * `u` Update entries within an archive (ie, replace if they're newer) * `t` List out the contents of an archive * `x` Extract an archive to disk The other flags and options modify how this top level function works. ## High-Level API These 5 functions are the high-level API. All of them have a single-character name (for unix nerds familiar with `tar(1)`) as well as a long name (for everyone else). All the high-level functions take the following arguments, all three of which are optional and may be omitted. 1. `options` - An optional object specifying various options 2. `paths` - An array of paths to add or extract 3. `callback` - Called when the command is completed, if async. (If sync or no file specified, providing a callback throws a `TypeError`.) If the command is sync (ie, if `options.sync=true`), then the callback is not allowed, since the action will be completed immediately. If a `file` argument is specified, and the command is async, then a `Promise` is returned. In this case, if async, a callback may be provided which is called when the command is completed. If a `file` option is not specified, then a stream is returned. For `create`, this is a readable stream of the generated archive. For `list` and `extract` this is a writable stream that an archive should be written into. If a file is not specified, then a callback is not allowed, because you're already getting a stream to work with. `replace` and `update` only work on existing archives, and so require a `file` argument. Sync commands without a file argument return a stream that acts on its input immediately in the same tick. For readable streams, this means that all of the data is immediately available by calling `stream.read()`. For writable streams, it will be acted upon as soon as it is provided, but this can be at any time. ### Warnings and Errors Tar emits warnings and errors for recoverable and unrecoverable situations, respectively. In many cases, a warning only affects a single entry in an archive, or is simply informing you that it's modifying an entry to comply with the settings provided. Unrecoverable warnings will always raise an error (ie, emit `'error'` on streaming actions, throw for non-streaming sync actions, reject the returned Promise for non-streaming async operations, or call a provided callback with an `Error` as the first argument). Recoverable errors will raise an error only if `strict: true` is set in the options. Respond to (recoverable) warnings by listening to the `warn` event. Handlers receive 3 arguments: - `code` String. One of the error codes below. This may not match `data.code`, which preserves the original error code from fs and zlib. - `message` String. More details about the error. - `data` Metadata about the error. An `Error` object for errors raised by fs and zlib. All fields are attached to errors raisd by tar. Typically contains the following fields, as relevant: - `tarCode` The tar error code. - `code` Either the tar error code, or the error code set by the underlying system. - `file` The archive file being read or written. - `cwd` Working directory for creation and extraction operations. - `entry` The entry object (if it could be created) for `TAR_ENTRY_INFO`, `TAR_ENTRY_INVALID`, and `TAR_ENTRY_ERROR` warnings. - `header` The header object (if it could be created, and the entry could not be created) for `TAR_ENTRY_INFO` and `TAR_ENTRY_INVALID` warnings. - `recoverable` Boolean. If `false`, then the warning will emit an `error`, even in non-strict mode. #### Error Codes * `TAR_ENTRY_INFO` An informative error indicating that an entry is being modified, but otherwise processed normally. For example, removing `/` or `C:\` from absolute paths if `preservePaths` is not set. * `TAR_ENTRY_INVALID` An indication that a given entry is not a valid tar archive entry, and will be skipped. This occurs when: - a checksum fails, - a `linkpath` is missing for a link type, or - a `linkpath` is provided for a non-link type. If every entry in a parsed archive raises an `TAR_ENTRY_INVALID` error, then the archive is presumed to be unrecoverably broken, and `TAR_BAD_ARCHIVE` will be raised. * `TAR_ENTRY_ERROR` The entry appears to be a valid tar archive entry, but encountered an error which prevented it from being unpacked. This occurs when: - an unrecoverable fs error happens during unpacking, - an entry has `..` in the path and `preservePaths` is not set, or - an entry is extracting through a symbolic link, when `preservePaths` is not set. * `TAR_ENTRY_UNSUPPORTED` An indication that a given entry is a valid archive entry, but of a type that is unsupported, and so will be skipped in archive creation or extracting. * `TAR_ABORT` When parsing gzipped-encoded archives, the parser will abort the parse process raise a warning for any zlib errors encountered. Aborts are considered unrecoverable for both parsing and unpacking. * `TAR_BAD_ARCHIVE` The archive file is totally hosed. This can happen for a number of reasons, and always occurs at the end of a parse or extract: - An entry body was truncated before seeing the full number of bytes. - The archive contained only invalid entries, indicating that it is likely not an archive, or at least, not an archive this library can parse. `TAR_BAD_ARCHIVE` is considered informative for parse operations, but unrecoverable for extraction. Note that, if encountered at the end of an extraction, tar WILL still have extracted as much it could from the archive, so there may be some garbage files to clean up. Errors that occur deeper in the system (ie, either the filesystem or zlib) will have their error codes left intact, and a `tarCode` matching one of the above will be added to the warning metadata or the raised error object. Errors generated by tar will have one of the above codes set as the `error.code` field as well, but since errors originating in zlib or fs will have their original codes, it's better to read `error.tarCode` if you wish to see how tar is handling the issue. ### Examples The API mimics the `tar(1)` command line functionality, with aliases for more human-readable option and function names. The goal is that if you know how to use `tar(1)` in Unix, then you know how to use `require('tar')` in JavaScript. To replicate `tar czf my-tarball.tgz files and folders`, you'd do: ```js tar.c( { gzip: <true|gzip options>, file: 'my-tarball.tgz' }, ['some', 'files', 'and', 'folders'] ).then(_ => { .. tarball has been created .. }) ``` To replicate `tar cz files and folders > my-tarball.tgz`, you'd do: ```js tar.c( // or tar.create { gzip: <true|gzip options> }, ['some', 'files', 'and', 'folders'] ).pipe(fs.createWriteStream('my-tarball.tgz')) ``` To replicate `tar xf my-tarball.tgz` you'd do: ```js tar.x( // or tar.extract( { file: 'my-tarball.tgz' } ).then(_=> { .. tarball has been dumped in cwd .. }) ``` To replicate `cat my-tarball.tgz | tar x -C some-dir --strip=1`: ```js fs.createReadStream('my-tarball.tgz').pipe( tar.x({ strip: 1, C: 'some-dir' // alias for cwd:'some-dir', also ok }) ) ``` To replicate `tar tf my-tarball.tgz`, do this: ```js tar.t({ file: 'my-tarball.tgz', onentry: entry => { .. do whatever with it .. } }) ``` To replicate `cat my-tarball.tgz | tar t` do: ```js fs.createReadStream('my-tarball.tgz') .pipe(tar.t()) .on('entry', entry => { .. do whatever with it .. }) ``` To do anything synchronous, add `sync: true` to the options. Note that sync functions don't take a callback and don't return a promise. When the function returns, it's already done. Sync methods without a file argument return a sync stream, which flushes immediately. But, of course, it still won't be done until you `.end()` it. To filter entries, add `filter: <function>` to the options. Tar-creating methods call the filter with `filter(path, stat)`. Tar-reading methods (including extraction) call the filter with `filter(path, entry)`. The filter is called in the `this`-context of the `Pack` or `Unpack` stream object. The arguments list to `tar t` and `tar x` specify a list of filenames to extract or list, so they're equivalent to a filter that tests if the file is in the list. For those who _aren't_ fans of tar's single-character command names: ``` tar.c === tar.create tar.r === tar.replace (appends to archive, file is required) tar.u === tar.update (appends if newer, file is required) tar.x === tar.extract tar.t === tar.list ``` Keep reading for all the command descriptions and options, as well as the low-level API that they are built on. ### tar.c(options, fileList, callback) [alias: tar.create] Create a tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Write the tarball archive to the specified filename. If this is specified, then the callback will be fired when the file has been written, and a promise will be returned that resolves when the file is written. If a filename is not specified, then a Readable Stream will be returned which will emit the file data. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. If this is set, and a file is not provided, then the resulting stream will already have the data ready to `read` or `emit('data')` as soon as you request it. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `mode` The mode to set on the created file archive - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. ### tar.x(options, fileList, callback) [alias: tar.extract] Extract a tarball archive. The `fileList` is an array of paths to extract from the tarball. If no paths are provided, then all the entries are extracted. If the archive is gzipped, then tar will detect this and unzip it. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. Most extraction errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then the extraction will fail completely. The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. [Alias: `C`] - `file` The archive file to extract. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Create files and directories synchronously. - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. [Alias: `keep-newer`, `keep-newer-files`] - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. [Alias: `k`, `keep-existing`] - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. [Alias: `P`] - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. [Alias: `U`] - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. [Alias: `strip-components`, `stripComponents`] - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. [Alias: `p`] - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. [Alias: `m`, `no-mtime`] - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync extractions. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### tar.t(options, fileList, callback) [alias: tar.list] List the contents of a tarball archive. The `fileList` is an array of paths to list from the tarball. If no paths are provided, then all the entries are listed. If the archive is gzipped, then tar will detect this and unzip it. Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. However, they don't emit `'data'` or `'end'` events. (If you want to get actual readable entries, use the `tar.Parse` class instead.) The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. [Alias: `C`] - `file` The archive file to list. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Read the specified file synchronously. (This has no effect when a file option isn't specified, because entries are emitted as fast as they are parsed from the stream anyway.) - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. This is important for when both `file` and `sync` are set, because it will be called synchronously. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noResume` By default, `entry` streams are resumed immediately after the call to `onentry`. Set `noResume: true` to suppress this behavior. Note that by opting into this, the stream will never complete until the entry data is consumed. ### tar.u(options, fileList, callback) [alias: tar.update] Add files to an archive if they are newer than the entry already in the tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ### tar.r(options, fileList, callback) [alias: tar.replace] Add files to an existing archive. Because later entries override earlier entries, this effectively replaces any existing entries. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ## Low-Level API ### class tar.Pack A readable tar stream. Has all the standard readable stream interface stuff. `'data'` and `'end'` events, `read()` method, `pause()` and `resume()`, etc. #### constructor(options) The following options are supported: - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. #### add(path) Adds an entry to the archive. Returns the Pack stream. #### write(path) Adds an entry to the archive. Returns true if flushed. #### end() Finishes the archive. ### class tar.Pack.Sync Synchronous version of `tar.Pack`. ### class tar.Unpack A writable stream that unpacks a tar archive onto the file system. All the normal writable stream stuff is supported. `write()` and `end()` methods, `'drain'` events, etc. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. `'close'` is emitted when it's done writing stuff to the file system. Most unpack errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then an error will be emitted. #### constructor(options) - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. - `win32` True if on a windows platform. Causes behavior where filenames containing `<|>?` chars are converted to windows-compatible values while being unpacked. - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `strict` Treat warnings as crash-worthy errors. Default false. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") ### class tar.Unpack.Sync Synchronous version of `tar.Unpack`. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync unpack streams. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### class tar.Parse A writable stream that parses a tar archive stream. All the standard writable stream stuff is supported. If the archive is gzipped, then tar will detect this and unzip it. Emits `'entry'` events with `tar.ReadEntry` objects, which are themselves readable streams that you can pipe wherever. Each `entry` will not emit until the one before it is flushed through, so make sure to either consume the data (with `on('data', ...)` or `.pipe(...)`) or throw it away with `.resume()` to keep the stream flowing. #### constructor(options) Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. The following options are supported: - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") #### abort(error) Stop all parsing activities. This is called when there are zlib errors. It also emits an unrecoverable warning with the error provided. ### class tar.ReadEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being read out of a tar archive. It has the following fields: - `extended` The extended metadata object provided to the constructor. - `globalExtended` The global extended metadata object provided to the constructor. - `remain` The number of bytes remaining to be written into the stream. - `blockRemain` The number of 512-byte blocks remaining to be written into the stream. - `ignore` Whether this entry should be ignored. - `meta` True if this represents metadata about the next entry, false if it represents a filesystem object. - All the fields from the header, extended header, and global extended header are added to the ReadEntry object. So it has `path`, `type`, `size, `mode`, and so on. #### constructor(header, extended, globalExtended) Create a new ReadEntry object with the specified header, extended header, and global extended header values. ### class tar.WriteEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being written from the file system into a tar archive. Emits data for the Header, and for the Pax Extended Header if one is required, as well as any body data. Creating a WriteEntry for a directory does not also create WriteEntry objects for all of the directory contents. It has the following fields: - `path` The path field that will be written to the archive. By default, this is also the path from the cwd to the file system object. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `myuid` If supported, the uid of the user running the current process. - `myuser` The `env.USER` string if set, or `''`. Set as the entry `uname` field if the file's `uid` matches `this.myuid`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/` and filenames containing the windows-compatible forms of `<|>?:` characters are converted to actual `<|>?:` characters in the archive. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. #### constructor(path, options) `path` is the path of the entry as it is written in the archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `umask` Set to restrict the modes on the entries in the archive, somewhat like how umask works on file creation. Defaults to `process.umask()` on unix systems, or `0o22` on Windows. #### warn(message, data) If strict, emit an error with the provided message. Othewise, emit a `'warn'` event with the provided message and data. ### class tar.WriteEntry.Sync Synchronous version of tar.WriteEntry ### class tar.WriteEntry.Tar A version of tar.WriteEntry that gets its data from a tar.ReadEntry instead of from the filesystem. #### constructor(readEntry, options) `readEntry` is the entry being read out of another archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `strict` Treat warnings as crash-worthy errors. Default false. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. ### class tar.Header A class for reading and writing header blocks. It has the following fields: - `nullBlock` True if decoding a block which is entirely composed of `0x00` null bytes. (Useful because tar files are terminated by at least 2 null blocks.) - `cksumValid` True if the checksum in the header is valid, false otherwise. - `needPax` True if the values, as encoded, will require a Pax extended header. - `path` The path of the entry. - `mode` The 4 lowest-order octal digits of the file mode. That is, read/write/execute permissions for world, group, and owner, and the setuid, setgid, and sticky bits. - `uid` Numeric user id of the file owner - `gid` Numeric group id of the file owner - `size` Size of the file in bytes - `mtime` Modified time of the file - `cksum` The checksum of the header. This is generated by adding all the bytes of the header block, treating the checksum field itself as all ascii space characters (that is, `0x20`). - `type` The human-readable name of the type of entry this represents, or the alphanumeric key if unknown. - `typeKey` The alphanumeric key for the type of entry this header represents. - `linkpath` The target of Link and SymbolicLink entries. - `uname` Human-readable user name of the file owner - `gname` Human-readable group name of the file owner - `devmaj` The major portion of the device number. Always `0` for files, directories, and links. - `devmin` The minor portion of the device number. Always `0` for files, directories, and links. - `atime` File access time. - `ctime` File change time. #### constructor(data, [offset=0]) `data` is optional. It is either a Buffer that should be interpreted as a tar Header starting at the specified offset and continuing for 512 bytes, or a data object of keys and values to set on the header object, and eventually encode as a tar Header. #### decode(block, offset) Decode the provided buffer starting at the specified offset. Buffer length must be greater than 512 bytes. #### set(data) Set the fields in the data object. #### encode(buffer, offset) Encode the header fields into the buffer at the specified offset. Returns `this.needPax` to indicate whether a Pax Extended Header is required to properly encode the specified data. ### class tar.Pax An object representing a set of key-value pairs in an Pax extended header entry. It has the following fields. Where the same name is used, they have the same semantics as the tar.Header field of the same name. - `global` True if this represents a global extended header, or false if it is for a single entry. - `atime` - `charset` - `comment` - `ctime` - `gid` - `gname` - `linkpath` - `mtime` - `path` - `size` - `uid` - `uname` - `dev` - `ino` - `nlink` #### constructor(object, global) Set the fields set in the object. `global` is a boolean that defaults to false. #### encode() Return a Buffer containing the header and body for the Pax extended header entry, or `null` if there is nothing to encode. #### encodeBody() Return a string representing the body of the pax extended header entry. #### encodeField(fieldName) Return a string representing the key/value encoding for the specified fieldName, or `''` if the field is unset. ### tar.Pax.parse(string, extended, global) Return a new Pax object created by parsing the contents of the string provided. If the `extended` object is set, then also add the fields from that object. (This is necessary because multiple metadata entries can occur in sequence.) ### tar.types A translation table for the `type` field in tar headers. #### tar.types.name.get(code) Get the human-readable name for a given alphanumeric code. #### tar.types.code.get(name) Get the alphanumeric code for a given human-readable name. # ts-mixer [version-badge]: https://badgen.net/npm/v/ts-mixer [version-link]: https://npmjs.com/package/ts-mixer [build-badge]: https://img.shields.io/github/workflow/status/tannerntannern/ts-mixer/ts-mixer%20CI [build-link]: https://github.com/tannerntannern/ts-mixer/actions [ts-versions]: https://badgen.net/badge/icon/3.8,3.9,4.0?icon=typescript&label&list=| [node-versions]: https://badgen.net/badge/node/10%2C12%2C14/blue/?list=| [![npm version][version-badge]][version-link] [![github actions][build-badge]][build-link] [![TS Versions][ts-versions]][build-link] [![Node.js Versions][node-versions]][build-link] [![Minified Size](https://badgen.net/bundlephobia/min/ts-mixer)](https://bundlephobia.com/result?p=ts-mixer) [![Conventional Commits](https://badgen.net/badge/conventional%20commits/1.0.0/yellow)](https://conventionalcommits.org) ## Overview `ts-mixer` brings mixins to TypeScript. "Mixins" to `ts-mixer` are just classes, so you already know how to write them, and you can probably mix classes from your favorite library without trouble. The mixin problem is more nuanced than it appears. I've seen countless code snippets that work for certain situations, but fail in others. `ts-mixer` tries to take the best from all these solutions while accounting for the situations you might not have considered. [Quick start guide](#quick-start) ### Features * mixes plain classes * mixes classes that extend other classes * mixes classes that were mixed with `ts-mixer` * supports static properties * supports protected/private properties (the popular function-that-returns-a-class solution does not) * mixes abstract classes (with caveats [[1](#caveats)]) * mixes generic classes (with caveats [[2](#caveats)]) * supports class, method, and property decorators (with caveats [[3, 6](#caveats)]) * mostly supports the complexity presented by constructor functions (with caveats [[4](#caveats)]) * comes with an `instanceof`-like replacement (with caveats [[5, 6](#caveats)]) * [multiple mixing strategies](#settings) (ES6 proxies vs hard copy) ### Caveats 1. Mixing abstract classes requires a bit of a hack that may break in future versions of TypeScript. See [mixing abstract classes](#mixing-abstract-classes) below. 2. Mixing generic classes requires a more cumbersome notation, but it's still possible. See [mixing generic classes](#mixing-generic-classes) below. 3. Using decorators in mixed classes also requires a more cumbersome notation. See [mixing with decorators](#mixing-with-decorators) below. 4. ES6 made it impossible to use `.apply(...)` on class constructors (or any means of calling them without `new`), which makes it impossible for `ts-mixer` to pass the proper `this` to your constructors. This may or may not be an issue for your code, but there are options to work around it. See [dealing with constructors](#dealing-with-constructors) below. 5. `ts-mixer` does not support `instanceof` for mixins, but it does offer a replacement. See the [hasMixin function](#hasmixin) for more details. 6. Certain features (specifically, `@decorator` and `hasMixin`) make use of ES6 `Map`s, which means you must either use ES6+ or polyfill `Map` to use them. If you don't need these features, you should be fine without. ## Quick Start ### Installation ``` $ npm install ts-mixer ``` or if you prefer [Yarn](https://yarnpkg.com): ``` $ yarn add ts-mixer ``` ### Basic Example ```typescript import { Mixin } from 'ts-mixer'; class Foo { protected makeFoo() { return 'foo'; } } class Bar { protected makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { public makeFooBar() { return this.makeFoo() + this.makeBar(); } } const fooBar = new FooBar(); console.log(fooBar.makeFooBar()); // "foobar" ``` ## Special Cases ### Mixing Abstract Classes Abstract classes, by definition, cannot be constructed, which means they cannot take on the type, `new(...args) => any`, and by extension, are incompatible with `ts-mixer`. BUT, you can "trick" TypeScript into giving you all the benefits of an abstract class without making it technically abstract. The trick is just some strategic `// @ts-ignore`'s: ```typescript import { Mixin } from 'ts-mixer'; // note that Foo is not marked as an abstract class class Foo { // @ts-ignore: "Abstract methods can only appear within an abstract class" public abstract makeFoo(): string; } class Bar { public makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { // we still get all the benefits of abstract classes here, because TypeScript // will still complain if this method isn't implemented public makeFoo() { return 'foo'; } } ``` Do note that while this does work quite well, it is a bit of a hack and I can't promise that it will continue to work in future TypeScript versions. ### Mixing Generic Classes Frustratingly, it is _impossible_ for generic parameters to be referenced in base class expressions. No matter what, you will eventually run into `Base class expressions cannot reference class type parameters.` The way to get around this is to leverage [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html), and a slightly different mixing function from ts-mixer: `mix`. It works exactly like `Mixin`, except it's a decorator, which means it doesn't affect the type information of the class being decorated. See it in action below: ```typescript import { mix } from 'ts-mixer'; class Foo<T> { public fooMethod(input: T): T { return input; } } class Bar<T> { public barMethod(input: T): T { return input; } } interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { } @mix(Foo, Bar) class FooBar<T1, T2> { public fooBarMethod(input1: T1, input2: T2) { return [this.fooMethod(input1), this.barMethod(input2)]; } } ``` Key takeaways from this example: * `interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { }` makes sure `FooBar` has the typing we want, thanks to declaration merging * `@mix(Foo, Bar)` wires things up "on the JavaScript side", since the interface declaration has nothing to do with runtime behavior. * The reason we have to use the `mix` decorator is that the typing produced by `Mixin(Foo, Bar)` would conflict with the typing of the interface. `mix` has no effect "on the TypeScript side," thus avoiding type conflicts. ### Mixing with Decorators Popular libraries such as [class-validator](https://github.com/typestack/class-validator) and [TypeORM](https://github.com/typeorm/typeorm) use decorators to add functionality. Unfortunately, `ts-mixer` has no way of knowing what these libraries do with the decorators behind the scenes. So if you want these decorators to be "inherited" with classes you plan to mix, you first have to wrap them with a special `decorate` function exported by `ts-mixer`. Here's an example using `class-validator`: ```typescript import { IsBoolean, IsIn, validate } from 'class-validator'; import { Mixin, decorate } from 'ts-mixer'; class Disposable { @decorate(IsBoolean()) // instead of @IsBoolean() isDisposed: boolean = false; } class Statusable { @decorate(IsIn(['red', 'green'])) // instead of @IsIn(['red', 'green']) status: string = 'green'; } class ExtendedObject extends Mixin(Disposable, Statusable) {} const extendedObject = new ExtendedObject(); extendedObject.status = 'blue'; validate(extendedObject).then(errors => { console.log(errors); }); ``` ### Dealing with Constructors As mentioned in the [caveats section](#caveats), ES6 disallowed calling constructor functions without `new`. This means that the only way for `ts-mixer` to mix instance properties is to instantiate each base class separately, then copy the instance properties into a common object. The consequence of this is that constructors mixed by `ts-mixer` will _not_ receive the proper `this`. **This very well may not be an issue for you!** It only means that your constructors need to be "mostly pure" in terms of how they handle `this`. Specifically, your constructors cannot produce [side effects](https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29) involving `this`, _other than adding properties to `this`_ (the most common side effect in JavaScript constructors). If you simply cannot eliminate `this` side effects from your constructor, there is a workaround available: `ts-mixer` will automatically forward constructor parameters to a predesignated init function (`settings.initFunction`) if it's present on the class. Unlike constructors, functions can be called with an arbitrary `this`, so this predesignated init function _will_ have the proper `this`. Here's a basic example: ```typescript import { Mixin, settings } from 'ts-mixer'; settings.initFunction = 'init'; class Person { public static allPeople: Set<Person> = new Set(); protected init() { Person.allPeople.add(this); } } type PartyAffiliation = 'democrat' | 'republican'; class PoliticalParticipant { public static democrats: Set<PoliticalParticipant> = new Set(); public static republicans: Set<PoliticalParticipant> = new Set(); public party: PartyAffiliation; // note that these same args will also be passed to init function public constructor(party: PartyAffiliation) { this.party = party; } protected init(party: PartyAffiliation) { if (party === 'democrat') PoliticalParticipant.democrats.add(this); else PoliticalParticipant.republicans.add(this); } } class Voter extends Mixin(Person, PoliticalParticipant) {} const v1 = new Voter('democrat'); const v2 = new Voter('democrat'); const v3 = new Voter('republican'); const v4 = new Voter('republican'); ``` Note the above `.add(this)` statements. These would not work as expected if they were placed in the constructor instead, since `this` is not the same between the constructor and `init`, as explained above. ## Other Features ### hasMixin As mentioned above, `ts-mixer` does not support `instanceof` for mixins. While it is possible to implement [custom `instanceof` behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance), this library does not do so because it would require modifying the source classes, which is deliberately avoided. You can fill this missing functionality with `hasMixin(instance, mixinClass)` instead. See the below example: ```typescript import { Mixin, hasMixin } from 'ts-mixer'; class Foo {} class Bar {} class FooBar extends Mixin(Foo, Bar) {} const instance = new FooBar(); // doesn't work with instanceof... console.log(instance instanceof FooBar) // true console.log(instance instanceof Foo) // false console.log(instance instanceof Bar) // false // but everything works nicely with hasMixin! console.log(hasMixin(instance, FooBar)) // true console.log(hasMixin(instance, Foo)) // true console.log(hasMixin(instance, Bar)) // true ``` `hasMixin(instance, mixinClass)` will work anywhere that `instance instanceof mixinClass` works. Additionally, like `instanceof`, you get the same [type narrowing benefits](https://www.typescriptlang.org/docs/handbook/advanced-types.html#instanceof-type-guards): ```typescript if (hasMixin(instance, Foo)) { // inferred type of instance is "Foo" } if (hasMixin(instance, Bar)) { // inferred type of instance of "Bar" } ``` ## Settings ts-mixer has multiple strategies for mixing classes which can be configured by modifying `settings` from ts-mixer. For example: ```typescript import { settings, Mixin } from 'ts-mixer'; settings.prototypeStrategy = 'proxy'; // then use `Mixin` as normal... ``` ### `settings.prototypeStrategy` * Determines how ts-mixer will mix class prototypes together * Possible values: - `'copy'` (default) - Copies all methods from the classes being mixed into a new prototype object. (This will include all methods up the prototype chains as well.) This is the default for ES5 compatibility, but it has the downside of stale references. For example, if you mix `Foo` and `Bar` to make `FooBar`, then redefine a method on `Foo`, `FooBar` will not have the latest methods from `Foo`. If this is not a concern for you, `'copy'` is the best value for this setting. - `'proxy'` - Uses an ES6 Proxy to "soft mix" prototypes. Unlike `'copy'`, updates to the base classes _will_ be reflected in the mixed class, which may be desirable. The downside is that method access is not as performant, nor is it ES5 compatible. ### `settings.staticsStrategy` * Determines how static properties are inherited * Possible values: - `'copy'` (default) - Simply copies all properties (minus `prototype`) from the base classes/constructor functions onto the mixed class. Like `settings.prototypeStrategy = 'copy'`, this strategy also suffers from stale references, but shouldn't be a concern if you don't redefine static methods after mixing. - `'proxy'` - Similar to `settings.prototypeStrategy`, proxy's static method access to base classes. Has the same benefits/downsides. ### `settings.initFunction` * If set, `ts-mixer` will automatically call the function with this name upon construction * Possible values: - `null` (default) - disables the behavior - a string - function name to call upon construction * Read more about why you would want this in [dealing with constructors](#dealing-with-constructors) ### `settings.decoratorInheritance` * Determines how decorators are inherited from classes passed to `Mixin(...)` * Possible values: - `'deep'` (default) - Deeply inherits decorators from all given classes and their ancestors - `'direct'` - Only inherits decorators defined directly on the given classes - `'none'` - Skips decorator inheritance # Author Tanner Nielsen <[email protected]> * Website - [tannernielsen.com](http://tannernielsen.com) * Github - [tannerntannern](https://github.com/tannerntannern) # tr46.js > An implementation of the [Unicode TR46 specification](http://unicode.org/reports/tr46/). ## Installation [Node.js](http://nodejs.org) `>= 6` is required. To install, type this at the command line: ```shell npm install tr46 ``` ## API ### `toASCII(domainName[, options])` Converts a string of Unicode symbols to a case-folded Punycode string of ASCII symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`processingOption`](#processingOption) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) * [`verifyDNSLength`](#verifyDNSLength) ### `toUnicode(domainName[, options])` Converts a case-folded Punycode string of ASCII symbols to a string of Unicode symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) ## Options ### `checkBidi` Type: `Boolean` Default value: `false` When set to `true`, any bi-directional text within the input will be checked for validation. ### `checkHyphens` Type: `Boolean` Default value: `false` When set to `true`, the positions of any hyphen characters within the input will be checked for validation. ### `checkJoiners` Type: `Boolean` Default value: `false` When set to `true`, any word joiner characters within the input will be checked for validation. ### `processingOption` Type: `String` Default value: `"nontransitional"` When set to `"transitional"`, symbols within the input will be validated according to the older IDNA2003 protocol. When set to `"nontransitional"`, the current IDNA2008 protocol will be used. ### `useSTD3ASCIIRules` Type: `Boolean` Default value: `false` When set to `true`, input will be validated according to [STD3 Rules](http://unicode.org/reports/tr46/#STD3_Rules). ### `verifyDNSLength` Type: `Boolean` Default value: `false` When set to `true`, the length of each DNS label within the input will be checked for validation. <p align="center"> <a href="http://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # interpret [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] A dictionary of file extensions and associated module loaders. ## What is it This is used by [Liftoff](http://github.com/tkellen/node-liftoff) to automatically require dependencies for configuration files, and by [rechoir](http://github.com/tkellen/node-rechoir) for registering module loaders. ## API ### extensions Map file types to modules which provide a [require.extensions] loader. ```js { '.babel.js': [ { module: '@babel/register', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) hook({ extensions: '.js' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.js' }); }, }, ], '.babel.ts': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.buble.js': 'buble/register', '.cirru': 'cirru-script/lib/register', '.cjsx': 'node-cjsx/register', '.co': 'coco', '.coffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.coffee.md': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.csv': 'require-csv', '.eg': 'earlgrey/register', '.esm.js': { module: 'esm', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) var esmLoader = hook(module); require.extensions['.js'] = esmLoader('module')._extensions['.js']; }, }, '.iced': ['iced-coffee-script/register', 'iced-coffee-script'], '.iced.md': 'iced-coffee-script/register', '.ini': 'require-ini', '.js': null, '.json': null, '.json5': 'json5/lib/require', '.jsx': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'node-jsx', register: function(hook) { hook.install({ extension: '.jsx', harmony: true }); }, }, ], '.litcoffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.liticed': 'iced-coffee-script/register', '.ls': ['livescript', 'LiveScript'], '.mjs': '/absolute/path/to/interpret/mjs-stub.js', '.node': null, '.toml': { module: 'toml-require', register: function(hook) { hook.install(); }, }, '.ts': [ 'ts-node/register', 'typescript-node/register', 'typescript-register', 'typescript-require', 'sucrase/register/ts', { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.tsx': [ 'ts-node/register', 'typescript-node/register', 'sucrase/register', { module: '@babel/register', register: function(hook) { hook({ extensions: '.tsx' }); }, }, ], '.wisp': 'wisp/engine/node', '.xml': 'require-xml', '.yaml': 'require-yaml', '.yml': 'require-yaml', } ``` ### jsVariants Same as above, but only include the extensions which are javascript variants. ## How to use it Consumers should use the exported `extensions` or `jsVariants` object to determine which module should be loaded for a given extension. If a matching extension is found, consumers should do the following: 1. If the value is null, do nothing. 2. If the value is a string, try to require it. 3. If the value is an object, try to require the `module` property. If successful, the `register` property (a function) should be called with the module passed as the first argument. 4. If the value is an array, iterate over it, attempting step #2 or #3 until one of the attempts does not throw. [require.extensions]: http://nodejs.org/api/globals.html#globals_require_extensions [downloads-image]: http://img.shields.io/npm/dm/interpret.svg [npm-url]: https://www.npmjs.com/package/interpret [npm-image]: http://img.shields.io/npm/v/interpret.svg [travis-url]: https://travis-ci.org/gulpjs/interpret [travis-image]: http://img.shields.io/travis/gulpjs/interpret.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/interpret [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/interpret.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/interpret [coveralls-image]: http://img.shields.io/coveralls/gulpjs/interpret/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # ASBuild A simple build tool for [AssemblyScript](https://assemblyscript.org) projects, similar to `cargo`, etc. ## Usage ``` asb [entry file] [options] -- [args passed to asc] ``` ### Background AssemblyScript greater than v0.14.4 provides a `asconfig.json` configuration file that can be used to describe the options for building a project. ASBuild uses this and some adds defaults to create an easier CLI interface. ### Defaults #### Project structure ``` project/ package.json asconfig.json assembly/ index.ts build/ release/ project.wasm debug/ project.wasm ``` - If no entry file passed and no `entry` field is in `asconfig.json`, `project/assembly/index.ts` is assumed. - `asconfig.json` allows for options for different compile targets, e.g. release, debug, etc. `asc` defaults to the release target. - The default build directory is `./build`, and artifacts are placed at `./build/<target>/packageName.wasm`. ### Workspaces If a `workspace` field is added to a top level `asconfig.json` file, then each path in the array is built and placed into the top level `outDir`. For example, `asconfig.json`: ```json { "workspaces": ["a", "b"] } ``` Running `asb` in the directory below will use the top level build directory to place all the binaries. ``` project/ package.json asconfig.json a/ asconfig.json assembly/ index.ts b/ asconfig.json assembly/ index.ts build/ release/ a.wasm b.wasm debug/ a.wasm b.wasm ``` To see an example in action check out the [test workspace](./test)
heavenswill_Near-Practice
README.md as-pect.config.js asconfig.json package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts simple __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
# `near-sdk-as` Starter Kit This is a good project to use as a starting point for your AssemblyScript project. ## Samples This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage There are 2 AssemblyScript contracts in this project, each in their own folder: - **simple** in the `src/simple` folder - **singleton** in the `src/singleton` folder ### Simple We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions. In this case, all exported functions become public contract methods. ```ts // return the string 'hello world' export function helloWorld(): string {} // read the given key from account (contract) storage export function read(key: string): string {} // write the given value at the given key to account (contract) storage export function write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} ``` ### Singleton We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`. In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh). ```ts @nearBindgen export class Contract { // return the string 'hello world' helloWorld(): string {} // read the given key from account (contract) storage read(key: string): string {} // write the given value at the given key to account (contract) storage @mutateState() write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} } ``` ## Usage ### Getting started (see below for video recordings of each of the following steps) INSTALL `NEAR CLI` first like this: `npm i -g near-cli` 1. clone this repo to a local folder 2. run `yarn` 3. run `./scripts/1.dev-deploy.sh` 3. run `./scripts/2.use-contract.sh` 4. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 5. run `./scripts/3.cleanup.sh` ### Videos **`1.dev-deploy.sh`** This video shows the build and deployment of the contract. [![asciicast](https://asciinema.org/a/409575.svg)](https://asciinema.org/a/409575) **`2.use-contract.sh`** This video shows contract methods being called. You should run the script twice to see the effect it has on contract state. [![asciicast](https://asciinema.org/a/409577.svg)](https://asciinema.org/a/409577) **`3.cleanup.sh`** This video shows the cleanup script running. Make sure you add the `BENEFICIARY` environment variable. The script will remind you if you forget. ```sh export BENEFICIARY=<your-account-here> # this account receives contract account balance ``` [![asciicast](https://asciinema.org/a/409580.svg)](https://asciinema.org/a/409580) ### Other documentation - See `./scripts/README.md` for documentation about the scripts - Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` ## The file system ```sh ├── README.md # this file ├── as-pect.config.js # configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts) ├── package.json # NodeJS project manifest ├── scripts │   ├── 1.dev-deploy.sh # helper: build and deploy contracts │   ├── 2.use-contract.sh # helper: call methods on ContractPromise │   ├── 3.cleanup.sh # helper: delete build and deploy artifacts │   └── README.md # documentation for helper scripts ├── src │   ├── as_types.d.ts # AssemblyScript headers for type hints │   ├── simple # Contract 1: "Simple example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 1 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 1 │   ├── singleton # Contract 2: "Singleton-style example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 2 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 2 │   ├── tsconfig.json # Typescript configuration │   └── utils.ts # common contract utility functions └── yarn.lock # project manifest version lock ``` You may clone this repo to get started OR create everything from scratch. Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files: ``` ./assembly/ ./assembly/tests/ ./assembly/tests/example.spec.ts ./assembly/tests/as-pect.d.ts ``` https://www.patika.dev/tr # `near-sdk-as` Starter Kit This is a good project to use as a starting point for your AssemblyScript project. ## Samples This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage There are 2 AssemblyScript contracts in this project, each in their own folder: - **simple** in the `src/simple` folder - **singleton** in the `src/singleton` folder ### Simple We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions. In this case, all exported functions become public contract methods. ```ts // return the string 'hello world' export function helloWorld(): string {} // read the given key from account (contract) storage export function read(key: string): string {} // write the given value at the given key to account (contract) storage export function write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} ``` ### Singleton We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`. In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh). ```ts @nearBindgen export class Contract { // return the string 'hello world' helloWorld(): string {} // read the given key from account (contract) storage read(key: string): string {} // write the given value at the given key to account (contract) storage @mutateState() write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} } ``` ## Usage ### Getting started (see below for video recordings of each of the following steps) INSTALL `NEAR CLI` first like this: `npm i -g near-cli` 1. clone this repo to a local folder 2. run `yarn` 3. run `./scripts/1.dev-deploy.sh` 3. run `./scripts/2.use-contract.sh` 4. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 5. run `./scripts/3.cleanup.sh` ### Videos **`1.dev-deploy.sh`** This video shows the build and deployment of the contract. [![asciicast](https://asciinema.org/a/409575.svg)](https://asciinema.org/a/409575) **`2.use-contract.sh`** This video shows contract methods being called. You should run the script twice to see the effect it has on contract state. [![asciicast](https://asciinema.org/a/409577.svg)](https://asciinema.org/a/409577) **`3.cleanup.sh`** This video shows the cleanup script running. Make sure you add the `BENEFICIARY` environment variable. The script will remind you if you forget. ```sh export BENEFICIARY=<your-account-here> # this account receives contract account balance ``` [![asciicast](https://asciinema.org/a/409580.svg)](https://asciinema.org/a/409580) ### Other documentation - See `./scripts/README.md` for documentation about the scripts - Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` ## The file system ```sh ├── README.md # this file ├── as-pect.config.js # configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts) ├── package.json # NodeJS project manifest ├── scripts │   ├── 1.dev-deploy.sh # helper: build and deploy contracts │   ├── 2.use-contract.sh # helper: call methods on ContractPromise │   ├── 3.cleanup.sh # helper: delete build and deploy artifacts │   └── README.md # documentation for helper scripts ├── src │   ├── as_types.d.ts # AssemblyScript headers for type hints │   ├── simple # Contract 1: "Simple example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 1 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 1 │   ├── singleton # Contract 2: "Singleton-style example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 2 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 2 │   ├── tsconfig.json # Typescript configuration │   └── utils.ts # common contract utility functions └── yarn.lock # project manifest version lock ``` You may clone this repo to get started OR create everything from scratch. Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files: ``` ./assembly/ ./assembly/tests/ ./assembly/tests/example.spec.ts ./assembly/tests/as-pect.d.ts ``` https://www.patika.dev/tr ## Setting up your terminal The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project. It uses the following setup: ```sh # set your terminal up to have 2 windows, A and B like this: ┌─────────────────────────────────┬─────────────────────────────────┐ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands _helper scripts_ ```sh 1.dev-deploy.sh # helper: build and deploy contracts 2.use-contract.sh # helper: call methods on ContractPromise 3.cleanup.sh # helper: delete build and deploy artifacts ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068) ## Setting up your terminal The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project. It uses the following setup: ```sh # set your terminal up to have 2 windows, A and B like this: ┌─────────────────────────────────┬─────────────────────────────────┐ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands _helper scripts_ ```sh 1.dev-deploy.sh # helper: build and deploy contracts 2.use-contract.sh # helper: call methods on ContractPromise 3.cleanup.sh # helper: delete build and deploy artifacts ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068)
nsejim_NEAR-open-recruit
README.md as-pect.config.js asconfig.json package.json src as-pect.d.ts as_types.d.ts openboard __tests__ application.unit.spec.ts as-pect.d.ts index.unit.spec.ts job.unit.spec.ts asconfig.json assembly index.ts models application.ts job.ts openProofAPI.ts states.ts openproofs __tests__ index.unit.spec.ts proof.unit.spec.ts asconfig.json assembly index.ts models proof.ts states.ts tsconfig.json utils.ts
# OpenRecruit OpenRecruit is a multi smart contract DApp to proof the concept of an open and trustless recruitment process running on NEAR Blockchain Protocol. ## Concept (DONE) Today's online recruitment services experience different trust-related challenges that natively result from the centralized architecture of their online jobboards. The latters are the user interfaces for posting jobs (recruiter user) and submitting applications (job candidate). To name a few of those challenges: - a job candidate has to upload its proofs of qualification in each of different jobboards where he/she want to apply for a job - once application submiited, the candidate has to trust the online service to effectively transmit its application to the recruiter - it is not guaranteed that jobs posted under the same publication package (price) are listed in the pre-defined order (newest on top foe instance) With the proposed collaborative smart contracts, we empower both type of users in the following ways: 1. A candidate can manage his/her open proofs of qualification in an open way 2. A candidate can verify if the recruiter has effectively consulted his/her application 3. Recruiters can verify that the positions of their jobs in the listing is as promised ### Example Story (DONE) Let's describe a typical end to end user story as a sequence of actions from the following different type of users: 1. Two recruiters: "NEAR" and "TESLA" 2. One candidate "Alice" The following actions 1. Each recruiter registers as Recruiter 2. Each recruiter posts one or several jobs on the "open recruitment" jobboard. 3. Alice upload her open proofs of qualifications in the OpenProofs Dapp. 4. Alice visits the "open recruitment" jobboard and she opens the "RUST developer" job at "NEAR" for applying. 5. On the application form, Alice checks the box authorizing to link its "open proofs" information to the submitted application. 6. The NEAR recruiter receives the Alice's application and ack its reception ## Repository contents (TODO) This repository includes: - Two smart contracts - [Unit tests](https://docs.near.org/docs/roles/developer/contracts/test-contracts#unit-tests) and [simulation tests](https://docs.near.org/docs/roles/developer/contracts/test-contracts#simulation-tests) for the contract(s) - Wireframes for the potential dApp UI of each smart contract - Utilities for building, testing, and deploying contracts (facilitated by the [NEAR CLI](https://docs.near.org/docs/development/near-cli)) ### Installation 1. clone this repo 2. run `yarn install` (or `npm install`) 3. run `yarn build` (or `npm run build`) 4. run `yarn test` (or `npm run test`) 5. explore the contents of `src/` See below for more convenience scripts ... ### Commands (TODO) **Compile source to WebAssembly** ```sh yarn build # asb --target debug yarn build:release # asb ``` **Run unit tests** ```sh yarn test:unit # asp --verbose --nologo -f unit.spec ``` **Run simulation tests** These tests can be run from within VSCode (or any Rust-compatible IDE) or from the command line. _NOTE: Rust is required_ ```sh yarn test:simulate # yarn build:release && cargo test -- --nocapture ``` **Run all tests** ```sh yarn test # yarn test:unit && test:simulate ``` ## UI Wireframes (TODO) ## File Structure (TODO) ### Factory (TO UNDERSTAND) ## Live DApps on NEAR testnet (DONE) The 2 smart-contracts have been deployed on NEAR testnet under the following accounts: - openproofs.ncd.nsejim.testnet - openboard.ncd.nsejim.testnet ### Future Development (DONE) Some ideas for future feature development: - Enable each recruiter to open its own open jobboard ### Key Contributors (DONE) - [Jimmy NSENGA - @amgando](https://github.com/nsejim)
anbork_next-js-near
.eslintrc.json README.md next.config.js package.json pages _app.js api hello.js index.js public vercel.svg styles Home.module.css globals.css
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file. [API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`. The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
NEAR-Hispano_NEAR-book
README.md api index.js routes uploader.js assets img logo1.svg contract lib.rs jsconfig.json nuxt.config.js package-lock.json package.json services api.js static vuetify-logo.svg store README.md
# nearbook ## Build Setup ```bash # install dependencies $ npm install # serve with hot reload at localhost:3000 $ npm run dev # build for production and launch server $ npm run build $ npm run start # STORE **This directory is not required, you can delete it if you don't want to use it.** This directory contains your Vuex Store files. Vuex Store option is implemented in the Nuxt.js framework. Creating a file in this directory automatically activates the option in the framework. More information about the usage of this directory in [the documentation](https://nuxtjs.org/guide/vuex-store).
joesixpack_near-suricate
README.md package.json src alerts ISuricateAlert.ts ISuricateAlertEmitter.ts ISuricateAlertsReport.ts alerts-manager.ts alerts.ts console-emitter.ts mail-emitter.ts telegram-emitter.ts flow-runner.ts index.ts logger-factory.ts metrics metrics-manager.ts prometheus-exporter.ts near-utils.ts rebalancing IRebalancingAction.ts rebalancing-manager.ts stake-unstake-actions.ts utils.ts tsconfig.json
*DISCLAIMER : Proof of concept in intense development. For use in Near Betanet ONLY* # Suricate Monitoring program for Near Protocol validators ## Features In the Near network : - Keeps track of the next validator seat price and the funds staked in `poolAccoundId`. - Using the funds staked/unstaked from `delegatorAccountId`, rebalances the staked funds in the `poolAccountId` pool so the staked funds stay in between defined thresholds (default: between 110% of seat price and 190% of seat price). - Publishes delegator and pool Prometheus metrics (default on `http://<yourHost>:3039/metrics`). - Emits alerts when node is outdated or when validator status changes or online rate is below 95% (more alerts to come). Know limitations : Not epoch-aware (gets info on `next` epoch), bad arithmetic precision. ## Usage ### Production (betanet) Install *suricate* globally ``` npm install -g near-suricate ``` Run ``` near-suricate monitor --delegatorAccountId <yourAccountId> --poolAccountId <yourPoolId> ``` See [Configuring](#configuring) section for advanced usage. ### Development The bot is written in Javascript/Typescript and requires `nodejs` and `npm`. Install dependencies : ``` npm install ``` Compile, then start monitoring using `suricate.config.json` config file (See [Configuring](#configuring) section below) ``` npm start ``` Alternatively, for debugging, you can compile... ``` npm run tsc ``` ... and run with given config file (at least the required <delegatorAccountId> and <poolAccountId> fields must be present in the file) ``` node dist --config suricate.config.json ``` ## Configuring Suricate accepts parameters either via command line arguments or from a config file passed with `--config`. Other command line arguments override config file values (ex: `--alerts.enabled=false`). ### Configuration file Copy the configuration file example. ``` cp suricate.config.json.example suricate.config.json ``` And modify it according to your needs : ``` { "delegatorAccountId": "neozaru14.betanet", "poolAccountId": "neozaru.stakehouse.betanet", "near": { "networkId": "betanet", "nodeUrl": "https://rpc.betanet.near.org/", "keystoreDir": "./neardev/" }, "rebalancing": { "enabled": true, "autoping": true, "levels": { "lowThreshold": 1.2, "lowTarget": 1.3, "highTarget": 1.7, "highThreshold": 1.8 }, "policy": { "type": "BEST", "minRebalanceAmount": 1000 } }, "alerts": { "enabled": true, "emitters": ["console"] }, "metrics": { "enabled": true, "hostname": "0.0.0.0", "port": 3039 } } ``` #### near{} - `near.keystoreDir` should have the same structure as your `~/.near-credentials/` folder (which is default value if you simply omit it). It should contain at least of keys associated with `delegatorAccountId`. #### rebalancing{} - `rebalancing.autoping` means that a `ping` command will be sent before every rebalancing check (every `interval`). This should consume a tiny amount of gas but will allow your node to automatically restake without manual intervention if it gets kicked out. - `rebalancing.levels` defines at what levels (`lowThreshold`, `highThreshold`) the automatic rebalancing should be triggered and to what levels (`lowTarget`, `highTarget`) it should put the stake by rebalancing. Ex: If current seat price is 1000 and the currently staked balance in the pool is 1850, it will trigger the `highThreshold` (1850 > 1000 * `1.8`) and take action to set the staked balance in the pool to 1700 (`1.7` * 1000). - `rebalancing.policy` defines what to do when the delegator account does have enough fund deposited in the pool to meet the stake/unstake target. Setting the type to `BEST` will make the delegator account stake/unstake as many tokens as it can even if it is not enough to meet the `lowTarget`/`highTarget`. It is triggered only if the user can stake/unstake at least `minRebalanceAmount` (in NEAR). Another option for `rebalancing.policy` is FOK, which simply doesn't take any action if the delegator account doesn't have enough fund deposited : ``` "rebalancing": { "policy": { "type": "FOK" }, "levels": { [...] } } ``` #### alerts{} Alerts are scanned every `interval` seconds (default every 5 minutes). The same alert won't be triggered twice for the same epoch, but the same alert will be triggered again if the epoch changes and the same alert persists. By default, they are logged to the console. You can set up email alerts by modifying the `alerts{}` configuration : ``` "alerts": { "enabled": true, "emitters": ["mail", "console"], "mail": { "smtp": { "host": "smtp.gmail.com", "port": 465, "secure": true, "auth": { "user": "[email protected]", "pass": "<yourMailPassword>" } }, "sender": "[email protected]", "recipients": ["[email protected]"] } }, ``` ... will send alert both by mail and to the console. Note that the `alerts.mail.smtp{}` field format is the same as [Nodemailer](https://nodemailer.com/about/) library syntax. [NEW] Use your own Telegram Bot to receive alerts : ``` "alerts": { "enabled": true, "emitters": ["telegram", "console"], "telegram": { "token": "<yourBotToken>", "channelId": "<yourChannelIdOrUserId>" } } ``` Where `token` is the "HTTP API" token given by `@FatherBot` when creating your bot from Telegram (https://core.telegram.org/bots#creating-a-new-bot) and `channelId` can be your own user ID given by talking with `@userinfobot` (it can probably be the ID of an actual channel as well but I am not familiar with Telegram). Right now, alert emitted are : - `NOT_CURRENT_VALIDATOR` the validator account `validatorAccountId` (`poolAccountId`) is not in the validators list for current epoch. - `NOT_NEXT_VALIDATOR` the validator account `validatorAccountId` (`poolAccountId`) is not in the validators list for next epoch. - `VALIDATOR_EXPECTED_PRODUCED_BLOCKS` is triggered when a validator produced only 95% (or less) of the expected blocks. - `VALIDATOR_KICKED_OUT` is triggered when validator was kicked out during previous (ie: for being offline for too long during previous epoch). - `VALIDATOR_SLASHED` the validator account `validatorAccountId` (`poolAccountId`) has been slashed. - `PROTOCOL_VERSION` your target RPC node is outdated (not reliable if you use a public RPC instead of your own node) #### metrics{} The following metrics are exported for *Prometheus* on `http://<yourHost>:3039/metrics` by default. ``` # HELP suricate_pool_total_staked_balance suricate_pool_total_staked_balance # TYPE suricate_pool_total_staked_balance gauge suricate_pool_total_staked_balance 168524.20893628307 # HELP suricate_pool_delegator_staked_balance suricate_pool_delegator_staked_balance # TYPE suricate_pool_delegator_staked_balance gauge suricate_pool_delegator_staked_balance 56390.831213471494 # HELP suricate_pool_delegator_unstaked_balance suricate_pool_delegator_unstaked_balance # TYPE suricate_pool_delegator_unstaked_balance gauge suricate_pool_delegator_unstaked_balance 19485.220010316676 # HELP suricate_seat_price_current suricate_seat_price_current # TYPE suricate_seat_price_current gauge suricate_seat_price_current 107168.27592853646 # HELP suricate_seat_price_next suricate_seat_price_next # TYPE suricate_seat_price_next gauge suricate_seat_price_next 112327.51129207034 # HELP suricate_seat_price_proposals suricate_seat_price_proposals # TYPE suricate_seat_price_proposals gauge suricate_seat_price_proposals 113267.00549267698 # HELP suricate_seat_price_low_threshold suricate_seat_price_low_threshold # TYPE suricate_seat_price_low_threshold gauge suricate_seat_price_low_threshold 157258.21357744085 # HELP suricate_seat_price_high_threshold suricate_seat_price_high_threshold # TYPE suricate_seat_price_high_threshold gauge suricate_seat_price_high_threshold 213422.27145493322 # HELP suricate_validator_produced_blocks suricate_validator_produced_blocks # TYPE suricate_validator_produced_blocks gauge suricate_validator_produced_blocks 32 # HELP suricate_validator_expected_blocks suricate_validator_expected_blocks # TYPE suricate_validator_expected_blocks gauge suricate_validator_expected_blocks 32 # HELP suricate_validator_uptime_ratio suricate_validator_uptime_ratio # TYPE suricate_validator_uptime_ratio gauge suricate_validator_uptime_ratio 100 # HELP suricate_epoch_id suricate_epoch_id # TYPE suricate_epoch_id gauge suricate_epoch_id 10 # HELP suricate_epoch_id_float suricate_epoch_id_float # TYPE suricate_epoch_id_float gauge suricate_epoch_id_float 10.3278 # HELP suricate_epoch_start_height suricate_epoch_start_height # TYPE suricate_epoch_start_height gauge suricate_epoch_start_height 9040874 # HELP suricate_epoch_progress suricate_epoch_progress # TYPE suricate_epoch_progress gauge suricate_epoch_progress 32.69 # HELP suricate_epoch_blocks suricate_epoch_blocks # TYPE suricate_epoch_blocks gauge suricate_epoch_blocks 3269 # HELP suricate_alerts_count suricate_alerts_count # TYPE suricate_alerts_count gauge suricate_alerts_count 0 ``` ## Bugs & Feature requests Please use *Github*'s *issues* section. I'll be happy to try to help you.
Graate-Org_NEAR-Block-Dice--AssemblyScript-II
README.md as-pect.config.js asconfig.json package.json scripts 1.deploy.sh 10.get_active_games.sh 11.get_completed_games.sh 12.get_created_games.sh 2.create_new_game.sh 3.join_game.sh 4.roll_dice.sh 5.get_winners.sh 6.claim_winnings.sh 7.get_game_details.sh 8.get_players_details.sh 9.get_profile_details.sh README.md src as-pect.d.ts as_types.d.ts block-dice README.md __tests__ README.md index.unit.spec.ts asconfig.json assembly index.ts model.ts utils.ts tsconfig.json
## Unit tests Unit tests can be run from the top level folder using the following command: ``` yarn test:unit ``` ### Tests for Contract in `index.unit.spec.ts` ``` [Describe]: Checks for creating account [Success]: ✔ creates a new game [Success]: ✔ creates throws when fee is not attached [Describe]: Checks for joining a game [Success]: ✔ allows a new user join a game [Success]: ✔ can't when join when fee is zero [Success]: ✔ can't when join when completed [Describe]: Rolling dice [Success]: ✔ rolls the dice [Success]: ✔ Doesn't return rolls if game has not ended [Success]: ✔ can't roll the dice twice [Describe]: Claiming winning error catch [Success]: ✔ verifies if game has ended before win is claimed [Describe]: Claiming winning [Success]: ✔ claims win if among winners [Success]: ✔ verifies winners [Success]: ✔ cant claims win if not among winners [Success]: ✔ cannot claim winnings twice [File]: src/block-dice/__tests__/index.unit.spec.ts [Groups]: 6 pass, 6 total [Result]: ✔ PASS [Snapshot]: 0 total, 0 added, 0 removed, 0 different [Summary]: 13 pass, 0 fail, 13 total [Time]: 318.942ms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Result]: ✔ PASS [Files]: 1 total [Groups]: 6 count, 6 pass [Tests]: 13 pass, 0 fail, 13 total [Time]: 16963.038ms ✨ Done in 17.81s. ``` ## Deploying contract through your terminal The `deploy.sh` file within the scripts folder demonstrates a simple way of deploying a smart contract to the testnet. ```sh [ -z "$CONTRACT" ] && echo "Missing \$CONTRACT environment variable" [ -z "$OWNER" ] && echo "Missing \$OWNER environment variable" ``` The above commands searches the environment variables for `$CONTRACT` and `$OWNER` variables. ```sh echo "deleting $CONTRACT and setting $OWNER as beneficiary" echo near delete $CONTRACT $OWNER ``` These commands deletes the two environment variable , `$CONTRACT` and `$OWNER` if any is found in the codebase, resolving the conflict of having two set of `$CONTRACT` and `$OWNER` variables. ```sh echo -------------------------------------------- echo echo "cleaning up the /neardev folder" echo rm -rf ./neardev ``` The above shell commands deletes the `./neardev` folder. This folder contains details about the smart contract once deploy, expample is the `CONTRACT_NAME` found in the `dev-account.env` file. This way we can always generate a new `./neardev` folder on every deploy. ```sh echo -------------------------------------------- echo echo "rebuilding the contract (release build)" echo yarn build:release ``` These commands compiles/builds the AssemlyScript code down to WebAssembly code. This action generates a file with `.wasm` extension that contains the WebAssembly code. ```sh echo -------------------------------------------- echo echo "redeploying the contract" echo near dev-deploy ../build/release/block-dice.wasm ``` These commands deploys/redeploys the resulting WebAssembly file from the previous action, `yarn build:release`. This file is deployed to the Near blockchain. ```sh echo -------------------------------------------- echo run the following commands echo echo 'export CONTRACT=__new_contract_account_id__' echo echo ``` These final commands prompts the developer to export the exported interfaces, making it available for consumption on the local machine. # Block-Dice This repository includes a complete Smart Contract for a dice game built on the NEAR blockchain. This is a second sample that corrects a leak in the initial sample. - The error in the initial smart contract is that you can see what other players rolled before a game has ended, this gives those joining late an edge as they can make a decision based on what other players rolled. We are correcting this by only revealing a players roll if a game has ended. For additional informtion on the smart contract methods view [here](src/block-dice/) ``` It's a simple contract demonstrating how to build a dic game on the NEAR blockchain using assembly script: - Why you should avoid leaks and have data restrictions on your smart contracts - How to implement random number generation and id checks on the NEAR block chain ## Usage ### Getting started 1. clone this repo to a local folder 2. run `yarn` 3. run `yarn test:unit` ### Top-level `yarn` commands - run `yarn test` to run all tests - (!) be sure to run `yarn build:release` at least once before: - run `yarn test:unit` to run only unit tests - run `yarn test:simulate` to run only simulation tests - run `yarn build` to quickly verify build status - run `yarn clean` to clean up build folder ### Other documentation - Sample contract and test documentation - see `/src/block-dice/README` for contract interface - see `/src/block-dice/__tests__/README` for Sample unit testing details ``` ![Near, Inc. logo](https://near.org/wp-content/themes/near-19/assets/img/logo.svg?t=1553011311) ## Design ### Interface ```ts function createNewGame ``` - "Change" function (ie. a function that alters contract state) - Creates a new game and returns the unique id for that game ```ts function joinGame ``` - "Change" function (ie. a function that alters contract state) - Recieves a game's unique id as parameter - Allows the account initiating the contract call tp join the game with id passed in ```ts function rollDice ``` - "Change" function (ie. a function that alters contract state) - Recieves a game's unique id as parameter - Allows the account initiating the contract call to roll dice for the game - Once the first dice is rolled in a game, it becomes active - Each active game lasts for 30 minutes on being active ```ts function getWinners ``` - "View" function - Recieves a game's unique id as parameter - Returns an array with the account id of the winners for the game id passed in ```ts function claimWinnings ``` - "Change" function (ie. a function that alters contract state) - Recieves a game's unique id as parameter - Allows the account initiating the contract call to claim winning for the game - Panics if account has already claimed winnings or is not a winner - Returns true if winnings was successfully claimed ```ts function getGameDetails ``` - "View" function - Recieves a game's unique id as parameter - Returns details of the game id passed in ```ts function getPlayersDetails ``` - "View" function - Recieves a game's unique id as parameter - Returns details of the players for the game id passed in ```ts function getProfileDetails ``` - "View" function - Returns details of the profile of the user calling the contract ```ts function getActiveGames ``` - "Change" function - Returns active games ```ts function getCompletedGames ``` - "Change" function - Returns completed games ```ts function getCreatedGames ``` - "Change" function - Returns created games
near_units-js
.github ISSUE_TEMPLATE BOUNTY.yml workflows lint.yml tests.yml .vim coc-settings.json .vscode extensions.json settings.json .yarn sdks integrations.yml typescript lib tsc.js tsserver.js tsserverlibrary.js typescript.js package.json .yarnrc.yml CONTRIBUTING.md README.md __tests__ gas.spec.ts near.spec.ts parse.spec.ts dist bn.d.ts bn.js cli.d.ts cli.js gas.d.ts gas.js index.d.ts index.js near.d.ts near.js parse.d.ts parse.js utils.d.ts utils.js package.json src bn.ts cli.ts gas.ts index.ts near.ts parse.ts utils.ts tsconfig.json
NEAR Units ========== TypeScript/JavaScript tools to help parse and format NEAR units. For now, this means NEAR tokens and [gas units](https://docs.near.org/concepts/basics/transactions/gas). # Install npm i --save near-units Or using [Yarn](https://yarnpkg.com/): yarn add near-units # Parsing strings ```js import { NEAR, Gas, parse } from 'near-units'; const near = NEAR.parse('1.25 mN'); console.log(near.toHuman()); // 1.25 mN const gas = Gas.parse('1 Tgas'); console.log(gas.toHuman()); // 1 Tgas // equivalent to the above, but TS typings might not be as helpful const near = parse('1.25 mN'); const gas = parse('1 Tgas'); ``` See [\_\_tests__](./__tests__) for a full list of examples of inputs that can be parsed and the human-readable version that can be returned by `toHuman`. # Doing math `NEAR` and `Gas` both wrap `BN` from [bn.js], so you can perform any math with them that you need: ```js import { NEAR } from 'near-units'; const amount1 = NEAR.parse('100'); const amount2 = NEAR.parse('0.5'); const amount3 = amount1.mul(amount2); ``` See [the bn.js docs for all possible operations][bn.js]. [bn.js]: https://github.com/indutny/bn.js/ # Interop Since they wrap `BN`, they can be passed directly to function calls with [near-api-js](https://github.com/near/near-api-js) or [near-runner](https://github.com/near/runner-js): ```js // with an Account object from near-api-js someAccount.functionCall({ contractId: 'example.near', methodName: 'do_something', args: { param1: 'whatever' }, gas: Gas.parse('50,000,000,000,000'), attachedDeposit: NEAR.parse('1'), }); // with an Account object from near-runner someAccount.call( 'example.near', 'do_something', { param1: 'whatever' }, { gas: Gas.parse('50,000,000,000,000'), attachedDeposit: NEAR.parse('1'), } }); ``` `NEAR` and `Gas` also both override `toJSON` to get to a string version that can be passed as an argument to near-cli and in other contexts. # CLI This package ships with a minimal CLI: npm i -g near-units Now you can `near-units --help`: Parse and format NEAR tokens and gas units. Examples: near-units 10 N # => 10000000000000000000000000 near-units -h 10000000000000000000000000 yN # => 10 N near-units 50 Tgas # => 50000000000000 near-units -h 50000000000000 gas # => 50 Tgas You can use it anywhere near units are accepted. For example, on macOS & Linux, you can: ```bash near call $LOCKUP transfer '{ "receiver_id": "example.near", "amount": "'$(near-units 1N)'" }' --accountId=$ACCOUNT --gas=$(near-units 50Tgas) ```
inc4_near-misfits-nft
.env README.md package.json public index.html src Main.js assets images copy-icon.svg footer-near-logo.svg hero-cloud1.svg hero-cloud2.svg hero-cloud3.svg hero-ellipse.svg leran-background-circle.svg leran-background-ellipse.svg link-drop-background.svg nft-background.svg rarity-background-gradient.svg rarity-common.svg rarity-rare.svg rarity-super-rare.svg rarity-uncommon.svg rarity-very-rare.svg share-social discord.svg email.svg facebook.svg instagram.svg linkedin.svg telegram.svg twitter.svg wechat.svg social-face.svg social-twitter.svg components Buy BuyMore index.js index.js BuyMoreBtn index.js ConnectWalletBtn index.js FAQ index.js Generate index.js GenerateCountBtn index.js Hero index.js Learn index.js Loader Loader.js index.js Navigation Navigation.js index.js NftItem NftItem.js index.js NftItemInfo NftItemInfo.js index.js NftList NftList.js index.js NoNfts index.js Price index.js Rarity index.js rarityData.js RateList index.js RenderRoutes RenderRoutes.js RouteWithSubRoutes RouteWithSubRoutes.js index.js index.js ScrollToTop index.js ShareSocialLinks index.js SocialLinks index.js config.js hooks useBuy.js useCopyToClipboard.js useLinkDrop.js useMintNft.js useTransfer.js index.js layouts Footer Footer.js index.js Header Header.js index.js Layout Layout.js index.js Modal index.js pages Home Home.js index.js LinkDrop LinkDrop.js SaveBtn index.js ShareableCircle index.js ShareableInput index.js ShareableLink index.js index.js MyNFTS MyNFTS.js index.js react-app-env.d.ts routes.js setupTests.js state app.js near.js utils near-utils.js state-utils.js tsconfig.json
## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
muhammedalibilgin_Web3-first-fundamental
README.md as-pect.config.js asconfig.json package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts simple __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
## Setting up your terminal The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project. It uses the following setup: ```sh # set your terminal up to have 2 windows, A and B like this: ┌─────────────────────────────────┬─────────────────────────────────┐ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands _helper scripts_ ```sh 1.dev-deploy.sh # helper: build and deploy contracts 2.use-contract.sh # helper: call methods on ContractPromise 3.cleanup.sh # helper: delete build and deploy artifacts ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068) # `near-sdk-as` Starter Kit This is a good project to use as a starting point for your AssemblyScript project. ## Samples This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage There are 2 AssemblyScript contracts in this project, each in their own folder: - **simple** in the `src/simple` folder - **singleton** in the `src/singleton` folder ### Simple We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions. In this case, all exported functions become public contract methods. ```ts // return the string 'hello world' export function helloWorld(): string {} // read the given key from account (contract) storage export function read(key: string): string {} // write the given value at the given key to account (contract) storage export function write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} ``` ### Singleton We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`. In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh). ```ts @nearBindgen export class Contract { // return the string 'hello world' helloWorld(): string {} // read the given key from account (contract) storage read(key: string): string {} // write the given value at the given key to account (contract) storage @mutateState() write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} } ``` ## Usage ### Getting started (see below for video recordings of each of the following steps) INSTALL `NEAR CLI` first like this: `npm i -g near-cli` 1. clone this repo to a local folder 2. run `yarn` 3. run `./scripts/1.dev-deploy.sh` 3. run `./scripts/2.use-contract.sh` 4. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 5. run `./scripts/3.cleanup.sh` ### Videos **`1.dev-deploy.sh`** This video shows the build and deployment of the contract. [![asciicast](https://asciinema.org/a/409575.svg)](https://asciinema.org/a/409575) **`2.use-contract.sh`** This video shows contract methods being called. You should run the script twice to see the effect it has on contract state. [![asciicast](https://asciinema.org/a/409577.svg)](https://asciinema.org/a/409577) **`3.cleanup.sh`** This video shows the cleanup script running. Make sure you add the `BENEFICIARY` environment variable. The script will remind you if you forget. ```sh export BENEFICIARY=<your-account-here> # this account receives contract account balance ``` [![asciicast](https://asciinema.org/a/409580.svg)](https://asciinema.org/a/409580) ### Other documentation - See `./scripts/README.md` for documentation about the scripts - Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` ## The file system ```sh ├── README.md # this file ├── as-pect.config.js # configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts) ├── package.json # NodeJS project manifest ├── scripts │   ├── 1.dev-deploy.sh # helper: build and deploy contracts │   ├── 2.use-contract.sh # helper: call methods on ContractPromise │   ├── 3.cleanup.sh # helper: delete build and deploy artifacts │   └── README.md # documentation for helper scripts ├── src │   ├── as_types.d.ts # AssemblyScript headers for type hints │   ├── simple # Contract 1: "Simple example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 1 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 1 │   ├── singleton # Contract 2: "Singleton-style example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 2 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 2 │   ├── tsconfig.json # Typescript configuration │   └── utils.ts # common contract utility functions └── yarn.lock # project manifest version lock ``` You may clone this repo to get started OR create everything from scratch. Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files: ``` ./assembly/ ./assembly/tests/ ./assembly/tests/example.spec.ts ./assembly/tests/as-pect.d.ts ```
kry2323_NCD-demo-project-guess-the-number
README.md as-pect.config.js asconfig.json package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts simple __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
## Setting up your terminal The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project. It uses the following setup: ```sh # set your terminal up to have 2 windows, A and B like this: ┌─────────────────────────────────┬─────────────────────────────────┐ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands _helper scripts_ ```sh 1.dev-deploy.sh # helper: build and deploy contracts 2.use-contract.sh # helper: call methods on ContractPromise 3.cleanup.sh # helper: delete build and deploy artifacts ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068) # `near-sdk-as` Starter Kit This is a good project to use as a starting point for your AssemblyScript project. ## Samples This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage There are 2 AssemblyScript contracts in this project, each in their own folder: - **simple** in the `src/simple` folder - **singleton** in the `src/singleton` folder ### Simple We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions. In this case, all exported functions become public contract methods. ```ts // return the string 'hello world' export function helloWorld(): string {} // read the given key from account (contract) storage export function read(key: string): string {} // write the given value at the given key to account (contract) storage export function write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} ``` ### Singleton We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`. In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh). ```ts @nearBindgen export class Contract { // return the string 'hello world' helloWorld(): string {} // read the given key from account (contract) storage read(key: string): string {} // write the given value at the given key to account (contract) storage @mutateState() write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} } ``` ## Usage ### Getting started (see below for video recordings of each of the following steps) INSTALL `NEAR CLI` first like this: `npm i -g near-cli` 1. clone this repo to a local folder 2. run `yarn` 3. run `./scripts/1.dev-deploy.sh` 3. run `./scripts/2.use-contract.sh` 4. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 5. run `./scripts/3.cleanup.sh` ### Videos **`1.dev-deploy.sh`** This video shows the build and deployment of the contract. [![asciicast](https://asciinema.org/a/409575.svg)](https://asciinema.org/a/409575) **`2.use-contract.sh`** This video shows contract methods being called. You should run the script twice to see the effect it has on contract state. [![asciicast](https://asciinema.org/a/409577.svg)](https://asciinema.org/a/409577) **`3.cleanup.sh`** This video shows the cleanup script running. Make sure you add the `BENEFICIARY` environment variable. The script will remind you if you forget. ```sh export BENEFICIARY=<your-account-here> # this account receives contract account balance ``` [![asciicast](https://asciinema.org/a/409580.svg)](https://asciinema.org/a/409580) ### Other documentation - See `./scripts/README.md` for documentation about the scripts - Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` ## The file system ```sh ├── README.md # this file ├── as-pect.config.js # configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts) ├── package.json # NodeJS project manifest ├── scripts │   ├── 1.dev-deploy.sh # helper: build and deploy contracts │   ├── 2.use-contract.sh # helper: call methods on ContractPromise │   ├── 3.cleanup.sh # helper: delete build and deploy artifacts │   └── README.md # documentation for helper scripts ├── src │   ├── as_types.d.ts # AssemblyScript headers for type hints │   ├── simple # Contract 1: "Simple example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 1 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 1 │   ├── singleton # Contract 2: "Singleton-style example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 2 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 2 │   ├── tsconfig.json # Typescript configuration │   └── utils.ts # common contract utility functions └── yarn.lock # project manifest version lock ``` You may clone this repo to get started OR create everything from scratch. Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files: ``` ./assembly/ ./assembly/tests/ ./assembly/tests/example.spec.ts ./assembly/tests/as-pect.d.ts ```
NEAR-DevHub_neardevhub-bos
.devcontainer devcontainer.json post-create.sh .github ISSUE_TEMPLATE bug_report.md feature-request.md workflows continuous-integration-workflow.yml deploy-dev-testnet.yml deploy-prod-mainnet.yml promote-develop-to-main.yml .gitpod.yml CONTRIBUTING.md README.md docs developing dontaskagain.md how-we-work.md module core lib autocomplete.js data-request.js gui form.js uuid.js entity viewer.js package-lock.json package.json playwright-tests storage-states wallet-connected-admin.json wallet-connected-chain-abstraction-community-admin.json wallet-connected-community-admin.json wallet-connected-moderator.json wallet-connected-not-kyc-verified-account.json wallet-connected-peter.json wallet-connected-with-devhub-access-key.json wallet-connected.json wallet-not-connected.json wallet-permissioned.json testUtils.js tests activity-feed.spec.js addons.spec.js admin.spec.js announcements.spec.js blog.spec.js bosloaderenvironment.spec.js communities.spec.js community.spec.js create.spec.js discussions.spec.js dontaskagain.spec.js feed.spec.js funding.spec.js proposals.spec.js search.spec.js tracking-visits.spec.js util addons.js bos-loader.js cache.js socialapi.js transaction.js playwright.config.js replacements.dev.json replacements.mainnet.json replacements.testnet.json scripts deploy_preview_environment.sh dev.sh migrate_tabs_addons.sh
# 👋 Welcome to the NEAR DevHub <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section --> [![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-) <!-- ALL-CONTRIBUTORS-BADGE:END --> [NEAR DevHub](http://devgovgigs.near.social) is a decentralized community platform for NEAR developers to contribute to the ecosystem and stay informed on the latest topics. It enables anyone to share ideas, match solutions, and access technical support and funding. The Developer DAO team is actively developing the DevHub and welcoming open contributions from the community. We strive to maintain a transparent and efficient process for all. This repository holds [NEAR Social](https://near.social) widgets to interact with the [DevHub smart-contract](https://github.com/near/devgigsboard). ## How to contribute? Anyone is welcome to contribute. Here are ways to get involved: * **Contribute code**: Review the list of [good first issues](https://github.com/near/devgigsboard-widgets/contribute). You can pick any issues from the [Backlog column](https://github.com/orgs/near/projects/60) and indicate your interest by leaving comments. Before you get started, we encourage you to check out [how we work](https://github.com/near/devgigsboard-widgets/blob/main/docs/how-we-work.md) and the [developer guidelines](https://github.com/near/devgigsboard-widgets/blob/main/CONTRIBUTING.md). * **Report issues**: To report a [bug](https://github.com/near/devgigsboard-widgets/issues/new?assignees=&labels=bug&template=bug_report.md&title=) or a [feature request](https://github.com/near/devgigsboard-widgets/issues/new?assignees=&labels=enhancement&template=feature-request.md&title=), please review all open and closed [issues](https://github.com/near/devgigsboard-widgets/issues?q=is%3Aissue+is%3Aall+) to make sure no one has previously created a similar topic. * **Triage issues**: You are welcome to help us triage by verifying or reproducing bugs, adding more specific reproduction instructions, or voting on issues by adding a 👍 thumbs-up reaction to the issue's description comment. We grant commit access to the Developer DAO team and any active developers who have gained our trust by demonstrating high-quality contributions and ongoing commitment to our ecosystem. ## How we work We communicate primarily over GitHub. We recommend configuring your [notifications](https://docs.github.com/en/account-and-profile/managing-subscriptions-and-notifications-on-github/setting-up-notifications/configuring-notifications) to ensure you get the latest updates. [Learn more](https://github.com/near/devgigsboard-widgets/blob/main/docs/how-we-work.md) about how we work asynchronously. ## Getting Help If you are working on a specific issue, you can leave a comment. You can also drop a message on the [NEAR Dev](https://t.me/neardev) Telegram channel. ## Contributors ✨ <a href="https://github.com/near/neardevhub-widgets/graphs/contributors"> <img src="https://contrib.rocks/image?repo=near/neardevhub-widgets" /> </a> Made with [contrib.rocks](https://contrib.rocks).
here-wallet_js-sdk
README.md example index.html index.ts success.html package-lock.json package.json src helpers actions.ts nep0314.ts proxyMethods.ts types.ts utils.ts index.ts qrcode-strategy core index.js utils.js index.ts logo.ts qrcode.ts storage HereKeyStore.ts JSONStorage.ts strategies HereStrategy.ts InjectedStrategy.ts TelegramAppStrategy.ts WidgetStrategy.ts WindowStrategy.ts types.ts wallet.ts tsconfig.json
# @herewallet/core In contrast to the synchronous signing of transactions in web near wallets, where the user is redirected to the wallet site for signing -- **HERE Wallet** provides the ability to sign transactions using async/await API calls. ```bash npm i near-api-js@^0.44.2 --save npm i @here-wallet/core --save ``` ## Usage ```ts import { HereWallet } from "@here-wallet/core"; const here = await HereWallet.connect(); const account = await here.signIn({ contractId: "social.near" }); console.log(`Hello ${account}!`); ``` **You can also login to the wallet without adding a key. For this you can call `signIn` without `contractId`** ## How it works By default, all near-selector api calls that you make with this library run a background process and generate a unique link that the user can go to their mobile wallet and confirm the transaction. This is a link of the form: https://h4n.app/TRX_PART_OF_SHA1_IN_BASE64 If a user has logged into your application from a phone and has a wallet installed, we immediately transfer him to the application for signing. In all other cases, we open a new window on the web.herewallet.app site, where the user can find information about installing the wallet and sign the transaction there. All this time while user signing the transaction, a background process in your application will monitor the status of the transaction requested for signing. ## Sign in is optional! You can generate a signing transaction without knowing your user's accountId (without calling signIn). There are cases when you do not need to receive a public key from the user to call your contract, but you want to ask the user to perform an action in your application once: ```ts import { HereWallet } from "@here-wallet/core"; const here = await HereWallet.connect(); const tx = await here.signAndSendTransaction({ actions: [{ type: "FunctionCall", params: { deposit: 1000 } }], receiverId: "donate.near", }); console.log("Thanks for the donation!"); ``` ## Build Telegram App and connect HOT Telegram Wallet ```ts import { HereWallet } from "@here-wallet/core"; const here = await HereWallet.connect({ botId: "HOTExampleConnectBot/app", // Your bot MiniApp walletId: "herewalletbot/app", // HOT Wallet }); ``` ## Login without AddKey In order to use the wallet for authorization on the backend, you need to use the signMessage method. This method signs your message with a private full access key inside the wallet. You can also use this just to securely get your user's accountId without any extra transactions. ```ts import { HereWallet } from "@here-wallet/core"; const here = await HereWallet.connect(); const nonce = Array.from(crypto.getRandomValues(new Uint8Array(32))); const recipient = window.location.host; const message = "Authenticate message"; const { signature, publicKey, accountId } = await here.signMessage({ recipient, nonce, message }); // Verify on you backend side, check NEP0413 const accessToken = await axios.post(yourAPI, { signature, accountId, publicKey, nonce, message, recipient }); console.log("Auth completed!"); ``` Or you can verify signMessage on client side, just call: ```ts try { const { accountId } = await here.authenticate(); console.log(`Hello ${accountId}!`); } catch (e) { console.log(e); } ``` If you use js-sdk on your backend, then you do not need to additionally check the signature and key, the library does this, and if the signature is invalid or the key is not a full access key, then the method returns an error. Otherwise, on the backend, you need to verify the signature and message with this public key. And also check that this public key is the full access key for this accountId. **It's important to understand** that the returned message is not the same as the message you submitted for signature. This message conforms to the standard: https://github.com/near/NEPs/pull/413 ## Instant Wallet with AppClip If your goal is to provide the user with a convenient way to log in to your desktop app, you can use Here Instant Wallet, which allows users without a wallet to instantly create one via appclip. > At the moment here wallet is only available for IOS users You have the option to override how your user is delivered the signing link. This is how you can create a long-lived transaction signature request and render it on your web page: ```ts import { HereStrategy, HereWallet } from "@here-wallet/core"; import { QRCodeStrategy } from "@here-wallet/core/qrcode-strategy"; const putQrcode = document.getElementById("qr-container"); // Instant wallet signin HERE! const here = await HereWallet.connect(); await here.signIn({ contractId: "social.near", // override default connect strategy strategy: new QRCodeStrategy({ element: putQrcode, theme: "dark", size: 128, }), }); ``` You can also look at an example in this repository /example/index.ts or in sandbox: https://codesandbox.io/s/here-wallet-instant-app-6msgmn ## Security To transfer data between the application and the phone, we use our own proxy service. On the client side, a transaction confirmation request is generated with a unique request_id, our wallet receives this request_id and requests this transaction from the proxy. **To make sure that the transaction was not forged by the proxy service, the link that opens inside the application contains a hash-sum of the transaction. If the hashes do not match, the wallet will automatically reject the signing request**
FurkanHaydari_pratik
README.md as-pect.config.js asconfig.json package-lock.json package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts simple __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
## Setting up your terminal The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project. It uses the following setup: ```sh # set your terminal up to have 2 windows, A and B like this: ┌─────────────────────────────────┬─────────────────────────────────┐ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands _helper scripts_ ```sh 1.dev-deploy.sh # helper: build and deploy contracts 2.use-contract.sh # helper: call methods on ContractPromise 3.cleanup.sh # helper: delete build and deploy artifacts ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068) # `near-sdk-as` Starter Kit This is a good project to use as a starting point for your AssemblyScript project. ## Samples This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage There are 2 AssemblyScript contracts in this project, each in their own folder: - **simple** in the `src/simple` folder - **singleton** in the `src/singleton` folder ### Simple We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions. In this case, all exported functions become public contract methods. ```ts // return the string 'hello world' export function helloWorld(): string {} // read the given key from account (contract) storage export function read(key: string): string {} // write the given value at the given key to account (contract) storage export function write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} ``` ### Singleton We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`. In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh). ```ts @nearBindgen export class Contract { // return the string 'hello world' helloWorld(): string {} // read the given key from account (contract) storage read(key: string): string {} // write the given value at the given key to account (contract) storage @mutateState() write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} } ``` ## Usage ### Getting started (see below for video recordings of each of the following steps) INSTALL `NEAR CLI` first like this: `npm i -g near-cli` 1. clone this repo to a local folder 2. run `yarn` 3. run `./scripts/1.dev-deploy.sh` 3. run `./scripts/2.use-contract.sh` 4. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 5. run `./scripts/3.cleanup.sh` ### Videos **`1.dev-deploy.sh`** This video shows the build and deployment of the contract. [![asciicast](https://asciinema.org/a/409575.svg)](https://asciinema.org/a/409575) **`2.use-contract.sh`** This video shows contract methods being called. You should run the script twice to see the effect it has on contract state. [![asciicast](https://asciinema.org/a/409577.svg)](https://asciinema.org/a/409577) **`3.cleanup.sh`** This video shows the cleanup script running. Make sure you add the `BENEFICIARY` environment variable. The script will remind you if you forget. ```sh export BENEFICIARY=<your-account-here> # this account receives contract account balance ``` [![asciicast](https://asciinema.org/a/409580.svg)](https://asciinema.org/a/409580) ### Other documentation - See `./scripts/README.md` for documentation about the scripts - Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` ## The file system ```sh ├── README.md # this file ├── as-pect.config.js # configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts) ├── package.json # NodeJS project manifest ├── scripts │   ├── 1.dev-deploy.sh # helper: build and deploy contracts │   ├── 2.use-contract.sh # helper: call methods on ContractPromise │   ├── 3.cleanup.sh # helper: delete build and deploy artifacts │   └── README.md # documentation for helper scripts ├── src │   ├── as_types.d.ts # AssemblyScript headers for type hints │   ├── simple # Contract 1: "Simple example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 1 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 1 │   ├── singleton # Contract 2: "Singleton-style example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 2 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 2 │   ├── tsconfig.json # Typescript configuration │   └── utils.ts # common contract utility functions └── yarn.lock # project manifest version lock ``` You may clone this repo to get started OR create everything from scratch. Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files: ``` ./assembly/ ./assembly/tests/ ./assembly/tests/example.spec.ts ./assembly/tests/as-pect.d.ts ``` # NEAR_WEB3_FIRST_PROJECT
hskang9_aurora-dao-demo
.idea discord.xml modules.xml vcs.xml Cargo.toml README.md src common.rs lib.rs main.rs
# aurora-dao-demo demo for aurora dao deployment
nidakus_Web3-Fundamentals-with-NEAR
README.md as-pect.config.js asconfig.json package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts simple __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
# `near-sdk-as` Starter Kit This is a good project to use as a starting point for your AssemblyScript project. ## Samples This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage There are 2 AssemblyScript contracts in this project, each in their own folder: - **simple** in the `src/simple` folder - **singleton** in the `src/singleton` folder ### Simple We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions. In this case, all exported functions become public contract methods. ```ts // return the string 'hello world' export function helloWorld(): string {} // read the given key from account (contract) storage export function read(key: string): string {} // write the given value at the given key to account (contract) storage export function write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} ``` ### Singleton We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`. In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh). ```ts @nearBindgen export class Contract { // return the string 'hello world' helloWorld(): string {} // read the given key from account (contract) storage read(key: string): string {} // write the given value at the given key to account (contract) storage @mutateState() write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} } ``` ## Usage ### Getting started (see below for video recordings of each of the following steps) INSTALL `NEAR CLI` first like this: `npm i -g near-cli` 1. clone this repo to a local folder 2. run `yarn` 3. run `./scripts/1.dev-deploy.sh` 3. run `./scripts/2.use-contract.sh` 4. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 5. run `./scripts/3.cleanup.sh` ### Videos **`1.dev-deploy.sh`** This video shows the build and deployment of the contract. [![asciicast](https://asciinema.org/a/409575.svg)](https://asciinema.org/a/409575) **`2.use-contract.sh`** This video shows contract methods being called. You should run the script twice to see the effect it has on contract state. [![asciicast](https://asciinema.org/a/409577.svg)](https://asciinema.org/a/409577) **`3.cleanup.sh`** This video shows the cleanup script running. Make sure you add the `BENEFICIARY` environment variable. The script will remind you if you forget. ```sh export BENEFICIARY=<your-account-here> # this account receives contract account balance ``` [![asciicast](https://asciinema.org/a/409580.svg)](https://asciinema.org/a/409580) ### Other documentation - See `./scripts/README.md` for documentation about the scripts - Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` ## The file system ```sh ├── README.md # this file ├── as-pect.config.js # configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts) ├── package.json # NodeJS project manifest ├── scripts │   ├── 1.dev-deploy.sh # helper: build and deploy contracts │   ├── 2.use-contract.sh # helper: call methods on ContractPromise │   ├── 3.cleanup.sh # helper: delete build and deploy artifacts │   └── README.md # documentation for helper scripts ├── src │   ├── as_types.d.ts # AssemblyScript headers for type hints │   ├── simple # Contract 1: "Simple example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 1 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 1 │   ├── singleton # Contract 2: "Singleton-style example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 2 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 2 │   ├── tsconfig.json # Typescript configuration │   └── utils.ts # common contract utility functions └── yarn.lock # project manifest version lock ``` You may clone this repo to get started OR create everything from scratch. Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files: ``` ./assembly/ ./assembly/tests/ ./assembly/tests/example.spec.ts ./assembly/tests/as-pect.d.ts ``` ## Setting up your terminal The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project. It uses the following setup: ```sh # set your terminal up to have 2 windows, A and B like this: ┌─────────────────────────────────┬─────────────────────────────────┐ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands _helper scripts_ ```sh 1.dev-deploy.sh # helper: build and deploy contracts 2.use-contract.sh # helper: call methods on ContractPromise 3.cleanup.sh # helper: delete build and deploy artifacts ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068)
nearprotocol_near-contract-standards-rs
hack-a-chain-software_near.monorepo
.eslintrc.js .github ISSUE_TEMPLATE bug-report.yml feature-creation.yml PULL_REQUEST_TEMPLATE.md workflows CI.yml .husky commit-msg.sh LICENSE.md commitlint.config.js cypress.config.ts cypress e2e base.cy.ts fixtures example.json support commands.ts e2e.ts format_rust.sh package.json packages contracts .rustfmt.toml Cargo.toml README.md compile.js contract Cargo.toml README.md src lib.rs jest.config.js package.json tests-rs Cargo.toml src main.rs methods mod.rs storage.rs token.rs tsconfig.json front index.html package.json postcss.config.js public logo-black.svg logo-white.svg src components index.ts index.css utils constants contracts.ts index.ts near.ts tailwind.config.js tsconfig.json tsconfig.node.json vite.config.ts tsconfig.json
contract ================== This app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `contract.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `contract.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account contract.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'contract.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages contract Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html
nearnautnft_astro-token-contract
Cargo.toml build.sh lib.rs
osamarizk_near-rust-smartcontract
Cargo.toml README.md build.bat build.sh src lib.rs test.sh
# Rust Smart Contract Template ## Getting started To get started with this template: 1. Click the "Use this template" button to create a new repo based on this template 2. Update line 2 of `Cargo.toml` with your project name 3. Update line 4 of `Cargo.toml` with your project author names 4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites) 5. Begin writing your smart contract in `src/lib.rs` 6. Test the contract `cargo test -- --nocapture` 8. Build the contract `RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release` **Get more info at:** * [Rust Smart Contract Quick Start](https://docs.near.org/docs/develop/contracts/rust/intro) * [Rust SDK Book](https://www.near-sdk.io/)
Habeebtoyin_Nearcoin-flip-js
README.md contract README.md babel.config.json build.sh deploy.sh package.json src contract.ts tsconfig.json frontend assets global.css logo-black.svg logo-white.svg index.html index.js near-wallet.js package.json start.sh integration-tests package.json src main.ava.ts package.json
# Coin Flip Contract The smart contract implements a flip coin game in which the player tries to guess the next outcome. The player gets a point on each correct guess, and losses one for each wrong one. ```ts function simulateCoinFlip(): Side { const randomString: string = near.randomSeed(); return randomString.charCodeAt(0) % 2 ? 'heads' : 'tails'; } flip_coin({ player_guess }: { player_guess: Side }): Side { // Check who called the method const player = near.predecessorAccountId(); near.log(`${player} chose ${player_guess}`); // Simulate a Coin Flip const outcome = simulateCoinFlip(); // Get the current player points let player_points: number = (this.points.get(player) || 0) as number // Check if their guess was right and modify the points accordingly if(player_guess == outcome) { near.log(`The result was ${outcome}, you get a point!`); player_points += 1; } else { near.log(`The result was ${outcome}, you lost a point`); player_points = player_points? player_points - 1 : 0; } // Store the new points this.points.set(player, player_points) return outcome } ``` <br /> # Quickstart 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash npm run deploy ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Get the Score `points_of` performs read-only operations, therefore it is a `view` method. `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the points near view <dev-account> points_of '{"player": "<dev-account>"}' ``` <br /> ## 3. Flip a Coin and Try to Guess the Outcome `flip_coin` takes a guess ("heads" or "tails"), simulates a coin flip and gives/removes points to the player. It changes the contract's state, for which it is a `call` method. `Call` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to play near call <dev-account> flip_coin '{"player_guess":"tails"}' --accountId <dev-account> ``` **Tip:** If you would like to call `flip_coin` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. ## A Note on Random Numbers Generating random numbers in an adversarial environment such as a blockchain is very difficult. This spawns from the fact that everything is public on the network. Please check our documentation to learn more about handling [random numbers in a blockchain](https://docs.near.org/develop/contracts/security/storage). # Coin Flip 🪙 [![](https://img.shields.io/badge/⋈%20Examples-Basics-green)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Gitpod-Ready-orange)](https://gitpod.io/#/https://github.com/near-examples/coin-flip-js) [![](https://img.shields.io/badge/Contract-js-yellow)](https://docs.near.org/develop/contracts/anatomy) [![](https://img.shields.io/badge/Frontend-JS-yellow)](https://docs.near.org/develop/integrate/frontend) [![](https://img.shields.io/badge/Testing-passing-green)](https://docs.near.org/develop/integrate/frontend) Coin Flip is a game were the player tries to guess the outcome of a coin flip. It is one of the simplest contracts implementing random numbers. # What This Example Shows 1. How to store and retrieve information in the NEAR network. 2. How to integrate a smart contract in a web frontend. 3. How to generate random numbers in a contract. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/https://github.com/near-examples/coin-flip-js). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` ### 3. Deploy the Contract Build the contract and deploy it in a testnet account ```bash npm run deploy ``` ### 4. Start the Frontend Start the web application to interact with your smart contract ```bash npm start ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome).
fredericBui_apprenticeNFT
.gitpod.yml .prettierrc.json README.md __test__ avalanche.test.ts polygon.test.ts secret.test.ts solana.test.ts components protocols avalanche components index.ts lib index.ts celo components index.ts lib index.ts ceramic lib figmentLearnSchema.json figmentLearnSchemaCompact.json identityStore LocalStorage.ts index.ts index.ts types index.ts near components index.ts lib index.ts polkadot components index.ts lib index.ts polygon challenges balance.ts connect.ts deploy.ts getter.ts index.ts query.ts restore.ts setter.ts transfer.ts components index.ts lib index.ts pyth components index.ts lib index.ts swap.ts secret components index.ts lib index.ts solana components index.ts lib index.ts tezos components index.ts lib index.ts the_graph graphql query.ts the_graph_near graphql query.ts shared Button.styles.ts CustomMarkdown Markdown.styles.ts VideoPlayer VideoPlayer.styles.ts utils markdown-utils.ts string-utils.ts ProtocolNav ProtocolNav.styles.ts contracts celo HelloWorld.json near Cargo.toml README.md compile.js src lib.rs polygon SimpleStorage README.md SimpleStorage.json migrations 1_initial_migration.js 2_deploy_contracts.js package.json truffle-config.js solana program Cargo.toml Xargo.toml src lib.rs tests lib.rs tezos counter.js the_graph CryptopunksData.abi.json docker docker-compose-near.yml docker-compose.yml hooks index.ts useColors.ts useLocalStorage.ts useSteps.ts jest.config.js lib constants.ts markdown PREFACE.md avalanche CHAIN_CONNECTION.md CREATE_KEYPAIR.md EXPORT_TOKEN.md FINAL.md GET_BALANCE.md IMPORT_TOKEN.md PROJECT_SETUP.md TRANSFER_TOKEN.md celo CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md SWAP_TOKEN.md TRANSFER_TOKEN.md ceramic BASIC_PROFILE.md CHAIN_CONNECTION.md CUSTOM_DEFINITION.md FINAL.md LOGIN.md PROJECT_SETUP.md near CHAIN_CONNECTION.md CREATE_ACCOUNT.md CREATE_KEYPAIR.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md polkadot CHAIN_CONNECTION.md CREATE_ACCOUNT.md ESTIMATE_DEPOSIT.md ESTIMATE_FEES.md FINAL.md GET_BALANCE.md PROJECT_SETUP.md RESTORE_ACCOUNT.md TRANSFER_TOKEN.md polygon CHAIN_CONNECTION.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md QUERY_CHAIN.md RESTORE_ACCOUNT.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md pyth FINAL.md PROJECT_SETUP.md PYTH_CONNECT.md PYTH_EXCHANGE.md PYTH_LIQUIDATE.md PYTH_SOLANA_WALLET.md PYTH_VISUALIZE_DATA.md secret CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md solana CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md FUND_ACCOUNT.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md SOLANA_CREATE_GREETER.md TRANSFER_TOKEN.md tezos CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md the_graph FINAL.md GRAPH_NODE.md PROJECT_SETUP.md SUBGRAPH_MANIFEST.md SUBGRAPH_MAPPINGS.md SUBGRAPH_QUERY.md SUBGRAPH_SCAFFOLD.md SUBGRAPH_SCHEMA.md the_graph_near FINAL.md GRAPH_NODE.md PROJECT_SETUP.md SUBGRAPH_MANIFEST.md SUBGRAPH_MAPPINGS.md SUBGRAPH_QUERY.md SUBGRAPH_SCAFFOLD.md SUBGRAPH_SCHEMA.md | n : | next-env.d.ts next.config.js package.json pages api avalanche account.ts balance.ts connect.ts export.ts import.ts transfer.ts celo account.ts balance.ts connect.ts deploy.ts getter.ts setter.ts swap.ts transfer.ts near balance.ts check-account.ts connect.ts create-account.ts deploy.ts getter.ts keypair.ts setter.ts transfer.ts polkadot account.ts balance.ts connect.ts deposit.ts estimate.ts restore.ts transfer.ts pyth connect.ts secret account.ts balance.ts connect.ts deploy.ts getter.ts setter.ts transfer.ts solana balance.ts connect.ts deploy.ts fund.ts getter.ts greeter.ts keypair.ts setter.ts transfer.ts tezos account.ts balance.ts connect.ts deploy.ts getter.ts setter.ts transfer.ts the-graph-near entity.ts manifest.ts scaffold.ts the-graph entity.ts manifest.ts mapping.ts node.ts scaffold.ts public discord.svg figment-learn-compact.svg vercel.svg theme colors.ts index.ts media.ts tsconfig.json types index.ts utils colors.ts context.ts external.ts markdown.ts networks.ts pages.ts string-utils.ts tracking-utils.ts
Based on: MetaCoin tutorial from Truffle docs https://www.trufflesuite.com/docs/truffle/quickstart SimpleStorage example contract from Solidity docs https://docs.soliditylang.org/en/v0.4.24/introduction-to-smart-contracts.html#storage 1. Install truffle (https://www.trufflesuite.com/docs/truffle/getting-started/installation) `npm install -g truffle` 2. Navigate to this directory (/contracts/polygon/SimpleStorage) 3. Install dependencies `yarn` 4. Test contract `truffle test ./test/TestSimpleStorage.sol` **Possible issue:** "Something went wrong while attempting to connect to the network. Check your network configuration. Could not connect to your Ethereum client with the following parameters:" **Solution:** run `truffle develop` and make sure port matches the one in truffle-config.js under development and test networks 5. Run locally via `truffle develop` $ truffle develop ``` migrate let instance = await SimpleStorage.deployed(); let storedDataBefore = await instance.get(); storedDataBefore.toNumber() // Should print 0 instance.set(50); let storedDataAfter = await instance.get(); storedDataAfter.toNumber() // Should print 50 ``` 6. Create Polygon testnet account - Install MetaMask (https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn?hl=en) - Add a custom network with the following params: Network Name: "Polygon Mumbai" RPC URL: https://rpc-mumbai.maticvigil.com/ Chain ID: 80001 Currency Symbol: MATIC Block Explorer URL: https://mumbai.polygonscan.com 7. Fund your account from the Matic Faucet https://faucet.matic.network Select MATIC Token, Mumbai Network Enter your account address from MetaMask Wait until time limit is up, requests tokens 3-4 times so you have enough to deploy your contract 8. Add a `.secret` file in this directory with your account's seed phrase or mnemonic (you should be required to write this down or store it securely when creating your account in MetaMask). In `truffle-config.js`, uncomment the three constant declarations at the top, along with the matic section of the networks section of the configuration object. 9. Deploy contract `truffle migrate --network matic` 10. Interact via web3.js ```js const {ethers} = require('ethers'); const fs = require('fs'); const mnemonic = fs.readFileSync('.secret').toString().trim(); const signer = new ethers.Wallet.fromMnemonic(mnemonic); const provider = new ethers.providers.JsonRpcProvider( 'https://matic-mumbai.chainstacklabs.com', ); const json = JSON.parse( fs.readFileSync('build/contracts/SimpleStorage.json').toString(), ); const contract = new ethers.Contract( json.networks['80001'].address, json.abi, signer.connect(provider), ); contract.get().then((val) => console.log(val.toNumber())); // should log 0 contract.set(50).then((receipt) => console.log(receipt)); contract.get().then((val) => console.log(val.toNumber())); // should log 50 ``` # Pathway Smart Contract A [smart contract] written in [Rust] for [figment pathway] # Quick Start Before you compile this code, you will need to install Rust with [correct target] # Exploring The Code 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [rust]: https://www.rust-lang.org/ [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html # 👋🏼 What is `learn-web3-dapp`? We made this decentralized application (dApp) to help developers learn about Web 3 protocols. It's a Next.js app that uses React, TypeScript and various smart contract languages (mostly Solidity and Rust). We will guide you through using the various blockchain JavaScript SDKs to interact with their networks. Each protocol is slightly different, but we have attempted to standardize the workflow so that you can quickly get up to speed on networks like Solana, NEAR, Polygon and more! - ✅ Solana - ✅ Polygon - ✅ Avalanche - ✅ NEAR - ✅ Tezos - ✅ Secret - ✅ Polkadot - ✅ Celo - ✅ The Graph - ✅ The Graph for NEAR - ✅ Pyth - 🔜 Ceramic - 🔜 Arweave - 🔜 Chainlink - [Let us know which one you'd like us to cover](https://github.com/figment-networks/learn-web3-dapp/issues) <img width="1024" alt="Screen Shot 1" src="https://raw.githubusercontent.com/figment-networks/learn-web3-dapp/main/markdown/__images__/readme_01.png"> <img width="1024" alt="Screen Shot 2" src="https://raw.githubusercontent.com/figment-networks/learn-web3-dapp/main/markdown/__images__/readme-02.png"> <img width="1024" alt="Screen Shot 3" src="https://raw.githubusercontent.com/figment-networks/learn-web3-dapp/main/markdown/__images__/readme-03.png"> # 🧑‍💻 Get started ## 🤖 Using Gitpod (Recommended) The best way to go through those courses is using [Gitpod](https://gitpod.io). Gitpod provides prebuilt developer environments in your browser, powered by VS Code. Just sign in using GitHub and you'll be up and running in seconds without having to do any manual setup 🔥 [**Open this repo on Gitpod**](https://gitpod.io/#https://github.com/figment-networks/learn-web3-dapp) ## 🐑 Clone locally Make sure you have installed [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git), [Node.js](https://nodejs.org/en/) (Please install **v14.17.0**, we recommend using [nvm](https://github.com/nvm-sh/nvm)) and [yarn](https://yarnpkg.com/getting-started/install). Then clone the repo, install dependencies and start the server by running all these commands: ```text git clone https://github.com/figment-networks/learn-web3-dapp.git cd learn-web3-dapp yarn yarn dev ``` # 🤝 Feedback and contributing If you encounter any errors during this process, please join our [Discord](https://figment.io/devchat) for help. Feel free to also open an Issue or a Pull Request on the repo itself. We hope you enjoy our Web 3 education dApps 🚀 -- ❤️ The Figment Learn Team
Learn-NEAR-Club_superise-ui
.postcssrc.json .prettierrc.json README.md package.json src assets favicon.svg domain near config.ts ft metadata.ts methods.ts models.ts global.ts models.ts nft methods.ts models.ts wrap-near.ts paras methods.ts models.ts ref constants.ts methods.ts superise methods.ts models.ts fakedata account.json pool.json index.html jest.config.js locales en_US.ts zh_CN.ts services SpecialWallet.ts near.ts state prize.ts token.ts typings.d.ts utils device.ts near.ts numbers.ts time.js time.ts token.ts tailwind.config.js tsconfig.json
## Surprise Surprise is a mystery box dapp built on top of the NEAR protocol.
Hugoo_near-rocket-approval
.gitpod.yml README.md babel.config.js contract README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts tsconfig.json compile.js package-lock.json package.json package.json src App.js __mocks__ fileMock.js assets logo-black.svg logo-white.svg config.js global.css index.html index.js jest.init.js main.test.js utils.js wallet login index.html
near-rocket-approval Smart Contract ================== A [smart contract] written in [AssemblyScript] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install [Node.js] ≥ 12 Exploring The Code ================== 1. The main smart contract code lives in `assembly/index.ts`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard AssemblyScript tests using [as-pect]. [smart contract]: https://docs.near.org/docs/roles/developer/contracts/intro [AssemblyScript]: https://www.assemblyscript.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [as-pect]: https://www.npmjs.com/package/@as-pect/cli near-rocket-approval ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-rocket-approval.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-rocket-approval.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-rocket-approval.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-rocket-approval.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages
NEARWEEK_api.news
.eslintrc.js .github ISSUE_TEMPLATE BOUNTY.yml README.md app.js config app.js calendly.js currency.js grant.js hellosign.js invoice.js kycDaoConfig.js near.js ecosystem.config.js locales en.json middlewares near.js verifyNearSignatureHeader.js modules GrantApplication GrantApplicationController.js GrantApplicationFormSchema.js GrantApplicationModel.js GrantApplicationRoutes.js Invoice InvoiceController.js InvoiceGenerator.js InvoiceRoutes.js Milestone FullMilestoneFormSchema.js MilestoneController.js MilestoneFormSchema.js MilestoneRoutes.js Signature SignatureController.js SignatureRoutes.js package-lock.json package.json prettier.config.js services calendlyService.js errorReportingService.js hellosignService.js nearService.js utilities authorizer.js generateContract.js getCountry.js getGrant.js getNearConfig.js getPayments.js getVerifyAndSaveGrantData.js hashProposal.js loadAndVerifyMilestoneAndGrant.js logger.js setUpNear.js sha256.js verifySignatureOfObject.js verifySignatureOfString.js
# api.grants [![NEAR](https://img.shields.io/badge/NEAR-%E2%8B%88-111111.svg)](https://near.org/) [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](LICENSE) > Easy to set up end to end grant application form for DAOs on NEAR Protocol ## Repositories - [ui.grants](https://github.com/NEARFoundation/ui.grants) - [api.grants](https://github.com/NEARFoundation/api.grants) - [admin.grants](https://github.com/NEARFoundation/admin.grants) ## Technology stack - Blockchain: **[NEAR](https://near.org/)** - Smart Contracts: **[Sputnik DAO Factory V2](https://github.com/near-daos/sputnik-dao-contract/tree/main/sputnikdao-factory2), [Sputnik DAO V2](https://github.com/near-daos/sputnik-dao-contract/tree/main/sputnikdao2)** - Package manager: **[NPM](https://www.npmjs.com/)** - Application framework: **[ExpressJS](https://expressjs.com/)** - Code quality: **[Eslint](https://eslint.org/), [Prettier](https://prettier.io/)** - Database: **[MongoDB](https://www.mongodb.com/)** - Docx Templating: **[docx-templates](https://github.com/guigrpa/docx-templates)** - Contract Signature: **[hellosign](https://github.com/HelloFax/hellosign-nodejs-sdk)** - KYC: **[KYC DAO](https://github.com/kycdao)** - Invoicing: **[Node microinvoice](https://github.com/baptistejamin/node-microinvoice)** - Scheduling: **[Calendly](https://developer.calendly.com/)** ## Guides ### Configuration ```bash cp .env.dist .env # 1. set up variables on .env # 2. update the template in templates/agreement.docx # 3. replace the logo in `assets` ``` ### Special routes for admin > These special routes should be moved to the admin panel with a better security. They are protected by a secret URL using ADMIN_TOKEN and basic auth using ADMIN_LOGIN and ADMIN_PASSWORD #### Invoice downloading > Use this route to download the invoice - Route: `/admin/:adminToken/accounts/:nearId/grants/:id/invoices/:invoiceId` - `adminToken`: ADMIN_TOKEN from the env variable to authorize the request - `nearId`: The near account id of the grant user - `id`: The grant id that can be found in the database - `invoiceId`: The invoice id (0 for the first payment, 1 for milestone 1, ...) - Example: `/admin/TdgB349TfjpUnOqQMIIMOQoPf2kU/accounts/sound.testnet/grants/6/invoices/0` #### Agreement signature > This route has been created as a workaround because it seems like the hellosign API doesn't allow to have one signer using the embedded widget and the other using the hello sign website; more info here: https://github.com/NEARFoundation/api.grants/issues/22#issuecomment-1180164237 - Route: `/admin/:adminToken/accounts/:nearId/grants/:id/agreement/signature` - `adminToken`: ADMIN_TOKEN from the env variable to authorize the request - `nearId`: The near account id of the grant user - `id`: The grant id that can be found in the database - Example: `/admin/TdgB349TfjpUnOqQMIIMOQoPf2kU/accounts/sound.testnet/grants/6/agreement/signature` ### Installation ```bash npm install ``` Set up .env ### Development ```bash # run mongodb npm run dev ``` Open [http://localhost:4000](http://localhost:4000) with your browser to see the result. ### Deployment ```bash npm install npm start ``` ### Testing No tests are implemented yet. ## Authors - [Sandoche](https://github.com/sandoche)
nearprotocol_booth
README.md assembly main.ts model.ts tsconfig.json babel.config.js gulpfile.js package-lock.json package.json src App.css App.js App.test.js __mocks__ fileMock.js assets gray_near_logo.svg logo.svg near.svg config.js index.html index.js jest.init.js main.test.js wallet login index.html
<br /> <br /> <p> <img src="https://nearprotocol.com/wp-content/themes/near-19/assets/img/logo.svg?t=1553011311" width="240"> </p> <br /> <br /> ## Template for NEAR dapps ### Features * Create NEAR dapps with a React frontend 🐲 * We got Gulp! 💦 ### Requirements ##### IMPORTANT: Make sure you have the latest version of NEAR Shell and Node Version > 10.x 1. node and npm 2. near shell ``` npm i -g near-shell ``` 3.(optional) install yarn to build ``` npm i -g yarn ``` ### To run on testnet #### Step 1: Create account for the contract and deploy the contract. You'll now want to authorize NEAR shell on your NEAR account, which will allow NEAR Shell to deploy contracts on your NEAR account's behalf \(and spend your NEAR account balance to do so\). Type the command `near login` which should return a url: ```bash Please navigate to this url and follow the instructions to log in: https://wallet.nearprotocol.com/login/?title=NEAR+Shell&public_key={publicKey} ``` From there enter in your terminal the same account ID that you authorized: `Please enter the accountId that you logged in with: <asdfasdf>` Once you have entered your account ID, it will display the following message: `Missing public key for <asdfasdf> in default` `Logged in with masternode24` This message is not an error, it just means that it will create a public key for you. #### Step 2: Modify src/config.js line that sets the contractName. Set it to id from step 1. ```javascript (function() { const CONTRACT_NAME = 'react-template'; /* TODO: Change this to your contract's name! */ const DEFAULT_ENV = 'development'; ... })(); ``` #### Step 3: Finally, run the command in your terminal. ``` npm install && npm start ``` with yarn: ``` yarn install && yarn start ``` The server that starts is for static assets and by default serves them to localhost:3000. Navigate there in your browser to see the app running! ### Deploy Check the scripts in the package.json, for frontend and backend both, run the command: ```bash npm run(yarn) deploy ``` ### Test For test file src/App.test.js, it works for the template after finishing step 3 above. If smart contract and index.js change, user should change to their functions to test. The command is: ```bash npm run(yarn) test ``` ### To Explore - `assembly/main.ts` for the contract code - `public/index.html` for the front-end HTML - `src/index.js` for the JavaScript front-end code and how to integrate contracts - `src/App.js` for the first react component
NEARBuilders_hack.near
README.md bos.config.json src ABC Page.metadata.json View Page.metadata.json Academy.metadata.json Common library.metadata.json CreateQuest index.metadata.json Customization.metadata.json DAO Groups.metadata.json Members.metadata.json RemoveMember.metadata.json badge.metadata.json badges.metadata.json candidate.metadata.json election.metadata.json gigs.metadata.json Factory.metadata.json ForkThis.metadata.json FunctionCallProposal.metadata.json Map dwell.metadata.json MultiDAO.metadata.json NFT Badge.metadata.json Onboarding.metadata.json Page Settings.metadata.json SocialPosts.metadata.json StartHere.metadata.json africa election.metadata.json asia election.metadata.json aurora Page.metadata.json australia election.metadata.json bos-landing-page.metadata.json bos Page.metadata.json build.metadata.json communities page.metadata.json community join.metadata.json onboarding.metadata.json connect badge.metadata.json page.metadata.json continent join.metadata.json data Page.metadata.json demo.metadata.json dev.metadata.json dev View Page.metadata.json docs cli.metadata.json vscode.metadata.json edu Page.metadata.json election demo.metadata.json europe election.metadata.json event create.metadata.json every DAO.metadata.json gov badge.metadata.json hack library.metadata.json hackathon Page.metadata.json near Hashtag Feed.metadata.json north-america election.metadata.json scholarship card.metadata.json scholarships.metadata.json scholarships menu.metadata.json south-america election.metadata.json verified holders.metadata.json widgets rank.metadata.json xyz View Page.metadata.json
# hack.near ## Current 1. Install [bos-workspace](https://github.com/NEARBuilders/bos-workspace) 2. Install [bos-cli-rs](https://github.com/bos-cli-rs/bos-cli-rs) 3. ```mkdir hack.near``` 4. ```cd hack.near && bos components download hack.near``` 5. Components are in /src, nested by . dotation 6. bos.config.json, gitignore... I would like to be able to easily download my widgets and immediately start building with them in my workspace Devhub and near-discovery-components also hold all their widgets in a src directory. Existing bos-workspace's hold all their widgets in apps/{{appName}} ## Ideal 1. Install [bos-workspace](https://github.com/NEARBuilders/bos-workspace) 2. ```bw init hack.near``` 3. ```bw dev``` 4. ```bw deploy``` Let's hack!
near_node-docs
.github ISSUE_TEMPLATE BOUNTY.yml workflows build.yml links.yml spellcheck.yml README.md docs README.md archival _category_.json hardware-archival.md run-archival-node-with-nearup.md run-archival-node-without-nearup.md split-storage-archival.md bug-report _category_.json feature-request-and-bug-report.md intro _category_.json keys.md snapshots.md types-of-node.md what-is-a-node.md maintenance _category_.json community-channels.md db-migrations.md node-maintenance.md recompress-storage.md upgrade_alert.md rpc _category_.json hardware-rpc.md run-rpc-node-with-nearup.md run-rpc-node-without-nearup.md state-sync.md troubleshooting _category_.json common-errors.md debug_pages.md resharding.md validator _category_.json compile-and-run-a-node.md debug-rpc-and-debug-pages.md deploy-on-mainnet.md exposing-validators-metrics-to-pagoda.md hardware.md running-a-node-macos-linux.md running-a-node-windows.md staking-and-delegation.md staking-pool-migration.md validator-bootcamp.md | website README.md babel.config.js docusaurus.config.js mlc_config.json package.json sidebars.js src css custom.css theme Footer index.js Root.js static images network_layout.svg img near_logo.svg js hotjar.js
# Website This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator. ### Installation ``` $ yarn ``` ### Local Development ``` $ yarn start ``` This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. ### Build ``` $ yarn build ``` This command generates static content into the `build` directory and can be served using any static contents hosting service. ### Deployment Using SSH: ``` $ USE_SSH=true yarn deploy ``` Not using SSH: ``` $ GIT_USER=<Your GitHub username> yarn deploy ``` If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. <br /> <br /> <p align="center"> <img src="website/static/img/near_logo.svg" width="400"> </p> <br /> <br /> ## NEAR Protocol - scalable and usable blockchain [![Discord](https://img.shields.io/discord/490367152054992913.svg)](http://near.chat) [![CI](https://github.com/near/node-docs/actions/workflows/build.yml/badge.svg)](https://github.com/near/node-docs/actions/workflows/build.yml) * ⚖️ NEAR Protocol is a new smart-contract platform that delivers scalability and usability. * 🛠 Through sharding, it will linearly scale with the number of validation nodes on the network. * 🗝 Leveraging WebAssembly (via Rust and AssemblyScript), more sane contract management, ephemeral accounts and many other advancements, NEAR finally makes using a blockchain protocol easy for both developers and consumers. ## Quick start Check out the following links - Deployed, live node documentation: https://near-nodes.io - Example applications: https://near.dev - Community chat: https://near.chat ## Contributing NEAR uses [Docusaurus](https://docusaurus.io) for documentation. Please refer to their documentation for details on major structural contributions to the documentation. For simple content changes you have 2 options - [Submit an issue](https://github.com/near/node-docs/issues) - [Submit a pull request](https://github.com/near/node-docs/pulls) *(we prefer PRs of course)* ### The instant PR This is the fastest way to submit content changes directly from the page where you notice a mistake. 1. Open any page in the docs on https://near-nodes.io 2. Click the `[ Edit ]` button at the top right hand side of _every_ content page 3. Make your edits to the document that opens in GitHub by clicking the ✎ (pencil) icon 4. Submit a PR with your changes and comments for context ### The typical PR This is the standard fork-branch-commit workflow for submitting pull requests to open source repositories 1. Fork this repo to your own GitHub account (or just clone it directly if you are currently a member of NEAR) 2. Open your editor to the _top level repo folder_ to view the directory structure as seen below 3. Move into the `/website` folder where you will run the following commands: - Make sure all the dependencies for the website are installed: ```sh # Install dependencies yarn ``` - Run the local docs development server ```sh # Start the site yarn start ``` _Expected Output_ ```sh # Website with live reload is started Docusaurus server started on port 3000 ``` The website for docs will open your browser locally to port `3000` 4. Make changes to the docs 5. Observe those changes reflected in the local docs 6. Submit a pull request with your changes --- sidebar_position: 1 --- # NEAR Nodes NEAR Protocol runs on a collection of publicly maintained computers (or "nodes"). All nodes are running the same `nearcore` codebase with the latest releases available on [GitHub](https://github.com/near/nearcore/releases/). It is important to keep in mind all nodes run the same codebase, with different configurations. As such, we have split up the documentation for running different types of node into sections specific to the node's type. | Node Type | Description | |-----------|-------------| | [Validator Node](/validator) | Validator nodes participate in the consensus and produce blocks and/or chunks. | | [RPC Node](/rpc) | RPC nodes are service providers that provide public RPC endpoints for developers to use. | | [Archival Node](/archival) | Archival nodes store full blockchain data, and build an archive of historical states. |
NEARBuilders_FunctionCallLibrary
README.md
# FunctionCallLibrary A library for common function calls on NEAR ## Motivation - Easily create Keypom onboarding flow for Flex-A-Tech Hackathon - Easily allow for templates to port into BOS Widgets ## Inspiration AstroDAO DAO Recipes https://app.astrodao.com/cfc-library?search=
pmarangone_rust-api
Cargo.toml README.md src consts.rs main.rs models.rs mongo_impl.rs redis_impl.rs routes.rs utils.rs
# Indexer # API ## Export (more information about redis [here](https://github.com/redis-developer/rust-redis-101)): `export REDIS_HOSTNAME=localhost:6379`
icerove_calculator
.dependabot config.yml .gitpod.yml .travis.yml LICENSE-APACHE.txt LICENSE-MIT.txt README-Gitpod.md README.md __tests__ calculator.spec.js as-pect.config.js asconfig.js assembly __tests__ as-pect.d.ts as_types.d.ts calculator.ts caller.ts model.ts tsconfig.json dist index.html index.js main.1f19ae8e.js neardev shared-test-staging test.near.json shared-test test.near.json package.json src config.js index.html loader.html main.js test.js
Token Contract in AssemblyScript ================================ [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near-examples/token-contract-as) <!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page --> This project contains an implementation of a token contract similar to [ERC20](https://theethereum.wiki/w/index.php/ERC20_Token_Standard) but simpler. We'll visit a page, sign in and use your browser's console to run commands to initialize, send, and get the balance of a custom token. Getting started =============== There's a button at the top of this file that says "Open in Gitpod." If you want to try out this project as fast as possible, that's what you want. It will open the project in your browser with a complete integrated development environment configured for you. If you want to run the project yourself locally, read on. There are two ways to run this project locally. The first is quick, and a good way to instantly become familiar with this example. Once familiar, the next step is to create your own NEAR account and deploy the contract to testnet. Quick option --------------- 1. Install dependencies: yarn 2. Build and deploy this smart contract to a development account. This development account will be created automatically and is not intended for reuse: yarn dev Standard deploy option ---------------------- In this second option, the smart contract will get deployed to a specific account created with the NEAR Wallet. 1. Ensure `near-shell` is installed by running: near --version If needed, install `near-shell`: npm install near-shell -g 2. If you do not have a NEAR account, please create one with [NEAR Wallet](https://wallet.nearprotocol.com). Then, in the project root, login with `near-shell` by following the instructions after this command: near login 3. Modify the top of `src/config.js`, changing the `CONTRACT_NAME` to be the NEAR account that you just used to log in. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'YOUR_ACCOUNT_NAME_HERE'; /* TODO: fill this in! */ 4. Start the example! yarn start Exploring The Code ================== 1. The backend code lives in the `/assembly` folder. This code gets deployed to the NEAR blockchain when you run `yarn deploy:contract`. This sort of code-that-runs-on-a-blockchain is called a "smart contract" – [learn more about NEAR smart contracts][smart contract docs]. 2. The frontend code lives in the `/src` folder. [/src/index.html](/src/index.html) is a great place to start exploring. Note that it loads in `/src/main.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and backend. The backend code gets tested with the [asp] command for running the backend AssemblyScript tests, and [jest] for running frontend tests. You can run both of these at once with `yarn test`. Both contract and client-side code will auto-reload as you change source files. [smart contract docs]: https://docs.nearprotocol.com/docs/roles/developer/contracts/assemblyscript [asp]: https://www.npmjs.com/package/@as-pect/cli [jest]: https://jestjs.io/
farahdian_near-challenge-1
.gitpod.yml babel.config.js contract Cargo.toml README.md compile.js src lib.rs target .rustc_info.json debug .fingerprint Inflector-0ecab8b3702817d3 lib-inflector.json autocfg-78b84d7dffc77806 lib-autocfg.json borsh-derive-3e3bf370d0b942d5 lib-borsh-derive.json borsh-derive-internal-f658ea5233e0ab85 lib-borsh-derive-internal.json borsh-schema-derive-internal-93b209d6e3577051 lib-borsh-schema-derive-internal.json byteorder-073ef261a7679018 build-script-build-script-build.json convert_case-6d81cd1f6e54b221 lib-convert_case.json derive_more-d04a550c09ff950e lib-derive_more.json generic-array-b287dff5ae5246bd build-script-build-script-build.json hashbrown-2d15130f9f870f56 lib-hashbrown.json hashbrown-72b77a2cd424306f run-build-script-build-script-build.json hashbrown-826c460487c5ce8f build-script-build-script-build.json indexmap-698512748515ea6e build-script-build-script-build.json indexmap-e5de54a0f5f485db lib-indexmap.json indexmap-f3157c2948328b97 run-build-script-build-script-build.json itoa-ec344dc8fe0d8488 lib-itoa.json memchr-5d50a115644bcbc5 build-script-build-script-build.json near-rpc-error-core-f5b6ff8eedd9a9ab lib-near-rpc-error-core.json near-rpc-error-macro-8fa8eaf3a408e2ed lib-near-rpc-error-macro.json near-sdk-core-d4771b9a54ee012f lib-near-sdk-core.json near-sdk-macros-e0757c4b118de0e0 lib-near-sdk-macros.json num-bigint-2366e6eba98e90ec build-script-build-script-build.json num-integer-bfee632204bb2068 build-script-build-script-build.json num-rational-55d8481b4ef16ddc build-script-build-script-build.json num-traits-8e5212748524679e build-script-build-script-build.json proc-macro-crate-3680e733e2851f34 lib-proc-macro-crate.json proc-macro2-83898bc2ad176bf6 lib-proc-macro2.json proc-macro2-ebaeb54dd566f9ee run-build-script-build-script-build.json proc-macro2-f6dea862824656f5 build-script-build-script-build.json quote-f1423e0b0e2fa744 lib-quote.json ryu-1fc3a7e5872c6e61 lib-ryu.json ryu-471b62e862f87194 build-script-build-script-build.json ryu-7b10d204d445bd76 run-build-script-build-script-build.json serde-c3bc8aa3a2478116 build-script-build-script-build.json serde-d2ed7e8afe3f2566 lib-serde.json serde-efa65d9c972f8c56 run-build-script-build-script-build.json serde_derive-86e32bd3048c0ecf lib-serde_derive.json serde_derive-8886893da993d956 run-build-script-build-script-build.json serde_derive-b4fbd4f66110b305 build-script-build-script-build.json serde_json-0f2bdda611d2599d build-script-build-script-build.json serde_json-58b293fa6d741da4 run-build-script-build-script-build.json serde_json-9ddc602712814d7f lib-serde_json.json syn-022d451c46cf5944 build-script-build-script-build.json syn-85f62e4ee4ca5c7b lib-syn.json syn-c3ece0ee80f59dd3 run-build-script-build-script-build.json toml-e0f72e9956a96b9f lib-toml.json typenum-5096d410c417d929 build-script-build-script-main.json unicode-xid-d60ae00ac7cf6bac lib-unicode-xid.json version_check-03d83b2ea51e6e2a lib-version_check.json wee_alloc-8e344a393d3ecc3c build-script-build-script-build.json release .fingerprint Inflector-26b4c1b7473555f0 lib-inflector.json autocfg-4dcf897448c6830b lib-autocfg.json borsh-derive-2a4b4b8aa1de8ac6 lib-borsh-derive.json borsh-derive-internal-2987be10e552dc44 lib-borsh-derive-internal.json borsh-schema-derive-internal-a7cb3c57d19bb9d9 lib-borsh-schema-derive-internal.json byteorder-5cf40f376c43ed1f build-script-build-script-build.json convert_case-a148678f0b06e3ca lib-convert_case.json derive_more-464f0915d1a15a96 lib-derive_more.json generic-array-c23a209f567d3e6e build-script-build-script-build.json hashbrown-3b826b55021f8eec build-script-build-script-build.json hashbrown-50c19af74cf35dc5 run-build-script-build-script-build.json hashbrown-88f21a6fdaf30f2d lib-hashbrown.json indexmap-22f16813545cdec9 run-build-script-build-script-build.json indexmap-5a2ee75ba34680a2 lib-indexmap.json indexmap-5c80fc2e3698e53b build-script-build-script-build.json itoa-280aa38a2a458b94 lib-itoa.json memchr-9f168debc28e3d69 build-script-build-script-build.json near-rpc-error-core-932ae68eb46e55ba lib-near-rpc-error-core.json near-rpc-error-macro-e851e895ed06c64e lib-near-rpc-error-macro.json near-sdk-core-2d0f6a51e4f267fe lib-near-sdk-core.json near-sdk-macros-e1ad4615690976d4 lib-near-sdk-macros.json num-bigint-99da5036eba44282 build-script-build-script-build.json num-integer-f037bf0b5327aae2 build-script-build-script-build.json num-rational-7c2e1a10357640e1 build-script-build-script-build.json num-traits-cb71ef9ba1d8ad99 build-script-build-script-build.json proc-macro-crate-dbe27ea0fb3e396e lib-proc-macro-crate.json proc-macro2-3e779388ffb51586 lib-proc-macro2.json proc-macro2-9a3d5e4a4047bca8 build-script-build-script-build.json proc-macro2-b57abef28a537655 run-build-script-build-script-build.json quote-6f3b2e777065eca9 lib-quote.json ryu-791fe7413e2448c3 run-build-script-build-script-build.json ryu-bf84b4db540128f3 lib-ryu.json ryu-c756306a79fb0abb build-script-build-script-build.json serde-231aaee2302a22cb run-build-script-build-script-build.json serde-a7481fa04ac6e610 lib-serde.json serde-ab259f9447c6c852 build-script-build-script-build.json serde_derive-332432c962abb22e build-script-build-script-build.json serde_derive-ed37513283f91cf0 run-build-script-build-script-build.json serde_derive-f19afa7dbfa447b9 lib-serde_derive.json serde_json-24f014e6f0993d9e lib-serde_json.json serde_json-69ef8ff21b0e74ad build-script-build-script-build.json serde_json-b925c8ee41baa5d9 run-build-script-build-script-build.json syn-15d0c97a3ed9bd24 lib-syn.json syn-bf6417daf55dc082 build-script-build-script-build.json syn-fe98d2ac6e799626 run-build-script-build-script-build.json toml-736eda6b0ec4c896 lib-toml.json typenum-3f361f1e801b32fa build-script-build-script-main.json unicode-xid-693d4c3d0678726d lib-unicode-xid.json version_check-b3f759b172376a9d lib-version_check.json wee_alloc-25993eb3e83354ea build-script-build-script-build.json wasm32-unknown-unknown debug .fingerprint ahash-8d02c10893d0c971 lib-ahash.json aho-corasick-609040b8302fee81 lib-aho_corasick.json base64-8ba1e7c7c4a5303a lib-base64.json block-buffer-3097f12b12979d1b lib-block-buffer.json block-buffer-8a6365c77879839d lib-block-buffer.json block-padding-9b6103f4260bff3a lib-block-padding.json borsh-0dba0338ef5818db lib-borsh.json bs58-a69e1e7999a8ecef lib-bs58.json byte-tools-44bad75020d80ca0 lib-byte-tools.json byteorder-258a97db24efb8cf run-build-script-build-script-build.json byteorder-d06e9d4d5282c18e lib-byteorder.json cfg-if-98951856501651c9 lib-cfg-if.json cfg-if-c4a0f68303b9a21f lib-cfg-if.json digest-5a8acbf9a5f030d0 lib-digest.json digest-82d5d2c0eded9d10 lib-digest.json generic-array-3053f126142bd858 run-build-script-build-script-build.json generic-array-d70a3d07c9fd9bb2 lib-generic_array.json generic-array-e947f55d9973580b lib-generic_array.json greeter-98ace302c5fafa12 lib-greeter.json hashbrown-1c0a8b9498e183bf lib-hashbrown.json hashbrown-e021aea7a1dfecaf lib-hashbrown.json hashbrown-fc6b918d6779fef7 run-build-script-build-script-build.json hex-9c75efa095a5522e lib-hex.json indexmap-01e8d07cd88e6813 run-build-script-build-script-build.json indexmap-d958913752edb136 lib-indexmap.json itoa-d7831418986eec51 lib-itoa.json keccak-bf725368a5d13e5d lib-keccak.json lazy_static-c74ad9e4fbd55487 lib-lazy_static.json memchr-29db335368d8435e run-build-script-build-script-build.json memchr-dd868793abe20472 lib-memchr.json memory_units-7cfd09105015aae0 lib-memory_units.json near-primitives-core-9cbc562d799042d3 lib-near-primitives-core.json near-runtime-utils-0e01afd9343b9723 lib-near-runtime-utils.json near-sdk-6d5c7a7d30c7697a lib-near-sdk.json near-vm-errors-44371955281409f4 lib-near-vm-errors.json near-vm-logic-a05283986d20ad41 lib-near-vm-logic.json num-bigint-0547c39abeae5ecb run-build-script-build-script-build.json num-bigint-35e535e4ae0133af lib-num-bigint.json num-integer-2687bf7fd504e262 lib-num-integer.json num-integer-b0e1aaeefd64304f run-build-script-build-script-build.json num-rational-3c241da8bb818229 lib-num-rational.json num-rational-459fb50adfee74a6 run-build-script-build-script-build.json num-traits-687569f78152b17f lib-num-traits.json num-traits-8c71548bacdac913 run-build-script-build-script-build.json opaque-debug-3e02cbeba19dad26 lib-opaque-debug.json opaque-debug-b89df9dd37b0d98f lib-opaque-debug.json regex-7f70a57a92c46f20 lib-regex.json regex-syntax-a16834903b6991c3 lib-regex-syntax.json ryu-2d6df48499be8d15 run-build-script-build-script-build.json ryu-c717cc2c2c1065d7 lib-ryu.json serde-00d86cf857cc97f7 lib-serde.json serde-ea7c0879e02fcfe2 run-build-script-build-script-build.json serde_json-1e49aaa7cc28934d run-build-script-build-script-build.json serde_json-8aab9b9007861b52 lib-serde_json.json sha2-634486e48e6f9dd4 lib-sha2.json sha3-681fea8462e2db7b lib-sha3.json typenum-13860977d372dc11 lib-typenum.json typenum-670aa0a41b9b095c run-build-script-build-script-main.json wee_alloc-5209a4c4cf09f88a run-build-script-build-script-build.json wee_alloc-d13745a859908b7f lib-wee_alloc.json build num-bigint-0547c39abeae5ecb out radix_bases.rs typenum-670aa0a41b9b095c out consts.rs op.rs tests.rs wee_alloc-5209a4c4cf09f88a out wee_alloc_static_array_backend_size_bytes.txt release .fingerprint ahash-d471c4b33efc270b lib-ahash.json aho-corasick-98bdbfe664f3579d lib-aho_corasick.json base64-8ab7302f3d4dd41a lib-base64.json block-buffer-53013f455862ec99 lib-block-buffer.json block-buffer-bb80bd4fbb03a069 lib-block-buffer.json block-padding-239b09d78b41c201 lib-block-padding.json borsh-fa98be6a82bbba2c lib-borsh.json bs58-a35f02f2e01c8709 lib-bs58.json byte-tools-8502921bc3739358 lib-byte-tools.json byteorder-0261746b2e58586e lib-byteorder.json byteorder-891a8a6f7ce50533 run-build-script-build-script-build.json cfg-if-862d5378fa399bc6 lib-cfg-if.json cfg-if-86f3e6935ce80fca lib-cfg-if.json digest-22ac43f022286158 lib-digest.json digest-8a2f798647ad87a8 lib-digest.json generic-array-04388040495677b4 lib-generic_array.json generic-array-a3ead5f6ca75c5f8 run-build-script-build-script-build.json generic-array-ce878c5a1a4d47cb lib-generic_array.json greeter-98ace302c5fafa12 lib-greeter.json hashbrown-489115f93022baa5 run-build-script-build-script-build.json hashbrown-d0bcc872e50a7925 lib-hashbrown.json hashbrown-ec0347fa6337d118 lib-hashbrown.json hex-a66c2327cbed4cf6 lib-hex.json indexmap-5978cedb685ccc70 lib-indexmap.json indexmap-79cc2b1c42bf53db run-build-script-build-script-build.json itoa-d1591278d83c97a5 lib-itoa.json keccak-423707e041f9bce5 lib-keccak.json lazy_static-e2104e45f6909b47 lib-lazy_static.json memchr-25b4544404533634 lib-memchr.json memchr-7bdfc22d7838d680 run-build-script-build-script-build.json memory_units-6a0b36fa458f94ce lib-memory_units.json near-primitives-core-ae1403522c250d6d lib-near-primitives-core.json near-runtime-utils-6b8cc0e130d143c2 lib-near-runtime-utils.json near-sdk-afc63463bc96f5f2 lib-near-sdk.json near-vm-errors-a3e5a74f07174445 lib-near-vm-errors.json near-vm-logic-f51f069b8b2b1828 lib-near-vm-logic.json num-bigint-355d749d9309084d lib-num-bigint.json num-bigint-fdf5f81de80e9401 run-build-script-build-script-build.json num-integer-632391c9fbed8bfe run-build-script-build-script-build.json num-integer-7785e85048b84c3d lib-num-integer.json num-rational-95c24a57c1ee34bd run-build-script-build-script-build.json num-rational-cf39fe66547d9a99 lib-num-rational.json num-traits-2a3af47e4099721b run-build-script-build-script-build.json num-traits-d083107fe31d8102 lib-num-traits.json opaque-debug-a4f49a9d9259db97 lib-opaque-debug.json opaque-debug-f1d0178cfbad32d7 lib-opaque-debug.json regex-db479f95a8e2fee7 lib-regex.json regex-syntax-86e6103038a7626b lib-regex-syntax.json ryu-0309e94ee0960e99 lib-ryu.json ryu-4b3f7c01e67934a4 run-build-script-build-script-build.json serde-57a6eda163545edc lib-serde.json serde-87d4c259a29a9333 run-build-script-build-script-build.json serde_json-85ff1be2dad23572 run-build-script-build-script-build.json serde_json-e4fc59e1e802d855 lib-serde_json.json sha2-af91140802c756f1 lib-sha2.json sha3-b5a26bffa1bbf823 lib-sha3.json typenum-0b5c8bdc1867d6ba run-build-script-build-script-main.json typenum-7d5b3055d7ce8af5 lib-typenum.json wee_alloc-352d6458340348f9 run-build-script-build-script-build.json wee_alloc-94c8641e22bad578 lib-wee_alloc.json build num-bigint-fdf5f81de80e9401 out radix_bases.rs typenum-0b5c8bdc1867d6ba out consts.rs op.rs tests.rs wee_alloc-352d6458340348f9 out wee_alloc_static_array_backend_size_bytes.txt package.json src App.js __mocks__ fileMock.js assets logo-black.svg logo-white.svg config.js global.css index.html index.js jest.init.js main.test.js utils.js wallet login index.html
my-project Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html
puzzle-com_filesys-rust
ATTRIBUTIONS.md Cargo.toml README.md async-utils Cargo.toml src lib.rs chain chain Cargo.toml src chain.rs error.rs lib.rs store.rs test_utils.rs types.rs tests simple_chain.rs sync_chain.rs client Cargo.toml src client.rs lib.rs sync.rs test_utils.rs types.rs view_client.rs tests process_blocks.rs query_client.rs jsonrpc Cargo.toml src client.rs lib.rs message.rs test_utils.rs tests http_query.rs rpc_query.rs rpc_transactions.rs network Cargo.toml src codec.rs lib.rs peer.rs peer_manager.rs peer_store.rs test_utils.rs types.rs tests peer_handshake.rs pool Cargo.toml src lib.rs types.rs core primitives Cargo.toml benches bls.rs src account.rs crypto aggregate_signature.rs group_signature.rs mod.rs signature.rs signer.rs hash.rs lib.rs logging.rs merkle.rs network.rs receipt.rs rpc.rs serialize.rs sharding.rs test_utils.rs transaction.rs types.rs utils.rs protos Cargo.toml README.md build.rs src lib.rs uint128_ext.rs store Cargo.toml benches trie_bench.rs src lib.rs test_utils.rs trie mod.rs nibble_slice.rs update.rs docker README.md scripts hosted_alphanet_chain_spec.json docs logo.svg filesys-api Cargo.toml examples add_file.rs add_tar.rs bootstrap_default.rs default_config.json dns.rs get_commands.rs get_stats.rs get_swarm.rs get_version.rs mfs.rs ping_peer.rs pubsub.rs replace_config.rs resolve_name.rs src client.rs header.rs lib.rs read.rs request add.rs bitswap.rs block.rs bootstrap.rs cat.rs commands.rs config.rs dag.rs dht.rs diag.rs dns.rs file.rs files.rs filestore.rs get.rs id.rs key.rs log.rs ls.rs mod.rs name.rs object.rs pin.rs ping.rs pubsub.rs refs.rs shutdown.rs stats.rs swarm.rs tar.rs version.rs response add.rs bitswap.rs block.rs bootstrap.rs commands.rs config.rs dag.rs dht.rs diag.rs dns.rs error.rs file.rs files.rs filestore.rs id.rs key.rs log.rs ls.rs mod.rs mount.rs name.rs object.rs pin.rs ping.rs pubsub.rs refs.rs repo.rs resolve.rs serde.rs shutdown.rs stats.rs swarm.rs tar.rs tests v0_bitswap_stat_0.json v0_block_stat_0.json v0_bootstrap_list_0.json v0_commands_0.json v0_dag_get_0.json v0_file_ls_0.json v0_file_ls_1.json v0_files_ls_0.json v0_files_stat_0.json v0_id_0.json v0_key_gen_0.json v0_key_list_0.json v0_key_rename_0.json v0_key_rm_0.json v0_log_ls_0.json v0_ls_0.json v0_ls_1.json v0_mount_0.json v0_name_resolve_0.json v0_object_diff_0.json v0_object_links_0.json v0_object_stat_0.json v0_pin_add_0.json v0_pin_ls_0.json v0_ping_0.json v0_ping_1.json v0_ping_2.json v0_pubsub_ls_0.json v0_pubsub_ls_1.json v0_pubsub_peers_0.json v0_pubsub_sub_0.json v0_pubsub_sub_1.json v0_refs_local_0.json v0_repo_gc_0.json v0_repo_stat_0.json v0_repo_verify_0.json v0_repo_verify_1.json v0_repo_version_0.json v0_resolve_0.json v0_stats_bw_0.json v0_swarm_addrs_local_0.json v0_swarm_peers_0.json v0_swarm_peers_1.json v0_swarm_peers_2.json v0_tar_add_0.json v0_version_0.json version.rs filesys-cli Cargo.toml src command add.rs bitswap.rs block.rs bootstrap.rs cat.rs commands.rs config.rs dag.rs dht.rs diag.rs dns.rs file.rs files.rs filestore.rs mod.rs shutdown.rs version.rs main.rs filesysmint Cargo.toml README.md src lib.rs main.rs tests test.rs tools bench __init__.py b58.py key_store.py lib.py main.py protos __init__.py signed_transaction_pb2.py ipfstools .travis.yml Cargo.toml README.md examples client1.rs client2.rs ipfs_bitswap_test.rs ipfs_ipns_test.rs readme.rs regen_protobuf_structs.sh src bitswap behaviour.rs bitswap_pb.rs ledger.rs mod.rs protocol.rs strategy.rs block.rs config.rs error.rs future.rs ipld dag.rs error.rs formats cbor.rs mod.rs pb dag_pb.rs mod.rs ipld.rs mod.rs ipns dns.rs entry.rs ipns_pb.rs mod.rs lib.rs p2p behaviour.rs mod.rs transport.rs path error.rs mod.rs repo ds.rs fs.rs mem.rs mod.rs unixfs mod.rs near Cargo.toml src config.rs lib.rs main.rs runtime.rs test_utils.rs validator_manager.rs tests run_nodes.rs runtime_fork.rs stake_nodes.rs sync_nodes.rs neardev devkey.json nearlib .eslintrc.yml API.md README.md account.js browser-exports.js browser.js dev.js dist nearlib.js nearlib.min.js index.js internal send-json.js local_node_connection.js near.js nearclient.js package-lock.json package.json protos.js signing account_info.js browser_local_storage_key_store.js in_memory_key_store.js key_pair.js simple_key_store_signer.js unencrypted_file_system_keystore.js test .eslintrc.yml browser_keystore.test.js integration.test.js promise.test.js test-utils.js unencrypted_file_system_keystore.test.js wallet-access-key.js wallet-account.js ops README.md deploy_alphanet.sh deploy_local.sh deploy_remote.sh local_alphanet.sh reset_alphanet.sh run.sh teardown_local.sh teardown_remote.sh tendermint-config.toml update_alphanet.sh update_remote_studio.sh update_remote_testnet.sh update_studio.sh utils README.md requirements.txt package-lock.json protos builder Cargo.toml src bin protos_autogen.rs lib.rs pynear bin generate_python_transaction_proto.sh setup.py src near __init__.py pynear __init__.py b58.py cli.py key_store.py lib.py protos __init__.py signed_transaction_pb2.py test_utils __init__.py cli.py fixtures.py tests integration __init__.py test_cli.py runtime aes Cargo.toml README.md src aes_crypto.rs constants.rs main.rs cbor .travis.yml CONTRIBUTING.md Cargo.toml README.md examples readme.rs fuzz Cargo.toml appendix_a.json fuzz_targets from_reader.rs from_slice.rs make_corpus.py src de.rs error.rs lib.rs read.rs ser.rs value mod.rs ser.rs value.rs write.rs tests bennofs.rs canonical.rs de.rs enum.rs ser.rs std_types.rs value.rs handler Cargo.toml src error.rs lib.rs route.rs primitives Cargo.toml benches bls.rs src account.rs beacon.rs block_traits.rs chain.rs consensus.rs crypto aggregate_signature.rs group_signature.rs mod.rs signature.rs signer.rs hash.rs lib.rs logging.rs merkle.rs network.rs proofs.rs receipt.rs rpc.rs serialize.rs test_utils.rs traits.rs transaction.rs types.rs utils.rs protos Cargo.toml README.md build.rs src lib.rs serde.rs repo Cargo.toml src ds.rs fs.rs lib.rs mod.rs runtime Cargo.toml benches bench.rs src adapter.rs chain_spec.rs economics_config.rs ethereum.rs ext.rs lib.rs state_viewer.rs system.rs tx_stakes.rs tests test_evil_contracts.rs storage Cargo.toml benches storage_bench.rs trie_bench.rs src lib.rs storages beacon.rs mod.rs shard.rs test.c test_utils.rs trie mod.rs nibble_slice.rs update.rs verifier Cargo.toml src lib.rs wasm Cargo.toml runtest Cargo.toml generate-wasm build.sh to-wasm Cargo.toml src lib.rs src lib.rs src cache.rs executor.rs ext.rs lib.rs prepare.rs runtime.rs types.rs rustfmt.toml scripts build_wasm.sh coverage.sh generate_js_transaction_proto.sh kill_devnet.sh kill_near.sh run_clippy.sh setup_hooks.sh start_near.sh start_nearmint.sh test_nearlib.sh waitonserver.sh test-utils keystore Cargo.toml src main.rs loadtester Cargo.toml README.md src main.rs remote_node.rs sampler.rs stats.rs transactions_executor.rs transactions_generator.rs state-viewer Cargo.toml src main.rs testcgo Cargo.toml src build.rs main.rs testlib Cargo.toml src actix_utils.rs generate_test_spec.rs lib.rs node mod.rs process_node.rs remote_node.rs runtime_node.rs shard_client_node.rs thread_node.rs nodes_monitor.rs run_nodes.rs runtime_utils.rs sampler.rs standard_test_cases.rs test_helpers.rs transactions_executor.rs transactions_generator.rs user mod.rs rpc_user.rs runtime_user.rs shard_client_user.rs thread_user.rs txflow-test-gen README.md beacon.js common_rust_code_for_tests.txt gen_tests.js index.html nighty_gen.js txflow.js utils.js tests hello assembly main.ts model.ts tsconfig.json gulpfile.js package.json test_cases_runtime.rs test_cases_runtime_shard.rs test_cases_testnet_direct.rs test_cases_testnet_rpc.rs test_catchup.rs test_custom_handler.rs test_errors.rs test_rejoin.rs test_simple.rs test_tps_regression.rs
Visual test gen for TxFlow ========================== This is a visual editor for TxFlow graphs. It contains an alternative naive implementation of TxFlow in JavaScript, that always DFSes from scratch without precaching to reduce the chance of errors. Generated TxFlow graphs annotated with the alternative TxFlow implementation can then be converted into Rust unit tests. # How to use: Open index.html in the browser. On top there are four buttons represnting four users. Pressing on the button creates a new message for the user and selects it. Clicking on an existing message selects or deselects it. When a new message is created, all the selected messages become it's parents. Whenever any number of messages is selected, the TxFlow graph is traversed from the selected messages, and annotated with epochs, representatives, kickouts and endorsements. The kickout messages are marked with bold letter 'K'; The representative messages are marked in a form 'R5(A,B)' where 5 is what epoch the representative message is for (it might be different from the message epoch, if the representative message was not created via an epoch increase) and A and B are endorsements. # Comments, Serializing / Deserializing Use the `comment` text area to provide a short description of the test. The `Serialized` text area contains JSON of the txflow. It is autoupdated whenever the graph is changed. To save the serialialized JSON just copy-paste it from the textarea. To restore to previously saved JSON copy-paste it back to the textarea and press `Deserialize`. # Generating Rust test cases Enter a function name for the test into the textbox under the `Serialized` textarea, and press `Gen Rust Test`. Presently it only tests epochs, representative and kickout, but not endorsements. <img src="" width="200px" align="right" /> ## FileSys - scalable and usable blockchain,Official Rust implementation of the FileSys protocol # Setup ## Install python requirements ```bash pip install -r requirements.txt ``` ## Install kubectl **MacOS** ```bash brew install kubectl ``` **Ubuntu** ```bash sudo snap install kubectl --classic ``` ## Setup AWS Credentials (optional) If you do not have your key pair set in a [credentials file](https://docs.aws.amazon.com/cli/latest/userguide/cli-config-files.html), you will need to have `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` set when running `build_and_run`. ## Install minikube (local only) 1) [Install virtualbox](https://www.virtualbox.org/wiki/Downloads) 2) [Install minikube](https://github.com/kubernetes/minikube/releases) 3) Configure minikube ```bash minikube addons enable ingress minikube addons enable registry ``` # Near lib Near lib is a javascript library for development of dapps on near. ## Install dependencies ``` npm install ``` ## Integration Test Start the node by following instructions from nearcore/README.md, then ``` npm test ``` Contract "hello.wasm" source code location: <https://github.com/nearprotocol/nearcore/tree/master/tests/hello> ### Building ```bash ./build ${PACKAGE} ${IMAGE_TAG} ``` See other usage options with: ```bash ./build --help ``` # aes Rust AES implementation # NEAR Application Layer with Tendermint Consensus #### Table of contents 1. [Running Locally](#running-locally) 2. [Running Remotely](#running-remotely) 3. [Developing NEAR Runtime](#developing-near-runtime) 4. [Building and Pushing Docker Image](#building-and-pushing-docker-image) ## Running Locally To run NEAR locally you would need docker, see [installation instructions](https://www.docker.com/get-started). Then run the following: ```bash ./ops/deploy_local.sh ``` After it starts you can open studio at [http://localhost](http://localhost). To tear it down run: ```bash ./ops/teardown_local.sh ``` Note, it is not advised to run more than two nodes locally, especially on low performance machines. While the network itself is able to function and produce blocks, the development tools might currently timeout on certain commands, because the nodes do not produce blocks fast enough. ## Running Remotely Similarly you deploy the network to the GCloud: ```bash ./ops/deploy_remote.sh ``` When the network is deployed it will print the address of the studio. ## Developing NEAR Runtime This section is for those who want to develop the NEAR Runtime. If you only want to develop dApps then the above sections suffice. Developing NEAR Runtime locally requires more installation and configuration. ### Installation This mode of running requires compilation of the Rust code and installed Tendermint. **1. Dependencies** Install protobufs: ```bash # Mac OS: brew install protobuf # Ubuntu: apt-get install protobuf-compiler ``` **2. Rust** Currently, the only way to install NEARMint application layer is to compile it from the source. For that we would need to install Rust. ```bash curl https://sh.rustup.rs -sSf | sh rustup component add clippy-preview rustup default nightly ``` **3. Source code** We would need to copy the entire repository: ```bash git clone https://github.com/nearprotocol/nearcore cd nearcore ``` **4. Tendermint** Follow the official instructions to install Tendermint: https://tendermint.com/docs/introduction/install.html ### Configure and run To configure Tendermint run: ```bash tendermint init ``` Configure Tendermint to use `3030` for its RPC. Open `~/.tendermint/config/config.toml` and change: ```yaml [rpc] laddr = "tcp://0.0.0.0:3030" ``` For local development we also recommend setting: ```yaml create_empty_blocks = false ``` First, we want to set `alice.near` as a single validator. Open `~/.tendermint/config/priv_validator_key.json` and replace with: ```json { "address": "27B2B6C138DDF7B77E4318A22CAE1A38F55AA29A", "pub_key": { "type": "tendermint/PubKeyEd25519", "value": "D1al8CjfwInsfDnBGDsyG02Pibpb7J4XYoA8wkkfbvg=" }, "priv_key": { "type": "tendermint/PrivKeyEd25519", "value": "YWxpY2UubmVhciAgICAgICAgICAgICAgICAgICAgICAPVqXwKN/Aiex8OcEYOzIbTY+JulvsnhdigDzCSR9u+A==" } } ``` Navigate to the root of the repository, and run: ```bash cargo run --package nearmint -- --devnet ``` This will start NEARMint in application mode, without consensus backing it up. To start Tendermint run: ```bash tendermint node ``` Now we can issue specific commands to the node: ```bash curl http://localhost:3030/status curl -s 'localhost:3030/abci_query?path="account/alice.near"' curl -s 'localhost:3030/validators' ``` See full list of RPC endpoints here: https://tendermint.com/rpc/#endpoints Unfortunately, transactions can be only submitted in base64 encoding, which is hard to do from the command line. ## Building and Pushing Docker Image If you have modified the source code of NEAR Runtime and want to see how it performs in prod you would need to build an docker image from it. Once the docker image is built you can run it locally or remotely. ### Building NEAR Runtime To build docker image run from the root: ```bash make docker-nearcore ``` This will build an image with `nearcore` name. ### Running locally To run this image locally, run: ```bash ./ops/deploy_local.sh nearcore ``` ### Running remotely To run this image remotely we would need to tag and publish it to the docker hub. For instance, when using `nearprotocol` docker hub repo: ```bash sudo docker tag nearcore nearprotocol/mynearcore sudo docker push nearprotocol/mynearcore ``` Then run: ```bash ./ops/deploy_remote.sh nearprotocol/mynearcore ``` ## Development `.proto` files are under the `protos` directory. To add/delete protos, one also needs to change the include macro at the beginning of `src/lib.rs`. For example, if `example.proto` is added to `protos`, `include!(concat!(env!("OUT_DIR"), "/example.rs"))` needs to be added to `src/lib.rs`. # Serde CBOR [![Build Status](https://travis-ci.org/pyfisch/cbor.svg?branch=master)](https://travis-ci.org/pyfisch/cbor) [![Crates.io](https://img.shields.io/crates/v/serde_cbor.svg)](https://crates.io/crates/serde_cbor) [![Documentation](https://docs.rs/serde_cbor/badge.svg)](https://docs.rs/serde_cbor) This crate implements the Concise Binary Object Representation from [RFC 7049]. It builds on [Serde] the generic serialization framework for Rust. CBOR provides a binary encoding for a superset of the JSON data model that is small and very fast to parse. [RFC 7049]: https://tools.ietf.org/html/rfc7049 [Serde]: https://github.com/serde-rs/serde ## Usage Serde CBOR supports Rust 1.31 and up. Add this to your `Cargo.toml`: ```toml [dependencies] serde_cbor = "0.9" ``` Storing and loading Rust types is easy and requires only minimal modifications to the program code. ```rust use serde_derive::{Deserialize, Serialize}; use std::error::Error; use std::fs::File; // Types annotated with `Serialize` can be stored as CBOR. // To be able to load them again add `Deserialize`. #[derive(Debug, Serialize, Deserialize)] struct Mascot { name: String, species: String, year_of_birth: u32, } fn main() -> Result<(), Box<Error>> { let ferris = Mascot { name: "Ferris".to_owned(), species: "crab".to_owned(), year_of_birth: 2015, }; let mut ferris_file = File::create("examples/ferris.cbor")?; // Write Ferris to the given file. // Instead of a file you can use any type that implements `io::Write` // like a HTTP body, database connection etc. serde_cbor::to_writer(&mut ferris_file, &ferris)?; let mut tux_file = File::open("examples/tux.cbor")?; // Load Tux from a file. // Serde CBOR performs roundtrip serialization meaning that // the data will not change in any way. let tux: Mascot = serde_cbor::from_reader(&mut tux_file)?; println!("{:?}", tux); // prints: Mascot { name: "Tux", species: "penguin", year_of_birth: 1996 } Ok(()) } ``` There are a lot of options available to customize the format. To operate on untyped CBOR values have a look at the `Value` type. ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. ## Development `.proto` files are under the `protos` directory. To add/delete protos, one also needs to change the include macro at the beginning of `src/lib.rs`. For example, if `example.proto` is added to `protos`, `include!(concat!(env!("OUT_DIR"), "/example.rs"))` needs to be added to `src/lib.rs`. # Rust IPFS implementation [![Build Status](https://travis-ci.org/dvc94ch/rust-ipfs.svg?branch=master)](https://travis-ci.org/dvc94ch/rust-ipfs) Currently implements an altruistic bitswap strategy over mdns. ## Getting started ```rust #![feature(async_await, await_macro, futures_api)] use ipfs::{Ipfs, IpfsOptions, Ipld, Types}; use futures::join; fn main() { let options = IpfsOptions::<Types>::default(); env_logger::Builder::new().parse_filters(&options.ipfs_log).init(); let mut ipfs = Ipfs::new(options); tokio::run_async(async move { // Start daemon and initialize repo let fut = ipfs.start_daemon().unwrap(); tokio::spawn_async(fut); await!(ipfs.init_repo()).unwrap(); await!(ipfs.open_repo()).unwrap(); // Create a DAG let block1: Ipld = "block1".to_string().into(); let block2: Ipld = "block2".to_string().into(); let f1 = ipfs.put_dag(block1); let f2 = ipfs.put_dag(block2); let (res1, res2) = join!(f1, f2); let root: Ipld = vec![res1.unwrap(), res2.unwrap()].into(); let path = await!(ipfs.put_dag(root)).unwrap(); // Query the DAG let path1 = path.sub_path("0").unwrap(); let path2 = path.sub_path("1").unwrap(); let f1 = ipfs.get_dag(path1); let f2 = ipfs.get_dag(path2); let (res1, res2) = join!(f1, f2); println!("Received block with contents: {:?}", res1.unwrap()); println!("Received block with contents: {:?}", res2.unwrap()); // Exit ipfs.exit_daemon(); }); } ``` ## License ISC License Copyright (c) 2019, David Craven and others Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # NEARMint NEAR application layer running with Tendermint consensus. ## Installation 0. Install general development tools. Ubuntu: sudo apt-get install binutils-dev libcurl4-openssl-dev zlib1g-dev libdw-dev libiberty-dev cmake gcc build-essential libssl-dev pkg-config protobuf-compiler 1. Follow instruction on Tendermint installation: https://tendermint.com/docs/introduction/install.html 2. Install rust ``` curl https://sh.rustup.rs -sSf | sh ``` 3. Download this repo git clone https://github.com/nearprotocol/nearcore ## Configure ### Tendermint tendermint init You can modify configuration of the node in `~/.tendermint/config/config.toml`. Specifically, change RPC server to 3030 port: ```$toml [rpc] laddr = "tcp://0.0.0.0:3030" ``` ## Running Start in one console tendermint (from any location if it was installed, or from directory you put binary into): tendermint node Note, that if you want to reset state of tendermint that has already ran, use `tendermint unsafe_reset_all`. In the second console: cargo run --package nearmint Note, that if you want to reset state of nearmint that has already ran, use `rm -rf storage`. ## Running local cluster Note, this is done way easier on Ubuntu and we will be working on simplifying it for Mac OS. Link `tendermint` binary to target/release folder ln -s We use docker compose to spin up 4 node local cluster: cargo run --release --package nearmint cd ops/local docker-compose up ## Development To run single validator mode (e.g. DevNet mode), you can set Tendermint validator key to `alice.near` key in `~/.tendermint/config/priv_validator_key.json`: ```json { "address": "27B2B6C138DDF7B77E4318A22CAE1A38F55AA29A", "pub_key": { "type": "tendermint/PubKeyEd25519", "value": "D1al8CjfwInsfDnBGDsyG02Pibpb7J4XYoA8wkkfbvg=" }, "priv_key": { "type": "tendermint/PrivKeyEd25519", "value": "YWxpY2UubmVhciAgICAgICAgICAgICAgICAgICAgICAPVqXwKN/Aiex8OcEYOzIbTY+JulvsnhdigDzCSR9u+A==" } } ``` And then when running `nearmint` use `--devnet` flag, e.g. `cargo run --package nearmint -- --devnet` or `target/release/nearmint --devnet`. ## Interacting Use JSONRPC to send transaction: http post localhost:26657 method=broadcast_tx_commit jsonrpc=2.0 id=dontcare tx=0x<hex bytes of transaction> See full list of JSONRPC http get localhost:26657 # Load testing tool This tool can be used to test a local or remote set of nodes. It submits transactions at a given rate and monitors the output TPS by periodically requesting the most recent block from the leading nodes. ## Example The following is an example of how to crash a locally running TestNet by saturating it with transactions. As of 2019-04-16, this has not been fixed. Start the local TestNet: ```bash ./ops/local_alphanet.sh ``` Host machine needs to have keys that nodes use for their associated accounts. Generate the keys like this: ```bash cargo run --package keystore --bin keystore keygen --test-seed near.0 -p /tmp/keys/ cargo run --package keystore --bin keystore keygen --test-seed near.1 -p /tmp/keys/ cargo run --package keystore --bin keystore keygen --test-seed near.2 -p /tmp/keys/ cargo run --package keystore --bin keystore keygen --test-seed near.3 -p /tmp/keys/ ``` Make sure the load tester is configured to send 700 TPS of monetary transactions. See the `main.rs` file: ```rust Executor::spawn(nodes, TransactionType::Monetary, None, None, 700, TrafficType::Regular); ``` Launch the load tester: ```bash cargo run --package loadtester --bin loadtester -- --key-files-path /tmp/keys \ --addresses 127.0.0.1:3030 127.0.0.1:3031 127.0.0.1:3032 127.0.0.1:3033 \ --public-keys 82M8LNM7AzJHhHKn6hymVW1jBzSwFukHp1dycVcU7MD CTVkQMjLyr4QzoXrTDVzfCUp95sCJPwLJZ34JTiekxMV EJ1DMa6s2ngC5GtZb3Z2DZzat2xFZ34j15VLY37dcdXX 3DToePHssYc75SsxZgzgVLwXE8XQXKjdpdL7CT7D34UE \ --account-ids near.0 near.1 near.2 near.3 2>&1 | tee /tmp/out2.txt ``` Observe that the TestNet produces up to 700 TPS and then after a random amount of time it stops creating new blocks. ## Benchmark NEAR (1 node) Here how you can run benchmarking for one local node: ``` cargo build --release -p near cargo build --release -p loadtester # Start NEAR node ./target/release/near init ./target/release/near run # Run load tester mkdir /tmp/keys cp ~/.near/validator_key.json /tmp/keys/ # Get public key to use for next command. cat ~/.near/validator_key.json ./target/release/loadtester --key-files-path /tmp/keys \ --address 127.0.0.1:3030 \ --public-keys <PUBLIC KEY> \ --account-ids test.near 2>&1 | tee /tmp/out.txt ```
max-mainnet_ref-trading-view-component
README.md package-lock.json package.json postcss.config.js src App.css charting_library ar-tv-chart.e2a841ff.html bundles 1403.5c193407bf9023ec51df.css 1403.5c193407bf9023ec51df.rtl.css 1413.0beb5c102530e80c962f.css 1413.0beb5c102530e80c962f.rtl.css 1529.30943dc0c4f6a9ddaaa6.js 167.4a7b6d5ac49e0365fb9f.css 167.4a7b6d5ac49e0365fb9f.rtl.css 1778.3dcfedd5fc468612cdc9.css 1778.3dcfedd5fc468612cdc9.rtl.css 1829.1d41207f53b42b7a2cba.js 1941.ae71d13122bc90f281f2.css 1941.ae71d13122bc90f281f2.rtl.css 2091.b5cd26b120d8f015a5f6.css 2091.b5cd26b120d8f015a5f6.rtl.css 2162.da7cb9d498f064a9ef84.css 2162.da7cb9d498f064a9ef84.rtl.css 2269.e35db23226edaf77f36d.css 2269.e35db23226edaf77f36d.rtl.css 2273.c8e768dcdd52b58e948e.css 2273.c8e768dcdd52b58e948e.rtl.css 2321.4f5fec7d39b99277caa5.css 2321.4f5fec7d39b99277caa5.rtl.css 2359.18a49f656f3259463f4f.css 2359.18a49f656f3259463f4f.rtl.css 2391.07217bcacc2a0c3b5526.js 2402.4ce4e3425dce9bceed85.js 2444.89916595bdde00535f06.js 2614.9b290389192f690dd33c.css 2614.9b290389192f690dd33c.rtl.css 2778.22f147dbe677a02ae3db.css 2778.22f147dbe677a02ae3db.rtl.css 2850.8a920beb86b4e0f023f2.css 2850.8a920beb86b4e0f023f2.rtl.css 306.547d2bcc2b4af2c3a922.js 3223.783979b0683ba0a325de.css 3223.783979b0683ba0a325de.rtl.css 339.79f004acba5fa5c1b85f.css 339.79f004acba5fa5c1b85f.rtl.css 3463.65423ae1c1f3301a6bc0.js 3537.273ebe86a4260eff8e80.css 3537.273ebe86a4260eff8e80.rtl.css 3590.9ba8c934cf8289ea708f.js 3708.b21be6dee862262304cf.css 3708.b21be6dee862262304cf.rtl.css 3876.fbb750fd312778403036.css 3876.fbb750fd312778403036.rtl.css 3894.6c50d72ee9e079af3dab.css 3894.6c50d72ee9e079af3dab.rtl.css 3996.3cdbd2dcf744b8239723.css 3996.3cdbd2dcf744b8239723.rtl.css 40566afd832a155e5e370a8bd423de4b.svg 4078.43552fd4fee41d29f435.css 4078.43552fd4fee41d29f435.rtl.css 4093.8b84af355871cc700cb8.js 4336.1228643b9325cd73ea59.css 4336.1228643b9325cd73ea59.rtl.css 439.cf0a8c77353b34e465e2.css 439.cf0a8c77353b34e465e2.rtl.css 4595.6423e4f6860a7dd905ff.css 4595.6423e4f6860a7dd905ff.rtl.css 4652.c4c887154b57ce62bd2d.css 4652.c4c887154b57ce62bd2d.rtl.css 4736.2eccdb294faa8c6685ac.css 4736.2eccdb294faa8c6685ac.rtl.css 4834.07c319579bda11b57fc3.css 4834.07c319579bda11b57fc3.rtl.css 4882.acb0c10fdfd40a912b89.css 4882.acb0c10fdfd40a912b89.rtl.css 4940.6aeb4a6f298568a71905.js 4985.6abfd9453389325f7436.css 4985.6abfd9453389325f7436.rtl.css 5019.5e7f23f81809b4af9b28.js 5030.3f535fc5b94422bc913a.js 5254.776db7a6898f96fdd81f.js 5383.22c502e2ba80f4b4fc32.js 5410.21bcd4914bfb1cf880be.css 5410.21bcd4914bfb1cf880be.rtl.css 5453.142c8996edfadb5669ae.css 5453.142c8996edfadb5669ae.rtl.css 5527.b19a3c2c68b0d873fe2b.css 5527.b19a3c2c68b0d873fe2b.rtl.css 5551.407668886ab3145df3b5.css 5551.407668886ab3145df3b5.rtl.css 5637.a1b98549b1c9f19a01cf.css 5637.a1b98549b1c9f19a01cf.rtl.css 5698.9f7ef23e439b8f550541.css 5698.9f7ef23e439b8f550541.rtl.css 587.144039f5c693ee079edb.css 587.144039f5c693ee079edb.rtl.css 5984.fce1e6b0306b3072be07.css 5984.fce1e6b0306b3072be07.rtl.css 6062.56b57d0c5c641ee6c503.css 6062.56b57d0c5c641ee6c503.rtl.css 6143.1f43f1c13a5153841646.css 6143.1f43f1c13a5153841646.rtl.css 6253.8ddff4c976b3edf9f34c.css 6253.8ddff4c976b3edf9f34c.rtl.css 6333.75d8cc7be7c14f60fb3b.css 6333.75d8cc7be7c14f60fb3b.rtl.css 6473.e5bfe6a8cd8097cebb56.css 6473.e5bfe6a8cd8097cebb56.rtl.css 6548.bda2305976fecdd6ca1a.css 6548.bda2305976fecdd6ca1a.rtl.css 6612.6ea4b89e354fef333be4.css 6612.6ea4b89e354fef333be4.rtl.css 6637.b9569ad7b9c1ffb59c7c.css 6637.b9569ad7b9c1ffb59c7c.rtl.css 7039.873153a7278857ebfcd1.css 7039.873153a7278857ebfcd1.rtl.css 706.af12d57a740fb6b1ba5b.css 706.af12d57a740fb6b1ba5b.rtl.css 708.7f4b99c8dfd3f4cda1d1.js 7353.9bb4f9381a2ee34bec3c.css 7353.9bb4f9381a2ee34bec3c.rtl.css 7365.fb40181a46db7cf2d8b0.js 7371.81bb2bc38b8ec23308e1.js 739.ac9682232ee125adb331.js 7400.30502d5397989951046f.css 7400.30502d5397989951046f.rtl.css 7591.cea4aee1089cbf340ee7.js 7607.99350c6a482907066b03.css 7607.99350c6a482907066b03.rtl.css 7610.9e79032a52ca259701ef.css 7610.9e79032a52ca259701ef.rtl.css 7703.be823882173b57ef030c.js 7757.6d2b490c3cc2ed78d4dd.css 7757.6d2b490c3cc2ed78d4dd.rtl.css 7799.681df0cf83dba8ef3cc5.js 7936.1e4e780ffda134d965f5.css 7936.1e4e780ffda134d965f5.rtl.css 7962.eed46026b7fd77b57cb3.js 8193.01090d4d9384825040ad.css 8193.01090d4d9384825040ad.rtl.css 83.46ce2798763a3d5c2748.css 83.46ce2798763a3d5c2748.rtl.css 8434.99d7135551ebc9e84366.js 8445.e3ed5f183ca7539d37f0.css 8445.e3ed5f183ca7539d37f0.rtl.css 847.0e2ec220427667ac4afb.js 8604.9200d240b82687bc2a27.css 8604.9200d240b82687bc2a27.rtl.css 8625.2718a9cf5d44ca766c9d.js 8680.a98f949c3d71bf32d2c7.js 8856.15adfc3af04a9cdeadc5.css 8856.15adfc3af04a9cdeadc5.rtl.css 8858.535457f61e1b51d9add2.css 8858.535457f61e1b51d9add2.rtl.css 8933.9d36818107c1f276f948.css 8933.9d36818107c1f276f948.rtl.css 8969.d72c3357aff6000fd03e.css 8969.d72c3357aff6000fd03e.rtl.css 9256.c6fbca120598828685f3.css 9256.c6fbca120598828685f3.rtl.css 9305.009b7d4c21c45de9ca48.css 9305.009b7d4c21c45de9ca48.rtl.css 9354.a21ae4055d6f7729f892.css 9354.a21ae4055d6f7729f892.rtl.css 9423.0ad3a6d06b6bac488bb0.css 9423.0ad3a6d06b6bac488bb0.rtl.css 9448.cd38beceb14c87b723f6.css 9448.cd38beceb14c87b723f6.rtl.css 9602.a0fc3bf3e40760a87f74.css 9602.a0fc3bf3e40760a87f74.rtl.css 9628.8f8514eafeb1da3bbdee.js 9772.0967c8fb7beae0056cf7.js 9843.9822f0a3a15262042b3e.css 9843.9822f0a3a15262042b3e.rtl.css 9917.f67e7443dbbc7357fda3.css 9917.f67e7443dbbc7357fda3.rtl.css a6506134daec7169f68f563f084a9d41.svg add-compare-dialog.0e0f4b81cf8178378c14.js change-interval-dialog.15fea722d205fbdde7d1.js chart-bottom-toolbar.05a57b6389d7ddc2a351.js chart-event-hint.cb517ed06ee9725b8a76.js chart-screenshot-hint.6d0f2e7ac3cebd7b650c.js chart-widget-gui.9891573a47b469e91df5.js compare-model.08356f64fbfcdcdc3776.js context-menu-renderer.9a0385060e4241baf12d.js currency-label-menu.6dde8a17826b1fb3712c.js custom-intervals-add-dialog.3506afd973a0a43dc42a.js drawing-toolbar.8399395e7103ba30e756.js export-data.429732b8c4ae52bcac7d.js floating-toolbars.913e12fe2b73959f49ca.js full-tooltips-popup.c97f4f88ba2959dd66bb.js general-chart-properties-dialog.742b577b84c6f9fdb26f.js general-property-page.86f95ff011c77a44071d.js get-error-card.dfe1662b6e974e519b68.js go-to-date-dialog-impl.dadfac644efdcd254d91.js hammerjs.c69dac2431e462e3fc71.js header-toolbar.d302e948bcd970bc1897.js line-tools-icons.2ebfde56d4ef0139cc64.js load-chart-dialog.418fa6c99a7803f5cc10.js lollipop-tooltip-renderer.76349a508c9e9d8b8af2.js lt-pane-views.a54c6c59d86ab4d390bf.js lt-property-pages-with-definitions.ced0df22c184338b3396.js manage-drawings-dialog.ce43d4b42ea019cc5518.js new-confirm-inputs-dialog.88813711209cf273d882.js new-edit-object-dialog.e069889125138e0cf97a.js object-tree-dialog.ec325666665d14d13dd5.js react.13567dea1b1173009d35.js redux.e48a9c831cd697f8a38d.js restricted-toolset.8f58ab2a275c8e1f72b1.js runtime.f1210af3518e525e94d7.js series-icons-map.9d92dfe755e0c94c0c8d.js series-pane-views.d49b8ec162ba0c43260c.js share-chart-to-social-utils.830f7e41690ac8285de5.js show-theme-save-dialog.b99932982e0d8e47d562.js simple-dialog.4965864a1f87b628af01.js source-properties-editor.6854af2788acfa4ef4d4.js study-inputs-pane-views.1763111669ad2eaa2f52.js study-market.aaf59e23fa593dd538bc.js study-pane-views.d9686c973fa1f1a93ff4.js study-property-pages-with-definitions.72083d0a0868166ca2b7.js study-template-dialog.fd30d0463b77c8858d31.js symbol-info-dialog-impl.6aa56a0ae77115394b2f.js symbol-search-dialog.4e741ef8a94e2a1cdf8c.js take-chart-image-impl.013638618dfc6d4c1eaa.js vendors.3197279804dd7477f3fb.js charting_library.cjs.js charting_library.d.ts charting_library.esm.js charting_library.js charting_library.standalone.js cs-tv-chart.e2a841ff.html da_DK-tv-chart.e2a841ff.html datafeed-api.d.ts de-tv-chart.e2a841ff.html el-tv-chart.e2a841ff.html en-tv-chart.e2a841ff.html es-tv-chart.e2a841ff.html et_EE-tv-chart.e2a841ff.html fa-tv-chart.e2a841ff.html fr-tv-chart.e2a841ff.html he_IL-tv-chart.e2a841ff.html hu_HU-tv-chart.e2a841ff.html id_ID-tv-chart.e2a841ff.html it-tv-chart.e2a841ff.html ja-tv-chart.e2a841ff.html ko-tv-chart.e2a841ff.html ms_MY-tv-chart.e2a841ff.html nl_NL-tv-chart.e2a841ff.html no-tv-chart.e2a841ff.html package.json pl-tv-chart.e2a841ff.html pt-tv-chart.e2a841ff.html ro-tv-chart.e2a841ff.html ru-tv-chart.e2a841ff.html sk_SK-tv-chart.e2a841ff.html sv-tv-chart.e2a841ff.html th-tv-chart.e2a841ff.html tr-tv-chart.e2a841ff.html vi-tv-chart.e2a841ff.html zh-tv-chart.e2a841ff.html zh_TW-tv-chart.e2a841ff.html components ChartHeader state.ts TVChartContainer charting_library ar-tv-chart.e2a841ff.html bundles 1403.5c193407bf9023ec51df.css 1403.5c193407bf9023ec51df.rtl.css 1413.0beb5c102530e80c962f.css 1413.0beb5c102530e80c962f.rtl.css 1529.30943dc0c4f6a9ddaaa6.js 167.4a7b6d5ac49e0365fb9f.css 167.4a7b6d5ac49e0365fb9f.rtl.css 1778.3dcfedd5fc468612cdc9.css 1778.3dcfedd5fc468612cdc9.rtl.css 1829.1d41207f53b42b7a2cba.js 1941.ae71d13122bc90f281f2.css 1941.ae71d13122bc90f281f2.rtl.css 2091.b5cd26b120d8f015a5f6.css 2091.b5cd26b120d8f015a5f6.rtl.css 2162.da7cb9d498f064a9ef84.css 2162.da7cb9d498f064a9ef84.rtl.css 2269.e35db23226edaf77f36d.css 2269.e35db23226edaf77f36d.rtl.css 2273.c8e768dcdd52b58e948e.css 2273.c8e768dcdd52b58e948e.rtl.css 2321.4f5fec7d39b99277caa5.css 2321.4f5fec7d39b99277caa5.rtl.css 2359.18a49f656f3259463f4f.css 2359.18a49f656f3259463f4f.rtl.css 2391.07217bcacc2a0c3b5526.js 2402.4ce4e3425dce9bceed85.js 2444.89916595bdde00535f06.js 2614.9b290389192f690dd33c.css 2614.9b290389192f690dd33c.rtl.css 2778.22f147dbe677a02ae3db.css 2778.22f147dbe677a02ae3db.rtl.css 2850.8a920beb86b4e0f023f2.css 2850.8a920beb86b4e0f023f2.rtl.css 306.547d2bcc2b4af2c3a922.js 3223.783979b0683ba0a325de.css 3223.783979b0683ba0a325de.rtl.css 339.79f004acba5fa5c1b85f.css 339.79f004acba5fa5c1b85f.rtl.css 3463.65423ae1c1f3301a6bc0.js 3537.273ebe86a4260eff8e80.css 3537.273ebe86a4260eff8e80.rtl.css 3590.9ba8c934cf8289ea708f.js 3708.b21be6dee862262304cf.css 3708.b21be6dee862262304cf.rtl.css 3876.fbb750fd312778403036.css 3876.fbb750fd312778403036.rtl.css 3894.6c50d72ee9e079af3dab.css 3894.6c50d72ee9e079af3dab.rtl.css 3996.3cdbd2dcf744b8239723.css 3996.3cdbd2dcf744b8239723.rtl.css 40566afd832a155e5e370a8bd423de4b.svg 4078.43552fd4fee41d29f435.css 4078.43552fd4fee41d29f435.rtl.css 4093.8b84af355871cc700cb8.js 4336.1228643b9325cd73ea59.css 4336.1228643b9325cd73ea59.rtl.css 439.cf0a8c77353b34e465e2.css 439.cf0a8c77353b34e465e2.rtl.css 4595.6423e4f6860a7dd905ff.css 4595.6423e4f6860a7dd905ff.rtl.css 4652.c4c887154b57ce62bd2d.css 4652.c4c887154b57ce62bd2d.rtl.css 4736.2eccdb294faa8c6685ac.css 4736.2eccdb294faa8c6685ac.rtl.css 4834.07c319579bda11b57fc3.css 4834.07c319579bda11b57fc3.rtl.css 4882.acb0c10fdfd40a912b89.css 4882.acb0c10fdfd40a912b89.rtl.css 4940.6aeb4a6f298568a71905.js 4985.6abfd9453389325f7436.css 4985.6abfd9453389325f7436.rtl.css 5019.5e7f23f81809b4af9b28.js 5030.3f535fc5b94422bc913a.js 5254.776db7a6898f96fdd81f.js 5383.22c502e2ba80f4b4fc32.js 5410.21bcd4914bfb1cf880be.css 5410.21bcd4914bfb1cf880be.rtl.css 5453.142c8996edfadb5669ae.css 5453.142c8996edfadb5669ae.rtl.css 5527.b19a3c2c68b0d873fe2b.css 5527.b19a3c2c68b0d873fe2b.rtl.css 5551.407668886ab3145df3b5.css 5551.407668886ab3145df3b5.rtl.css 5637.a1b98549b1c9f19a01cf.css 5637.a1b98549b1c9f19a01cf.rtl.css 5698.9f7ef23e439b8f550541.css 5698.9f7ef23e439b8f550541.rtl.css 587.144039f5c693ee079edb.css 587.144039f5c693ee079edb.rtl.css 5984.fce1e6b0306b3072be07.css 5984.fce1e6b0306b3072be07.rtl.css 6062.56b57d0c5c641ee6c503.css 6062.56b57d0c5c641ee6c503.rtl.css 6143.1f43f1c13a5153841646.css 6143.1f43f1c13a5153841646.rtl.css 6253.8ddff4c976b3edf9f34c.css 6253.8ddff4c976b3edf9f34c.rtl.css 6333.75d8cc7be7c14f60fb3b.css 6333.75d8cc7be7c14f60fb3b.rtl.css 6473.e5bfe6a8cd8097cebb56.css 6473.e5bfe6a8cd8097cebb56.rtl.css 6548.bda2305976fecdd6ca1a.css 6548.bda2305976fecdd6ca1a.rtl.css 6612.6ea4b89e354fef333be4.css 6612.6ea4b89e354fef333be4.rtl.css 6637.b9569ad7b9c1ffb59c7c.css 6637.b9569ad7b9c1ffb59c7c.rtl.css 7039.873153a7278857ebfcd1.css 7039.873153a7278857ebfcd1.rtl.css 706.af12d57a740fb6b1ba5b.css 706.af12d57a740fb6b1ba5b.rtl.css 708.7f4b99c8dfd3f4cda1d1.js 7353.9bb4f9381a2ee34bec3c.css 7353.9bb4f9381a2ee34bec3c.rtl.css 7365.fb40181a46db7cf2d8b0.js 7371.81bb2bc38b8ec23308e1.js 739.ac9682232ee125adb331.js 7400.30502d5397989951046f.css 7400.30502d5397989951046f.rtl.css 7591.cea4aee1089cbf340ee7.js 7607.99350c6a482907066b03.css 7607.99350c6a482907066b03.rtl.css 7610.9e79032a52ca259701ef.css 7610.9e79032a52ca259701ef.rtl.css 7703.be823882173b57ef030c.js 7757.6d2b490c3cc2ed78d4dd.css 7757.6d2b490c3cc2ed78d4dd.rtl.css 7799.681df0cf83dba8ef3cc5.js 7936.1e4e780ffda134d965f5.css 7936.1e4e780ffda134d965f5.rtl.css 7962.eed46026b7fd77b57cb3.js 8193.01090d4d9384825040ad.css 8193.01090d4d9384825040ad.rtl.css 83.46ce2798763a3d5c2748.css 83.46ce2798763a3d5c2748.rtl.css 8434.99d7135551ebc9e84366.js 8445.e3ed5f183ca7539d37f0.css 8445.e3ed5f183ca7539d37f0.rtl.css 847.0e2ec220427667ac4afb.js 8604.9200d240b82687bc2a27.css 8604.9200d240b82687bc2a27.rtl.css 8625.2718a9cf5d44ca766c9d.js 8680.a98f949c3d71bf32d2c7.js 8856.15adfc3af04a9cdeadc5.css 8856.15adfc3af04a9cdeadc5.rtl.css 8858.535457f61e1b51d9add2.css 8858.535457f61e1b51d9add2.rtl.css 8933.9d36818107c1f276f948.css 8933.9d36818107c1f276f948.rtl.css 8969.d72c3357aff6000fd03e.css 8969.d72c3357aff6000fd03e.rtl.css 9256.c6fbca120598828685f3.css 9256.c6fbca120598828685f3.rtl.css 9305.009b7d4c21c45de9ca48.css 9305.009b7d4c21c45de9ca48.rtl.css 9354.a21ae4055d6f7729f892.css 9354.a21ae4055d6f7729f892.rtl.css 9423.0ad3a6d06b6bac488bb0.css 9423.0ad3a6d06b6bac488bb0.rtl.css 9448.cd38beceb14c87b723f6.css 9448.cd38beceb14c87b723f6.rtl.css 9602.a0fc3bf3e40760a87f74.css 9602.a0fc3bf3e40760a87f74.rtl.css 9628.8f8514eafeb1da3bbdee.js 9772.0967c8fb7beae0056cf7.js 9843.9822f0a3a15262042b3e.css 9843.9822f0a3a15262042b3e.rtl.css 9917.f67e7443dbbc7357fda3.css 9917.f67e7443dbbc7357fda3.rtl.css a6506134daec7169f68f563f084a9d41.svg add-compare-dialog.0e0f4b81cf8178378c14.js change-interval-dialog.15fea722d205fbdde7d1.js chart-bottom-toolbar.05a57b6389d7ddc2a351.js chart-event-hint.cb517ed06ee9725b8a76.js chart-screenshot-hint.6d0f2e7ac3cebd7b650c.js chart-widget-gui.9891573a47b469e91df5.js compare-model.08356f64fbfcdcdc3776.js context-menu-renderer.9a0385060e4241baf12d.js currency-label-menu.6dde8a17826b1fb3712c.js custom-intervals-add-dialog.3506afd973a0a43dc42a.js drawing-toolbar.8399395e7103ba30e756.js export-data.429732b8c4ae52bcac7d.js floating-toolbars.913e12fe2b73959f49ca.js full-tooltips-popup.c97f4f88ba2959dd66bb.js general-chart-properties-dialog.742b577b84c6f9fdb26f.js general-property-page.86f95ff011c77a44071d.js get-error-card.dfe1662b6e974e519b68.js go-to-date-dialog-impl.dadfac644efdcd254d91.js hammerjs.c69dac2431e462e3fc71.js header-toolbar.d302e948bcd970bc1897.js line-tools-icons.2ebfde56d4ef0139cc64.js load-chart-dialog.418fa6c99a7803f5cc10.js lollipop-tooltip-renderer.76349a508c9e9d8b8af2.js lt-pane-views.a54c6c59d86ab4d390bf.js lt-property-pages-with-definitions.ced0df22c184338b3396.js manage-drawings-dialog.ce43d4b42ea019cc5518.js new-confirm-inputs-dialog.88813711209cf273d882.js new-edit-object-dialog.e069889125138e0cf97a.js object-tree-dialog.ec325666665d14d13dd5.js react.13567dea1b1173009d35.js redux.e48a9c831cd697f8a38d.js restricted-toolset.8f58ab2a275c8e1f72b1.js runtime.f1210af3518e525e94d7.js series-icons-map.9d92dfe755e0c94c0c8d.js series-pane-views.d49b8ec162ba0c43260c.js share-chart-to-social-utils.830f7e41690ac8285de5.js show-theme-save-dialog.b99932982e0d8e47d562.js simple-dialog.4965864a1f87b628af01.js source-properties-editor.6854af2788acfa4ef4d4.js study-inputs-pane-views.1763111669ad2eaa2f52.js study-market.aaf59e23fa593dd538bc.js study-pane-views.d9686c973fa1f1a93ff4.js study-property-pages-with-definitions.72083d0a0868166ca2b7.js study-template-dialog.fd30d0463b77c8858d31.js symbol-info-dialog-impl.6aa56a0ae77115394b2f.js symbol-search-dialog.4e741ef8a94e2a1cdf8c.js take-chart-image-impl.013638618dfc6d4c1eaa.js vendors.3197279804dd7477f3fb.js charting_library.cjs.js charting_library.d.ts charting_library.esm.js charting_library.js charting_library.standalone.js cs-tv-chart.e2a841ff.html da_DK-tv-chart.e2a841ff.html datafeed-api.d.ts de-tv-chart.e2a841ff.html el-tv-chart.e2a841ff.html en-tv-chart.e2a841ff.html es-tv-chart.e2a841ff.html et_EE-tv-chart.e2a841ff.html fa-tv-chart.e2a841ff.html fr-tv-chart.e2a841ff.html he_IL-tv-chart.e2a841ff.html hu_HU-tv-chart.e2a841ff.html id_ID-tv-chart.e2a841ff.html it-tv-chart.e2a841ff.html ja-tv-chart.e2a841ff.html ko-tv-chart.e2a841ff.html ms_MY-tv-chart.e2a841ff.html nl_NL-tv-chart.e2a841ff.html no-tv-chart.e2a841ff.html package.json pl-tv-chart.e2a841ff.html pt-tv-chart.e2a841ff.html ro-tv-chart.e2a841ff.html ru-tv-chart.e2a841ff.html sk_SK-tv-chart.e2a841ff.html sv-tv-chart.e2a841ff.html th-tv-chart.e2a841ff.html tr-tv-chart.e2a841ff.html vi-tv-chart.e2a841ff.html zh-tv-chart.e2a841ff.html zh_TW-tv-chart.e2a841ff.html index.css UserBoard index.css state.ts config.ts datafeed helpers.ts index.ts streaming.ts global.d.ts near.ts orderly api.ts constant.ts error.ts off-chain-api.ts off-chain-ws.ts on-chain-api.ts state.ts type.ts utils.ts styles tailwind.css tailwind.css utiles.ts tailwind.config.js tsconfig.json tsdx.config.js
# TSDX React User Guide Congrats! You just saved yourself hours of work by bootstrapping this project with TSDX. Let’s get you oriented with what’s here and how to use it. > This TSDX setup is meant for developing React component libraries (not apps!) that can be published to NPM. If you’re looking to build a React-based app, you should use `create-react-app`, `razzle`, `nextjs`, `gatsby`, or `react-static`. > If you’re new to TypeScript and React, checkout [this handy cheatsheet](https://github.com/sw-yx/react-typescript-cheatsheet/) ## Commands TSDX scaffolds your new library inside `/src`, and also sets up a [Parcel-based](https://parceljs.org) playground for it inside `/example`. The recommended workflow is to run TSDX in one terminal: ```bash npm start # or yarn start ``` This builds to `/dist` and runs the project in watch mode so any edits you save inside `src` causes a rebuild to `/dist`. Then run the example inside another: ```bash cd example npm i # or yarn to install dependencies npm start # or yarn start ``` The default example imports and live reloads whatever is in `/dist`, so if you are seeing an out of date component, make sure TSDX is running in watch mode like we recommend above. **No symlinking required**, we use [Parcel's aliasing](https://parceljs.org/module_resolution.html#aliases). To do a one-off build, use `npm run build` or `yarn build`. To run tests, use `npm test` or `yarn test`. ## Configuration Code quality is set up for you with `prettier`, `husky`, and `lint-staged`. Adjust the respective fields in `package.json` accordingly. ### Jest Jest tests are set up to run with `npm test` or `yarn test`. ### Bundle analysis Calculates the real cost of your library using [size-limit](https://github.com/ai/size-limit) with `npm run size` and visulize it with `npm run analyze`. #### Setup Files This is the folder structure we set up for you: ```txt /example index.html index.tsx # test your component here in a demo app package.json tsconfig.json /src index.tsx # EDIT THIS /test blah.test.tsx # EDIT THIS .gitignore package.json README.md # EDIT THIS tsconfig.json ``` #### React Testing Library We do not set up `react-testing-library` for you yet, we welcome contributions and documentation on this. ### Rollup TSDX uses [Rollup](https://rollupjs.org) as a bundler and generates multiple rollup configs for various module formats and build settings. See [Optimizations](#optimizations) for details. ### TypeScript `tsconfig.json` is set up to interpret `dom` and `esnext` types, as well as `react` for `jsx`. Adjust according to your needs. ## Continuous Integration ### GitHub Actions Two actions are added by default: - `main` which installs deps w/ cache, lints, tests, and builds on all pushes against a Node and OS matrix - `size` which comments cost comparison of your library on every pull request using [`size-limit`](https://github.com/ai/size-limit) ## Optimizations Please see the main `tsdx` [optimizations docs](https://github.com/palmerhq/tsdx#optimizations). In particular, know that you can take advantage of development-only optimizations: ```js // ./types/index.d.ts declare var __DEV__: boolean; // inside your code... if (__DEV__) { console.log('foo'); } ``` You can also choose to install and use [invariant](https://github.com/palmerhq/tsdx#invariant) and [warning](https://github.com/palmerhq/tsdx#warning) functions. ## Module Formats CJS, ESModules, and UMD module formats are supported. The appropriate paths are configured in `package.json` and `dist/index.js` accordingly. Please report if any issues are found. ## Deploying the Example Playground The Playground is just a simple [Parcel](https://parceljs.org) app, you can deploy it anywhere you would normally deploy that. Here are some guidelines for **manually** deploying with the Netlify CLI (`npm i -g netlify-cli`): ```bash cd example # if not already in the example folder npm run build # builds to dist netlify deploy # deploy the dist folder ``` Alternatively, if you already have a git repo connected, you can set up continuous deployment with Netlify: ```bash netlify init # build command: yarn build && cd example && yarn && yarn build # directory to deploy: example/dist # pick yes for netlify.toml ``` ## Named Exports Per Palmer Group guidelines, [always use named exports.](https://github.com/palmerhq/typescript#exports) Code split inside your React app instead of your React library. ## Including Styles There are many ways to ship styles, including with CSS-in-JS. TSDX has no opinion on this, configure how you like. For vanilla CSS, you can include it at the root directory and add it to the `files` section in your `package.json`, so that it can be imported separately by your users and run through their bundler's loader. ## Publishing to NPM We recommend using [np](https://github.com/sindresorhus/np). ## Usage with Lerna When creating a new package with TSDX within a project set up with Lerna, you might encounter a `Cannot resolve dependency` error when trying to run the `example` project. To fix that you will need to make changes to the `package.json` file _inside the `example` directory_. The problem is that due to the nature of how dependencies are installed in Lerna projects, the aliases in the example project's `package.json` might not point to the right place, as those dependencies might have been installed in the root of your Lerna project. Change the `alias` to point to where those packages are actually installed. This depends on the directory structure of your Lerna project, so the actual path might be different from the diff below. ```diff "alias": { - "react": "../node_modules/react", - "react-dom": "../node_modules/react-dom" + "react": "../../../node_modules/react", + "react-dom": "../../../node_modules/react-dom" }, ``` An alternative to fixing this problem would be to remove aliases altogether and define the dependencies referenced as aliases as dev dependencies instead. [However, that might cause other problems.](https://github.com/palmerhq/tsdx/issues/64)
munanadi_graph-near
README.md networks.json package.json src mappings.ts tsconfig.json
> Not working on this anymore Turns out that the graph actually tracks only `ActionReceipts` on near and not `DataReceipts` and also skips the `Failed` tranasctions which I found out from their [source code](https://github.com/graphprotocol/graph-node/blob/992121bbe95880b6ed6960bd5e9732829dc98c3d/chain/near/src/chain.rs#L248) #### STEPS ``` yarn codegen ``` ``` yarn build ``` > graph auth here ``` yarn depoloy ```
ialexander28_web3-dapp
.gitpod.yml .prettierrc.json README.md __test__ avalanche.test.ts polygon.test.ts secret.test.ts solana.test.ts components protocols avalanche components index.ts lib index.ts celo components index.ts lib index.ts ceramic lib figmentLearnSchema.json figmentLearnSchemaCompact.json identityStore LocalStorage.ts index.ts index.ts types index.ts near components index.ts lib index.ts polkadot components index.ts lib index.ts polygon challenges balance.ts connect.ts deploy.ts getter.ts index.ts query.ts restore.ts setter.ts transfer.ts components index.ts lib index.ts secret components index.ts lib index.ts solana components index.ts lib index.ts tezos components index.ts lib index.ts the_graph graphql query.ts shared Button.styles.ts CustomMarkdown Markdown.styles.ts VideoPlayer VideoPlayer.styles.ts utils markdown-utils.ts string-utils.ts ProtocolNav ProtocolNav.styles.ts contracts celo HelloWorld.json near Cargo.toml README.md compile.js src lib.rs polygon SimpleStorage README.md SimpleStorage.json migrations 1_initial_migration.js 2_deploy_contracts.js package-lock.json package.json truffle-config.js solana program Cargo.toml Xargo.toml src lib.rs tests lib.rs tezos counter.js the_graph CryptopunksData.abi.json docker docker-compose.yml hooks index.ts useColors.ts useLocalStorage.ts useSteps.ts jest.config.js lib constants.ts markdown PREFACE.md avalanche CHAIN_CONNECTION.md CREATE_KEYPAIR.md EXPORT_TOKEN.md FINAL.md GET_BALANCE.md IMPORT_TOKEN.md PROJECT_SETUP.md TRANSFER_TOKEN.md celo CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md SWAP_TOKEN.md TRANSFER_TOKEN.md ceramic BASIC_PROFILE.md CHAIN_CONNECTION.md CUSTOM_DEFINITION.md FINAL.md LOGIN.md PROJECT_SETUP.md near CHAIN_CONNECTION.md CREATE_ACCOUNT.md CREATE_KEYPAIR.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md polkadot CHAIN_CONNECTION.md CREATE_ACCOUNT.md ESTIMATE_DEPOSIT.md ESTIMATE_FEES.md FINAL.md GET_BALANCE.md PROJECT_SETUP.md RESTORE_ACCOUNT.md TRANSFER_TOKEN.md polygon CHAIN_CONNECTION.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md QUERY_CHAIN.md RESTORE_ACCOUNT.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md secret CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md solana CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md FUND_ACCOUNT.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md SOLANA_CREATE_GREETER.md TRANSFER_TOKEN.md tezos CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md the_graph FINAL.md GRAPH_NODE.md PROJECT_SETUP.md SUBGRAPH_MANIFEST.md SUBGRAPH_MAPPINGS.md SUBGRAPH_QUERY.md SUBGRAPH_SCAFFOLD.md SUBGRAPH_SCHEMA.md | n : | next-env.d.ts next.config.js package.json pages api avalanche account.ts balance.ts connect.ts export.ts import.ts transfer.ts celo account.ts balance.ts connect.ts deploy.ts getter.ts setter.ts swap.ts transfer.ts near balance.ts check-account.ts connect.ts create-account.ts deploy.ts getter.ts keypair.ts setter.ts transfer.ts polkadot account.ts balance.ts connect.ts deposit.ts estimate.ts restore.ts transfer.ts secret account.ts balance.ts connect.ts deploy.ts getter.ts setter.ts transfer.ts solana balance.ts connect.ts deploy.ts fund.ts getter.ts greeter.ts keypair.ts setter.ts transfer.ts tezos account.ts balance.ts connect.ts deploy.ts getter.ts setter.ts transfer.ts the-graph entity.ts manifest.ts mapping.ts node.ts scaffold.ts public discord.svg figment-learn-compact.svg vercel.svg theme colors.ts index.ts media.ts tsconfig.json types index.ts utils colors.ts context.ts datahub.ts markdown.ts networks.ts pages.ts string-utils.ts tracking-utils.ts
# 👋🏼 What is `learn-web3-dapp`? We made this decentralized application (dApp) to help developers learn about Web 3 protocols. It's a Next.js app that uses React, TypeScript and various smart contract languages (mostly Solidity and Rust). We will guide you through using the various blockchain JavaScript SDKs to interact with their networks. Each protocol is slightly different, but we have attempted to standardize the workflow so that you can quickly get up to speed on networks like Solana, NEAR, Polygon and more! - ✅ Solana - ✅ Polygon - ✅ Avalanche - ✅ NEAR - ✅ Tezos - ✅ Secret - ✅ Polkadot - ✅ Celo - ✅ Ceramic - ✅ The Graph - 🔜 Arweave - 🔜 Chainlink - 🔜 Pyth - [Let us know which one you'd like us to cover](https://github.com/figment-networks/learn-web3-dapp/issues) <img width="1024" alt="Screen Shot 1" src="https://raw.githubusercontent.com/figment-networks/learn-web3-dapp/main/markdown/__images__/readme-01.png"> <img width="1024" alt="Screen Shot 2" src="https://raw.githubusercontent.com/figment-networks/learn-web3-dapp/main/markdown/__images__/readme-02.png"> <img width="1024" alt="Screen Shot 3" src="https://raw.githubusercontent.com/figment-networks/learn-web3-dapp/main/markdown/__images__/readme-03.png"> # 🧑‍💻 Get started ## 🤖 Using Gitpod (Recommended) The best way to go through those courses it using [Gitpod](https://gitpod.io). Gitpod provides prebuilt developer environments in your browser, powered by VS Code. Just sign in using GitHub and you'll be up and running in seconds without having to do any manual setup 🔥 [**Open this repo on Gitpod**](https://gitpod.io/#https://github.com/figment-networks/learn-web3-dapp) ## 🐑 Clone locally Make sure you have installed [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git), [Node.js](https://nodejs.org/en/) (Please install **v14.17.0**, we recommend using [nvm](https://github.com/nvm-sh/nvm)) and [yarn](https://yarnpkg.com/getting-started/install). Then clone the repo, install dependencies and start the server by running all these commands: ```text git clone https://github.com/figment-networks/learn-web3-dapp.git cd learn-web3-dapp yarn yarn dev ``` # 🤝 Feedback and contributing If you encounter any errors during this process, please join our [Discord](https://figment.io/devchat) for help. Feel free to also open an Issue or a Pull Request on the repo itself. We hope you enjoy our Web 3 education dApps 🚀 -- ❤️ The Figment Learn Team # Pathway Smart Contract A [smart contract] written in [Rust] for [figment pathway] # Quick Start Before you compile this code, you will need to install Rust with [correct target] # Exploring The Code 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [rust]: https://www.rust-lang.org/ [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html Based on: MetaCoin tutorial from Truffle docs https://www.trufflesuite.com/docs/truffle/quickstart SimpleStorage example contract from Solidity docs https://docs.soliditylang.org/en/v0.4.24/introduction-to-smart-contracts.html#storage 1. Install truffle (https://www.trufflesuite.com/docs/truffle/getting-started/installation) `npm install -g truffle` 2. Navigate to this directory (/contracts/polygon/SimpleStorage) 3. Install dependencies `yarn` 4. Test contract `truffle test ./test/TestSimpleStorage.sol` **Possible issue:** "Something went wrong while attempting to connect to the network. Check your network configuration. Could not connect to your Ethereum client with the following parameters:" **Solution:** run `truffle develop` and make sure port matches the one in truffle-config.js under development and test networks 5. Run locally via `truffle develop` $ truffle develop ``` migrate let instance = await SimpleStorage.deployed(); let storedDataBefore = await instance.get(); storedDataBefore.toNumber() // Should print 0 instance.set(50); let storedDataAfter = await instance.get(); storedDataAfter.toNumber() // Should print 50 ``` 6. Create Polygon testnet account - Install MetaMask (https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn?hl=en) - Add a custom network with the following params: Network Name: "Polygon Mumbai" RPC URL: https://rpc-mumbai.maticvigil.com/ Chain ID: 80001 Currency Symbol: MATIC Block Explorer URL: https://mumbai.polygonscan.com 7. Fund your account from the Matic Faucet https://faucet.matic.network Select MATIC Token, Mumbai Network Enter your account address from MetaMask Wait until time limit is up, requests tokens 3-4 times so you have enough to deploy your contract 8. Add a `.secret` file in this directory with your account's seed phrase or mnemonic (you should be required to write this down or store it securely when creating your account in MetaMask). In `truffle-config.js`, uncomment the three constant declarations at the top, along with the matic section of the networks section of the configuration object. 9. Deploy contract `truffle migrate --network matic` 10. Interact via web3.js ```js const {ethers} = require('ethers'); const fs = require('fs'); const mnemonic = fs.readFileSync('.secret').toString().trim(); const signer = new ethers.Wallet.fromMnemonic(mnemonic); const provider = new ethers.providers.JsonRpcProvider( 'https://matic-mumbai.chainstacklabs.com', ); const json = JSON.parse( fs.readFileSync('build/contracts/SimpleStorage.json').toString(), ); const contract = new ethers.Contract( json.networks['80001'].address, json.abi, signer.connect(provider), ); contract.get().then((val) => console.log(val.toNumber())); // should log 0 contract.set(50).then((receipt) => console.log(receipt)); contract.get().then((val) => console.log(val.toNumber())); // should log 50 ```
plat-group_plat-app
.styleci.yml README.md app Console Commands CreateFastGameSC.php LanguageJS.php Kernel.php Events CampaignCreatedEvent.php LessonCompletedEvent.php OrderConfirmedEvent.php OrderCreatedEvent.php PlayedGameEvent.php Exceptions Handler.php Helpers Constants admin_routes.php auth_routes.php constant.php utils.php web_routes.php Http Controllers Auth Authenticates.php ThrottlesLogins.php Web Login.php Register.php AuthController.php Controller.php Traits SessionFormRequestTrait.php Web Campaign.php Game.php Learning.php LearningCourse.php Lesson.php Market.php MyGame.php MyOrder.php Pool.php Question.php Transaction.php Kernel.php Middleware Authenticate.php EncryptCookies.php PreventRequestsDuringMaintenance.php RedirectIfAuthenticated.php TrimStrings.php TrustHosts.php TrustProxies.php VerifyCsrfToken.php Requests Web CreateCampaignRequest.php CreateGameRequest.php CreateGameTemplateRequest.php FinishGameRequest.php OrderGameRequest.php RegisterRequest.php StoreCourseRequest.php SubmitAssignmentsRequest.php Listeners PayCoinListener.php PushToPoolListener.php SaveTransactionListener.php Traits SmartContract.php TransferGameToOwnerListener.php Models Campaign.php Course.php Game.php GameTemplate.php Lesson.php LessonAnswer.php Order.php Question.php Traits GameModelHelper.php UuidTrait.php Transaction.php User.php Policies CampaignPolicy.php CoursePolicy.php GamePolicy.php GameTemplatePolicy.php LearnPolicy.php Providers AppServiceProvider.php AuthServiceProvider.php BroadcastServiceProvider.php EventServiceProvider.php NearUserProvider.php RouteServiceProvider.php Repositories CampaignRepository.php Concerns BaseRepository.php CourseRepository.php GameRepository.php GameTemplateRepository.php LessonRepository.php OrderRepository.php QuestionRepository.php TransactionRepository.php UserRepository.php Services CampaignService.php Concerns BaseService.php SearchBaseServiceAbstract.php CourseService.php GameService.php GameTemplateService.php LessonService.php OrderService.php QuestionService.php Traits CollectionPaginationTraitService.php MessageTraitService.php Poolable.php TransactionService.php UserService.php View Components Alert.php Forms BaseComponent.php Checkbox.php Group.php Input.php Label.php Open.php Select.php Textarea.php bootstrap app.php composer.json config app.php auth.php broadcasting.php cache.php cors.php database.php filesystems.php hashing.php logging.php mail.php queue.php sanctum.php services.php session.php view.php database factories CampaignFactory.php GameFactory.php GameTemplateFactory.php LearningCourseFactory.php LessonFactory.php QuestionFactory.php TransactionFactory.php UserFactory.php migrations 2014_10_12_000000_create_users_table.php 2014_10_12_100000_create_password_resets_table.php 2019_08_19_000000_create_failed_jobs_table.php 2019_12_14_000001_create_personal_access_tokens_table.php 2021_11_21_195730_create_game_templates_table.php 2021_11_24_230317_create_orders_table.php 2021_11_25_170651_create_games_table.php 2021_11_26_104722_create_campaigns_table.php 2021_11_27_192642_create_campaign_referrals_table.php 2021_11_28_013403_create_transactions_table.php 2022_01_29_224121_create_learning_courses_table.php 2022_01_29_224216_create_lessons_table.php 2022_01_29_224228_create_questions_table.php 2022_02_09_204418_create_leason_answers_table.php seeders CreateTemplateData.php CreateTemplateLearningData.php DatabaseSeeder.php package.json phpcs.xml phpmd.xml phpunit.xml public .htaccess index.php robots.txt static images web bg_concentric_circle.svg logo.svg play_game.svg referral_reward.svg total_reward.svg user_reward.svg lp css LineIcons.css app.css font-awesome.min.css responsive.css fonts LineIcons.svg fontawesome-webfont.svg js app.js jquery-3.6.0.min.js particles.min.js resources assets _common js blockUI.js form-validation-additional.js form-validation.js i18n jquery-validation.js lodash-install.js translator.js near_configs.js web js app.js pages create_game_template.js l2e.js l2e_video.js near_authentication.js near_deposit.js near_storage_deposit.js plats_deposit.js testsmartcontract.js utils.js vendor.js lang en app.php auth.php message.php pagination.php passwords.php validation.php web.php views auth web auth_layout.blade.php login.blade.php near_login.blade.php register.blade.php components alert.blade.php forms checkbox.blade.php group.blade.php input.blade.php label.blade.php open.blade.php select.blade.php textarea.blade.php lp index.blade.php web campaign create.blade.php create_l2e.blade.php referral_box.blade.php game _common item_detail.blade.php item_list.blade.php _forms campaign.blade.php referral_box.blade.php detail.blade.php market create_template.blade.php index.blade.php my_game.blade.php play.blade.php pool create.blade.php index.blade.php test_near_frontend.blade.php income history.blade.php l2e course _form.blade.php create.blade.php detail.blade.php edit.blade.php management.blade.php refer_box.blade.php create.blade.php index.blade.php learn.blade.php lesson create.blade.php item_list.blade.php layout.blade.php menus game.blade.php learning.blade.php order _forms order.blade.php _parts released.blade.php upload_game.blade.php detail.blade.php list.blade.php routes api.php channels.php console.php web.php server.php tests App Events CampaignCreatedEventTest.php CreatesApplication.php Feature ExampleTest.php SmartContractTest.php TestCase.php Unit ExampleTest.php webpack.mix.js
# Plats ecosystem ## Preparation - PHP 8.x - MySQL 8.x - Apache2 - Composer 2.x - Node 16.13.x - Npm 8.1.x ## Installation 1. Pull source code from github Move to project directory `cd path_of_project` 2. Setting local environment config `cp .env.example .env` edit file .env as other project (project name, database connection, logs, etc) and save it 3. Update all dependency `composer update` 4. Generate key `php artisan key:generate` 5. Create table of database `php artisan migrate --seed` 6. Install node module `npm i` 7. Build frontend (vuejs) ### For development `npm run dev` ### For Production `npm run prod` 8. Run laravel build-in server and access to page `php artisan serve` <!-- sudo apt -y install php8.0-mysql sudo apt install -y php8.0-simplexml sudo apt-get install -y php8.0-curl sudo apt install php8.0-mbstring sudo apt-get install php8.1-zip CREATE USER 'admin'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Abc@123'; GRANT ALL PRIVILEGES ON *.* TO 'admin'@'localhost' WITH GRANT OPTION; FLUSH PRIVILEGES; mysql -u admin -p sudo apt-get remove composer show DATABASES CREATE DATABASE plats; APP_URL=http://localhost:3000 -->
iOchando_Artemis-ContractNTF
Cargo.toml src event.rs lib.rs target .rustc_info.json release .fingerprint Inflector-5afbffc1f381f40a lib-inflector.json autocfg-e66a3272e8863782 lib-autocfg.json borsh-derive-1d5ae6b8e1cf1bb8 lib-borsh-derive.json borsh-derive-internal-15c7803f3bf56420 lib-borsh-derive-internal.json borsh-schema-derive-internal-9940d5739ea7d2e9 lib-borsh-schema-derive-internal.json convert_case-7f94ef861a302c67 lib-convert_case.json darling-b481aa80855253aa lib-darling.json darling_core-5f7dfbf7022d25d5 lib-darling_core.json darling_macro-3aa95d98a3fabe1c lib-darling_macro.json derive_more-7a68bf7dd96e3b84 lib-derive_more.json fnv-c5ea35942fedfb9e lib-fnv.json generic-array-3a7d11350224ae59 build-script-build-script-build.json hashbrown-a7635062d0db26a5 lib-hashbrown.json ident_case-6f2602726dfbf5a3 lib-ident_case.json indexmap-6804ffee2b636dbc run-build-script-build-script-build.json indexmap-95286e341442f6b6 lib-indexmap.json indexmap-db476c3f51721126 build-script-build-script-build.json itoa-3ce9694eb1fe77f5 lib-itoa.json memchr-23c19175ced138d9 build-script-build-script-build.json near-rpc-error-core-103ab1db77d8a62e lib-near-rpc-error-core.json near-rpc-error-macro-93eb99ae98a74b1f lib-near-rpc-error-macro.json near-sdk-core-fe5c50fb56ed623f lib-near-sdk-core.json near-sdk-macros-ac74edb8fceab312 lib-near-sdk-macros.json num-bigint-f348f049baf378a6 build-script-build-script-build.json num-integer-ea7273414e20ce80 build-script-build-script-build.json num-rational-5e7b375c66f17a37 build-script-build-script-build.json num-traits-1b78fae63394617d build-script-build-script-build.json proc-macro-crate-35a6162b74b6d468 lib-proc-macro-crate.json proc-macro2-0381a0aa14808750 run-build-script-build-script-build.json proc-macro2-adca2fb9cf65dc5d lib-proc-macro2.json proc-macro2-e249dfa19f1f4a31 build-script-build-script-build.json quote-4784e4e91c9c41b9 run-build-script-build-script-build.json quote-dcea9546d2d8f592 build-script-build-script-build.json quote-e315cda2b694296d lib-quote.json ryu-35a1ad5a6e7f8912 lib-ryu.json serde-207b3833f8c327b7 build-script-build-script-build.json serde-9392d534e15dafc2 lib-serde.json serde-d449afb1c95c565e run-build-script-build-script-build.json serde_derive-4ad457bdb875e6a9 build-script-build-script-build.json serde_derive-b6a9f242a150de35 run-build-script-build-script-build.json serde_derive-c5afa7a261cf19ec lib-serde_derive.json serde_json-99b344bf3f764ab1 build-script-build-script-build.json serde_json-d47ee32dc7f01a66 run-build-script-build-script-build.json serde_json-f739ecf0869cc3ee lib-serde_json.json serde_with_macros-98af83ce069cc761 lib-serde_with_macros.json strsim-ccccbd1179c29486 lib-strsim.json syn-b38151015e4608a2 build-script-build-script-build.json syn-de000e0daceff612 lib-syn.json syn-e0177b2227736eae run-build-script-build-script-build.json toml-a55a431401b1b9c1 lib-toml.json typenum-f94bfce3f66f9366 build-script-build-script-main.json unicode-ident-808ec906ca634d69 lib-unicode-ident.json unicode-xid-d9ac2e4d6e09eb79 lib-unicode-xid.json version_check-e99ac1345353eecd lib-version_check.json wee_alloc-313ada6273a678f7 build-script-build-script-build.json wasm32-unknown-unknown release .fingerprint ahash-8918e2efed4880b2 lib-ahash.json aho-corasick-8e6e4aa56cd8c58d lib-aho_corasick.json base64-c77909cce00ad818 lib-base64.json block-buffer-45a6607161318e79 lib-block-buffer.json block-padding-0462ba6063c02747 lib-block-padding.json borsh-c5e370ed1095fe3b lib-borsh.json bs58-6281cd471907c799 lib-bs58.json byteorder-e23c453ea907e6a6 lib-byteorder.json cfg-if-0d97a5046a84c8ac lib-cfg-if.json cfg-if-ae99629d1f676482 lib-cfg-if.json contract_nft-ec4ee3ac7dda9a2c lib-contract_nft.json digest-7c19cb8c8bb9c68f lib-digest.json generic-array-28ebe296c1e51ebf run-build-script-build-script-build.json generic-array-8f6d39f33e3a2f9e lib-generic_array.json hashbrown-5c2f77bbf15a6f3b lib-hashbrown.json hashbrown-b19b36a49ce16b1f lib-hashbrown.json hex-14a08c23573c9b08 lib-hex.json indexmap-2c364abf22b165e5 run-build-script-build-script-build.json indexmap-bc302ac4d6fc13fd lib-indexmap.json itoa-fcd24d0ddcbad4e2 lib-itoa.json keccak-1d0cc6b2ae54377e lib-keccak.json lazy_static-0c71e18dd7cbe9ba lib-lazy_static.json memchr-00438d692be7f7d1 run-build-script-build-script-build.json memchr-878b41491e7be052 lib-memchr.json memory_units-fa328f12995e6708 lib-memory_units.json near-contract-standards-c767c57558be692e lib-near-contract-standards.json near-primitives-core-1f76e58530c4d604 lib-near-primitives-core.json near-runtime-utils-c164fb9b37bcfde4 lib-near-runtime-utils.json near-sdk-d0a8829f87b358e2 lib-near-sdk.json near-vm-errors-99e8e4ecde1012db lib-near-vm-errors.json near-vm-logic-328b7b0ced97581d lib-near-vm-logic.json num-bigint-7921252b9acb1302 lib-num-bigint.json num-bigint-df6c8e0171ff679d run-build-script-build-script-build.json num-integer-0f2a8595e2ec2002 run-build-script-build-script-build.json num-integer-ea97e745c122c2fa lib-num-integer.json num-rational-725db5b0f294a25c run-build-script-build-script-build.json num-rational-f9871c5204d1cded lib-num-rational.json num-traits-42ee74a2c818058b lib-num-traits.json num-traits-f9bc0672c40382f0 run-build-script-build-script-build.json opaque-debug-84243b91ed1ae3a6 lib-opaque-debug.json regex-2271755795e68740 lib-regex.json regex-syntax-c27a86262da089da lib-regex-syntax.json ryu-6af2ce044cf2e2ae lib-ryu.json serde-503a705e7ff3f259 run-build-script-build-script-build.json serde-fc7ea55cecbbce44 lib-serde.json serde_json-6e5081cccafa79c1 run-build-script-build-script-build.json serde_json-f6e6d4bdd63a03ec lib-serde_json.json serde_with-25a5669bb8b24956 lib-serde_with.json sha2-914f08488eb35870 lib-sha2.json sha3-8f8f1c6f93cd1ffb lib-sha3.json typenum-5e8e516739d1f8cc lib-typenum.json typenum-619a1395bffcb487 run-build-script-build-script-main.json wee_alloc-3004284b32418a0d run-build-script-build-script-build.json wee_alloc-d7a5d1841d501bc5 lib-wee_alloc.json build num-bigint-df6c8e0171ff679d out radix_bases.rs typenum-619a1395bffcb487 out consts.rs op.rs tests.rs wee_alloc-3004284b32418a0d out wee_alloc_static_array_backend_size_bytes.txt
Jonathansoufer_awesome-list-rpc-nodes-providers
.github CONTRIBUTING.md FUNDING.yml workflows links.yml README.md
<p align="center"> <a href="https://multinodes.xyz" target="_blank" rel="noopener"> <img src="https://i.imgur.com/IB0hvnJ.png" alt="MultiNodes - awesome RPC nodes providers" /> </a> </p> ## awesome-list-rpc-nodes-providers<!-- omit in toc --> [MultiNodes](https://multinodes.xyz) provides you with a list of PUBLIC RPC endpoints and Node providers for most of the Networks such as Ethereum, BSC, Polygon, Gnosis, Fantom, Avalanche, Solana, Tezos, Harmony, Arbitrum, Optimism, Flow etc. ## Contents <!-- omit in toc --> - [MultiChain](#multichain) - [Etherspot](#etherspot) - [GetBlock](https://getblock.io/) - [Account Abstraction / ERC-4337](#account-abstraction-rpc-providers) - [Ethereum](#ethereum) - [BSC](#bsc) - [Solana](#solana) - [Avalanche](#avalanche) - [Polygon](#polygon) - [Algorand](#algorand) - [Fantom](#fantom) - [Tezos](#tezos) - [Harmony](#harmony) - [KuCoin](#kucoin) - [IoTeX](#iotex) - [Gnosis (xDAI)](#gnosis-xdai) - [Fuse](#fuse) - [Optimism](#optimism) - [Arbitrum One](#arbitrum-one) - [Arbitrum Nova](#arbitrum-nova) - [Celo](#celo) - [Near](#near) - [Cosmos](#cosmos) - [Aurora](#aurora) - [TomoChain](#tomochain) - [Polkadot](#polkadot) - [Moonbeam](#moonbeam) - [Moonriver](#moonriver) - [Boba Network](#boba-network) - [Astar](#astar) - [Flow](#flow) - [Contributors](#contributors) ## MultiChain <p> If you would like to be on the #Multichain list <a href="mailto:[email protected]">Email Us</a> </p> ### Etherspot Etherspot gives developers and their applications the ability to use one or all the chains simultaneously with the same address for greater flexibility and speed. The Etherspot platform is built to work with any EVM-compatible network. With just few lines of [code](https://docs.etherspot.dev/getting-started/supported-ethereum-chains) you can instantiate Etherspot SDK on compatible EVM-chains such as: Polygon, BSC, xDAI, Fantom and Avalanche. Etherspot take hassle out of Ethereum development and allow you to focus on the most important thing – your product. Checkout: [etherspot.io](https://etherspot.io/) ### GetBlock GetBlock is the blockchain RPC provider that employs a ‘pay per use’ model: its requests have no ‘expiration date’ so that users only pay for the resources they actually use. It supports more than 50 multiple blockchains. GetBlock guarantees the highest rate limit in free tariff, 60 RPS. Web3 developers can set up an account and get an endpoint GetBlock currently supports RPC access to Ethereum, Solana, Avalanche, Polygon, Fantom, Optimism, BSC, Gnosis, Algorand and other blockchains (more than 50 blockchains). You can see the list of supported chains [here](https://getblock.io/nodes/). Checkout: [https://getblock.io/](https://getblock.io/) ### Infura Infura helps you build multichain applications by providing reliable and consistent RPC access to 10+ blockchain networks, including Ethereum, Polygon, Avalanche, NEAR, StarkNet, Optimism, and Arbitrum. You can see all the chains Infura supports on the [Networks page](https://www.infura.io/networks). Besides providing easy-to-integrate and scalable blockchain APIs, Infura empowers developers to “buidl” great dapps with value-add features like dedicated IPFS gateways, Infura [NFT API + SDK](https://www.infura.io/platform/nft-api), and [free archival data access](https://www.infura.io/solutions/archive-access). [Sign up for a free Infura account](https://app.infura.io/register) to get started. ## Account Abstraction RPC Providers **Providers** 1. Stackup.sh - [https://stackup.sh](https://stackup.sh) ## Ethereum **Providers:** 1. Infura.io - [https://infura.io](https://infura.io) 2. Alchemy - [https://www.alchemy.com](https://docs.alchemy.com/reference/ethereum-api-quickstart) 3. GetBlock - [https://getblock.io/nodes/eth/](https://getblock.io/nodes/eth/) 4. 0x - [https://0x.org](https://0x.org) 5. Amazon Managed Blockchain - [https://aws.amazon.com/managed-blockchain](https://aws.amazon.com/managed-blockchain) 6. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 7. Chainstack - [https://chainstack.com/build-better-with-ethereum/](https://chainstack.com/build-better-with-ethereum/) 8. ZMOK - [https://zmok.io/](https://zmok.io/) 9. Allnodes - [https://www.allnodes.com](https://www.allnodes.com) 10. Figment Datahub - [https://datahub.figment.io/](https://datahub.figment.io/) 11. Ankr - [https://ankr.com](https://ankr.com) 12. ArchiveNode - [https://archivenode.io/](https://archivenode.io/) 13. Blast - [https://blastapi.io/](https://blastapi.io/) 14. NodeReal - https://nodereal.io/ 15. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) 16. Kriptonio - [https://kriptonio.com/](https://kriptonio.com/) 17. Chainbase - [https://chainbase.online](https://chainbase.online) 18. LlamaNodes - [https://llamanodes.com/](https://llamanodes.com/) 19. Exaion Node - [https://node.exaion.com/](https://node.exaion.com/) 20. Chainnodes - [https://www.chainnodes.org/](https://www.chainnodes.org/) 21. Node RPC - [https://www.noderpc.xyz/](https://www.noderpc.xyz/) 22. OnFinality - [https://onfinality.io/](https://onfinality.io/) **Public Endpoints:** - [https://cloudflare-eth.com](https://cloudflare-eth.com) - [https://main-light.eth.linkpool.io](https://main-light.eth.linkpool.io) - [https://eth-rpc.gateway.pokt.network](https://eth-rpc.gateway.pokt.network) - [https://api.mycryptoapi.com/eth](https://api.mycryptoapi.com/eth) - [https://mainnet.eth.cloud.ava.do/](https://mainnet.eth.cloud.ava.do/) - [https://ethereumnodelight.app.runonflux.io](https://ethereumnodelight.app.runonflux.io) - [https://rpc.flashbots.net/](https://rpc.flashbots.net/) - [https://rpc.ankr.com/eth](https://rpc.ankr.com/eth) - [https://mainnet.eth.cloud.ava.do/](https://mainnet.eth.cloud.ava.do/) - [https://eth-mainnet.nodereal.io/v1/](https://eth-mainnet.nodereal.io/v1/) - [https://eth-mainnet.public.blastapi.io](https://eth-mainnet.public.blastapi.io) - [https://api.securerpc.com/v1](https://api.securerpc.com/v1) - [https://eth-mainnet.rpcfast.com](https://eth-mainnet.rpcfast.com) - [https://1rpc.io/eth](https://1rpc.io/eth) - [https://ethereum.publicnode.com](https://ethereum.publicnode.com) - [https://rpc.payload.de](https://rpc.payload.de) - [https://llamanodes.com/](https://llamanodes.com/) - [https://eth.api.onfinality.io/public](https://eth.api.onfinality.io/public) **Spin up your own node:** - [https://ethereum.org/en/developers/docs/nodes-and-clients/run-a-node/](https://ethereum.org/en/developers/docs/nodes-and-clients/run-a-node/) - [https://meganode.nodereal.io/account/login](https://meganode.nodereal.io/account/login) ## BSC **Providers:** 1. ANKR - [https://ankr.com](https://ankr.com) 2. GetBlock - [https://getblock.io](https://getblock.io/nodes/bsc/) 3. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 4. Chainstack - [https://chainstack.com/build-better-with-binance-smart-chain/](https://chainstack.com/build-better-with-binance-smart-chain/) 5. Figment Datahub - [https://datahub.figment.io/](https://datahub.figment.io/) 6. NodeReal - https://nodereal.io/ 7. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) 8. Chainbase - [https://chainbase.online](https://chainbase.online) **Public Endpoints:** - [https://bsc-mainnet.gateway.pokt.network/v1/lb/6136201a7bad1500343e248d](https://bsc-mainnet.gateway.pokt.network/v1/lb/6136201a7bad1500343e248d) - [https://bsc-dataseed.binance.org](https://bsc-dataseed.binance.org) - [https://bsc-dataseed1.defibit.io](https://bsc-dataseed1.defibit.io) - [https://bsc-dataseed1.ninicoin.io](https://bsc-dataseed1.ninicoin.io) - [https://bscrpc.com](https://bscrpc.com) - [https://rpc.ankr.com/bsc](https://rpc.ankr.com/bsc) - [https://bsc.rpcgator.com/](https://bsc.rpcgator.com/) - RPC Agreggator / Gateway - [https://bsc-mainnet.nodereal.io/v1/](https://bsc-mainnet.nodereal.io/v1/) - [https://bsc.publicnode.com](https://bsc.publicnode.com) **WebSocket:** - `wss://bsc-ws-node.nariox.org:443` **Spin up your own node:** - [https://docs.binance.org/smart-chain/developer/fullnode.html](https://docs.binance.org/smart-chain/developer/fullnode.html) ## Solana **Providers:** 1. Chainstack - [https://chainstack.com/build-better-with-solana/](https://chainstack.com/build-better-with-solana/) 2. GetBlock - [https://getblock.io/nodes/sol/](https://getblock.io/nodes/sol/) 3. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 4. Figment Datahub - [https://datahub.figment.io/](https://datahub.figment.io/) 5. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) 6. Coinbase - [https://www.coinbase.com/blog/coinbase-cloud-launches-solana-archival-nodes-to-empower-the-solana](https://www.coinbase.com/blog/coinbase-cloud-launches-solana-archival-nodes-to-empower-the-solana) 7. Blockdaemon - [https://blockdaemon.com/documentation/guides/solana/solana-nodes/](https://blockdaemon.com/documentation/guides/solana/solana-nodes/) 8. Alchemy - [https://alchemy.com](https://docs.alchemy.com/reference/solana-api-quickstart) **Public Endpoints:** - [https://api.mainnet-beta.solana.com](https://api.mainnet-beta.solana.com) - [https://solana-api.projectserum.com](https://solana-api.projectserum.com) - [https://rpc.ankr.com/solana](https://rpc.ankr.com/solana) **Spin up your own node:** - [https://docs.solana.com/running-validator](https://docs.solana.com/running-validator) ## Avalanche **Providers:** 1. GetBlock - [https://getblock.io/nodes/avax/](https://getblock.io/nodes/avax/) 2. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 3. Chainstack - [https://chainstack.com/build-better-with-avalanche/](https://chainstack.com/build-better-with-avalanche/) 4. Allnodes - [https://www.allnodes.com](https://www.allnodes.com) 5. Figment Datahub - [https://datahub.figment.io/](https://datahub.figment.io/) 6. Ankr - [https://ankr.com](https://ankr.com) 7. Blast - [https://blastapi.io/](https://blastapi.io/) 8. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) 9. OnFinality.io - [https://onfinality.io](https://onfinality.io) 10. Chainbase - [https://chainbase.online](https://chainbase.online) 11. Exaion Node - [https://node.exaion.com/](https://node.exaion.com/) **Public Endpoints:** - [https://avax-mainnet.gateway.pokt.network/v1/lb/605238bf6b986eea7cf36d5e/ext/bc/C/rpc](https://avax-mainnet.gateway.pokt.network/v1/lb/605238bf6b986eea7cf36d5e/ext/bc/C/rpc) - [https://api.avax.network/ext/bc/C/rpc](https://api.avax.network/ext/bc/C/rpc) - [https://rpc.ankr.com/avalanche](https://rpc.ankr.com/avalanche) - [https://avax.rpcgator.com/](https://avax.rpcgator.com/) - RPC Agreggator / Gateway - [https://avalanche.public-rpc.com](https://avalanche.public-rpc.com) - [https://blastapi.io/public-api/avalanche](https://blastapi.io/public-api/avalanche) - [https://avalanche.api.onfinality.io/public](https://avalanche.api.onfinality.io/public) - [https://avalanche.publicnode.com](https://avalanche.publicnode.com) **Spin up your own node:** - [https://docs.avax.network/build/tutorials/nodes-and-staking/run-avalanche-node](https://docs.avax.network/build/tutorials/nodes-and-staking/run-avalanche-node) ## Polygon **Providers:** 1. Infura.io - [https://infura.io](https://infura.io) 2. GetBlock - [https://getblock.io/nodes/matic/](https://getblock.io/nodes/matic/) 3. MaticVigil - [https://maticvigil.com](https://maticvigil.com) 4. Chainstack - [https://chainstack.com](https://chainstack.com/build-better-with-polygon/) 5. ANKR - [https://ankr.com](https://ankr.com) 6. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 7. Allnodes - [https://www.allnodes.com](https://www.allnodes.com) 8. Figment Datahub - [https://datahub.figment.io/](https://datahub.figment.io/) 9. Ankr - [https://ankr.com](https://ankr.com) 10. Blast - [https://blastapi.io/](https://blastapi.io/) 11. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) 12. Kriptonio - [https://kriptonio.com/](https://kriptonio.com/) 13. Chainbase - [https://chainbase.online](https://chainbase.online) 14. Alchemy - [https://alchemy.com](https://docs.alchemy.com/reference/polygon-api-quickstart) 15. Chainnodes - [https://www.chainnodes.org/](https://www.chainnodes.org/) 16. Node RPC - [https://www.noderpc.xyz/](https://www.noderpc.xyz/) 17. OnFinality.io - [https://onfinality.io](https://onfinality.io) **Public Endpoints:** - [https://rpc-mainnet.matic.network](https://rpc-mainnet.matic.network) - [https://rpc-mainnet.maticvigil.com](https://rpc-mainnet.maticvigil.com) - [https://matic-mainnet.chainstacklabs.com](https://matic-mainnet.chainstacklabs.com) - [https://matic-mainnet-full-rpc.bwarelabs.com](https://matic-mainnet-full-rpc.bwarelabs.com) - [https://matic-mainnet-archive-rpc.bwarelabs.com](https://matic-mainnet-archive-rpc.bwarelabs.com) - [https://poly-rpc.gateway.pokt.network/](https://poly-rpc.gateway.pokt.network/) - [https://rpc.ankr.com/polygon](https://rpc.ankr.com/polygon) - [https://blastapi.io/public-api/polygon](https://blastapi.io/public-api/polygon) - [https://polygon-rpc.com](https://polygon-rpc.com) - [https://polygon.publicnode.com](https://polygon.publicnode.com) - [https://polygon.api.onfinality.io/public](https://polygon.api.onfinality.io/public) **WebSocket:** - `wss://rpc-mainnet.matic.network` - `wss://matic.getblock.io/api_key/mainnet/` - `wss://ws-matic-mainnet.chainstacklabs.com` - `wss://rpc-mainnet.maticvigil.com/ws` **Spin up your own node:** - [https://docs.polygon.technology/docs/maintain/validate/validator-index](https://docs.polygon.technology/docs/maintain/validate/validator-index) ## Algorand **Providers**: 1. GetBlock - [https://getblock.io/nodes/algo/](https://getblock.io/nodes/algo/) 2. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 3. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) **Spin up your own node:** - [https://developer.algorand.org/docs/run-a-node/setup/install/](https://developer.algorand.org/docs/run-a-node/setup/install/) ## Fantom **Providers:** 1. GetBlock - [https://getblock.io/nodes/ftm/](https://getblock.io/nodes/ftm/) 2. ANKR - [https://ankr.com](https://ankr.com) 3. Chainstack - [https://chainstack.com/build-better-with-fantom/](https://chainstack.com/build-better-with-fantom/) 4. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 5. Blast - [https://blastapi.io/](https://blastapi.io/) 6. Datahub - [https://datahub.figment.io/](https://datahub.figment.io/) 7. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) 8. Chainbase - [https://chainbase.online](https://chainbase.online) 9. OnFinality.io - [https://onfinality.io](https://onfinality.io) **Public Endpoints:** - [https://fantom-mainnet.gateway.pokt.network/v1/lb/6261a8a154c745003bcdb0f8](https://fantom-mainnet.gateway.pokt.network/v1/lb/6261a8a154c745003bcdb0f8) - [https://rpc.ftm.tools/](https://rpc.ftm.tools/) - [https://rpc.ankr.com/fantom](https://rpc.ankr.com/fantom) - [https://ftm.rpcgator.com/](https://ftm.rpcgator.com/) - RPC Agreggator / Gateway - [https://blastapi.io/public-api/fantom](https://blastapi.io/public-api/fantom) - [https://fantom.publicnode.com](https://fantom.publicnode.com) - [https://fantom.api.onfinality.io/public](https://fantom.api.onfinality.io/public) **WebSocket:** - `wss://wsapi.fantom.network` - wss://bsc.getblock.io/api_key/mainnet/ **Spin up your own node:** - [https://docs.fantom.foundation/node/how-to-run-a-validator-node](https://docs.fantom.foundation/node/how-to-run-a-validator-node) ## Tezos **Providers:** 1. Tezos - [https://getblock.io/nodes/xtz/](https://getblock.io/nodes/xtz) 2. Chainstack - [https://chainstack.com/build-better-with-tezos/](https://chainstack.com/build-better-with-tezos/) 3. [MIDL.dev](https://midl.dev) Tezos RPC Service - [https://midl.dev/tezos-rpc](https://midl.dev/tezos-rpc) 4. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) 5. Exaion Node - [https://node.exaion.com/](https://node.exaion.com/) **Public Endpoints:** - [https://mainnet.api.tez.ie](https://mainnet.api.tez.ie) - [https://rpc.tzbeta.net/](https://rpc.tzbeta.net/) **Spin up your own node:** - [https://opentezos.com/deploy-a-node](https://opentezos.com/deploy-a-node) ## Harmony **Providers:** 1. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 2. Chainstack - [https://chainstack.com/build-better-with-harmony/](https://chainstack.com/build-better-with-harmony/) 3. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) 4. OnFinality.io - [https://onfinality.io](https://onfinality.io) **Public Endpoints:** - [https://harmony-0-rpc.gateway.pokt.network](https://harmony-0-rpc.gateway.pokt.network) - [https://api.harmony.one](https://api.harmony.one) - [https://harmony.public-rpc.com](https://harmony.public-rpc.com) - [https://harmony-mainnet.chainstacklabs.com](https://harmony-mainnet.chainstacklabs.com) - [https://harmony.api.onfinality.io/public](https://harmony.api.onfinality.io/public) **WebSocket:** - `wss://ws.s0.t.hmny.io` - `wss://ws-harmony-mainnet.chainstacklabs.com` **Spin up your own node:** - [https://docs.harmony.one/home/network/validators/node-setup](https://docs.harmony.one/home/network/validators/node-setup) ## KuCoin **Providers:** - GetBlock - [https://getblock.io/nodes/kcc/](https://getblock.io/nodes/kcc/) **Public Endpoints:** - [https://rpc-mainnet.kcc.network/](https://rpc-mainnet.kcc.network/) **Spin up your own node:** - [https://docs.kcc.io/#/en-us/?id=node](https://docs.kcc.io/#/en-us/?id=node) ## IoTeX **Providers:** 1. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 2. ANKR - [https://ankr.com](https://ankr.com) **Public Endpoints:** - [https://iotex-mainnet.gateway.pokt.network/v1/lb/6176f902e19001003499f492](https://iotex-mainnet.gateway.pokt.network/v1/lb/6176f902e19001003499f492) - [https://rpc.ankr.com/iotex](https://rpc.ankr.com/iotex) - [https://iotexrpc.com](https://iotexrpc.com) **Spin up your own node:** - [https://github.com/iotexproject/iotex-bootstrap](https://github.com/iotexproject/iotex-bootstrap) ## Gnosis (xDAI) **Providers:** 1. ANKR - [https://ankr.com](https://ankr.com) 2. GetBlock - [https://getblock.io](https://getblock.io) 3. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 4. Blast - [https://blastapi.io/](https://blastapi.io/) 5. Chainstack - [https://chainstack.com/build-better-with-gnosis-chain/](https://chainstack.com/build-better-with-gnosis-chain/) 6. OnFinality.io - [https://onfinality.io](https://onfinality.io) **Public Endpoints:** - [https://rpc.gnosischain.com](https://rpc.gnosischain.com) - [https://rpc.xdaichain.com](https://rpc.xdaichain.com) - [https://xdai-rpc.gateway.pokt.network](https://xdai-rpc.gateway.pokt.network) - [https://gnosis.public-rpc.com](https://gnosis.public-rpc.com) - [https://blastapi.io/public-api/gnosis](https://blastapi.io/public-api/gnosis) - [https://gnosis.api.onfinality.io/public](https://gnosis.api.onfinality.io/public) **WebSocket:** - `wss://rpc.gnosischain.com/wss` **Spin up your own node:** - [https://docs.gnosischain.com/validator-info/get-started-node-setup](https://docs.gnosischain.com/validator-info/get-started-node-setup) ## Fuse **Providers:** 1. GetBlock - [https://getblock.io/nodes/fuse/](https://getblock.io/nodes/fuse/) 2. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 3. Chainstack - [https://chainstack.com/build-better-with-fuse/](https://chainstack.com/build-better-with-fuse/) **Public Endpoints:** - [https://fuse-rpc.gateway.pokt.network/](https://fuse-rpc.gateway.pokt.network/) - [https://fuse-mainnet.chainstacklabs.com/](https://fuse-mainnet.chainstacklabs.com/) *WebSocket:* - [wss://ws-fuse-mainnet.chainstacklabs.com/](wss://ws-fuse-mainnet.chainstacklabs.com/) **Spin up your own node:** - [https://docs.fuse.io/general-1/how-to-run-network-nodes](https://docs.fuse.io/general-1/how-to-run-network-nodes) ## Optimism **Providers:** 1. GetBlock - [https://getblock.io/nodes/op/](https://getblock.io/nodes/op/) 2. Infura - [https://infura.io](https://infura.io) 3. Ankr - [https://ankr.com](https://ankr.com) 4. Blast - [https://blastapi.io/](https://blastapi.io/) 5. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) 6. Chainbase - [https://chainbase.online](https://chainbase.online) 7. Alchemy - [https://alchemy.com](https://docs.alchemy.com/reference/optimism-api-quickstart) 8. Chainnodes - [https://www.chainnodes.org/](https://www.chainnodes.org/) 9. OnFinality.io - [https://onfinality.io](https://onfinality.io) **Public Endpoints:** - [https://mainnet.optimism.io/](https://mainnet.optimism.io//) - [https://blastapi.io/public-api/optimism](https://blastapi.io/public-api/optimism) - [https://optimism.api.onfinality.io/public](https://optimism.api.onfinality.io/public) ## Arbitrum One **Providers:** 1. GetBlock - [https://getblock.io/nodes/arbitrum/](https://getblock.io/nodes/arbitrum/) 2. Infura - [https://infura.io](https://infura.io) 3. Alchemy - [https://www.alchemy.com](https://docs.alchemy.com/reference/arbitrum-api-quickstart) 4. ANKR - [https://ankr.com](https://ankr.com) 5. Datahub - [https://datahub.figment.io/](https://datahub.figment.io/) 6. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) 7. Chainstack - [https://chainstack.com/build-better-with-arbitrum/](https://chainstack.com/build-better-with-arbitrum/) 8. Chainbase - [https://chainbase.online](https://chainbase.online) 9. Chainnodes - [https://www.chainnodes.org/](https://www.chainnodes.org/) 10. OnFinality.io - [https://onfinality.io](https://onfinality.io) **Public Endpoints:** - [https://arb1.arbitrum.io/rpc](https://arb1.arbitrum.io/rpc) - [https://rpc.ankr.com/arbitrum](https://rpc.ankr.com/arbitrum) - [https://arbitrum.public-rpc.com](https://arbitrum.public-rpc.com) - [https://arbitrum.api.onfinality.io/public](https://arbitrum.api.onfinality.io/public) ## Arbitrum Nova 1. GetBlock - [https://getblock.io](https://getblock.io) **Public Endpoints:** - [https://nova.arbitrum.io/rpc](https://nova.arbitrum.io/rpc) ## Celo **Providers:** 1. GetBlock - [https://getblock.io/nodes/celo/](https://getblock.io/nodes/celo/) 2. ANKR - [https://ankr.com](https://ankr.com) 3. Datahub - [https://datahub.figment.io/](https://datahub.figment.io/) **Public Endpoints:** - [https://forno.celo.org](https://forno.celo.org) - [https://rpc.ankr.com/celo](https://rpc.ankr.com/celo) **Spin up your own node:** - [https://docs.celo.org/getting-started/mainnet/running-a-full-node-in-mainnet](https://docs.celo.org/getting-started/mainnet/running-a-full-node-in-mainnet) ## Near **Providers:** 1. ANKR - [https://ankr.com](https://ankr.com) 2. Infura - [https://infura.io](https://infura.io) 3. GetBlock - [https://getblock.io/nodes/near/](https://getblock.io/nodes/near/) 4. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) 5. Datahub - [https://datahub.figment.io/](https://datahub.figment.io/) 6. Chainstack - [https://chainstack.com/build-better-with-near/](https://chainstack.com/build-better-with-near/) **Public Endpoints:** - [https://rpc.ankr.com/near](https://rpc.ankr.com/near) - [https://near.public-rpc.com](https://near.public-rpc.com) **Spin up your own node:** - [https://near-nodes.io/rpc/hardware-rpc#recommended-hardware-specifications](https://near-nodes.io/rpc/hardware-rpc#recommended-hardware-specifications) ## Cosmos **Providers** 1. GetBlock - [https://getblock.io/nodes/atom/](https://getblock.io/nodes/atom/) 2. OnFinality.io - [https://onfinality.io](https://onfinality.io) **Public Endpoints:** - [https://juno.api.onfinality.io/public](https://juno.api.onfinality.io/public) ## Aurora **Providers:** 1. Infura - [https://infura.io](https://infura.io) **Public Endpoints:** - [https://mainnet.aurora.dev](https://mainnet.aurora.dev) **Spin up your own node:** - [https://doc.aurora.dev/#running-your-own-aurora-node](https://doc.aurora.dev/#running-your-own-aurora-node) ## TomoChain **Providers:** 1. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) **Public Endpoints:** - [https://rpc.tomochain.com](https://rpc.tomochain.com) **Websocket:** - `wss://ws.tomochain.com` **Spin up your own node:** - [https://docs.tomochain.com/masternode-and-dex/masternode](https://docs.tomochain.com/masternode-and-dex/masternode) ## Polkadot **Providers:** 1. GetBlock - [https://getblock.io/nodes/dot/](https://getblock.io/nodes/dot/) 2. OnFinality - [https://www.onfinality.io](https://www.onfinality.io) 3. NOWNodes.io - [https://nownodes.io/](https://nownodes.io/) **Public Endpoints:** - [https://polkadot.api.onfinality.io/public](https://polkadot.api.onfinality.io/public) **WebSocket:** - `wss://polkadot.api.onfinality.io/public-ws` ## Moonbeam **Providers:** 1. GetBlock - [https://getblock.io/nodes/glmr/](https://getblock.io/nodes/glmr/) 2. Blast - [https://blastapi.io/](https://blastapi.io/) 3. OnFinality - [https://www.onfinality.io](https://www.onfinality.io) 4. Dwellir - [https://dwellir.com](https://dwellir.com) **Public Endpoints:** - [https://rpc.api.moonbeam.network]([https://rpc.api.moonriver.moonbeam.network](https://rpc.api.moonbeam.network)) - [https://moonbeam.public.blastapi.io](https://moonbeam.public.blastapi.io) - [https://moonbeam.api.onfinality.io/public](https://moonbeam.api.onfinality.io/public) **Spin up your own node:** - [https://docs.moonbeam.network/node-operators/networks/run-a-node/](https://docs.moonbeam.network/node-operators/networks/run-a-node/) ## Moonriver **Providers:** 1. GetBlock - [https://getblock.io/nodes/movr/](https://getblock.io/nodes/movr/) 2. Blast - [https://blastapi.io/](https://blastapi.io/) 3. OnFinality - [https://www.onfinality.io](https://www.onfinality.io) 4. Dwellir - [https://dwellir.com](https://dwellir.com) **Public Endpoints:** - [https://rpc.api.moonriver.moonbeam.network](https://rpc.api.moonriver.moonbeam.network) - [https://blastapi.io/public-api/moonriver](https://blastapi.io/public-api/moonriver) - [https://moonriver.api.onfinality.io/public](https://polkadot.api.onfinality.io/public) **Websocket:** - `wss://moonbeam.public.blastapi.io` - `wss://moonbeam-rpc.dwellir.com` - wss://moonriver.getblock.io/api_key/mainnet/ - `wss://moonbeam.api.onfinality.io/public-ws` **Spin up your own node:** - [https://docs.moonbeam.network/node-operators/networks/run-a-node/](https://docs.moonbeam.network/node-operators/networks/run-a-node/) ## Boba Network **Providers:** 1. Pocket Network - [https://mainnet.portal.pokt.network](https://mainnet.portal.pokt.network) **Public Endpoints:** - [https://boba-mainnet.gateway.pokt.network/v1/lb/6258298b981a0200395864f0 ](https://boba-mainnet.gateway.pokt.network/v1/lb/6258298b981a0200395864f0) **Spin up your own node:** - [https://boba.network/start-here/#8](https://boba.network/start-here/#8) ## Astar **Providers:** 1. Blast - [https://blastapi.io/](https://blastapi.io/) 2. OnFinality - [https://www.onfinality.io](https://www.onfinality.io) 3. Alchemy - [https://alchemy.com](https://docs.alchemy.com/reference/astar-api-quickstart) **Public Endpoints:** - [https://evm.astar.network](https://evm.astar.network) - [https://astar.api.onfinality.io/public](https://astar.api.onfinality.io/public) - [https://evm.astar.network](https://evm.astar.network) **Spin up your own node:** - [https://docs.astar.network/maintain/archive-node/docker#running-rpc-node](https://docs.astar.network/maintain/archive-node/docker#running-rpc-node) ## Flow **Providers:** 1. GetBlock - [https://getblock.io/nodes/flow/](https://getblock.io/nodes/flow/) **Public Endpoints:** - [https://developers.flow.com/nodes/access-api](https://developers.flow.com/nodes/access-api) - [https://developers.flow.com/http-api/](https://developers.flow.com/http-api/) **Spin up your own node:** - [Run a Flow node](https://developers.flow.com/nodes/node-operation) ## Donate Your donation will help us move forward with our project and make sure that it can benefit the entire community. Address: `0x99ac38dA3298fA7B0B8cB42a2aE9F1a8C74D98ea` ## Contributors <a href="https://github.com/arddluma/awesome-list-rpc-nodes-providers/graphs/contributors"> <img src="https://contrib.rocks/image?repo=arddluma/awesome-list-rpc-nodes-providers" /> </a>
prasad-kumkar_cypher-kidz-client
.eslintrc.js README.md contracts Cargo.toml README.md build.sh src lib.rs package.json server app.js middleware near.js package.json utils near-utils.js src App.js components Contract.js Gallery.js Keys.js Wallet.js config.js fonts SIL Open Font License.txt img ethkats.svg index.html index.js state app.js near.js utils near-utils.js state.js storage.js test app.test.js near-utils.js server.test.js test-utils.js utils patch-config.js
# Live App Review 6 - Progressive Onboarding This repo is a companion to the "NFT Example Progressive Onboarding" video series: [![Live App Review 6 - NFT Example - Part 1 Contract](https://img.youtube.com/vi/Y-HYCcYVmz8/0.jpg)](https://youtu.be/Y-HYCcYVmz8) [![Live App Review 6 - NFT Example - Part 2 App Demo and Tests](https://img.youtube.com/vi/W29QmxiJh84/0.jpg)](https://youtu.be/W29QmxiJh84) [![Live App Review 6 - NFT Example - Part 3 Frontend](https://img.youtube.com/vi/8kbxBqDSe_A/0.jpg)](https://youtu.be/8kbxBqDSe_A) # Notes on this Example This example is not an NFT Standard and should be considered "experimental". However, it does work and is deployable to testnet. Prior to deploying to mainnet, please join our [Discord](https://near.chat) and check with NEAR **#dev-support** if there are any security concerns. ## Quickstart ```js yarn // see installation notes for Rust yarn test:unit // 1 test will fail due to bug in mocked blockchain yarn test:deploy // runs /test/app.test.js (all passing) yarn start ``` WIP Server Tests incomplete e.g. `yarn test:server` will not work. Despite server tests being incomplete, you still need to run the server (see notes below) `yarn && yarn start`. After running `yarn start` you'll have an app running (localhost:1234). The app has 2 types of logins for the user. 1. Connect Wallet 2. Sign In As Guest Connect Wallet is a standard NEAR App flow (think allow this app to view my account from MetaMask). Sign In As Guest creates a temporary keypair on the dev account where the contract is deployed. This gives the guest 3 free mints. When a guest mints, the owner_id of the TokenData is going to be the implicit account of the guest. See video "Part 1 Contract" for a detailed explanation of this. The guest can earn NEAR tokens from sales (other users with NEAR purchase their artwork) and then decide how to use their sale proceeds. Typically they will fund an account. ## NEAR Wallet Testnet has no "Funding Account Flow" In the video "Part 2 App and Testing" I am running the NEAR Wallet on localhost. On testnet NEAR Wallet funds accounts on behalf of users and developers to make the experience easy. If you'd like to test the funding account flow yourself, clone the [NEAR Wallet](https://github.com/near/near-wallet) and run it with a `.env` file in the root with the following entry `DISABLE_CREATE_ACCOUNT=true`. ## Installation Beyond having npm and node (latest versions), you should have Rust installed. I recommend nightly because living on the edge is fun. https://rustup.rs/ Also recommend installing near-cli globally `npm i -g near-cli` Everything else can be installed via: `yarn` `cd server && yarn` ## NEAR Config There is only one config.js file found in `src/config.js`, this is also used for running tests. Using `src/config.js` you can set up your different environments. Use `REACT_APP_ENV` to switch environments e.g. in `package.json` script `deploy`. ## Running Tests You can run unit tests in the Rust contracts themselves, but it may be more useful to JS tests against testnet itself. Note: to run the app and server tests make sure you install and start the server. - cd server - yarn && yarn start Commands: - `test` will simply run app tests against the contract already deployed. You can mess around with `app.test.js` and try different frontend stuff - `test:deploy` - will deploy a new dev account (`/neardev`) and deploy a new contract to this account, then run `test` - `test:server` - will test the server, make sure you start it (see "Note" above) - `test:unit` - runs the rust unit tests If you've changed your contract or your dev account has run out of funds use `test:deploy`, if you're updating your JS tests only then use `test`. ## Test Utils There are helpers in `test/test-utils.js` that take care of: 1. creating a near connection and establishing a keystore for the dev account 2. creating test accounts each time a test is run 3. establishing a contract instance so you can call methods You can change the default funding amount for test accounts in `src/config.js` ## Using the NEAR Config in your app In `src/state/near.js` you will see that `src/config.js` is loaded as a function. This is to satisfy the jest/node test runner. You can destructure any properies of the config easily in any module you import it in like this: ``` // example file app.js import getConfig from '../config'; export const { GAS, networkId, nodeUrl, walletUrl, nameSuffix, contractName, } = getConfig(); ``` Note the export const in the destructuring? Now you can import these like so: ``` //example file Component.js import { GAS } from '../app.js' ... await contract.withdraw({ amount: parseNearAmount('1') }, GAS) ... ``` # Notes on React 17, Parcel with useContext and useReducer - Bundled with Parcel 2.0 (@next) && eslint - *Minimal all-in-one state management with async/await support* ## Getting Started: State Store & useContext >The following steps describe how to use `src/utils/state` to create and use your own `store` and `StateProvider`. 1. Create a file e.g. `/state/app.js` and add the following code ```js import { State } from '../utils/state'; // example const initialState = { app: { mounted: false } }; export const { store, Provider } = State(initialState); ``` 2. Now in your `index.js` wrap your `App` component with the `StateProvider` ```js import { Provider } from './state/app'; ReactDOM.render( <Provider> <App /> </Provider>, document.getElementById('root') ); ``` 3. Finally in `App.js` you can `useContext(store)` ```js const { state, dispatch, update } = useContext(store); ``` ## Usage in Components ### Print out state values ```js <p>Hello {state.foo && state.foo.bar.hello}</p> ``` ### Update state directly in component functions ```js const handleClick = () => { update('clicked', !state.clicked); }; ``` ### Dispatch a state update function (action listener) ```js const onMount = () => { dispatch(onAppMount('world')); }; useEffect(onMount, []); ``` ## Dispatched Functions with context (update, getState, dispatch) When a function is called using dispatch, it expects arguments passed in to the outer function and the inner function returned to be async with the following json args: `{ update, getState, dispatch }` Example of a call: ```js dispatch(onAppMount('world')); ``` All dispatched methods **and** update calls are async and can be awaited. It also doesn't matter what file/module the functions are in, since the json args provide all the context needed for updates to state. For example: ```js import { helloWorld } from './hello'; export const onAppMount = (message) => async ({ update, getState, dispatch }) => { update('app', { mounted: true }); update('clicked', false); update('data', { mounted: true }); await update('', { data: { mounted: false } }); console.log('getState', getState()); update('foo.bar', { hello: true }); update('foo.bar', { hello: false, goodbye: true }); update('foo', { bar: { hello: true, goodbye: false } }); update('foo.bar.goodbye', true); await new Promise((resolve) => setTimeout(() => { console.log('getState', getState()); resolve(); }, 2000)); dispatch(helloWorld(message)); }; ``` ## Prefixing store and Provider The default names the `State` factory method returns are `store` and `Provider`. However, if you want multiple stores and provider contexts you can pass an additional `prefix` argument to disambiguate. ```js export const { appStore, AppProvider } = State(initialState, 'app'); ``` ## Performance and memo The updating of a single store, even several levels down, is quite quick. If you're worried about components re-rendering, use `memo`: ```js import React, { memo } from 'react'; const HelloMessage = memo(({ message }) => { console.log('rendered message'); return <p>Hello { message }</p>; }); export default HelloMessage; ``` Higher up the component hierarchy you might have: ```js const App = () => { const { state, dispatch, update } = useContext(appStore); ... const handleClick = () => { update('clicked', !state.clicked); }; return ( <div className="root"> <HelloMessage message={state.foo && state.foo.bar.hello} /> <p>clicked: {JSON.stringify(state.clicked)}</p> <button onClick={handleClick}>Click Me</button> </div> ); }; ``` When the button is clicked, the component HelloMessage will not re-render, it's value has been memoized (cached). Using this method you can easily prevent performance intensive state updates in further down components until they are neccessary. Reference: - https://reactjs.org/docs/context.html - https://dmitripavlutin.com/use-react-memo-wisely/ Minimal NEP#4 Implementation ============================ This contract implements bare-minimum functionality to satisfy the [NEP#4](https://github.com/nearprotocol/NEPs/pull/4) specification Notable limitations of this implementation ========================================== * Only the token owner can mint tokens. * You cannot give another account escrow access to a limited set of your tokens; an escrow must be trusted with all of your tokens or none at all * No functions to return the maximum or current supply of tokens * No functions to return metadata such as the name or symbol of this NFT * No functions (or storage primitives) to find all tokens belonging to a given account * Usability issues: some functions (e.g. `revoke_access`, `transfer`, `get_token_owner`) do not verify that they were given sensible inputs; if given non-existent keys, the errors they throw will not be very useful Still, if you track some of this information in an off-chain database, these limitations may be acceptable for your needs. In that case, this implementation may help reduce gas and storage costs. Notable additions that go beyond the specification of NEP#4 =========================================================== `mint_token`: the spec gives no guidance or requirements on how tokens are minted/created/assigned. This specific implementation only allows the contract owner to mint new tokens. If this implementation of `mint_token` is close to matching your needs, feel free to ship your NFT with only minor modifications. If you'd rather go with a strategy such as minting the whole supply of tokens upon deploy of the contract, or something else entirely, you may want to drastically change this behavior.
gadillacer_babylon-exchange-interface
.env .eslintrc.json .postcssrc.json README.md babel-plugin-macros.config.js instructions.txt package.json public 451.html favicon.svg index.html manifest.json src assets images arrow-down-blue.svg arrow-down-grey.svg arrow-right.svg blue-loader.svg circle-grey.svg circle.svg coinbaseWalletIcon.svg dropdown-blue.svg dropdown.svg dropup-blue.svg link.svg magnifying-glass.svg menu.svg plus-blue.svg plus-grey.svg question-mark.svg question.svg spinner.svg x.svg svg QR.svg arbitrum_logo.svg discord-logo.svg lightcircle.svg logo.svg logo_pink.svg logo_white.svg optimism_logo.svg switch.svg tokenlist.svg wordmark.svg wordmark_pink.svg wordmark_white.svg components LiquidityChartRangeInput hooks.ts types.ts SearchModal filtering.ts sorting.ts swap confirmPriceImpactWithoutFee.ts constants addresses.ts chains.ts cyclos-core.json lists.ts locales.ts misc.ts proposals index.ts uniswap_grants_proposal_description.ts rewards.json routing.ts tokens.ts contexts modal-ui components Modal.types.ts styles.css index.ts modal.types.ts walletIcons.ts global.css hooks Tokens.ts useActiveLocale.ts useAllCurrencyCombinations.ts useAllV3Routes.ts useApeModeQueryParamReader.ts useBestV3Trade.ts useColor.ts useContract.ts useCopyClipboard.ts useCurrentBlockTimestamp.ts useDebounce.ts useDerivedPositionInfo.ts useFeeTierDistribution.ts useHttpLocations.ts useInterval.ts useIsWindowVisible.ts useLast.ts useParsedQueryString.ts usePoolTickData.ts usePools.ts usePositionTokenURI.ts usePrevious.ts useSwapCallback.ts useSwapSlippageTolerance.ts useTheme.ts useToggle.ts useTransactionDeadline.ts useUSDTPrice.ts useV3PositionFees.ts useV3Positions.ts useV3SwapPools.ts useVerifyATA.ts useWindowSize.ts web3.ts pages RemoveLiquidity styled.ts Swap swap-near.js react-app-env.d.ts service-worker.ts serviceWorkerRegistration.ts services SpecialWallet.ts account.ts api.ts config.ts creators storage.ts token.ts ft-contract.ts indexer.ts near.ts parallelSwapLogic.ts pool.ts smartRouteLogic.js swap.ts token.ts transaction.ts wrap-near.ts state application actions.ts hooks.ts reducer.test.ts reducer.ts updater.ts burn v3 actions.ts hooks.ts reducer.ts global actions.ts hooks.ts index.ts lists wrappedTokenInfo.ts logs hooks.ts slice.ts updater.ts utils.ts mint v3 actions.ts hooks.ts reducer.ts utils.ts multicall actions.test.ts actions.ts hooks.ts reducer.test.ts reducer.ts updater.test.ts utils.ts pool.ts swap.ts swap actions.ts hooks.test.ts hooks.ts reducer.test.ts reducer.ts token.ts transactions actions.ts reducer.test.ts reducer.ts updater.test.ts user actions.ts reducer.test.ts reducer.ts wallet hooks.ts store BabyDatabase.ts theme styled.d.ts types cyclos-core.ts position.d.ts utils anonymizeLink.test.ts anonymizeLink.ts calculateSlippageAmount.test.ts calculateSlippageAmount.ts chunkArray.test.ts chunkArray.ts computeSurroundingTicks.ts constructSameAddressMap.ts currencyId.ts device.ts formatCurrencyAmount.ts getExplorerLink.ts getTickToPrice.ts getUserAgent.ts index.ts isZero.ts maxAmountSpend.ts metadata.ts numbers.ts pool.ts prices.test.ts prices.ts retry.test.ts retry.ts supportedChainId.ts token.ts unwrappedToken.ts uriToHttp.test.ts uriToHttp.ts wallets-integration.ts tailwind.config.js tsconfig.json
# Babylon interface Concentrated AMM UI on Near Blockchain Comming soon! ## Developed by yoshitoke
near_learn
.github ISSUE_TEMPLATE BOUNTY.yml README.md
# LEARN.NEAR HOME - Learn and Earn about NEAR, building on NEAR and building NEAR ## Objective: **At LEARN.NEAR we want to onboard to NEAR Users and Devs so they can use and build meaningful applications and improve NEAR itself as Measured by:** TBD - Developer on-boarding time - https://explorer.near.org/stats - https://explorer.testnet.near.org/stats - MAU - Contracts deployed Testnet/MainNet ## Tools: - Internal Communication: #learn-near Discord channel - External communication: TBD - Outbound Communication: Discourse - Project Board: GitHub project - https://github.com/near/learn/projects/1 - Curriculum drafts/content: Google Docs - Meetings: Google Calendar/Zoom ## Collective (alphabetical order): - Erik Trautman - Evgeny Kuzyakov - Mike Purvis - Robert Yan - Sasha Baksht - Sherif Abushadi
esaminu_test-rs-boilerplate-3
.eslintrc.yml .github ISSUE_TEMPLATE 01_BUG_REPORT.md 02_FEATURE_REQUEST.md 03_CODEBASE_IMPROVEMENT.md 04_SUPPORT_QUESTION.md config.yml PULL_REQUEST_TEMPLATE.md labels.yml workflows codeql.yml deploy-to-console.yml labels.yml lock.yml pr-labels.yml stale.yml .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh src lib.rs docs CODE_OF_CONDUCT.md CONTRIBUTING.md SECURITY.md frontend App.js assets global.css logo-black.svg logo-white.svg index.html index.js near-interface.js near-wallet.js package.json start.sh ui-components.js integration-tests Cargo.toml src tests.rs package.json
<h1 align="center"> <a href="https://github.com/near/boilerplate-template-rs"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/near/boilerplate-template-rs/main/docs/images/pagoda_logo_light.png"> <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/near/boilerplate-template-rs/main/docs/images/pagoda_logo_dark.png"> <img alt="" src="https://raw.githubusercontent.com/near/boilerplate-template-rs/main/docs/images/pagoda_logo_dark.png"> </picture> </a> </h1> <div align="center"> Rust Boilerplate Template <br /> <br /> <a href="https://github.com/near/boilerplate-template-rs/issues/new?assignees=&labels=bug&template=01_BUG_REPORT.md&title=bug%3A+">Report a Bug</a> · <a href="https://github.com/near/boilerplate-template-rs/issues/new?assignees=&labels=enhancement&template=02_FEATURE_REQUEST.md&title=feat%3A+">Request a Feature</a> . <a href="https://github.com/near/boilerplate-template-rs/issues/new?assignees=&labels=question&template=04_SUPPORT_QUESTION.md&title=support%3A+">Ask a Question</a> </div> <div align="center"> <br /> [![Pull Requests welcome](https://img.shields.io/badge/PRs-welcome-ff69b4.svg?style=flat-square)](https://github.com/near/boilerplate-template-rs/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) [![code with love by near](https://img.shields.io/badge/%3C%2F%3E%20with%20%E2%99%A5%20by-near-ff1414.svg?style=flat-square)](https://github.com/near) </div> <details open="open"> <summary>Table of Contents</summary> - [About](#about) - [Built With](#built-with) - [Getting Started](#getting-started) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Usage](#usage) - [Roadmap](#roadmap) - [Support](#support) - [Project assistance](#project-assistance) - [Contributing](#contributing) - [Authors & contributors](#authors--contributors) - [Security](#security) </details> --- ## About This project is created for easy-to-start as a React + Rust skeleton template in the Pagoda Gallery. It was initialized with [create-near-app]. Clone it and start to build your own gallery project! ### Built With [create-near-app], [amazing-github-template](https://github.com/dec0dOS/amazing-github-template) Getting Started ================== ### Prerequisites Make sure you have a [current version of Node.js](https://nodejs.org/en/about/releases/) installed – we are targeting versions `16+`. Read about other [prerequisites](https://docs.near.org/develop/prerequisites) in our docs. ### Installation Install all dependencies: npm install Build your contract: npm run build Deploy your contract to TestNet with a temporary dev account: npm run deploy Usage ===== Test your contract: npm test Start your frontend: npm start Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages ## Roadmap See the [open issues](https://github.com/near/boilerplate-template-rs/issues) for a list of proposed features (and known issues). - [Top Feature Requests](https://github.com/near/boilerplate-template-rs/issues?q=label%3Aenhancement+is%3Aopen+sort%3Areactions-%2B1-desc) (Add your votes using the 👍 reaction) - [Top Bugs](https://github.com/near/boilerplate-template-rs/issues?q=is%3Aissue+is%3Aopen+label%3Abug+sort%3Areactions-%2B1-desc) (Add your votes using the 👍 reaction) - [Newest Bugs](https://github.com/near/boilerplate-template-rs/issues?q=is%3Aopen+is%3Aissue+label%3Abug) ## Support Reach out to the maintainer: - [GitHub issues](https://github.com/near/boilerplate-template-rs/issues/new?assignees=&labels=question&template=04_SUPPORT_QUESTION.md&title=support%3A+) ## Project assistance If you want to say **thank you** or/and support active development of Rust Boilerplate Template: - Add a [GitHub Star](https://github.com/near/boilerplate-template-rs) to the project. - Tweet about the Rust Boilerplate Template. - Write interesting articles about the project on [Dev.to](https://dev.to/), [Medium](https://medium.com/) or your personal blog. Together, we can make Rust Boilerplate Template **better**! ## Contributing First off, thanks for taking the time to contribute! Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make will benefit everybody else and are **greatly appreciated**. Please read [our contribution guidelines](docs/CONTRIBUTING.md), and thank you for being involved! ## Authors & contributors The original setup of this repository is by [Dmitriy Sheleg](https://github.com/shelegdmitriy). For a full list of all authors and contributors, see [the contributors page](https://github.com/near/boilerplate-template-rs/contributors). ## Security Rust Boilerplate Template follows good practices of security, but 100% security cannot be assured. Rust Boilerplate Template is provided **"as is"** without any **warranty**. Use at your own risk. _For more information and to report security issues, please refer to our [security documentation](docs/SECURITY.md)._ # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`.
mikedotexe_password-wallet
config.js dist index.html new-account.25b41eab.js new-account.2bbcefac.js new-account.3719758e.js new-account.3dd8587a.js new-account.3eda7a17.js new-account.45c50be9.js new-account.5adb25d4.js new-account.5fea3b4e.js new-account.69123698.js new-account.6f0d5dac.js new-account.7237bf04.js new-account.822344fb.js new-account.94125636.js new-account.98b845e2.js new-account.9cef133a.js new-account.a2ef444c.js new-account.a7cac32e.js new-account.a8c16e3c.js new-account.b3020dc8.js new-account.bb119dc8.js new-account.beb8f78c.js new-account.cfcf15bc.js new-account.d1e599bd.js new-account.e3bf720a.js new-account.ee3e5e4d.js new-account.ef4320fe.js new-account.f3f465c4.js new-account.fe1de237.js new-account.html plain-new-account.html script.75da7f30.js script.9a4b68ad.js style.c404bdcb.css style.e308ff8e.css style.e308ff8e.js index.html new-account.html new-account.js package-lock.json package.json plain-new-account.html script.js style.css
near-hackathon-luciferius_challenge-6-ukraine-nft
.cargo config.toml .github workflows node.js.yml .parcel-cache 33ea92a96b06453d.txt Cargo.toml README.md build.bat build.sh contract Cargo.toml README.md build.bat build.sh src lib.rs test.sh dist App.03fbd8d8.css App.03fbd8d8.js index.css index.html materialize.11fed4d9.css materialize.11fed4d9.js materialize.5467296b.js materialize.min.64694632.css materialize.min.64694632.js materialize.min.f120bc19.js src.e31bb0bc.css game_contract Cargo.toml README.md build.bat build.sh src lib.rs test.sh package.json public index.html manifest.json robots.txt publish.bat src App.css App.js config.js fonts OFL.txt README.txt index.html index.js layout.js test-mint.bat test-payout.bat
# Rust Smart Contract Template ## Getting started To get started with this template: 1. Click the "Use this template" button to create a new repo based on this template 2. Update line 2 of `Cargo.toml` with your project name 3. Update line 4 of `Cargo.toml` with your project author names 4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites) 5. Begin writing your smart contract in `src/lib.rs` 6. Test the contract `cargo test -- --nocapture` 8. Build the contract `RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release` **Get more info at:** * [Rust Smart Contract Quick Start](https://docs.near.org/docs/develop/contracts/rust/intro) * [Rust SDK Book](https://www.near-sdk.io/) # Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `env CONTRACT_NAME=kawaii-zoo.cryptosketches.testnet npm run start` Runs the app in the development mode.\ Open [http://localhost:1234](http://localhost:1234) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `yarn test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `yarn build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `yarn eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `yarn build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) # Rust Smart Contract Template ## Getting started To get started with this template: 1. Click the "Use this template" button to create a new repo based on this template 2. Update line 2 of `Cargo.toml` with your project name 3. Update line 4 of `Cargo.toml` with your project author names 4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites) 5. Begin writing your smart contract in `src/lib.rs` 6. Test the contract `cargo test -- --nocapture` 8. Build the contract `RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release` **Get more info at:** * [Rust Smart Contract Quick Start](https://docs.near.org/docs/develop/contracts/rust/intro) * [Rust SDK Book](https://www.near-sdk.io/)
kidrauhl14_NEP141_Factory
Cargo.toml README.md src lib.rs
# NEP141_Factory ## About NEP141_Factory NEP141_Factory allows you to mint standard NFT(Non-Fungible-Token) of [NEAR-Protocol](https://github.com/near/NEPs/blob/ea409f07f8/specs/Standards/NonFungibleToken/Core.md). ## Getting Started Clone this repository ```jsx git clone https://github.com/kidrauhl14/NEP141_Factory cd NEP141_Factory ``` Compile Contract code ```jsx cargo build --target wasm32-unknown-unknown --release ``` Login ```jsx near login ``` Deploy Contract ```jsx near deploy --wasmFile NEP141_Factory.wasm --accountId $ACCOUNTID ``` Init Contract ```jsx near call $ACCOUNTID new '{"owner_id": "$ACCOUNTID", "total_supply": "1000000000000000", "metadata": { "spec": "ft-1.0.0", "name": "$TOKEN_NAME", "symbol": "GGB", "decimals": 8 }}' --accountId $ACCOUNTID ``` Mint NFTs ```jsx near call YOUR_ACCOUNT nft_mint '{"token_id":"TOKEN_ID", "token_owner_id":"OWNER_ACCOUNT", "token_metadata":{"title":"TOKEN_TITLE", "media" : "YOUR_MEDIA" }}' --accountId YOUR_ACCOUNT --depositYocto 6380000000000000000000 ``` - [how to customize your metadata](https://github.com/near/NEPs/blob/ea409f07f8/specs/Standards/NonFungibleToken/Metadata.md#interface) - ``depositYocto`` can increase
PotLock_nadabot-docs
.github ISSUE_TEMPLATE BOUNTY.yml README.md SUMMARY.md extra devs-prod-staging-testnet.md future.md glossary.md our-contract.md guides for-admins.md for-applications.md for-bots.md for-sybil-providers.md for-users.md support.md
--- description: use nada.bot (the NEAR contract based bot protection protocol --- # 📍 Start Here [Nada.bot](http://nada.bot) is a NEAR Protocol-based smart contract based sybil resistance aggregator that safeguards web3 communities and applications from malicious actors. Try the [app here ](https://app.nada.bot) We are looking to create a trusted and inclusive web3 environment by eliminating sybil attacks and fostering genuine human interactions. ## Core Values * **Transparency**: all checks and decisions are made on chain * **Adaptability**: flexible scores and weights to prevent against sybil attacks * **Adoption / Integration**: become widely adopted and a resource to applications with a vibrant ecosystem * **Composability:** allow for other identity players to integrate and build with us easily and vice versa ## Stakeholders * **🙋🏽‍♂️ Users:** verify checks, confirm on nada.bot registry, earn points, get verified as human * **✅ Sybil providers:** add additional checks to get users to verify with you service * **📲 Applications / Protocols:** integrate our contract via cross contract call to enforce bot protection {% content-ref url="guides/for-users.md" %} [for-users.md](guides/for-users.md) {% endcontent-ref %} {% content-ref url="guides/for-sybil-providers.md" %} [for-sybil-providers.md](guides/for-sybil-providers.md) {% endcontent-ref %} {% content-ref url="guides/for-applications.md" %} [for-applications.md](guides/for-applications.md) {% endcontent-ref %} Extra Stakeholders * **👔 Admin** (in future DAO): approve checks, sets weights, flag weights, readjust human threshold * **🦹🏽 Developers / Bot Defense League:** get rewarded for developing tools to prevent and detect bots * **🤖 Bots:** get caught, displaced, incarcerated, torn away from their families and generationally disenfranchised&#x20; ## For Builders / Providers Want to integrate. in you application or get you stamp/check integrated into our registry?&#x20; {% content-ref url="guides/for-sybil-providers.md" %} [for-sybil-providers.md](guides/for-sybil-providers.md) {% endcontent-ref %} {% content-ref url="extra/our-contract.md" %} [our-contract.md](extra/our-contract.md) {% endcontent-ref %} {% content-ref url="guides/for-applications.md" %} [for-applications.md](guides/for-applications.md) {% endcontent-ref %} ## Case Studies Applications That Have Integrated nada.bot * [**Potlock**](https://potlock.org): public goods funding on NEAR, used for sybil protection for quadratic funding * [**Cplanet**](https://cplanet.org) Contests: art submission and funding platform, used to configure voting to delegate art contest for Sybil Providers that are part of registry * [I-AM-Human](https://i-am-human.app): aloow us to use liveness checks (face scans) via Fractal&#x20; * [Shard.dog](https://shard.dog): allow us to choose active users and provide bot protection service for claims {% content-ref url="extra/glossary.md" %} [glossary.md](extra/glossary.md) {% endcontent-ref %} ## Socials * Nada.bot Twitter [https://nada.bot/twitter](https://nada.bot/twitter) * Nada.bot Linkedin [https://nada.bot/linkedin](https://nada.bot/linkedin) * Nada.bot on PotLock: [https://nada.bot/potlock](https://nada.bot/potlock) * Nada.bot Support [https://nada.bot/support](https://nada.bot/support)
kidboy155_rust-counter-master
.github dependabot.yml scripts run_app.sh workflows readme-ci-.yml tests.yml .gitpod.yml .theia settings.json .travis.yml README-Gitpod.md README.md contract Cargo.toml src lib.rs frontend assets css global.css js main.js near config.js utils.js index.html integration-tests README.md rs Cargo.toml src tests.rs ts main.ava.ts neardev dev-account.env shared-test-staging test.near.json shared-test test.near.json package-lock.json package.json
Counter example in Rust ================================= [![Open in Gitpod!](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near-examples/rust-counter) <!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page --> ## Description This contract implements simple counter backed by storage on blockchain. Contract in `contract/src/lib.rs` provides methods to increment / decrement counter and get it's current value or reset. Plus and minus buttons increase and decrease value correspondingly. When button L is toggled, a little light turns on, just for fun. RS button is for reset. LE and RE buttons to let the robot wink at you. ## To Run Open in the Gitpod link above or clone the repository. ``` git clone https://github.com/near-examples/rust-counter ``` ## Setup [Or skip to Login if in Gitpod](#login) Install dependencies: ``` yarn ``` If you don't have `Rust` installed, complete the following 3 steps: 1) Install Rustup by running: ``` curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` ([Taken from official installation guide](https://www.rust-lang.org/tools/install)) 2) Configure your current shell by running: ``` source $HOME/.cargo/env ``` 3) Add wasm target to your toolchain by running: ``` rustup target add wasm32-unknown-unknown ``` Next, make sure you have `near-cli` by running: ``` near --version ``` If you need to install `near-cli`: ``` npm install near-cli -g ``` ## Login If you do not have a NEAR account, please create one with [NEAR Wallet](https://wallet.testnet.near.org). In the project root, login with `near-cli` by following the instructions after this command: ``` near login ``` Modify the top of `src/config.js`, changing the `CONTRACT_NAME` to be the NEAR account that was just used to log in. ```javascript … const CONTRACT_NAME = 'quocnv153251.testnet'; /* TODO: fill this in! */ … ``` Start the example! ``` yarn start ``` ## To Test ``` yarn test ``` ## To Explore - `contract/src/lib.rs` for the contract code - `src/index.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 ## To Build the Documentation ``` cd contract cargo doc --no-deps --open ```
Minting-Music_near-auth
.gitpod.yml README.md babel.config.js contract Cargo.toml README.md compile.js src lib.rs package.json src App.js GitHubLogin.js PopupWindow.js app-settings.js app.css assets logo-black.svg logo-white.svg config.js global.css index.html index.js jest.init.js main.test.js useDetectOutsideClick.js utils.js wallet login index.html
Meainnet: https://auth.nearspace.info Testnet: https://testnet.auth.nearspace.info near-auth ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-auth.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-auth.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-auth.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-auth.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages Near Auth Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/roles/developer/contracts/intro [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html
gencoglutugrul_near-protocol-challenge-with-rust
.gitpod.yml README.md contract Cargo.toml README.md compile.js src lib.rs init.sh package.json src assets logo-black.svg logo-white.svg config.js global.css index.html index.js main.test.js utils.js wallet login index.html
# near-protocol-challenge-with-rust Smart Contract A [smart contract] written in [Rust] for an app initialized with [create-near-app] # Quick Start Before you compile this code, you will need to install Rust with [correct target] # Exploring The Code 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html # near-protocol-challenge-with-rust This app was initialized with [create-near-app] # Quick Start To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. # Exploring The Code 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. # Deploy Every smart contract in NEAR has its [own associated account][near accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. ## Step 0: Install near-cli (optional) [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) ## Step 1: Create an account for the contract Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-protocol-challenge-with-rust.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-protocol-challenge-with-rust.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-protocol-challenge-with-rust.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet ## Step 2: set contract name in code Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-protocol-challenge-with-rust.YOUR-NAME.testnet' ## Step 3: deploy! One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. # Troubleshooting On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [near accounts]: https://docs.near.org/docs/concepts/account [near wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages
Mazout-Electric_Locus-QR-Payment
README.md mazout-main .eslintrc.json .github workflows main.yml README.md config constants.js supabase.js layer0.config.js layout LayoutWrapper.js Meta.js next.config.js package.json pages _app.js api hello.js home.js index.js postcss.config.js public Plug.svg capacity.svg charge.svg cycles.svg logo1.svg near.svg range.svg voltage.svg routes.js styles globals.css sw service-worker.js tailwind.config.js
Template Repo # Locus-QR-Payment This repository contains code to implement payment via NEAR tokens for EV charging. Demo video - https://youtu.be/anupSjCgYIM
GwangIl-Park_NEAR_Contract_Analyze
Advanced_Example factory-example README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src deploy.rs lib.rs manager.rs integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json multiple-cross-contract-calls README.md contract Cargo.toml README.md build.sh deploy.sh src batch_actions.rs lib.rs multiple_contracts.rs similar_contracts.rs integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json update-migrate-rust README.md contracts Cargo.toml basic-updates base Cargo.toml README.md src lib.rs update Cargo.toml README.md src lib.rs migrate.rs build.sh deploy.sh enum-updates base Cargo.toml README.md src lib.rs versioned_msg.rs update Cargo.toml README.md src lib.rs versioned_msg.rs neardev dev-account.env self-updates base Cargo.toml README.md src lib.rs update.rs update Cargo.toml README.md src lib.rs migrate.rs update.rs integration-tests package-lock.json package.json src enums.ava.ts main.ava.ts self.ava.ts package-lock.json package.json Basic_Example cross-contract-hello-rust README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src external.rs lib.rs integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json donation-rust README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src donation.rs lib.rs frontend assets global.css logo-black.svg logo-white.svg dist index.bc0daea6.css index.html logo-black.4514ed42.svg index.html index.js near-interface.js near-wallet.js package-lock.json package.json start.sh integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json guest-book-rust README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src lib.rs frontend .parcel-cache 95e4faa79ab2effb.txt App.js dist index.f9a43065.css index.html index.html index.js near-interface.js near-wallet.js package-lock.json package.json start.sh integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json hello-near .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src lib.rs frontend .parcel-cache 95e4faa79ab2effb.txt App.js assets global.css logo-black.svg logo-white.svg dist index.bc0daea6.css index.html logo-black.4514ed42.svg logo-white.a7716062.svg index.html index.js near-wallet.js package-lock.json package.json start.sh ui-components.js integration-tests Cargo.toml src tests.rs package-lock.json package.json rust-counter README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src lib.rs frontend .parcel-cache f6c2aacc42e8f766.txt assets global.css dist index.bc0daea6.css index.html index.html index.js near-wallet.js package-lock.json package.json start.sh integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json test .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh src lib.rs integration-tests Cargo.toml src tests.rs package-lock.json package.json NEPs nep_141 Cargo.toml src core.rs lib.rs macros.rs receiver.rs resolver.rs nep_145 Cargo.toml src lib.rs nep_148 Cargo.toml src lib.rs nep_171 .vscode settings.json Cargo.toml src core.rs lib.rs receiver.rs resolver.rs token.rs utils.rs nep_177 Cargo.toml src lib.rs nep_178 Cargo.toml src approval.rs approval_receiver.rs lib.rs nep_181 Cargo.toml src enumeration.rs lib.rs nep_199 Cargo.toml src lib.rs payout.rs nep_297 Cargo.toml src event.rs lib.rs nep_141.rs nep_171.rs Practice Signature EIP712 .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src lib.rs integration-tests Cargo.toml src tests.rs package-lock.json package.json src index.ts wallet.ts tsconfig.json personal_sign .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src lib.rs integration-tests Cargo.toml src tests.rs package-lock.json package.json src index.ts wallet.ts tsconfig.json Token .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env neardev_hello dev-account.env src hello Cargo.toml src lib.rs main Cargo.toml src lib.rs nft_main Cargo.toml src main.rs token Cargo.toml src event.rs fungible_token core.rs core_impl.rs events.rs macros.rs metadata.rs mod.rs receiver.rs resolver.rs storage_impl.rs lib.rs non_fungible_token core_impl.rs storage_management mod.rs integration-tests Cargo.toml src tests.rs package-lock.json package.json payload ft .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src core_impl.rs ft.rs lib.rs storage_impl.rs integration-tests Cargo.toml src tests.rs package-lock.json package.json nft .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env neardev_hello dev-account.env neardev_nft dev-account.env src approval_impl.rs core_impl.rs enumeration_impl.rs hello Cargo.toml src lib.rs lib.rs macros.rs royalty_impl.rs integration-tests Cargo.toml src tests.rs package-lock.json package.json
# Guest Book 📖 [![](https://img.shields.io/badge/⋈%20Examples-Basics-green)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Gitpod-Ready-orange)](https://gitpod.io/#/https://github.com/near-examples/guest-book-rust) [![](https://img.shields.io/badge/Contract-rust-red)](https://docs.near.org/develop/contracts/anatomy) [![](https://img.shields.io/badge/Frontend-React-blue)](https://docs.near.org/develop/integrate/frontend) [![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fnear-examples%2Fguest-book-rust%2Fbadge%3Fref%3Dmain&style=flat&label=Tests)](https://actions-badge.atrox.dev/near-examples/guest-book-rust/goto?ref=main) The Guest Book is a simple app that stores messages from users, allowing to pay for a premium message. ![](https://docs.near.org/assets/images/guest-book-b305a87a35cbef2b632ebe289d44f7b2.png) # What This Example Shows 1. How to receive $NEAR on a contract. 2. How to store and retrieve information from the blockchain. 3. How to use a `Vector`. 4. How to interact with a contract from `React JS`. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/guest_book-rust). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` ### 3. Deploy the Contract Build the contract and deploy it in a testnet account ```bash npm run deploy ``` ### 4. Start the Frontend Start the web application to interact with your smart contract ```bash npm start ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome). # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. # Donation 💸 [![](https://img.shields.io/badge/⋈%20Examples-Basics-green)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Gitpod-Ready-orange)](https://gitpod.io/#/https://github.com/near-examples/donation-rust) [![](https://img.shields.io/badge/Contract-rust-red)](https://docs.near.org/develop/contracts/anatomy) [![](https://img.shields.io/badge/Frontend-JS-yellow)](https://docs.near.org/develop/integrate/frontend) [![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fnear-examples%2Fdonation-rust%2Fbadge%3Fref%3Dmain&style=flat&label=Tests)](https://actions-badge.atrox.dev/near-examples/donation-rust/goto?ref=main) Our Donation example enables to forward money to an account while keeping track of it. It is one of the simplest examples on making a contract receive and send money. ![](https://docs.near.org/assets/images/donation-7cf65e5e131274fd1ae9aa34bc465bb8.png) # What This Example Shows 1. How to receive and transfer $NEAR on a contract. 2. How to divide a project into multiple modules. 3. How to handle the storage costs. 4. How to handle transaction results. 5. How to use a `Map`. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/donation-rust). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` ### 3. Deploy the Contract Build the contract and deploy it in a testnet account ```bash npm run deploy ``` ### 4. Start the Frontend Start the web application to interact with your smart contract ```bash npm start ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome). # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. # 📞 Cross-Contract Hello [![](https://img.shields.io/badge/⋈%20Examples-Basics-green)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Gitpod-Ready-orange)](https://gitpod.io/#/https://github.com/near-examples/xcc-rust) [![](https://img.shields.io/badge/Contract-rust-red)](https://docs.near.org/develop/contracts/anatomy) [![](https://img.shields.io/badge/Frontend-none-inactive)](#) [![](https://img.shields.io/badge/Testing-passing-green)](https://docs.near.org/develop/integrate/frontend) The smart contract implements the simplest form of cross-contract calls: it calls the [Hello NEAR example](https://docs.near.org/tutorials/examples/hello-near) to get and set a greeting. ![](https://docs.near.org/assets/images/hello-near-banner-af016d03e81a65653c9230b95a05fe4a.png) # What This Example Shows 1. How to query information from an external contract. 2. How to interact with an external contract. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/https://github.com/near-examples/xcc-rust). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` ### 3. Deploy the Contract Build the contract and deploy it in a testnet account ```bash npm run deploy ``` ### 4. Interact With the Contract Ask the contract to perform a cross-contract call to query or change the greeting in Hello NEAR. ```bash # Use near-cli to ask the contract to query te greeting near call <dev-account> query_greeting --accountId <dev-account> # Use near-cli to set increment the counter near call <dev-account> change_greeting '{"new_greeting":"XCC Hi"}' --accountId <dev-account> ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome). # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. # Factory Example This example presents a factory of [donation contracts](https://github.com/near-examples/donation-rust). It allows to: 1. Create a sub-account of the factory and deploy the stored contract on it (`create_factory_subaccount_and_deploy`). 2. Change the stored contract using the `update_stored_contract` method. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/multiple-cross-contract-calls). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome). # Guest Book Contract The [base](../base) contract was modified, removing the `payments` field and including that information in the `PostedMessage` structure. ```rust pub struct PostedMessage { pub payment: u128, pub premium: bool, pub sender: AccountId, pub text: String } pub struct GuestBook { messages: Vector<PostedMessage>, } ``` If we deploy this contract on top of the [base](../base/) one and call any method we will get the error: ``` panicked at 'Cannot deserialize the contract state.: ... }', ``` This is because the new contract expects to find `PostedMessages` with 4 fields (`payment`, `premium`, `sender`, `text`) but the saved messages only have 3 fields (they lack the `payment` field). In order to fix this problem we need to `migrate` the state, i.e. iterate through the current saved messages transforming them to the new version. ```rust #[private] #[init(ignore_state)] pub fn migrate() -> Self { let old_state: OldState = env::state_read().expect("failed"); let mut new_messages: Vector<PostedMessage> = Vector::new(b"p"); // iterate through the messages of the previous state for (idx, posted) in old_state.messages.iter().enumerate() { // get the payment using the message index let payment = old_state.payments.get(idx as u64).unwrap_or(0); // Create a PostedMessage with the new format and push it new_messages.push( &PostedMessage { payment, premium: posted.premium, sender: posted.sender, text: posted.text, } ) } // return the new state Self { messages: new_messages } } ``` <br /> # Upgrading Base Contract ## 1. Deploy & Migrate State You can deploy the updated contract by running: ```bash # deploy the updated contract near deploy <dev-account> --wasmFile target/wasm32-unknown-unknown/release/update.wasm # run this command to see the "Cannot deserialize..." error near view <dev-account> get_messages # Ask the contract to migrate the state near call <dev-account> migrate {} --accountId <dev-account> ``` #### Deploying and Migrating You can actually deploy the contract and migrate the state in one line: ```bash near deploy <dev-account> --wasmFile target/wasm32-unknown-unknown/release/update.wasm --initFunction migrate --initArgs {} ``` <br /> ## 2. Retrieve the Stored Messages `get_messages` will now return messages that include a `payment` field. ```bash near view <dev-account> get_messages ``` `get_payments` will raise an error since the method does not exist anymore. ```bash # raises an error since the method is gone near view <dev-account> get_payments ``` # Guest Book Contract - Versioned Messages The smart contract stores **versioned** messages. This simplifies further updates of the contract. ```rust // Versioned Messages pub struct PostedMessageV1 { pub premium: bool, pub sender: AccountId, pub text: String, } pub enum VersionedPostedMessage { V1(PostedMessageV1), } // Smart Contract pub struct GuestBook { messages: Vector<VersionedPostedMessage>, } pub fn add_message(&mut self, text: String) { let payment = env::attached_deposit(); let sender = env::predecessor_account_id(); let premium = payment > POINT_ONE; let message = VersionedPostedMessage::V1(PostedMessageV1 { sender, premium, text, }); self.messages.push(&message); } ``` <br /> # Quickstart ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash # build all examples, run from project-root/contracts ./build.sh # delete the project-root/contracts/neardev folder if present # rm -rf ./neardev # deploy enum base contract near dev-deploy --wasmFile target/wasm32-unknown-unknown/release/enums_base.wasm ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-X-Y ``` <br /> ## 2. Add a Message ```bash near call <dev-account> add_message '{"text": "a message"}' --amount 0.1 --accountId <account> ``` <br /> ## 3. Retrieve the Messages ```bash near view <dev-account> get_messages ``` <br /> ## 4. Continue in the Update Folder Navigate to the [update](../update/) folder to continue # Factory Contract A factory is a smart contract that stores a compiled contract on itself, and automatizes deploying it into sub-accounts. This particular example presents a factory of [donation contracts](https://github.com/near-examples/donation-rust), and enables to: 1. Create a sub-account of the factory and deploy the stored contract on it (`create_factory_subaccount_and_deploy`). 2. Change the stored contract using the `update_stored_contract` method. ```rust #[payable] pub fn create_factory_subaccount_and_deploy( &mut self, name: String, beneficiary: AccountId, ) -> Promise { let current_account = env::current_account_id().to_string(); let subaccount: AccountId = format!("{name}.{current_account}").parse().unwrap(); let init_args = near_sdk::serde_json::to_vec(&DonationInitArgs { beneficiary: beneficiary, }).unwrap(); Promise::new(subaccount.clone()) .create_account() .transfer(attached) .deploy_contract(self.code.clone()) .function_call("init".to_owned(), init_args, NO_DEPOSIT, TGAS * 5) .then( Self::ext(env::current_account_id()) .create_factory_subaccount_and_deploy_callback(subaccount, env::predecessor_account_id(), attached), ) } #[private] pub fn update_stored_contract(&mut self) { // This method receives the code to be stored in the contract directly // from the contract's input. In this way, it avoids the overhead of // deserializing parameters, which would consume a huge amount of GAS self.code = env::input().expect("Error: No input").to_vec(); } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Deploy the Stored Contract Into a Sub-Account `create_factory_subaccount_and_deploy` will create a sub-account of the factory and deploy the stored contract on it. ```bash near call <factory-account> create_factory_subaccount_and_deploy '{ "name": "sub", "beneficiary": "<account-to-be-beneficiary>"}' --deposit 1.24 --accountId <account-id> --gas 300000000000000 ``` This will create the `sub.<factory-account>`, which will have a `donation` contract deployed on it: ```bash near view sub.<factory-account> get_beneficiary # expected response is: <account-to-be-beneficiary> ``` <br /> ## 3. Update the Stored Contract `update_stored_contract` enables to change the compiled contract that the factory stores. The method is interesting because it has no declared parameters, and yet it takes an input: the new contract to store as a stream of bytes. To use it, we need to transform the contract we want to store into its `base64` representation, and pass the result as input to the method: ```bash # Use near-cli to update stored contract export BYTES=`cat ./src/to/new-contract/contract.wasm | base64` near call <factory-account> update_stored_contract "$BYTES" --base64 --accountId <factory-account> --gas 30000000000000 ``` > This works because the arguments of a call can be either a `JSON` object or a `String Buffer` <br> --- <br> ## Factories - Explanations & Limitations Factories are an interesting concept, here we further explain some of their implementation aspects, as well as their limitations. <br> ### Automatically Creating Accounts NEAR accounts can only create sub-accounts of itself, therefore, the `factory` can only create and deploy contracts on its own sub-accounts. This means that the factory: 1. **Can** create `sub.factory.testnet` and deploy a contract on it. 2. **Cannot** create sub-accounts of the `predecessor`. 3. **Can** create new accounts (e.g. `account.testnet`), but **cannot** deploy contracts on them. It is important to remember that, while `factory.testnet` can create `sub.factory.testnet`, it has no control over it after its creation. <br> ### The Update Method The `update_stored_contracts` has a very short implementation: ```rust #[private] pub fn update_stored_contract(&mut self) { self.code = env::input().expect("Error: No input").to_vec(); } ``` On first sight it looks like the method takes no input parameters, but we can see that its only line of code reads from `env::input()`. What is happening here is that `update_stored_contract` **bypasses** the step of **deserializing the input**. You could implement `update_stored_contract(&mut self, new_code: Vec<u8>)`, which takes the compiled code to store as a `Vec<u8>`, but that would trigger the contract to: 1. Deserialize the `new_code` variable from the input. 2. Sanitize it, making sure it is correctly built. When dealing with big streams of input data (as is the compiled `wasm` file to be stored), this process of deserializing/checking the input ends up **consuming the whole GAS** for the transaction. # Count on NEAR Contract The smart contract exposes methods to interact with a counter stored in the NEAR network. ```rust // Public read-only method: Returns the counter value. pub fn get_num(&self) -> i8 { return self.val; } // Public method: Increment the counter. pub fn increment(&mut self) { self.val += 1; log!("Increased number to {}", self.val); } // Public method: Decrement the counter. pub fn decrement(&mut self) { self.val -= 1; log!("Decreased number to {}", self.val); } // Public method - Reset to zero. pub fn reset(&mut self) { self.val = 0; log!("Reset counter to zero"); } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Get the Counter `get_num` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the counter value near view <dev-account> get_num ``` <br /> ## 3. Modify the Counter `increment`, `decrement` and `reset` change the contract's state, for which they are `call` methods. `Call` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set increment the counter near call <dev-account> increment --accountId <dev-account> ``` **Tip:** If you would like to call `increment` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. # Guest Book Contract The smart contract stores messages from users. Messages can be `premium` if the user attaches sufficient money (0.1 $NEAR). ```rust // Public - Adds a new message. #[payable] pub fn add_message(&mut self, text: String) { // If the user attaches more than 0.01N the message is premium let premium = env::attached_deposit() >= POINT_ONE; let sender = env::predecessor_account_id(); let message = PostedMessage{premium, sender, text}; self.messages.push(&message); } // Returns an array of messages. pub fn get_messages(&self, from_index:Option<U128>, limit:Option<u64>) -> Vec<PostedMessage>{ let from = u128::from(from_index.unwrap_or(U128(0))); self.messages.iter() .skip(from as usize) .take(limit.unwrap_or(10) as usize) .collect() } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Stored Messages `get_messages` is a read-only method (`view` method) that returns a slice of the vector `messages`. `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash near view <dev-account> get_messages '{"from_index":0, "limit":10}' ``` <br /> ## 3. Add a Message `add_message` adds a message to the vector of `messages` and marks it as premium if the user attached more than `0.1 NEAR`. `add_message` is a payable method for which can only be invoked using a NEAR account. The account needs to attach money and pay GAS for the transaction. ```bash # Use near-cli to donate 1 NEAR near call <dev-account> add_message '{"text": "a message"}' --amount 0.1 --accountId <account> ``` **Tip:** If you would like to add a message using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. # Donation Contract The smart contract exposes multiple methods to handle donating money to a `beneficiary` set on initialization. ```rust #[payable] // Public - People can attach money pub fn donate(&mut self) -> U128 { // Get who is calling the method // and how much $NEAR they attached let donor: AccountId = env::predecessor_account_id(); let donation_amount: Balance = env::attached_deposit(); let mut donated_so_far = self.donations.get(&donor).unwrap_or(0); let to_transfer: Balance = if donated_so_far == 0 { // Registering the user's first donation increases storage assert!(donation_amount > STORAGE_COST, "Attach at least {} yoctoNEAR", STORAGE_COST); // Subtract the storage cost to the amount to transfer donation_amount - STORAGE_COST }else{ donation_amount }; // Persist in storage the amount donated so far donated_so_far += donation_amount; self.donations.insert(&donor, &donated_so_far); log!("Thank you {} for donating {}! You donated a total of {}", donor.clone(), donation_amount, donated_so_far); // Send the money to the beneficiary Promise::new(self.beneficiary.clone()).transfer(to_transfer); // Return the total amount donated so far U128(donated_so_far) } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` The contract will be automatically initialized with a default `beneficiary`. To initialize the contract yourself do: ```bash # Use near-cli to initialize contract (optional) near call <dev-account> new '{"beneficiary":"<account>"}' --accountId <dev-account> ``` <br /> ## 2. Get Beneficiary `beneficiary` is a read-only method (`view` method) that returns the beneficiary of the donations. `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash near view <dev-account> beneficiary ``` <br /> ## 3. Get Number of Donations `donate` forwards any attached money to the `beneficiary` while keeping track of it. `donate` is a payable method for which can only be invoked using a NEAR account. The account needs to attach money and pay GAS for the transaction. ```bash # Use near-cli to donate 1 NEAR near call <dev-account> donate --amount 1 --accountId <account> ``` **Tip:** If you would like to `donate` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. # Guest Book Contract - Versioned Messages Update This examples adds a new version to the **versioned** messages of the [enum-base](../base/) contracts. ```rust pub struct PostedMessageV1 { pub premium: bool, pub sender: AccountId, pub text: String, } pub struct PostedMessageV2 { pub payment: u128, pub premium: bool, pub sender: AccountId, pub text: String, } pub enum VersionedPostedMessage { V1(PostedMessageV1), V2(PostedMessageV2), } impl From<VersionedPostedMessage> for PostedMessageV2 { fn from(message: VersionedPostedMessage) -> Self { match message { VersionedPostedMessage::V2(posted) => posted, VersionedPostedMessage::V1(posted) => PostedMessageV2 { payment: 0, premium: posted.premium, sender: posted.sender, text: posted.text, }, } } } ``` <br /> # Quickstart ## 1. Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash near dev-deploy --wasmFile target/wasm32-unknown-unknown/release/enums_update.wasm ``` In contrast with [the base update](../../basic-updates/update), here **no migration is needed**, because the contract was already prepared to handle versioned messages! <br /> ## 2. Add a Message ```bash near call <dev-account> add_message '{"text": "another message"}' --amount 0.1 --accountId <account> ``` <br /> ## 3. Retrieve the Messages You will see that the old `V1` messages always have `payment: 0`, while the new ones keep track of the payment ```bash near view <dev-account> get_messages ``` # Contract's Update & State Migration [![](https://img.shields.io/badge/⋈%20Examples-Intermediate-orange)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Contract-rust-red)](https://docs.near.org/develop/contracts/anatomy) [![](https://img.shields.io/badge/Frontend-None-gray)](https://docs.near.org/develop/integrate/frontend) [![](https://img.shields.io/github/workflow/status/near-examples/update-migrate-rust/Tests/main?color=green&label=Tests)](https://github.com/near-examples/update-migrate-rust/actions/workflows/tests.yml) Three examples on how to handle updates and [state migration](https://docs.near.org/develop/upgrade/migration): 1. [State Migration](./contracts/basic-updates/): How to implement a `migrate` method to migrate state between contract updates. 2. [State Versioning](./contracts/enum-updates/): How to use readily use versioning on a state, to simplify updating it later. 3. [Self Update](./contracts/self-updates/): How to implement a contract that can update itself. <br /> ## 1. [State Migration](./contracts/basic-updates/) The examples at [./contracts/basic-updates](./contracts/basic-updates) show how to handle state-breaking changes between contract updates. It is composed by 2 contracts: 1. Base: A Guest Book were people can write messages. 2. Update: An update in which we remove a parameter and change the internal structure. ```rust #[private] #[init(ignore_state)] pub fn migrate() -> Self { let old_state: OldState = env::state_read().expect("failed"); let mut new_messages: Vector<PostedMessage> = Vector::new(b"p"); // iterate through the messages of the previous state for (idx, posted) in old_state.messages.iter().enumerate() { // get the payment using the message index let payment = old_state.payments.get(idx as u64).unwrap_or(0); // Create a PostedMessage with the new format and push it new_messages.push(&PostedMessage { payment, premium: posted.premium, sender: posted.sender, text: posted.text, }) } // return the new state Self { messages: new_messages, } } ``` <br /> ## 2. [State Versioning](./contracts/enum-updates/) The example at [./contracts/enum-updates/](./contracts/enum-updates/) shows how to use [Enums](https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html) to implement versioning. Versioning simplifies updating the contract since you only need to add a new new version of the structure. All versions can coexist, thus you will not need to change previously existing structures. The example is composed by 2 contracts: 1. Base: The [guest-book](https://github.com/near-examples/guest-book-rust) contract using versioned `PostedMessages` (`PostedMessagesV1`). 2. Update: An update that adds a new version of `PostedMessages` (`PostedMessagesV2`). ```rust #[derive(BorshSerialize, BorshDeserialize)] pub enum VersionedPostedMessage { V1(PostedMessageV1), V2(PostedMessageV2), } impl From<VersionedPostedMessage> for PostedMessageV2 { fn from(message: VersionedPostedMessage) -> Self { match message { VersionedPostedMessage::V2(posted) => posted, VersionedPostedMessage::V1(posted) => PostedMessageV2 { payment: if posted.premium { POINT_ONE } else { 0 }, premium: posted.premium, sender: posted.sender, text: posted.text, }, } } } ``` <br /> ## 3. [Self Update](./contracts/self-updates/) The examples at [./contracts/self-updates](./contracts/self-updates) shows how to implement a contract that can update itself. It is composed by 2 contracts: 1. Base: A Guest Book were people can write messages, implementing a `update_contract` method. 2. Update: An update in which we remove a parameter and change the internal structure. ```rust pub fn update_contract(&self) -> Promise { // Check the caller is authorized to update the code assert!( env::predecessor_account_id() == self.manager, "Only the manager can update the code" ); // Receive the code directly from the input to avoid the // GAS overhead of deserializing parameters let code = env::input().expect("Error: No input").to_vec(); // Deploy the contract on self Promise::new(env::current_account_id()) .deploy_contract(code) .function_call( "migrate".to_string(), NO_ARGS, 0, CALL_GAS ) .as_return() } ``` <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/multiple-cross-contract-calls). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` --- # Learn More 1. Learn more on each contract's [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome). near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. # Cross-Contract Hello Contract The smart contract implements the simplest form of cross-contract calls: it calls the [Hello NEAR example](https://docs.near.org/tutorials/examples/hello-near) to get and set a greeting. ```rust // Public - query external greeting pub fn query_greeting(&self) -> Promise { // Create a promise to call HelloNEAR.get_greeting() let promise = hello_near::ext(self.hello_account.clone()) .with_static_gas(Gas(5*TGAS)) .get_greeting(); return promise.then( // Create a promise to callback query_greeting_callback Self::ext(env::current_account_id()) .with_static_gas(Gas(5*TGAS)) .query_greeting_callback() ) } #[private] // Public - but only callable by env::current_account_id() pub fn query_greeting_callback(&self, #[callback_result] call_result: Result<String, PromiseError>) -> String { // Check if the promise succeeded by calling the method outlined in external.rs if call_result.is_err() { log!("There was an error contacting Hello NEAR"); return "".to_string(); } // Return the greeting let greeting: String = call_result.unwrap(); greeting } // Public - change external greeting pub fn change_greeting(&mut self, new_greeting: String) -> Promise { // Create a promise to call HelloNEAR.set_greeting(message:string) hello_near::ext(self.hello_account.clone()) .with_static_gas(Gas(5*TGAS)) .set_greeting(new_greeting) .then( // Create a callback change_greeting_callback Self::ext(env::current_account_id()) .with_static_gas(Gas(5*TGAS)) .change_greeting_callback() ) } #[private] pub fn change_greeting_callback(&mut self, #[callback_result] call_result: Result<(), PromiseError>) -> bool { // Return whether or not the promise succeeded using the method outlined in external.rs if call_result.is_err() { env::log_str("set_greeting was successful!"); return true; } else { env::log_str("set_greeting failed..."); return false; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # dev-1659899566943-21539992274727 ``` <br /> ## 2. Get the Greeting `query_greeting` performs a cross-contract call, calling the `get_greeting()` method from `hello-nearverse.testnet`. `Call` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to ask the contract to query the greeting near call <dev-account> query_greeting --accountId <dev-account> ``` <br /> ## 3. Set a New Greeting `change_greeting` performs a cross-contract call, calling the `set_greeting({greeting:String})` method from `hello-nearverse.testnet`. `Call` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to change the greeting near call <dev-account> change_greeting '{"new_greeting":"XCC Hi"}' --accountId <dev-account> ``` **Tip:** If you would like to call `change_greeting` or `query_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # Guest Book Contract - Self Update A [Guest Book Contract](../../basic-updates/base/) that can self-update. This contract has a `update_contract` that takes as input a wasm file and deploys it on itself. ```rust pub fn update_contract(&self) -> Promise { // Check the caller is authorized to update the code assert!(env::predecessor_account_id() == self.manager, "Only the manager can update the code"); // Receive the code directly from the input to avoid the // GAS overhead of deserializing parameters let code = env::input().expect("Error: No input").to_vec(); // Deploy the contract on self Promise::new(env::current_account_id()) .deploy_contract(code) .function_call( "migrate".to_string(), NO_ARGS, 0, CALL_GAS ) .as_return() } ``` <br /> # Quickstart ## 1. Build and Deploy the Contract Compile, deploy, and initialize the contract setting the `manager`, this is the account that will be able to trigger the code update. ```bash # build all examples, run from project-root/contracts ./build.sh # delete the project-root/contracts/neardev folder if present # rm -rf ./neardev # deploy enum base contract near dev-deploy --wasmFile target/wasm32-unknown-unknown/release/self_base.wasm --initFunction init --initArgs '{"manager":"<manager-account>"}' ``` Once finished, check the `neardev/dev-account` file to find in which address the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-X-Y ``` <br /> ## 2. Lock the Account Check the account's full-access key and remove it from the account, thus leaving it locked: ```bash near keys <dev-account> # result: [access_key: {"nonce": ..., "public_key": '<key>'}] near delete-key <dev-account> '<key>' ``` <br /> ## 3. Add a Message ```bash near call <dev-account> add_message '{"text": "a message"}' --amount 0.1 --accountId <account> ``` <br /> ## 4. Retrieve the Stored Messages & Payments `get_messages` and `get_payments` are read-only method (`view` method) ```bash near view <dev-account> get_messages near view <dev-account> get_payments ``` <br /> ## 5. Continue in the Update Folder Navigate to the [update](../update/) folder to continue # Complex Cross-Contract Calls Examples This contract presents 3 examples on how to do complex cross-contract calls. Particularly, it shows: 1. How to batch method calls to a same contract. 2. How to call multiple contracts in parallel, each returning a different type. 3. Different ways of handling the responses in the callback. <br /> ## 1. Batch Actions You can aggregate multiple actions directed towards one same contract into a batched transaction. Methods called this way are executed sequentially, with the added benefit that, if one fails then they **all get reverted**. ```rust // Promise with batch actions Promise::new(self.hello_account.clone()) .function_call( ... ) .function_call( ... ) .function_call( ... ) .function_call( ... ) .then( Self::ext(env::current_account_id()).batch_actions_callback() ) ``` In this case, the callback has access to the value returned by the **last action** from the chain. <br /> ## 2. Calling Multiple Contracts A contract can call multiple other contracts. This creates multiple transactions that execute all in parallel. If one of them fails the rest **ARE NOT REVERTED**. ```rust let hello_promise = Promise::new(self.hello_account).function_call( ... ); let counter_promise = Promise::new(self.counter_account).function_call( ... ); let guestbook_promise = Promise::new(self.guestbook_account).function_call( ... ); // Calling multiple contracts in parallel hello_promise .and(counter_promise) .and(guestbook_promise) .then( Self::ext(env::current_account_id()).multiple_contracts_callback(), ) ``` In this case, the callback has access to an **array of responses**, which have either the value returned by each call, or an error message. <br /> ## 3. Calling Contracts With the Same Return Type This example is a particular case of the previous one ([2. Calling Multiple Contracts](#2-calling-multiple-contracts)). It simply showcases a different way to check the results by directly accessing the `promise_result` array. ```rust for index in 0..3 { let result = env::promise_result(index); // response of the i-th call match result { PromiseResult::Successful(value) => { if let Ok(message) = near_sdk::serde_json::from_slice::<String>(&value) { results.push(message.clone()); log!(format!("Call {index} returned: {message}")); } else { log!(format!("Error deserializing call {index} result.")); } } ... } } ``` # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. # Complex Cross-Contract Calls This contract presents 3 examples on how to do complex cross-contract calls. Particularly, it shows: 1. How to batch method calls to a same contract. 2. How to call multiple contracts in parallel, each returning a different type. 3. Different ways of handling the responses in the callback. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/multiple-cross-contract-calls). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome). near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # Guest Book Contract The smart contract stores messages, keeping track of how much money was deposited when adding the message. ```rust #[payable] pub fn add_message(&mut self, text: String) { let payment = env::attached_deposit(); let premium = payment >= POINT_ONE; let sender = env::predecessor_account_id(); let message = PostedMessage { premium, sender, text, }; self.messages.push(&message); self.payments.push(&payment); } ``` <br /> # Quickstart ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash # run from project-root/contracts ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-X-Y ``` <br /> ## 2. Add a Message ```bash near call <dev-account> add_message '{"text": "a message"}' --amount 0.1 --accountId <account> ``` <br /> ## 3. Retrieve the Stored Messages & Payments `get_messages` and `get_payments` are read-only method (`view` method) ```bash near view <dev-account> get_messages near view <dev-account> get_payments ``` <br /> ## 4. Continue in the Update Folder Navigate to the [update](../update/) folder to continue # Count on NEAR 🧮 [![](https://img.shields.io/badge/⋈%20Examples-Basics-green)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Gitpod-Ready-orange)](https://gitpod.io/#/https://github.com/near-examples/counter-rust) [![](https://img.shields.io/badge/Contract-rust-red)](https://docs.near.org/develop/contracts/anatomy) [![](https://img.shields.io/badge/Frontend-JS-yellow)](https://docs.near.org/develop/integrate/frontend) [![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fnear-examples%2Fcounter-rust%2Fbadge&style=flat&label=Tests)](https://actions-badge.atrox.dev/near-examples/counter-rust/goto) Count on NEAR is a decentralized app that stores a simple counter, enabling to increment, decrement and reset it. ![](https://docs.near.org/assets/images/count-on-near-banner-2df2978ef988be400aafd5e0f99878be.png) # What This Example Shows 1. How to store, modify and retrieve information in the NEAR network. 2. How to integrate a smart contract in a web frontend. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/counter-rust). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` ### 3. Deploy the Contract Build the contract and deploy it in a testnet account ```bash npm run deploy ``` ### 4. Start the Frontend Start the web application to interact with your smart contract ```bash npm start ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome). near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # Guest Book Contract - Self Update The [base](../base) contract was modified, removing the `payments` field and including that information in the `PostedMessage` structure. ```rust pub struct PostedMessage { pub payment: u128, pub premium: bool, pub sender: AccountId, pub text: String } pub struct GuestBook { messages: Vector<PostedMessage>, } ``` ## 1. Asking the Contract to Update Itself The [base contract](../base/) implements a `update_contract` method that only the `manager` can call. That method takes a compiled wasm as input and then: 1. Deploys in on itself. 2. Calls the `migrate` method on itself. Lets call `update_contract` passing the new code ([./src](./src/)) using the [`manager-account`](../base/README.md#1-build-and-deploy-the-contract). ```bash # run from project-root/contracts NEW_CONTRACT_BYTES=`cat ./target/wasm32-unknown-unknown/release/self_update.wasm | base64` near call <dev-account> update_contract "$NEW_CONTRACT_BYTES" --base64 --accountId <manager-account> --gas 300000000000000 ``` <br /> ## 2. Retrieve the Stored Messages `get_messages` will now return messages that include a `payment` field. ```bash near view <dev-account> get_messages ``` `get_payments` will raise an error since the method does not exist anymore. ```bash # raises an error since the method is gone near view <dev-account> get_payments ``` near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages
NEAR-Balkans_Transcendence-Protocol
.eslintrc.js .solhint.json README.md deploy near 100_deploy_alchemist_v2_near.ts 101_deploy_whitelist_near.ts 102_deploy_mock_underlying_token_near.ts 103_deploy_mock_yield_token_near.ts 104_deploy_debt_token.ts 105_deploy_cnear_adapter.ts 106_deploy_transmuter_buffer_near.ts 107_deploy_transmuter_v2_near.ts usd 000_deploy_whitelist.ts 000_deploy_whitelist_usdc.ts 000_deploy_whitelist_usdt.ts 001_deploy_alchemist_v2.ts 002_deploy_debt_token.ts 003_deploy_mock_underlying_token_usdc.ts 003_deploy_mock_underlying_token_usdt.ts 004_deploy_cusdc_adapter.ts 004_deploy_cusdt_adapter.ts 005_deploy_mock_yield_token_usdc.ts 005_deploy_mock_yield_token_usdt.ts 006_deploy_transmuter_buffer.ts 007_deploy_transmuter_v2_usdc.ts 008_deploy_transmuter_v2_usdt.ts deployments aurora_mainnet AlchemicTokenNEARV2.json AlchemicTokenV2.json AlchemistNEARV2.json AlchemistNEARV2_Implementation.json AlchemistNEARV2_Proxy.json AlchemistV2.json AlchemistV2_Implementation.json AlchemistV2_Proxy.json CTokenAdapterNEAR.json CTokenAdapterUSDC.json CTokenAdapterUSDT.json DefaultProxyAdmin.json TransmuterBuffer.json TransmuterBufferNEAR.json TransmuterBufferNEAR_Implementation.json TransmuterBufferNEAR_Proxy.json TransmuterBuffer_Implementation.json TransmuterBuffer_Proxy.json TransmuterV2NEAR.json TransmuterV2NEAR_Implementation.json TransmuterV2NEAR_Proxy.json TransmuterV2USDC.json TransmuterV2USDC_Implementation.json TransmuterV2USDC_Proxy.json TransmuterV2USDT.json TransmuterV2USDT_Implementation.json TransmuterV2USDT_Proxy.json Whitelist.json WhitelistNEAR.json WhitelistUSDC.json WhitelistUSDT.json solcInputs 1635d55d57a0a2552952c0d22586ed23.json ca5da8cc15d0faf656aceedb434ea182.json e10b647b5a9e5305840a694f8152f738.json ec11591208b408319e9acd72417a4117.json aurora_testnet AlchemicTokenNEARV2.json AlchemicTokenV2.json AlchemistNEARV2.json AlchemistNEARV2_Implementation.json AlchemistNEARV2_Proxy.json AlchemistV2.json AlchemistV2_Implementation.json AlchemistV2_Proxy.json CTokenAdapterNEAR.json CTokenAdapterUSDC.json CTokenAdapterUSDT.json DefaultProxyAdmin.json ERC20MockNEAR.json ERC20MockUSDC.json ERC20MockUSDT.json MockYieldTokenNEAR.json MockYieldTokenUSDC.json MockYieldTokenUSDT.json TransmuterBuffer.json TransmuterBufferNEAR.json TransmuterBufferNEAR_Implementation.json TransmuterBufferNEAR_Proxy.json TransmuterBuffer_Implementation.json TransmuterBuffer_Proxy.json TransmuterV2NEAR.json TransmuterV2NEAR_Implementation.json TransmuterV2NEAR_Proxy.json TransmuterV2USDC.json TransmuterV2USDC_Implementation.json TransmuterV2USDC_Proxy.json TransmuterV2USDT.json TransmuterV2USDT_Implementation.json TransmuterV2USDT_Proxy.json TransmuterV2_Implementation.json Whitelist.json WhitelistNEAR.json WhitelistUSDC.json WhitelistUSDT.json solcInputs 1635d55d57a0a2552952c0d22586ed23.json docs AlchemicTokenV2.md Alchemist.md AlchemixContractsSetup.md AlchemixCookbook.md AlchemixDeploymentSteps.md AlchemixDocumentation.md AlchemixElixir.md AlchemixHarvestandLoanRepayment.md AlchemixIntegrationIssues.md AlchemixMainnetContractInteraction.md AlchemixResearch.md AuditScope.md BastionAdapter.md Transmuter.md TransmuterBuffer.md USNvault.md WETHGateway.md hardhat.config.ts package-lock.json package.json scripts approve.ts deploy.ts setup setup-alchemist-near.ts setup-alchemist-usdc.ts setup-alchemist-usdt.ts tasks.ts utils.ts test AlchemicToken.spec.ts AlchemistV2.spec.ts CTokenAdapter.spec.ts Sets.spec.ts StableSwap.spec.ts TransmuterBuffer.spec.ts TransmuterV2.spec.ts Whitelist.spec.ts e2e cUSDCBastionAdapter.spec.ts cUSDTBastionAdapter.spec.ts wNEARBastionAdapter.spec.ts tsconfig.json utils helpers.ts logging.ts network.ts prompt.ts
# Transcendence-Protocol
kuutamolabs_hyper-util
.github workflows CI.yml Cargo.toml README.md examples client.rs src client client.rs connect dns.rs http.rs mod.rs legacy.rs mod.rs pool.rs service.rs common exec.rs lazy.rs mod.rs never.rs rewind.rs sync.rs error.rs lib.rs rt mod.rs tokio_executor.rs tokio_io.rs server conn auto.rs mod.rs mod.rs
# hyper-util A collection of utilities to be do common things with hyper.
near_near-explorer
frontend babel-jest-wrapper.js next.config-prod.js next.config.js utils stitches-plugin snapshots assignment-expression input.js output.js export-default input.js output.js nested input.js output.js object-property input.js output.js variable-declarator input.js output.js
hoangtrung18_near-nft-standard
.gitpod.yml README.md contract README.md babel.config.json build.sh deploy.sh package-lock.json package.json src approval.ts enumeration.ts index.ts internal.ts metadata.ts mint.ts nft_core.ts royalty.ts tsconfig.json integration-tests package.json src main.ava.ts package.json
near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```ts @NearBindgen({}) class HelloNear { greeting: string = "Hello"; @view // This method is read-only and can be called for free get_greeting(): string { return this.greeting; } @call // This method changes the state, for which it cost gas set_greeting({ greeting }: { greeting: string }): void { // Record a log permanently to the blockchain! near.log(`Saving greeting ${greeting}`); this.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash npm run deploy ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `call` method. `Call` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"greeting":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`.
near_fast-vault
.github ISSUE_TEMPLATE BOUNTY.yml README.md frontend src voyager index.metadata.json test.txt test2.txt test3.txt
# Fast Vault (Alpha) A secure and composable decentralized storage layer utilizing IPFS. This is currently a POC. Please test the product, but do not store anything vital or sensitive. The encryption underneath needs some work.
hanakannzashi_saika-ui
README.md package.json public index.html manifest.json robots.txt src assets account-icon.svg default-token-icon.svg near-icon.svg near-logo.svg config common-config.ts contract-config.ts near-config.ts token-config.ts wallet-config.ts hooks useRedPacketView.ts useRedPacketViews.ts useTokenMetadataList.ts logo.svg near fungible-token-contract.ts multi-action-wallet.ts near-service.ts red-packet-contract.ts react-app-env.d.ts reportWebVitals.ts serviceWorker.ts setupTests.ts stores global-stores.ts types near-types.ts storage-management.ts utils amount-utils.ts common-utils.ts custom-utils.ts fungible-token-utils.ts local-storage-utils.ts view methods change methods tsconfig.json
### Frontend of Saika https://github.com/hanakannzashi/saika.git ### start `npm run start:testnet` `npm run start:mainnet`
iamfortune_NEAR-notes-app
README.md as-pect.config.js asconfig.json package.json scripts 1.init.sh 2.run.sh README.md src as-pect.d.ts as_types.d.ts sample README.md __tests__ README.md index.unit.spec.ts asconfig.json assembly index.ts model.ts tsconfig.json utils.ts
## Unit Tests - Unit tests can be run from the top level directory using the following command: ``` yarn test:unit ``` ### Tests for Contract in index.unit.spec.ts [Describe]: Notes [Success]: ✔ verifies a note is added from addNote [Success]: ✔ deletes contact by calling deleteNote() [File]: src/sample/__tests__/index.unit.spec.ts [Groups]: 2 pass, 2 total [Result]: ✔ PASS [Snapshot]: 0 total, 0 added, 0 removed, 0 different [Summary]: 2 pass, 0 fail, 2 total [Time]: 10.657ms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Result]: ✔ PASS [Files]: 1 total [Groups]: 2 count, 2 pass [Tests]: 2 pass, 0 fail, 2 total [Time]: 15673.723ms Done in 16.13s. ## Unit tests Unit tests can be run from the top level folder using the following command: ``` yarn test:unit ``` ### Tests for Contract in `index.unit.spec.ts` ``` [Describe]: Greeting [Success]: ✔ should respond to showYouKnow() [Success]: ✔ should respond to showYouKnow2() [Success]: ✔ should respond to sayHello() [Success]: ✔ should respond to sayMyName() [Success]: ✔ should respond to saveMyName() [Success]: ✔ should respond to saveMyMessage() [Success]: ✔ should respond to getAllMessages() [File]: src/sample/__tests__/index.unit.spec.ts [Groups]: 2 pass, 2 total [Result]: ✔ PASS [Snapshot]: 0 total, 0 added, 0 removed, 0 different [Summary]: 7 pass, 0 fail, 7 total [Time]: 19.164ms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Result]: ✔ PASS [Files]: 1 total [Groups]: 2 count, 2 pass [Tests]: 7 pass, 0 fail, 7 total [Time]: 8217.768ms ✨ Done in 8.86s. ``` ## Setting up your terminal The scripts in this folder support a simple demonstration of the contract. It uses the following setup: ```txt ┌───────────────────────────────────────┬───────────────────────────────────────┐ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └───────────────────────────────────────┴───────────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands ```sh 1.init.sh # cleanup, compile and deploy contract 2.run.sh # call methods on the deployed contract ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linux-watch-command#191068) ![Near, Inc. logo](https://near.org/wp-content/themes/near-19/assets/img/logo.svg?t=1553011311) ## Design ### Interface ```ts export function showYouKnow(): void; ``` - "View" function (ie. a function that does NOT alter contract state) - Takes no parameters - Returns nothing ```ts export function showYouKnow2(): bool; ``` - "View" function (ie. a function that does NOT alter contract state) - Takes no parameters - Returns true ```ts export function sayHello(): string; ``` - "View" function - Takes no parameters - Returns a string ```ts export function sayMyName(): string; ``` - "Change" function (although it does NOT alter state, it DOES read from `context`, [see docs for details](https://docs.near.org/docs/develop/contracts/as/intro)) - Takes no parameters - Returns a string ```ts export function saveMyName(): void; ``` - "Change" function (ie. a function that alters contract state) - Takes no parameters - Saves the sender account name to contract state - Returns nothing ```ts export function saveMyMessage(message: string): bool; ``` - "Change" function - Takes a single parameter message of type string - Saves the sender account name and message to contract state - Returns nothing ```ts export function getAllMessages(): Array<string>; ``` - "Change" function - Takes no parameters - Reads all recorded messages from contract state (this can become expensive!) - Returns an array of messages if any are found, otherwise empty array
js13kGames_just-another-space-shooter
README.md back .gitpod.yml README.md contract README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts tsconfig.json compile.js package-lock.json package.json dist global.e50bbfba.css global.e50bbfba.js global.eca22910.css index.html index.js logo-black.3916bf24.svg logo-black.eab7a939.svg logo-white.7fec831f.svg logo-white.c927fc35.svg src.4085dabb.js src.e31bb0bc.js package.json src assets logo-black.svg logo-white.svg config.js global.css index.html index.js main.test.js utils.js wallet login index.html front README.md index.html pack index.html main.js package.json postcss.config.js r.json src index.js matrix.js shaders.js webpack.dev.js webpack.prod.js
game-js13k-back ================== This app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `game-js13k-back.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `game-js13k-back.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account game-js13k-back.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'game-js13k-back.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # JS 13K context 2021 # front ## install cd front yarn install ## run cd front yarn start and open bronwser in **http://localhost:8080** ## validate cd front yarn validate game-js13k-back Smart Contract ================== A [smart contract] written in [AssemblyScript] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install [Node.js] ≥ 12 Exploring The Code ================== 1. The main smart contract code lives in `assembly/index.ts`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard AssemblyScript tests using [as-pect]. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [AssemblyScript]: https://www.assemblyscript.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [as-pect]: https://www.npmjs.com/package/@as-pect/cli <img alt="Webpack Starter Basic Loo" src="https://github.com/lifenautjoe/webpack-starter-basic/blob/master/src/assets/logo-on-dark-bg.png?raw=true" width="250"> # webpack-starter-basic [![forthebadge](http://forthebadge.com/images/badges/fo-real.svg)](http://forthebadge.com)[![forthebadge](http://forthebadge.com/images/badges/built-with-love.svg)](http://forthebadge.com) [![dependencies](https://david-dm.org/lifenautjoe/webpack-starter-basic.svg)](https://david-dm.org/lifenautjoe/webpack-starter-basic) A simple **webpack 4 starter project** for your basic web development needs. Read more on the [demo website](https://lifenautjoe.github.io/webpack-starter-basic/) or continue reading below. ## Table of Contents - [Motivation](#motivation) - [Features](#features) - [Requirements](#requirements) - [Usage](#usage) - [FAQ](#faq) * [When should I use this starter?](#when-should-i-use-this-starter) * [Where's the common webpack config?](#wheres-the-common-webpack-config) * [How to load fonts](#how-to-load-fonts) * [How to load images](#how-to-load-images) + [In JavaScript](#in-javascript) + [In `index.html`](#in-indexhtml) * [How to install bootstrap 4](#how-to-install-bootstrap-4) - [Websites using this starter kit on the wild](#websites-using-this-starter-kit-on-the-wild) ## Motivation I needed to make a plain ol' "drop your mail to stay updated of ongoing developments" page. I did not need anything fancy, no frontend framework, no unit testing, simply a **starter project that would let me use sass, ES6, load assets, add vendor prefixes, start a dev server, generate sourcemaps and optimize everything for production.** I looked around and all I found were heavily specialized and complicated webpack starter projects (`webpack-angular-starter`, `webpack-react-starter`, etc) that are so intertwined with plugins that stripping undesired functionality is almost impossible. So I did this. ## Features * Separated development and production webpack settings you can understand * Sass * ES6 * Asset loading * CSS Vendor prefixing * Development server * Sourcemaps * Favicons generation * Production optimizations * Mobile browser header color ## Requirements * [Node](https://nodejs.org) > 7.6 ## Usage Substitute `PROJECT-NAME` for your project name. Clone the repository ```sh git clone https://github.com/lifenautjoe/webpack-starter-basic PROJECT-NAME cd PROJECT-NAME ``` Install npm dependencies ```sh npm install ``` Run the kickstart command ```sh npm run kickstart ``` **After the project has been kickstarted** To start the development server ```sh npm start ``` To build for production ```sh npm run build ``` To preview the production build ```sh npm run preview ``` ## FAQ ### When should I use this starter? You should use this starter if any of the following are true: * You want to make a static page. e.g. splash screen, onboarding screen, phaser game, threejs visualization, countdown. * You found no good starter kit for whatever you want to do and need a solid place to start from. **Please note**: If you are going to use a frontend framework like angular or react, you can of course add the required plugins and configuration but it's normally complicated and quirky enough that it's highly recommended to use one of the existing starter projects such as [react-webpack-babel](https://github.com/alicoding/react-webpack-babel) or for angular projects the [angular-cli](https://github.com/angular/angular-cli). ### Where's the common webpack config? **There is none and that is good thing.** The pattern creates unnecessary confusion over the setup, at the end the config will always be different across environments. People just put booleans everywhere on the common config to switch between these differing configuration options which is just awful to see and confusing for someone who's just starting on webpack. The only truly shared config between these files are the entry js point and the main html template. ### How to load fonts If you don't support Opera Mini, browsers support the .woff format. Its newer version .woff2, is widely supported by modern browsers and can be a good alternative. If you decide to use only this format you can load the fonts in a similar manner to images. In your `webpack.dev.js` and `webpack.prod.js` add the following ```js module.exports = { // .. module: { rules: [ // .. { test: /\.woff$/, loader: 'url-loader', options: { // Limit at 50k. Above that it emits separate files limit: 50000, // url-loader sets mimetype if it's passed. // Without this it derives it from the file extension mimetype: 'application/font-woff', // Output below fonts directory name: './fonts/[name].[ext]', }, } // .. ] } // .. }; ``` And let's say your font is in the folder `assets` with the name `pixel.woff` You can add it and use it in `index.scss` as ```scss @font-face { font-family: "Pixel"; src: url('./../assets/pixel.woff') format('woff'); } .body{ font-family: 'Pixel', sans-serif; } ``` If you would like to support all kinds of font types, remove the woff rule we previously added to `webpack.dev.js` and `webpack.prod.js` and add the following ```js module.exports = { // .. module: { rules: [ // .. { test: /\.(ttf|eot|woff|woff2)$/, loader: 'file-loader', options: { name: 'fonts/[name].[ext]', }, } // .. ] } // .. }; ``` And assuming you have your fonts in the directory `assets` with names `pixel.woff`, `pixel.ttf`, `pixel.eot` , etc. You can add it and use it in `index.scss` as ```scss @font-face { font-family: 'Pixel'; src: url('./../assets/pixel.woff2') format('woff2'), url('./../assets/pixel.woff') format('woff'), url('./../assets/pixel.eot') format('embedded-opentype'), url('./../assets/pixel.ttf') format('truetype'); /* Add other formats as you see fit */ } ``` ### How to load images #### In JavaScript You can require an image from JavaScript like ```js const myImage = require('./assets/icon.png'); ``` If the image size in bytes is smaller than `8192`you, `myImage` will be a string with the encoded image path such as ``` data:image/svg+xml;base64,bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICJhc3NldHMvaW1hZ2VzL3RpY2stQ3lydkhSdi5zdmciOw== ``` If the image size is larger than `8192` it will be a string with the url to the image such as ``` src/assets/icon.png?hash=5b1f36bc41ab31f5b801 ``` This limit is set so images like icons are not loaded through a request but you can force the loader to give you image urls always by doing the following but should not be necessary. The limit works 90% of the time. ```js const myImage = require('!!url!/assets/icon.png'); ``` #### In `index.html` If you would like to include an image on your `index.html` file, place the path of the image in a webpack require statement`<%= require(imagePath) %>`. ```html <img class="splash-title__img" src="<%= require('./src/assets/logo-on-dark-bg.png') %>" alt="webpack logo"></a> ``` ### How to install Bootstrap 4 **After the project has been kickstarted** Install bootstrap ````sh npm install bootstrap@4 --save ```` Install bootstrap dependencies. ````sh npm install popper.js --save npm install jquery --save ```` Replace the project `index.scss` with ````scss @import "~bootstrap/scss/bootstrap"; ```` And replace the project `index.js` with ````js require('./styles/index.scss'); import PopperJs from 'popper.js'; import jquery from 'jquery'; jquery(()=>{ console.log('Hello jQuery + bootstrap 4!'); }); ```` To see it all come together, replace the index.html body tag with ````html <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="https://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a> <div class="dropdown-menu" aria-labelledby="dropdown01"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> </div> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <main role="main" class="container"> <div class="starter-template"> <h1>Bootstrap starter template</h1> <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p> </div> </main><!-- /.container --> </body> ```` Start the development server and `voilà`. ```sh npm start ``` To build for production ```sh npm run build ``` To preview the production build ```sh npm run preview ``` ⚠️ Please remember to remove the Google Analytics tag in the `index.html` file as soon as you make the template yours. ```html <!-- Global Site Tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-101423651-2"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-101423651-2'); </script> ``` ## Websites using this starter kit on the wild * [Droppable library](https://github.com/lifenautjoe/droppable) * [Noel Event Emitter](https://github.com/lifenautjoe/noel) * [ChooseIT Wishbot](http://voeux2018.choosit.com/) * [Webpack Starter Basic](https://lifenautjoe.github.io/webpack-starter-basic/) * [Okuna](https://www.okuna.io/) Have a website online built with this starter kit and would like to add it to the list? Open an issue! ___ Author [Joel Hernandez](www.lifenautjoe.com)
NEAR-Analytics_Org-Project-Outline
README.md
# Org-Project-Outline
matiasberaldo_abstracting-hackathon
README.md apps mattb.near bos.config.json package-lock.json package.json tree.json
### NearBadger and Frensly projects NearBadger is the platform that allows users to prove that they own a profile in a given web3 social platform (such as Lens Protocol, Farcaster, Mirror...), by providing an intuitive and simple User Interface, where users have to sign a message with their EVM-based wallet and save the signature to their Near account in order to prove other users that they own a given handle Frensly is one of the platforms that leverages NearBadger tools to create a unique social platform on Near Protocol where users owning a Lens Profile can get to know and interact with other users owning a verified Lens Profile on Near Protocol in a fancy and cozy environment ## How to run the project 1. Install the dependencies of the project by running the following command ``` npm install ``` 2. Run the development environment ``` npm run dev ``` 3. Navigate ìn your browser to `http://127.0.0.1:8080/` or `http://127.0.0.1:4040/` depending if your port `8080` is already taken by another process 4. The path to the homepage of each platforms: - NearBadger: /mattb.near/widget/NearBadger.Pages.Main - Frensly: /mattb.near/widget/Frensly.Pages.Index > [!IMPORTANT] > Frensly leverages new and experimental dev tooling such as `RoutesManager` and `useSharedContext` ## Demo Video [Click here to see the video on Loom](https://www.loom.com/share/e50ef6196a5040f5b431d90e9c05d646?sid=4e906135-d582-487b-aa2a-36f83b44cd57) ## Bounties - General Prize - Abstraction on bOS
nathalyzatarain_Expediente-escolar-NEAR
.vscode settings.json Expediente escolar API Js README.md contract.html index.html login.html src css styles.css README.md | as-pect.config.js asconfig.json package-lock.json package.json src as_types.d.ts contrato __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly data.ts index.ts tsconfig.json utils.ts
# Expediente-escolar-NEAR Creación de un expediente académico digital de un alumno en la blockchain basado en el protocolo near mediante un contrato inteligente,donde también se podrá consultar la información por nombre y por carrera. Esto permitirá llevar el control de los datos generales de los alumnos de forma permanente y de fácil acceso. # Justificación Para una universidad es importante llevar un expediente de todos los alumnos, tener esta información guardada en el blockchain ayudaría a que los expedientes de los alumnos se guardarán de manera más rápida, de fácil acceso y de manera más permanente. El expediente debe contener la información de de la institución que lo emite, junto con la fecha de ingreso y la información general del estudiante, como su nombre, teléfono, fecha de nacimiento, su código o número de cuenta entres otros datos. También incluirá los resultados de la carga académica, anexo de documentos personales y registro de pagos. ## Contenido Este repositorio contiene un contrato inteligente con los siguientes métodos: ### Escritura: * `setEstudiante` * `deleteEstudiante` ### Lectura: * `getEstudiantes` * `getEstudiante` * `getEstudiantesByName` * `getEstudianteByCareer` El contrato se encuentra previamente desplegado en la cuenta `frankbizopps.testnet`. Las llamadas se realizaran de la siguiente manera: Lectura: ```sh near view frankbizopps.testnet getEstudiantes ``` Escritura: ```sh near call frankbizopps.testnet deleteEstudiante '{"id":"1"}' ``` ## Descripción general | Metodo | Descripcion | | | ------------------------------------------------- | ------------------------------------------------------------- | - | | [`/setEstudiante`](#setEstudiante) | Guarda la información de un estudiante en la blockchain. | | | [`/getEstudiantes`](#getEstudiantes) | Muestra la lista de estudiantes almacenados en la blockchain. | | | [`/getEstudiante`](#getEstudiante) | Muestra un estudiante por id o número de cuenta. | | | [`/getEstudiantesByName`](#getEstudiantesByName) | Muestra un listado de estudiantes filtrado por nombre. | | | [`/getEstudianteByCareer`](#getEstudianteByCareer) | Muestra un listado de estudiantes filtrado por carrera. | | | [`//deleteEstudiante`](#deleteEstudiante) | Elimina un estudiante del listado guardado en la blockchain. | | --- ## Requisitos - [Cuenta NEAR](https://docs.near.org/docs/develop/basics/create-account) - [Node.js](https://nodejs.org/en/download/package-manager/) - [npm](https://www.npmjs.com/get-npm) o [Yarn](https://yarnpkg.com/getting-started/install) - NEAR CLI - Cuenta Near - Cuenta Near testnet ## Configuración inicial 1. Clonar repositorio ```bash git clone https://github.com/nathalyzatarain/Expediente-escolar-NEAR.git ``` 2. Instalar dependencias ```bash npm install ``` ## Ejecutar contrato inteligente 1. Iniciar sesión en near cli ```bash near login ``` 2. Generar build ```bash npm run build ``` 3. Deployear contrato ```bash near dev-deploy build/debug/contrato.wasm ``` ## Instrucciones de uso de los metodos ## `/setEstudiante` > _Guarda la información de un estudiante en la blockchain_ | Parametros | Descripcion | | ------------------- | ---------------------------------------------- | | `nombre` | _Nombre del alumno_ | | `fechaNacimiento` | _Fecha de nacimiento del alumno_ | | `contract` | _Account id del contrato que estas llamando_ | | `edad` | _Edad del alumno_ | | `email` | _Cuenta de correo electronico del alumno_ | | `telefono` | _Numero de telefono del alumno_ | | `nacionalidad` | _País de nacimiento del alumno_ | | `carrera` | _Carrera a la que ingresa el alumno | | _ | | Ejemplo de registro: ```json { "nombre": "Maria Estrada", "fechaNacimiento": "2 de junio de 1997", "edad": 24, "email": "[email protected]", "telefono": "6691017155", "nacionalidad": "mexico", "carrera": "psicologia" } ``` ## `/getEstudiantes` > _Muestra todos los estudiantes que han sido registrados._ > _Sin parametros._ ## `/getEstudiante` > _Muestra un estudiante por id o número de cuenta._ | Parametros | Descripción | | ---------- | -------------------------- | | `id` | _Número de id a buscar_ | ## `/getEstudianteByName` > _Muestra un listado de estudiantes filtrado por nombre._ | Parametros | Descripción | | ---------- | ------------------------------ | | `nombre` | _Nombre del alumno a buscar_ | ## `/getEstudianteByCareer` > _Muestra un listado de estudiantes filtrado por carrera._ | Parametros | Descripción | | ----------- | --------------------------------------------------------- | | `carrera` | _Carrera por la que se quiera buscar a los estudiantes_ | ## `/deleteEstudiante` > _Elimina un estudiante del listado guardado en la blockchain._ | Parametros | Descripción | | ---------- | --------------------------- | | `id` | _Id del alumno a elimnar_ | ## Pruebas unitarias 1- en el archivo index.unit.spec.ts es importar todo el contenido de la carpeta assembly ``` import * ascontratofrom"../assembly"; ``` 2- por cada método que queramos probar creamos una función ***describe*** y le ponemos los parámetros que queramos revisar 3- en la carpeta del archivo ejecutar el comando: * npm run test ## Mockups ![1656708048547](image/README/1656708048547.png) ![1656708068314](image/README/1656708068314.png)
Moses00074_Near_wallet
.github dependabot.yml workflows tests.yml .gitpod.yml .travis.yml LICENSE-APACHE.txt LICENSE-MIT.txt README-Gitpod.md README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts model.ts tsconfig.json neardev shared-test-staging test.near.json shared-test test.near.json package.json src config.js index.html loader.html main.js styles.css test-setup.js test.js
Example of NEAR Wallet integration ================================== [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near-examples/wallet-example) <!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page --> This example demonstrates how to integrate your application with NEAR Wallet. The contract is quite simple. It can store the account_id of last sender and return it. It also shows how you can debug contracts using logs. ## Getting started There are two ways to run this project. The first is the quick and a good way to instantly become familiar with this example. Once familiar, the next step is for a developer to create their own NEAR account and deploy the contract to testnet. This is covered in the following section. There's a button at the top of this file that says "Open in Gitpod." This will open the project in a new tab with an integrated development environment. The other option is to clone this repository and follow the same instructions. ### Quickest option 1. Install dependencies: ``` yarn --frozen-lockfile ``` 2. Build and deploy this smart contract to a development account. This development account will be created automatically and is not intended for reuse: ``` yarn dev ``` Your command line which will display a link to localhost similar to: ```bash Server running at http://localhost:1234 ``` Please open that link your browser to continue and see how to log in with NEAR Wallet in a simple webapp. ### Standard deploy option In this second option, the smart contract will get deployed to a specific account created with the NEAR Wallet. 1. Ensure `near-cli` is installed by running: ``` near --version ``` If needed, install `near-cli`: ``` npm install near-cli -g ``` 2. If you do not have a NEAR account, please create one with [NEAR Wallet](wallet.testnet.near.org). In the project root, login with `near-cli` by following the instructions after this command: ``` near login ``` 3. Modify the top of `src/config.js`, changing the `CONTRACT_NAME` to be the NEAR account that was just used to log in. ```javascript … const CONTRACT_NAME = process.env.CONTRACT_NAME || 'YOUR_ACCOUNT_NAME_HERE'; /* TODO: fill this in! */ … ``` 4. Start the example! ``` yarn start ``` ## To Test ``` yarn asp // as-pect tests yarn jest // integration tests yarn test // both ``` ## To Explore - `assembly/main.ts` for the contract code - `src/index.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 ## Data collection By using Gitpod in this project, you agree to opt-in to basic, anonymous analytics. No personal information is transmitted. Instead, these usage statistics aid in discovering potential bugs and user flow information.
near_gas-station-event-indexer
.github ISSUE_TEMPLATE BOUNTY.yml README.md config.toml gas_station_event_indexer.py requirements.txt
# gas-station-event-indexer Picks up events emitted from the gas station contract used for generating signed foreign chain transactions and calls the multichain relayer `/send_funding_and_user_signed_txns` endpoint locally # Run 1. ensure you have https://github.com/near/multichain-relayer-server running on localhost:3030 2. `make install` create virtual environment and install `requirements.txt` 2. update the config.toml with the appropriate values 3. `make run` runs the `gas_station_event_indexer.py` script
nayeon21_secret-tutorial-setup
.gitpod.yml .prettierrc.json README.md __test__ avalanche.test.ts polygon.test.ts secret.test.ts solana.test.ts components protocols avalanche components index.ts lib index.ts celo components index.ts lib index.ts ceramic lib figmentLearnSchema.json figmentLearnSchemaCompact.json identityStore LocalStorage.ts index.ts index.ts types index.ts near components steps index.ts lib index.ts types index.ts polkadot components index.ts lib index.ts polygon components steps index.ts lib index.ts types index.ts secret components index.ts lib index.ts solana components index.ts lib index.ts tezos components index.ts lib index.ts the_graph graphql query.ts shared Button.styles.ts CustomMarkdown Markdown.styles.ts VideoPlayer VideoPlayer.styles.ts utils markdown-utils.ts string-utils.ts ProtocolNav ProtocolNav.styles.ts contracts celo HelloWorld.json near Cargo.toml README.md compile.js src lib.rs polygon SimpleStorage README.md build contracts Migrations.json SimpleStorage.json migrations 1_initial_migration.js 2_deploy_contracts.js package-lock.json package.json truffle-config.js solana program Cargo.toml Xargo.toml src lib.rs tests lib.rs tezos counter.js the_graph CryptopunksData.abi.json docker docker-compose.yml hooks index.ts useColors.ts useLocalStorage.ts useSteps.ts jest.config.js lib constants.ts markdown PREFACE.md avalanche CHAIN_CONNECTION.md CREATE_KEYPAIR.md EXPORT_TOKEN.md FINAL.md GET_BALANCE.md IMPORT_TOKEN.md PROJECT_SETUP.md TRANSFER_TOKEN.md celo CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md SWAP_TOKEN.md TRANSFER_TOKEN.md ceramic BASIC_PROFILE.md CHAIN_CONNECTION.md CUSTOM_DEFINITION.md FINAL.md LOGIN.md PROJECT_SETUP.md near CHAIN_CONNECTION.md CREATE_ACCOUNT.md CREATE_KEYPAIR.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md polkadot CHAIN_CONNECTION.md CREATE_ACCOUNT.md ESTIMATE_DEPOSIT.md ESTIMATE_FEES.md FINAL.md GET_BALANCE.md PROJECT_SETUP.md RESTORE_ACCOUNT.md TRANSFER_TOKEN.md polygon CHAIN_CONNECTION.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md QUERY_CHAIN.md RESTORE_ACCOUNT.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md secret CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md solana CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md FUND_ACCOUNT.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md SOLANA_CREATE_GREETER.md TRANSFER_TOKEN.md tezos CHAIN_CONNECTION.md CREATE_ACCOUNT.md DEPLOY_CONTRACT.md FINAL.md GET_BALANCE.md GET_CONTRACT_VALUE.md PROJECT_SETUP.md SET_CONTRACT_VALUE.md TRANSFER_TOKEN.md the_graph FINAL.md GRAPH_NODE.md PROJECT_SETUP.md SUBGRAPH_MANIFEST.md SUBGRAPH_MAPPINGS.md SUBGRAPH_QUERY.md SUBGRAPH_SCAFFOLD.md SUBGRAPH_SCHEMA.md | n : | next-env.d.ts next.config.js package.json pages api avalanche account.ts balance.ts connect.ts export.ts import.ts transfer.ts celo account.ts balance.ts connect.ts deploy.ts getter.ts setter.ts swap.ts transfer.ts near balance.ts check-account.ts connect.ts create-account.ts deploy.ts getter.ts keypair.ts setter.ts transfer.ts polkadot account.ts balance.ts connect.ts deposit.ts estimate.ts restore.ts transfer.ts polygon query.ts secret account.ts balance.ts connect.ts deploy.ts getter.ts setter.ts transfer.ts solana balance.ts connect.ts deploy.ts fund.ts getter.ts greeter.ts keypair.ts setter.ts transfer.ts tezos account.ts balance.ts connect.ts deploy.ts getter.ts setter.ts transfer.ts the-graph entity.ts manifest.ts mapping.ts node.ts scaffold.ts public discord.svg figment-learn-compact.svg vercel.svg theme colors.ts index.ts media.ts tsconfig.json types index.ts utils colors.ts context.ts datahub.ts markdown.ts networks.ts pages.ts string-utils.ts tracking-utils.ts
Based on: MetaCoin tutorial from Truffle docs https://www.trufflesuite.com/docs/truffle/quickstart SimpleStorage example contract from Solidity docs https://docs.soliditylang.org/en/v0.4.24/introduction-to-smart-contracts.html#storage 1. Install truffle (https://www.trufflesuite.com/docs/truffle/getting-started/installation) `npm install -g truffle` 2. Navigate to this directory (/contracts/polygon/SimpleStorage) 3. Install dependencies `yarn` 4. Test contract `truffle test ./test/TestSimpleStorage.sol` **Possible issue:** "Something went wrong while attempting to connect to the network. Check your network configuration. Could not connect to your Ethereum client with the following parameters:" **Solution:** run `truffle develop` and make sure port matches the one in truffle-config.js under development and test networks 5. Run locally via `truffle develop` $ truffle develop ``` migrate let instance = await SimpleStorage.deployed(); let storedDataBefore = await instance.get(); storedDataBefore.toNumber() // Should print 0 instance.set(50); let storedDataAfter = await instance.get(); storedDataAfter.toNumber() // Should print 50 ``` 6. Create Polygon testnet account - Install MetaMask (https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn?hl=en) - Add a custom network with the following params: Network Name: "Polygon Mumbai" RPC URL: https://rpc-mumbai.maticvigil.com/ Chain ID: 80001 Currency Symbol: MATIC Block Explorer URL: https://mumbai.polygonscan.com 7. Fund your account from the Matic Faucet https://faucet.matic.network Select MATIC Token, Mumbai Network Enter your account address from MetaMask Wait until time limit is up, requests tokens 3-4 times so you have enough to deploy your contract 8. Add a `.secret` file in this directory with your account's seed phrase or mnemonic (you should be required to write this down or store it securely when creating your account in MetaMask). In `truffle-config.js`, uncomment the three constant declarations at the top, along with the matic section of the networks section of the configuration object. 9. Deploy contract `truffle migrate --network matic` 10. Interact via web3.js ```js const {ethers} = require('ethers'); const fs = require('fs'); const mnemonic = fs.readFileSync('.secret').toString().trim(); const signer = new ethers.Wallet.fromMnemonic(mnemonic); const provider = new ethers.providers.JsonRpcProvider( 'https://matic-mumbai.chainstacklabs.com', ); const json = JSON.parse( fs.readFileSync('build/contracts/SimpleStorage.json').toString(), ); const contract = new ethers.Contract( json.networks['80001'].address, json.abi, signer.connect(provider), ); contract.get().then((val) => console.log(val.toNumber())); // should log 0 contract.set(50).then((receipt) => console.log(receipt)); contract.get().then((val) => console.log(val.toNumber())); // should log 50 ``` # 👋🏼 What is `learn-web3-dapp`? We made this decentralized application (dApp) to help developers learn about Web 3 protocols. It's a Next.js app that uses React, TypeScript and various smart contract languages (mostly Solidity and Rust). We will guide you through using the various blockchain JavaScript SDKs to interact with their networks. Each protocol is slightly different, but we have attempted to standardize the workflow so that you can quickly get up to speed on networks like Solana, NEAR, Polygon and more! - ✅ Solana - ✅ Polygon - ✅ Avalanche - ✅ NEAR - ✅ Tezos - ✅ Secret - ✅ Polkadot - ✅ Celo - ✅ Ceramic - ✅ The Graph - 🔜 Arweave - 🔜 Chainlink - 🔜 Pyth - [Let us know which one you'd like us to cover](https://github.com/figment-networks/learn-web3-dapp/issues) <img width="1024" alt="Screen Shot 1" src="https://raw.githubusercontent.com/figment-networks/learn-web3-dapp/main/markdown/__images__/readme-01.png"> <img width="1024" alt="Screen Shot 2" src="https://raw.githubusercontent.com/figment-networks/learn-web3-dapp/main/markdown/__images__/readme-02.png"> <img width="1024" alt="Screen Shot 3" src="https://raw.githubusercontent.com/figment-networks/learn-web3-dapp/main/markdown/__images__/readme-03.png"> # 🧑‍💻 Get started ## 🤖 Using Gitpod (Recommended) The best way to go through those courses it using [Gitpod](https://gitpod.io). Gitpod provides prebuilt developer environments in your browser, powered by VS Code. Just sign in using GitHub and you'll be up and running in seconds without having to do any manual setup 🔥 [**Open this repo on Gitpod**](https://gitpod.io/#https://github.com/figment-networks/learn-web3-dapp) ## 🐑 Clone locally Make sure you have installed [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git), [Node.js](https://nodejs.org/en/) (Please install **v14.17.0**, we recommend using [nvm](https://github.com/nvm-sh/nvm)) and [yarn](https://yarnpkg.com/getting-started/install). Then clone the repo, install dependencies and start the server by running all these commands: ```text git clone https://github.com/figment-networks/learn-web3-dapp.git cd learn-web3-dapp yarn yarn dev ``` # 🤝 Feedback and contributing If you encounter any errors during this process, please join our [Discord](https://figment.io/devchat) for help. Feel free to also open an Issue or a Pull Request on the repo itself. We hope you enjoy our Web 3 education dApps 🚀 -- ❤️ The Figment Learn Team # Pathway Smart Contract A [smart contract] written in [Rust] for [figment pathway] # Quick Start Before you compile this code, you will need to install Rust with [correct target] # Exploring The Code 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [rust]: https://www.rust-lang.org/ [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html
hoangnhxda_pet_shop
README.md migrations 1_initial_migration.js 2_deploy_adoption.js package-lock.json package.json src css bootstrap.min.css custom.css fonts glyphicons-halflings-regular.svg index.html js app.js bootstrap.min.js pets.json test testAdoption.test.js truffle-box.json truffle-config.js
# NEAR Pet Shop This project is based on Truffle's [Pet Shop Tutorial](https://www.trufflesuite.com/tutorials/pet-shop) but uses NEAR's custom provider called [near-web3-provider](https://github.com/nearprotocol/near-web3-provider) and deploys the Solidity contracts to the [NEAR EVM](https://github.com/near/near-evm). You may read more about the NEAR EVM in the link above. In brief, it's an implementation of the Ethereum Virtual Machine (EVM) incorporated into NEAR. This means developers may preserve existing investment by compiling existing Ethereum contracts and deploying them to the NEAR blockchain as well. This is made possible by two NEAR libraries: 1. [near-api-js](https://www.npmjs.com/package/near-api-js): the JavaScript library used to abstract JSON RPC calls. 2. [near-web3-provider](https://www.npmjs.com/package/near-web3-provider): the web3 provider for NEAR containing utilities and Ethereum routes (ex. `eth_call`, `eth_getBlockByHash`, etc.) This project uses Truffle for testing and migrating. Migrating, in this sense, also means deploying to an environment. Please see `truffle-config.js` for network connection details. ## Install mkdir near-pet-shop cd near-pet-shop npx truffle unbox near-examples/near-pet-shop ## Get NEAR Betanet account If you don't have a NEAR Betanet account, please create one using the Wallet interface at: https://wallet.betanet.near.org ## Betanet migration **Note**: for instructions on migrating to a local NEAR environment, please read [these instructions](https://docs.near.org/docs/evm/evm-local-setup). Replace `YOUR_NAME` in the command below and run it: env NEAR_MASTER_ACCOUNT=YOUR_NAME.betanet npx truffle migrate --network near_betanet ## Run the web app npm run betanet On this site you'll see a grid of pets to adopt with corresponding **Adopt** buttons. The first time you run this app, the **Adopt** buttons will be disabled until you've logged in. Click on the **Login** button in the upper-right corner of the screen. You will be redirected to the NEAR Betanet Wallet and asked to confirm creating a function-call access key, which you'll want to allow. After allowing, you're redirected back to Pet Shop, and a special key exists in your browser's local storage. Now you can adopt a pet! Once you've clicked the **Adopt** button pay attention to the top of the page, as a link to NEAR Explorer will appear. (This is similar to [etherscan](https://etherscan.io/) for Ethereum.) ## Testing Run a local `nearcore` node following [these instructions](https://docs.near.org/docs/evm/evm-local-setup#set-up-near-node). Then run: npm run test ### Troubleshooting During development while changing the Solidity code, if unexpected behavior continues, consider removing the `build` folder and migrating again.