repoName
stringlengths
7
77
tree
stringlengths
0
2.85M
readme
stringlengths
0
4.9M
francessNewdev_foodiz-near-101
README.md README LICENSE.txt 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 foodiz index.js css style.css index.css index.js reportWebVitals.js test.js utils config.js foodiz.js near.js
<div id="top"></div> [![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"> [//]: # (<img src="./README/images/logo.png" alt="Logo" width="80" height="80" />) [//]: # ( <a href="https://github.com/othneildrew/Best-README-Template">) [//]: # ( </a>) <h3 align="center">FOODIZ HUB</h3> </div> ![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/cloudy.png) Simple DApp that allows user to buy meal from multiple Restaurants at the same time. The dapp uses two contracts, the meal contract, where information about the meal is stored and the order contract which stores the order information for the user. User's can add their own stores and payment are made to a the foodiz hub payment address which is defined in the order contract. Live demo [here](https://foodiz-near.netlify.app/) <!-- GETTING STARTED --> ## :point_down: Getting Started ### Prerequisites - [Node.js](https://nodejs.org/en/) v16.xx.x ### Run locally 1. Clone repo 2. Install packages ```sh npm install ``` 3. Run application ```sh npm start ``` 4. Open development server on http://localhost:3000 <p align="right">(<a href="#top">back to top</a>)</p> ![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/cloudy.png) ## :computer: Development: Connect to testnet wallet - Create account on testnet using [MyAlgo Wallet](https://wallet.myalgo.com/) - Add funds using [faucet](https://bank.testnet.algorand.network/) - Start app, click "Connect Wallet" and use MyAlgo Wallet UI to connect testnet wallet <p align="right">(<a href="#top">back to top</a>)</p> ![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/cloudy.png) <!-- CONTRIBUTING --> ## :writing_hand: 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> ![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/cloudy.png) <!-- LICENSE --> ## :policeman: License Distributed under the MIT License. See `LICENSE.txt` for more information. <p align="right">(<a href="#top">back to top</a>)</p> ![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/cloudy.png) <!-- CONTACT --> ## :iphone: Contact Visit us at - [Dacade](https://dacade.org) <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/dacadeorg/algorand-react-marketplace.svg?style=for-the-badge [contributors-url]: https://github.com/dacadeorg/algorand-react-marketplace/graphs/contributors [forks-shield]: https://img.shields.io/github/forks/dacadeorg/algorand-react-marketplace.svg?style=for-the-badge [forks-url]: https://github.com/dacadeorg/algorand-react-marketplace/network/members [stars-shield]: https://img.shields.io/github/stars/dacadeorg/algorand-react-marketplace.svg?style=for-the-badge [stars-url]: https://github.com/dacadeorg/algorand-react-marketplace/stargazers [issues-shield]: https://img.shields.io/github/issues/dacadeorg/algorand-react-marketplace.svg?style=for-the-badge [issues-url]: https://github.com/dacadeorg/algorand-react-marketplace/issues [license-shield]: https://img.shields.io/github/license/dacadeorg/algorand-react-marketplace.svg?style=for-the-badge [license-url]: ./README/LICENSE.txt [product-screenshot]: ./README/images/shot1.png [product-screenshot-2]: ./README/images/shot2.png # 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.
near_schemafy
.github ISSUE_TEMPLATE BOUNTY.yml .travis.yml Cargo.toml README.md build.rs publish.sh schemafy_core Cargo.toml src lib.rs one_or_many.rs schemafy_lib Cargo.toml src generator.rs lib.rs schema.json schema.rs tests multiple-property-types.json test.rs src generate_tests.rs lib.rs main.rs test.sh tests any-properties.json array-type.json debugserver-schema.json empty-struct.json enum-names-int.json enum-names-str.json json_schema_test_suite.rs nested.json one-of-types.json option-type.json pattern-properties.json recursive_types.json root-array.json support schema-test.rs test.rs vega vega.json version.sh
# schemafy [![Build Status](https://travis-ci.org/Marwes/schemafy.svg?branch=master)](https://travis-ci.org/Marwes/schemafy) [![Docs](https://docs.rs/schemafy/badge.svg)](https://docs.rs/schemafy) This is a Rust crate which can take a [JSON schema (draft 4)](http://json-schema.org/) and generate Rust types which are serializable with [serde](https://serde.rs/). No checking such as `min_value` are done but instead only the structure of the schema is followed as closely as possible. As a schema could be arbitrarily complex this crate makes no guarantee that it can generate good types or even any types at all for a given schema but the crate does manage to bootstrap itself which is kind of cool. ## Example Generated types for VS Codes [debug server protocol][]: <https://docs.rs/debugserver-types> [debug server protocol]:https://code.visualstudio.com/docs/extensions/example-debuggers ## Development The types generated by the JSON schema specification can be regenerated with `cargo build --features internal-regenerate` if changes have been made in the library itself. Rustfmt is required so that `src/schema.rs` is readable.
near_abi
.github ISSUE_TEMPLATE BOUNTY.yml README.md
<div align="center"> <h1><code>NEAR ABI</code></h1> <p> <strong>ABI schema format and tooling to define interface to NEAR smart contracts.</strong> </p> </div> ⚠️ **Warning: Format and tooling are not final and changes are likely to happen.** > What is an ABI? An ABI (Application Binary Interface) traditionally defines the interface between two binary program modules. In the context of the NEAR ABI, this JSON schema defines the interface to the Wasm binary (smart contract) on the NEAR network, including parameter and result formats used through the NEAR runtime. > Why do we need ABI? - Human-readable format to easy indicate how to interact with the contract - Standard interface definition cross-language - Ability to be used with any combination of contract SDK and client libraries - Tooling built using the ABI to be able to generate code to interact with any contract easily ## Usage ### Rust Ensure you have [cargo-near](https://github.com/near/cargo-near) installed To generate an ABI for a contract within the directory containing contract's Cargo.toml ```console $ cargo near abi ``` Ensure that the project you are generating an ABI for depends on a version of `near-sdk` of `4.1.0` or later and has the `abi` feature enabled. ```toml near-sdk = { version = "4.1.0", features = ["abi"] } ``` ### TypeScript Ensure you have a [near-sdk-js](https://github.com/near/near-sdk-js) (version 0.7.0 or later) contract To generate an ABI for a contract within the directory containing contract's package.json ```console $ npx near-sdk-js build --generateABI path/to/contract.ts ``` The ABI will be put in `build/contract-abi.json` ## Supported tools: ### ABI generation - [near-sdk-rs](https://github.com/near/near-sdk-rs) (version `4.1.0` and above) and [cargo-near](https://github.com/near/cargo-near) (version `0.3.0` and above): `cargo-near` is a [cargo](https://doc.rust-lang.org/cargo/) extention that is used to build the contract and generate the ABI from a `near-sdk-rs` contract. - [near-sdk-js](https://github.com/near/near-sdk-js) (version `0.7.0` and above): invoke `near-sdk-js build` with `--generateABI` to generate the ABI from a TypeScript contract (pure JavaScript is not supported yet). ### ABI clients - [near-abi-client-rs](https://github.com/near/near-abi-client-rs): Generates glue code to interact with contracts through RPC using [workspaces-rs](https://github.com/near/workspaces-rs). - [near-sdk-abi](https://github.com/near/near-sdk-abi): Generates [near-sdk-rs](https://github.com/near/near-sdk-rs) glue code to make cross-contract calls within other contracts. - [near-api-js](https://github.com/near/near-api-js): integration with NAJ is coming soon, stay tuned. ### Utility Libraries - [near-abi-rs](https://github.com/near/near-abi-rs): Common Rust types used across Rust ABI crates. - [near-abi-js](https://github.com/near/near-abi-js): Common types used across JavaScript ABI libraries. <!-- markdownlint-disable MD014 --> # NEAR ABI Example Build a NEAR smart contract with ABI embedded, and inspect it on-chain. ## Requirements - [`cargo-near`](https://github.com/near/cargo-near) for building the smart contract. ```console $ cargo install cargo-near ``` - [`near-cli`](https://github.com/near/near-cli) for deploying the smart contract. ```console $ npm install -g near-cli ``` ## Usage - Clone and download the dependencies. ```console $ git clone https://github.com/near/abi-example $ cd abi-example $ npm install ``` - Next, we need to build and deploy a contract with ABI embedded. - Build the contract `$ cargo near build --release --embed-abi --doc --out-dir ./res` <img width="461" alt="demo" src="https://github.com/near/abi-example/raw/master/demo.png"> This would export the compiled contract to the `res` directory, with its ABI embedded within. - Deploy the contract. ```console $ NEAR_ENV=testnet near dev-deploy ./res/adder.wasm Starting deployment. Account id: dev-1661966288541-80307357536154, node: https://rpc.testnet.near.org, file: ./res/adder.wasm Transaction Id FqZPhkJ2YzFkrUXFpUetwmwtzgm9P7QMLyMtGZQhRx5u To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/FqZPhkJ2YzFkrUXFpUetwmwtzgm9P7QMLyMtGZQhRx5u Done deploying to dev-1661966288541-80307357536154 ``` - Next, inspect the ABI for the on-chain contract. (the returns JSON adhering to [this schema](https://github.com/near/near-abi-js/blob/d468185a012c77428cf07757292104fdd3e1ea0c/lib/index.d.ts)) - Quick inspection ```console $ NEAR_ENV=testnet node inspect.js dev-1661966288541-80307357536154 { schema_version: '0.3.0', metadata: { name: 'adder', version: '0.1.0', authors: [ 'Near Inc <[email protected]>' ], build: { compiler: 'rustc 1.64.0', builder: 'cargo-near 0.3.0' } }, body: { functions: [ ... ``` - Export the ABI as compact JSON (see [res/adder_abi.json](https://github.com/near/abi-example/blob/master/res/adder_abi.json) for a full output) ```console $ NEAR_ENV=testnet node inspect.js dev-1661966288541-80307357536154 --json --compact {"schema_version":"0.3.0","metadata":{"name":"adder","version":"0.1.0","authors":["Near Inc <[email protected]>"],"build":{"compiler":"rustc 1.64.0","builder":"cargo-near 0.3.0"}},"body":{"functions":[{ ... ``` - Export the raw, compressed ABI (should be the same as the file in `./res/adder_abi.zst`), you can test this with: ```console $ NEAR_ENV=testnet node inspect.js dev-1661966288541-80307357536154 --raw > contract_abi.zst $ diff -s contract_abi.zst ./res/adder_abi.zst Files contract_abi.zst and res/adder_abi.zst are identical ``` See `node inspect.js --help` for a complete list of options. - You can also install it globally if you find it useful. ```console $ npm link ``` Afterwards, you can use the `near-inspect` command anywhere instead of `node inspect.js`. ## 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 below, without any additional terms or conditions. ## 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.
near-examples_cross-contract-calls
.devcontainer devcontainer.json .github workflows tests-advanced-rs.yml tests-advanced-ts.yml tests-simple-rs.yml tests-simple-ts.yml README.md contract-advanced-rs Cargo.toml README.md rust-toolchain.toml src batch_actions.rs lib.rs multiple_contracts.rs similar_contracts.rs tests tests.rs contract-advanced-ts README.md package.json sandbox-ts main.ava.ts src contract.ts internal batch_actions.ts constants.ts multiple_contracts.ts similar_contracts.ts utils.ts tsconfig.json contract-simple-rs Cargo.toml README.md rust-toolchain.toml src external.rs lib.rs tests tests.rs contract-simple-ts README.md package.json sandbox-ts main.ava.ts src contract.ts tsconfig.json
# 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. <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) ## 1. Build and Test the Contract You can automatically compile and test the contract by running: ```bash # To solely build the contract npm run build # To build and execute the contract's tests npm run test ``` ## 2. Create an Account and Deploy the Contract You can create a new account and deploy the contract by running: ```bash near create-account <your-account.testnet> --useFaucet near deploy <your-account.testnet> ./build/cross_contract.wasm init '{"hello_account":"hello.near-example.testnet"}' ``` <br /> ## 3. CLI: Interacting with the Contract To interact with the contract through the console, you can use the following commands ```bash # Get message from the hello-near contract # Replace <your-account.testnet> with your account ID near call <your-account.testnet> query_greeting --accountId <your-account.testnet> # Set a new message for the hello-near contract # Replace <your-account.testnet> with your account ID near call <your-account.testnet> change_greeting '{"new_greeting":"XCC Hi"}' --accountId <your-account.testnet> ``` # Useful Links - [near CLI](https://near.cli.rs) - Interact with NEAR blockchain from command line - [NEAR Documentation](https://docs.near.org) - [NEAR StackOverflow](https://stackoverflow.com/questions/tagged/nearprotocol) - [NEAR Discord](https://near.chat) - [NEAR Telegram Developers Community Group](https://t.me/neardev) - NEAR DevHub: [Telegram](https://t.me/neardevhub), [Twitter](https://twitter.com/neardevhub) # 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. ## How to Build Locally? Install [`cargo-near`](https://github.com/near/cargo-near) and run: ```bash cargo near build ``` ## How to Test Locally? ```bash cargo test ``` ## How to Deploy? To deploy manually, install [`cargo-near`](https://github.com/near/cargo-near) and run: ```bash # Create a new account cargo near create-dev-account # Deploy the contract on it cargo near deploy <account-id> ``` ## CLI: Interacting with the Contract To interact with the contract through the console, you can use the following commands ```bash # Replace <your-account.testnet> with your account ID # Call batch_actions method near call <your-account.testnet> batch_actions --gas 300000000000000 --accountId <your-account.testnet> # Call multiple_contracts method near call <your-account.testnet> multiple_contracts --gas 300000000000000 --accountId <your-account.testnet> # Call similar_contracts method near call <your-account.testnet> similar_contracts --gas 300000000000000 --accountId <your-account.testnet> ``` # Useful Links - [cargo-near](https://github.com/near/cargo-near) - NEAR smart contract development toolkit for Rust - [near CLI](https://near.cli.rs) - Interact with NEAR blockchain from command line - [NEAR Rust SDK Documentation](https://docs.near.org/sdk/rust/introduction) - [NEAR Documentation](https://docs.near.org) - [NEAR StackOverflow](https://stackoverflow.com/questions/tagged/nearprotocol) - [NEAR Discord](https://near.chat) - [NEAR Telegram Developers Community Group](https://t.me/neardev) - NEAR DevHub: [Telegram](https://t.me/neardevhub), [Twitter](https://twitter.com/neardevhub) # 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. ## How to Build Locally? Install [`cargo-near`](https://github.com/near/cargo-near) and run: ```bash cargo near build ``` ## How to Test Locally? ```bash cargo test ``` ## How to Deploy? To deploy manually, install [`cargo-near`](https://github.com/near/cargo-near) and run: ```bash # Create a new account cargo near create-dev-account # Deploy the contract on it cargo near deploy <account-id> ``` ## CLI: Interacting with the Contract To interact with the contract through the console, you can use the following commands ```bash # Get message from the hello-near contract # Replace <account-id> with your account ID near call <account-id> query_greeting --accountId <account-id> # Set a new message for the hello-near contract # Replace <account-id> with your account ID near call <account-id> change_greeting '{"new_greeting":"XCC Hi"}' --accountId <account-id> ``` # Useful Links - [cargo-near](https://github.com/near/cargo-near) - NEAR smart contract development toolkit for Rust - [near CLI](https://near.cli.rs) - Interact with NEAR blockchain from command line - [NEAR Rust SDK Documentation](https://docs.near.org/sdk/rust/introduction) - [NEAR Documentation](https://docs.near.org) - [NEAR StackOverflow](https://stackoverflow.com/questions/tagged/nearprotocol) - [NEAR Discord](https://near.chat) - [NEAR Telegram Developers Community Group](https://t.me/neardev) - NEAR DevHub: [Telegram](https://t.me/neardevhub), [Twitter](https://twitter.com/neardevhub) # 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 /> # 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) ## 1. Build and Test the Contract You can automatically compile and test the contract by running: ```bash # To solely build the contract npm run build # To build and execute the contract's tests npm run test ``` ## 2. Create an Account and Deploy the Contract You can create a new account and deploy the contract by running: ```bash near create-account <your-account.testnet> --useFaucet near deploy <your-account.testnet> ./build/cross_contract.wasm init '{"hello_account":"hello.near-example.testnet", "counter_account":"counter.near-example.testnet", "guestbook_account":"guestbook.near-example.testnet"}' ``` <br /> ## 3. CLI: Interacting with the Contract To interact with the contract through the console, you can use the following commands ```bash # Replace <your-account.testnet> with your account ID # Call batch_actions method near call <your-account.testnet> batch_actions --gas 300000000000000 --accountId <your-account.testnet> # Call multiple_contracts method near call <your-account.testnet> multiple_contracts --gas 300000000000000 --accountId <your-account.testnet> # Call similar_contracts method near call <your-account.testnet> similar_contracts --gas 300000000000000 --accountId <your-account.testnet> ``` <br /> # Useful Links - [near CLI](https://near.cli.rs) - Interact with NEAR blockchain from command line - [NEAR Documentation](https://docs.near.org) - [NEAR StackOverflow](https://stackoverflow.com/questions/tagged/nearprotocol) - [NEAR Discord](https://near.chat) - [NEAR Telegram Developers Community Group](https://t.me/neardev) - NEAR DevHub: [Telegram](https://t.me/neardevhub), [Twitter](https://twitter.com/neardevhub) # Cross-Contract Call Examples 👋 [![](https://img.shields.io/badge/⋈%20Examples-Basics-green)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Contract-JS-yellow)](contract-ts) [![](https://img.shields.io/badge/Contract-Rust-red)](contract-rs) [![](https://img.shields.io/badge/Frontend-JS-yellow)](frontend) ![example workflow](https://github.com/near-examples/cross-contract-calls/actions/workflows/tests-ts.yml/badge.svg) ![example workflow](https://github.com/near-examples/cross-contract-calls/actions/workflows/tests-rs.yml/badge.svg) This repository contains examples on how to perform cross-contract calls in both JavaScript and Rust. - [contract-simple-rs](contract-simple-rs) - Rust example - [contract-simple-ts](contract-simple-ts) - JavaScript example - [contract-advanced-rs](contract-advanced-rs) - Rust advanced example - [contract-advanced-ts](ccontract-advanced-ts) - JavaScript advanced example <br /> # What These Examples Show 1. How to make cross contract call and handle their responses information in the NEAR network. 2. How to handle their responses. <br /> # Learn More 1. Learn more about the contract through its [README](./contract-ts/README.md). 2. Check [**our documentation**](https://docs.near.org/tutorials/examples/xcc).
nearprotocol_ethashproof
Readme.md build.sh cache.go cmd cache main.go epoch main.go relayer main.go dag_merkle_proof.go dag_merkle_root.go ethash algorithm.go algorithm_test.go api.go consensus.go consensus_test.go ethash.go ethash_test.go ethashproof_ext.go sealer.go sealer_test.go mtree branch.go branch_tree.go constants.go dag_mt.go merkle_tree.go util.go
jasperdg_w-near-dynamic-storage
Cargo.toml build.sh receiver Cargo.toml scripts build.sh flags.sh test.sh src lib.rs storage_manager.rs wnear Cargo.toml README.md build.sh src fungible_token_core.rs fungible_token_metadata.rs internal.rs lib.rs storage_manager.rs w_near.rs tests general.rs test_utils.rs
# TBD
Meowomen_NearYou
.travis.yml README.md babel.config.js gulpfile.js package.json src App.css App.js App.test.js Drops.js __mocks__ fileMock.js apis index.js assets gray_near_logo.svg logo.svg near.svg config.js index.html index.js jest.init.js main.test.js util near-util.js util.js wallet login index.html
# NEARYou Demo ## 🗝 Table of Contents - [About NEARYou](https://github.com/Meowomen/NEARYou#-about-nearyou) - [Getting Started](https://github.com/Meowomen/NEARYou#%EF%B8%8F-getting-started) - [How NEARYou Demo Works](https://github.com/Meowomen/NEARYou#-how-nearyou-demo-works) - [Features](https://github.com/Meowomen/NEARYou#features) - [Repo structure](https://github.com/Meowomen/NEARYou#repo-structure---src) - [Drop.js](https://github.com/Meowomen/NEARYou#dropjs) - [Suggestions](https://github.com/Meowomen/NEARYou#-suggestions) ## 🔎 About NEARYou ### For [2021 NEAR MetaBUIDL Hackathon](https://near.org/metabuidl) NEARYou allows NEAR wallet users(sender) to create a link for gifting their NFTs(Non-Fungible-Token) which follow [NEP-171](https://github.com/near/NEPs/blob/ea409f07f8/specs/Standards/NonFungibleToken/Core.md) standard. The user's friends(receiver) can claim NFT through the link. NEARYou contract stores the sender's NFT ``token_id`` and minimum amount of NEAR to activate new account. ### Contributors - [Juyeon Lee](https://github.com/kwklly) | Ewha Womans University - [Seungwon Choi](https://github.com/seungwon2) | Ewha Womans University - [Heesung Bae](https://github.com/HeesungB) | DSRV ## 🏃‍♀️ Getting Started #### Clone this repository ```jsx git clone https://github.com/Meowomen/NEARYou.git cd NEARYou ``` #### Install dependencies ```jsx yarn ``` #### Modify config.js ```jsx const CONTRACT_NAME = 'YOUR_NEARYou_CONTRACT'; const NFT_CONTRACT_NAME = 'NFT_MINTED_CONTRACT'; // account that minted your NFT ``` - Make sure to deploy [NEARYou contract](https://github.com/Meowomen/NEARYou_contract#getting-started) and init with your ``NFT_MINTED_CONTRACT`` as an argument. - If you don't have NFT, you can deploy a minting contract [here](https://github.com/kwklly/NEP171_Factory). #### Run ```jsx yarn dev ``` ## 🎨 How NEARYou Demo Works ### Features **Sender, who owns NFT:** - Login with NEAR web wallet. - Choose NFT that you want to send in ``My NFTs`` section. - Click ``Approve`` button to give authority to NEARYou contract. (This might take some time to NEAR protocol reflects the change. After a moment, the button will change to ``Drop`` automatically.) - Cilck ``Drop`` button to get link for dropping NFT. - Send copied link to receiver. - Click ``Reclaim`` button to cancel the linkdrop. (This removes the authority of NEARYou contract to transfer the sender's NFT.) **Receiver, who has NEAR wallet account:** - Login with NEAR web wallet. - Paste the link in the box and click claim button. - Get the NFT. **Receiver, who doesn’t have NEAR wallet account:** - Click the link that sender gave you. - Make new NEAR wallet account. - Get the NFT. (There could be a blockNumberSignature matching bug after creating account, but the creation and NFT-drop work successfully.) - - - ### Repo Structure - /src ```jsx ├── App.css ├── App.js ├── App.test.js ├── Drops.js ├── Drops.scss ├── __mocks__ │ └── fileMock.js ├── __snapshots__ │ └── App.test.js.snap ├── apis │ └── index.js ├── assets │ ├── gray_near_logo.svg │ ├── logo.svg │ └── near.svg ├── config.js ├── favicon.ico ├── index.html ├── index.js ├── jest.init.js ├── main.test.js ├── util │ ├── near-util.js │ └── util.js └── wallet └── login └── index.html ``` - `config.js` : manage network connection. - `Drop.js` : manage making linkdrop and claim NFT. - - - ### Drop.js Drop.js has functions that calls NEARYou contract's core function. It has `createNFTdrop()` , `approveUser()` and `getContract()` function which calls NEARYou contract's `send()` , `claim()` and ``NFT_MINTED_CONTRACT``'s `nft_approve()` . **createNFTdrop()** ```jsx async function fundDropNft(nft_id) { const newKeyPair = getNewKeyPair(); const public_key = (newKeyPair.public_key = newKeyPair.publicKey .toString() .replace("ed25519:", "")); downloadKeyFile(public_key, newKeyPair); newKeyPair.nft_id = nft_id; newKeyPair.ts = Date.now(); await addDrop(newKeyPair); const { contract } = window; try { const amount = toNear(minimumGasFee); await contract.send( { public_key: public_key, nft_id: nft_id }, BOATLOAD_OF_GAS, amount ); } catch (e) { console.warn(e); } } ``` - `createNFTdrop()` creates `newKeyPair` . - `createNFTdrop()` calls NEARYou's `send()` and passes `public key` and `nft_id` . **approveUser()** ```jsx async function approveUser(nft_id) { const account = (window.account = window.walletConnection.account()); const nftContract = await new nearApi.Contract(account, nftContractName, { viewMethods: ["get_key_balance"], changeMethods: ["nft_approve"], sender: window.currentUser.accountId, }); try { const amount = toNear(minimumGasFee); const result = await nftContract.nft_approve( { token_id: nft_id, account_id: contractName }, BOATLOAD_OF_GAS, amount ); console.log("result: ", result); } catch (e) { console.warn(e); } } ``` - `approveUser()` get current login account and nft contract. - `approveUser()` calls ``NFT_MINTED_CONTRACT``'s `nft_approve()` to give authority to the NEARYou contract. ## 🧑‍💻 Suggestions - Update [``createNewAccount``](https://github.com/near/near-wallet/blob/b98294ed8125ca63b6123f56195cc6d35995df37/packages/frontend/src/utils/wallet.js#L409) function in NEAR wallet ``fundingContract`` and ``fundingAccount`` must be included in the drop-link to receive NFT at the same time as account creation through the official wallet. However, if both exist, wallet call the function ``createNewAccountLinkdrop``, which [calls the ``create_account_and_claim``](https://github.com/near/near-wallet/blob/b98294ed8125ca63b6123f56195cc6d35995df37/packages/frontend/src/utils/wallet.js#L489) in the ``fundingContract``. For NEARYou contract to work in the official wallet, both the function name and the number of factors had to be the same. However, we needed the id of the ``NFT_MINTED_CONTRACT`` in ``create_account_and_claim`` [to transfer nft](https://github.com/Meowomen/NEARYou_contract/blob/master/src/lib.rs#L155), so we declared it a global variable through the init function because it shouldn't be hard-coded for scalability. If NEAR wallet flexibly handles account creation with ``fundingAccounts`` and ``fundingContracts``, init function will not be necessary. - Support `subaccount creation` in NEAR wallet This proposal begins with what we did not realize about the signer of the cross-contract call. When calling ``create_account`` of the ``testnet``(official contract) within the NEARYou contract, the top-level-account will be made normally because ``testnet`` signs it, but if ``NEARYou`` signs, only subAccount can be made. We realized this late, so we made subAccount using [a little trick](https://github.com/Meowomen/NEARYou_contract/blob/master/src/lib.rs#L144) because of the naming rules. We will, of course, update the contract later, but adding ``subaccount creation`` feature in official wallet can make NEAR users easily attract others through their own contract so that expand the NEAR ecosystem.
kuutamolabs_ldk-node
.github workflows build.yml kotlin.yml publish-android.yml publish-jvm.yml python.yml CHANGELOG.md Cargo.toml LICENSE.md Package.swift README.md bindings kotlin ldk-node-android gradlew.bat lib src main AndroidManifest.xml ldk-node-jvm gradlew.bat python pyproject.toml src ldk_node __init__.py test_ldk_node.py swift LDKNodeFFI.xcframework ios-arm64 LDKNodeFFI.framework Headers LDKNodeFFI-umbrella.h ios-arm64_x86_64-simulator LDKNodeFFI.framework Headers LDKNodeFFI-umbrella.h macos-arm64_x86_64 LDKNodeFFI.framework Headers LDKNodeFFI-umbrella.h Package.swift Sources LDKNode LDKNode.swift uniffi-bindgen Cargo.toml src main.rs build.rs docker-compose.yml rustfmt.toml scripts format_kotlin.sh python_create_package.sh swift_create_xcframework_archive.sh swift_update_package_checksum.py uniffi_bindgen_generate.sh uniffi_bindgen_generate_kotlin.sh uniffi_bindgen_generate_kotlin_android.sh uniffi_bindgen_generate_python.sh uniffi_bindgen_generate_swift.sh src builder.rs error.rs event.rs gossip.rs hex_utils.rs io mod.rs sqlite_store migrations.rs mod.rs test_utils.rs utils.rs vss_store.rs lib.rs logger.rs payment_store.rs peer_store.rs test functional_tests.rs mod.rs utils.rs types.rs uniffi_types.rs wallet.rs uniffi.toml
# LDK Node [![Crate](https://img.shields.io/crates/v/ldk-node.svg?logo=rust)](https://crates.io/crates/ldk-node) [![Documentation](https://img.shields.io/static/v1?logo=read-the-docs&label=docs.rs&message=ldk-node&color=informational)](https://docs.rs/ldk-node) A ready-to-go Lightning node library built using [LDK][ldk] and [BDK][bdk]. LDK Node is a self-custodial Lightning node in library form. Its central goal is to provide a small, simple, and straightforward interface that enables users to easily set up and run a Lightning node with an integrated on-chain wallet. While minimalism is at its core, LDK Node aims to be sufficiently modular and configurable to be useful for a variety of use cases. ## Getting Started The primary abstraction of the library is the [`Node`][api_docs_node], which can be retrieved by setting up and configuring a [`Builder`][api_docs_builder] to your liking and calling one of the `build` methods. `Node` can then be controlled via commands such as `start`, `stop`, `connect_open_channel`, `send_payment`, etc. ```rust use ldk_node::Builder; use ldk_node::lightning_invoice::Invoice; use ldk_node::lightning::ln::msgs::SocketAddress; use ldk_node::bitcoin::secp256k1::PublicKey; use ldk_node::bitcoin::Network; use std::str::FromStr; fn main() { let mut builder = Builder::new(); builder.set_network(Network::Testnet); builder.set_esplora_server("https://blockstream.info/testnet/api".to_string()); builder.set_gossip_source_rgs("https://rapidsync.lightningdevkit.org/testnet/snapshot".to_string()); let node = builder.build().unwrap(); node.start().unwrap(); let funding_address = node.new_onchain_address(); // .. fund address .. let node_id = PublicKey::from_str("NODE_ID").unwrap(); let node_addr = SocketAddress::from_str("IP_ADDR:PORT").unwrap(); node.connect_open_channel(node_id, node_addr, 10000, None, None, false).unwrap(); let event = node.wait_next_event(); println!("EVENT: {:?}", event); node.event_handled(); let invoice = Invoice::from_str("INVOICE_STR").unwrap(); node.send_payment(&invoice).unwrap(); node.stop().unwrap(); } ``` ## Modularity LDK Node currently comes with a decidedly opinionated set of design choices: - On-chain data is handled by the integrated [BDK][bdk] wallet. - Chain data may currently be sourced from an [Esplora][esplora] server, while support for Electrum and `bitcoind` RPC will follow soon. - Wallet and channel state may be persisted to an [SQLite][sqlite] database, to file system, or to a custom back-end to be implemented by the user. - Gossip data may be sourced via Lightning's peer-to-peer network or the [Rapid Gossip Sync](https://docs.rs/lightning-rapid-gossip-sync/*/lightning_rapid_gossip_sync/) protocol. - Entropy for the Lightning and on-chain wallets may be sourced from raw bytes or a [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic. In addition, LDK Node offers the means to generate and persist the entropy bytes to disk. ## Language Support LDK Node itself is written in [Rust][rust] and may therefore be natively added as a library dependency to any `std` Rust program. However, beyond its Rust API it also offers language bindings for [Swift][swift], [Kotlin][kotlin], and [Python][python] based on the [UniFFI](https://github.com/mozilla/uniffi-rs/). Moreover, [Flutter bindings][flutter_bindings] are also available. ## MSRV The Minimum Supported Rust Version (MSRV) is currently 1.63.0. [api_docs]: https://docs.rs/ldk-node/*/ldk_node/ [api_docs_node]: https://docs.rs/ldk-node/*/ldk_node/struct.Node.html [api_docs_builder]: https://docs.rs/ldk-node/*/ldk_node/struct.Builder.html [rust_crate]: https://crates.io/ [ldk]: https://lightningdevkit.org/ [bdk]: https://bitcoindevkit.org/ [esplora]: https://github.com/Blockstream/esplora [sqlite]: https://sqlite.org/ [rust]: https://www.rust-lang.org/ [swift]: https://www.swift.org/ [kotlin]: https://kotlinlang.org/ [python]: https://www.python.org/ [flutter_bindings]: https://github.com/LtbLightning/ldk-node-flutter
OmarMWarraich_near-dapp-react
README.md package-lock.json package.json public index.html manifest.json robots.txt src App.css App.js App.test.js index.css index.js reportWebVitals.js setupTests.js utils config.js courses.js near.js
<a name="readme-top"></a> <!-- HOW TO USE: This is an example of how you may give instructions on setting up your project locally. Modify this file to match your project and remove sections that don't apply. REQUIRED SECTIONS: - Table of Contents - About the Project - Built With - Live Demo - Getting Started - Authors - Future Features - Contributing - Show your support - Acknowledgements - License After you're finished please remove all the comments and instructions! --> <div align="center"> <img src="O-vaCorps.png" alt="logo" width="140" height="auto" /> <br/> <h3><b>README Template</b></h3> </div> <!-- TABLE OF CONTENTS --> # 📗 Table of Contents - [📖 About the Project](#about-project) - [🛠 Built With](#built-with) - [Tech Stack](#tech-stack) - [Key Features](#key-features) - [🚀 Live Demo](#live-demo) - [💻 Getting Started](#getting-started) - [Setup](#setup) - [Prerequisites](#prerequisites) - [Install](#install) - [Usage](#usage) - [Run tests](#run-tests) - [Deployment](#triangular_flag_on_post-deployment) - [👥 Authors](#authors) - [🔭 Future Features](#future-features) - [🤝 Contributing](#contributing) - [⭐️ Show your support](#support) - [🙏 Acknowledgements](#acknowledgements) - [❓ FAQ](#faq) - [📝 License](#license) <!-- PROJECT DESCRIPTION --> # 📖 [your_project_name] <a name="about-project"></a> > Describe your project in 1 or 2 sentences. **[your_project__name]** is a... ## 🛠 Built With <a name="built-with"></a> ### Tech Stack <a name="tech-stack"></a> > Describe the tech stack and include only the relevant sections that apply to your project. <details> <summary>Client</summary> <ul> <li><a href="https://reactjs.org/">React.js</a></li> </ul> </details> <details> <summary>Server</summary> <ul> <li><a href="https://expressjs.com/">Express.js</a></li> </ul> </details> <details> <summary>Database</summary> <ul> <li><a href="https://www.postgresql.org/">PostgreSQL</a></li> </ul> </details> <!-- Features --> ### Key Features <a name="key-features"></a> > Describe between 1-3 key features of the application. - **[key_feature_1]** - **[key_feature_2]** - **[key_feature_3]** <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- LIVE DEMO --> ## 🚀 Live Demo <a name="live-demo"></a> > Add a link to your deployed project. Coming Soon <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- GETTING STARTED --> ## 💻 Getting Started <a name="getting-started"></a> > Describe how a new developer could make use of your project. To get a local copy up and running, follow these steps. ### Prerequisites In order to run this project you need: <!-- Example command: ```sh gem install rails ``` --> ### Setup Clone this repository to your desired folder: <!-- Example commands: ```sh cd my-folder git clone [email protected]:myaccount/my-project.git ``` ---> ### Install Install this project with: <!-- Example command: ```sh cd my-project gem install ``` ---> ### Usage To run the project, execute the following command: <!-- Example command: ```sh rails server ``` ---> ### Run tests To run tests, run the following command: <!-- Example command: ```sh bin/rails test test/models/article_test.rb ``` ---> ### Deployment You can deploy this project using: <!-- Example: ```sh ``` --> <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- AUTHORS --> ## 👥 Author <a name="authors"></a> 👤 **OmarMWarraich** - GitHub: [@OmarMWarraich](https://github.com/OmarMWarraich) - Twitter: [@omarwarraich1](https://twitter.com/omarwarraich1) - LinkedIn: [LinkedIn](https://linkedin.com/in/o-va) <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- FUTURE FEATURES --> ## 🔭 Future Features <a name="future-features"></a> > Describe 1 - 3 features you will add to the project. - [ ] **[new_feature_1]** - [ ] **[new_feature_2]** - [ ] **[new_feature_3]** <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- CONTRIBUTING --> ## 🤝 Contributing <a name="contributing"></a> Contributions, issues, and feature requests are welcome! Feel free to check the [issues page](../../issues/). <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- SUPPORT --> ## ⭐️ Show your support <a name="support"></a> > Write a message to encourage readers to support your project If you like this project... <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- ACKNOWLEDGEMENTS --> ## 🙏 Acknowledgments <a name="acknowledgements"></a> > Give credit to everyone who inspired your codebase. I would like to thank... <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- FAQ (optional) --> ## ❓ FAQ <a name="faq"></a> > Add at least 2 questions new developers would ask when they decide to use your project. - **[Question_1]** - [Answer_1] - **[Question_2]** - [Answer_2] <p align="right">(<a href="#readme-top">back to top</a>)</p> <!-- LICENSE --> ## 📝 License <a name="license"></a> This project is [MIT](./LICENSE) licensed. _NOTE: we recommend using the [MIT license](https://choosealicense.com/licenses/mit/) - you can set it up quickly by [using templates available on GitHub](https://docs.github.com/en/communities/setting-up-your-project-for-healthy-contributions/adding-a-license-to-a-repository). You can also use [any other license](https://choosealicense.com/licenses/) if you wish._ <p align="right">(<a href="#readme-top">back to top</a>)</p>
PotLock_design-ops
.github ISSUE_TEMPLATE BOUNTY.yml README.md
# Design & Operations Repo A repo to put designs, specs, and operations related things for 🫕 PotLock UML Diagram https://PotLock.io/uml Figma https://PotLock.io/figma
kehindeegunjobi93_NEAR-dev-practice
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
https://app.patika.dev/courses/near-developer-course/practice-II-First-three-tasks ## 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)
nearnautnft_pups-nft-contract
Cargo.toml README.md build.sh src approval.rs enumeration.rs events.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs royalty.rs
# TBD
noemk2_enviar_recivir_rs
Cargo.toml README.md build.sh src lib.rs
Hola mundo en near con Rust ================== Introducción a holamundo en near (Rust) ================== un holamundo en near protocol, este contrato te perminte: 1. print "Hello world" 2. print "Hello " + $USER 👨‍💻 Instalación en local =========== Para correr este proyecto en local debes seguir los siguientes pasos: Paso 1: Pre - Requisitos ------------------------------ 1. Asegúrese de tener todos los [prequisitos para compilar en rust] (Install Rustup , Add wasm target to your toolchain) 3. Crear un test near account [NEAR test account] 4. Instalar el NEAR CLI globally: [near-cli] es una interfaz de linea de comando (CLI) para interacturar con NEAR blockchain yarn install --global near-cli Step 2: Configura tu NEAR CLI ------------------------------- Configura tu near-cli para autorizar su cuenta de prueba creada recientemente: near login Step 3: Clonar Repositorio ------------------------------- Este comando nos permite clonar el repositorio de nuestro proyecto ```bash git clone https://github.com/noemk2/holamundo_rs.git ``` Una vez que hayas descargado el repositorio, asegurate de ejecutar los comandos dentro del repositorio descargado. Puedes hacerlo con ```bash cd holamundo_rs/ ``` Step 4: Realiza el BUILD para implementación de desarrollo de contrato inteligente ------------------------------------------------------------------------------------ Instalar dependencias ```bash cargo check ``` Cree el código de contrato inteligente e implemente el servidor de desarrollo local: ```bash sh build.sh ``` Cree la variable local $CONTRACT_NAME (permite guardar tu contrato temporal en una variable facil de recordar) ```bash source ./neardev/dev-account.env ``` ¡Felicitaciones, ahora tendrá un entorno de desarrollo local ejecutándose en NEAR TestNet! ✏️ Comando view : request estatico ----------------------------------------------- Permite imprimir "Hello world" Para Linux: ```bash near view $CONTRACT_NAME hello_world --account-id <username>.testnet ``` ✏️ Comando call : request dinamico -------------------------------------------- Permite imprimir "Hello " + <username> .testnet Para Linux : ```bash near call $CONTRACT_NAME hello --account-id <username>.testnet ``` 🤖 Test ================== Las pruebas son parte del desarrollo, luego, para ejecutar las pruebas en el contrato inteligente , debe ejecutar el siguiente comando: ```bash cargo test -- --nocapture ``` ============================================== [create-near-app]: https://github.com/near/create-near-app [prequisitos para compilar en rust]: https://github.com/near/near-sdk-rs#pre-requisites [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [NEAR test account]: https://docs.near.org/docs/develop/basics/create-account#creating-a-testnet-account
NEAR-Analytics_SocialDB_Archive_Metrics
data_check.py extract_commits.py readme.md
oleksandrmarkelov_NCD.L1.goodAdvice
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 advice __tests__ advice.unit.spec.ts asconfig.json assembly index.ts model.ts 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) 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)
kdbvier_Near-NFT
.gitpod.yml Cargo.toml README-Windows.md README.md build.bat build.sh flags.sh nft Cargo.toml src lib.rs res README.md test-approval-receiver Cargo.toml src lib.rs test-token-receiver Cargo.toml src lib.rs tests sim main.rs test_approval.rs test_core.rs test_enumeration.rs utils.rs
# Folder that contains wasm files Non-fungible Token (NFT) =================== [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near-examples/NFT) This repository includes an example implementation of a [non-fungible token] contract which uses [near-contract-standards] and [simulation] tests. [non-fungible token]: https://nomicon.io/Standards/NonFungibleToken/README.html [near-contract-standards]: https://github.com/near/near-sdk-rs/tree/master/near-contract-standards [simulation]: https://github.com/near/near-sdk-rs/tree/master/near-sdk-sim Prerequisites ============= If you're using Gitpod, you can skip this step. * Make sure Rust is installed per the prerequisites in [`near-sdk-rs`](https://github.com/near/near-sdk-rs). * Make sure [near-cli](https://github.com/near/near-cli) is installed. Explore this contract ===================== The source for this contract is in `nft/src/lib.rs`. It provides methods to manage access to tokens, transfer tokens, check access, and get token owner. Note, some further exploration inside the rust macros is needed to see how the `NonFungibleToken` contract is implemented. Building this contract ====================== Run the following, and we'll build our rust project up via cargo. This will generate our WASM binaries into our `res/` directory. This is the smart contract we'll be deploying onto the NEAR blockchain later. ```bash ./build.sh ``` Testing this contract ===================== We have some tests that you can run. For example, the following will run our simple tests to verify that our contract code is working. ```bash cargo test -- --nocapture ``` The more complex simulation tests aren't run with this command, but we can find them in `tests/sim`. Using this contract =================== ### Quickest deploy You can build and deploy this smart contract to a development account. [Dev Accounts](https://docs.near.org/docs/concepts/account#dev-accounts) are auto-generated accounts to assist in developing and testing smart contracts. Please see the [Standard deploy](#standard-deploy) section for creating a more personalized account to deploy to. ```bash near dev-deploy --wasmFile res/non_fungible_token.wasm ``` Behind the scenes, this is creating an account and deploying a contract to it. On the console, notice a message like: >Done deploying to dev-1234567890123 In this instance, the account is `dev-1234567890123`. A file has been created containing a key pair to the account, located at `neardev/dev-account`. To make the next few steps easier, we're going to set an environment variable containing this development account id and use that when copy/pasting commands. Run this command to set the environment variable: ```bash source neardev/dev-account.env ``` You can tell if the environment variable is set correctly if your command line prints the account name after this command: ```bash echo $CONTRACT_NAME ``` The next command will initialize the contract using the `new` method: ```bash near call $CONTRACT_NAME new_default_meta '{"owner_id": "'$CONTRACT_NAME'"}' --accountId $CONTRACT_NAME ``` To view the NFT metadata: ```bash near view $CONTRACT_NAME nft_metadata ``` ### Standard deploy This smart contract will get deployed to your NEAR account. For this example, please create a new NEAR account. Because NEAR allows the ability to upgrade contracts on the same account, initialization functions must be cleared. If you'd like to run this example on a NEAR account that has had prior contracts deployed, please use the `near-cli` command `near delete`, and then recreate it in Wallet. To create (or recreate) an account, please follow the directions in [Test Wallet](https://wallet.testnet.near.org) or ([NEAR Wallet](https://wallet.near.org/) if we're using `mainnet`). In the project root, log in to your newly created account with `near-cli` by following the instructions after this command. near login To make this tutorial easier to copy/paste, we're going to set an environment variable for our account id. In the below command, replace `MY_ACCOUNT_NAME` with the account name we just logged in with, including the `.testnet` (or `.near` for `mainnet`): ID=MY_ACCOUNT_NAME We can tell if the environment variable is set correctly if our command line prints the account name after this command: echo $ID Now we can deploy the compiled contract in this example to your account: near deploy --wasmFile res/non_fungible_token.wasm --accountId $ID NFT contract should be initialized before usage. More info about the metadata at [nomicon.io](https://nomicon.io/Standards/NonFungibleToken/Metadata.html). But for now, we'll initialize with the default metadata. near call $ID new_default_meta '{"owner_id": "'$ID'"}' --accountId $ID We'll be able to view our metadata right after: near view $ID nft_metadata Then, let's mint our first token. This will create a NFT based on Olympus Mons where only one copy exists: near call $ID nft_mint '{"token_id": "0", "receiver_id": "'$ID'", "token_metadata": { "title": "Olympus Mons", "description": "Tallest mountain in charted solar system", "media": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Olympus_Mons_alt.jpg/1024px-Olympus_Mons_alt.jpg", "copies": 1}}' --accountId $ID --deposit 0.1 Transferring our NFT ==================== Let's set up an account to transfer our freshly minted token to. This account will be a sub-account of the NEAR account we logged in with originally via `near login`. near create-account alice.$ID --masterAccount $ID --initialBalance 10 Checking Alice's account for tokens: near view $ID nft_tokens_for_owner '{"account_id": "'alice.$ID'"}' Then we'll transfer over the NFT into Alice's account. Exactly 1 yoctoNEAR of deposit should be attached: near call $ID nft_transfer '{"token_id": "0", "receiver_id": "alice.'$ID'", "memo": "transfer ownership"}' --accountId $ID --depositYocto 1 Checking Alice's account again shows us that she has the Olympus Mons token. Notes ===== * The maximum balance value is limited by U128 (2**128 - 1). * JSON calls should pass U128 as a base-10 string. E.g. "100". * This does not include escrow functionality, as ft_transfer_call provides a superior approach. An escrow system can, of course, be added as a separate contract or additional functionality within this contract. AssemblyScript ============== Currently, AssemblyScript is not supported for this example. An old version can be found in the [NEP4 example](https://github.com/near-examples/NFT/releases/tag/nep4-example), but this is not recommended as it is out of date and does not follow the standards the NEAR SDK has set currently.
glue3_frontback
.eslintrc.json .prettierrc.json .vscode settings.json README.md lint-staged.config.js next-env.d.ts next.config.js package.json prisma migrations 20220913111809_init migration.sql migration_lock.toml public images near_icon.svg near_logo.svg vercel.svg src components CryptoInput types.ts grommetTheme.ts hooks redux.ts useGetBalance.ts useGetStats.ts near config.ts initContract.ts types.ts pages api apiKey.ts sendFromFund.ts sendToFund.ts redux api nearQuote.ts store.ts walletSlice.ts routes.ts styles Home.module.css globals.css utils numbers.ts tsconfig.json
# GLU3 Frontend and Backend GLU3 App built with Next.js + TypeScript + ESLint. # Get started ``` # Install dependencies yarn # Start dev server yarn dev # Start tests (or yarn test --watch for watch mode) yarn test # Lint (the dot is important) yarn lint . # If we want to build yarn build ``` # Technical choices - ESLint and Prettier are integrated with VSCode out of the box (you just need VSCode's ESLint plugin). - Prettier is integrated with ESLint, so you do not need the Prettier plugin. - Improved lint-staged configuration: linting will only happen on staged files, not all files. - Because of Husky settings, Typescript types and linting are checked before each commit. If for some reason you want to ignore and commit anyway you can use the `--no-verify` flag. (ex.: `git commit --no-verify -m "Updated README.md"`) For automatic ES-Lint corrections on VSCode you can add this setting on you environment: ``` // .vscode/settings.json { "editor.formatOnSave": false, "editor.codeActionsOnSave": { "source.fixAll.eslint": true } } ``` For the same in Webstorm follow these instructions: `https://www.jetbrains.com/help/webstorm/eslint.html#ws_eslint_configure_run_eslint_on_save` # GLU3 Design ## Factory Contract ``` deploy() createToken( tokenName: string, symbol: string, supply: number, decimals: number, canMint: boolean, canBurn: boolean ) ``` ## Child Contract ``` ft_transfer(receiver_id, amount) sendToFund(id, amount) sendFromFund(id, amount, walletAddress) ``` ## Backend REST API (to be used with generated API Key) - `GET /sendToFund?apiKey&amount&id` (send tokens of a user without a wallet to the temporary fund) - `POST /sendFromFund` (tokens that were stored on the temporary funds can be claimed via this API) ## WARNING! This project was coded in only 2 days for the Nearcon 2022 Hackathon. Therefore, it is just a proof of concept. The API routes are not secured whatsoever. Don't use this code in production!
longvuit18_marketplace-near-contract
Cargo.toml README.md build.sh deploy.sh src lib.rs
# Marketplace - mint - auction - bid - claim_nft - Claim_near - return_nft
jpzhangvincent_nft-hot-pot
README.md backend artworks attributes 0.json 1.json 10.json 11.json 12.json 13.json 14.json 15.json 16.json 17.json 18.json 19.json 2.json 20.json 21.json 22.json 23.json 24.json 25.json 26.json 27.json 28.json 29.json 3.json 30.json 31.json 32.json 33.json 34.json 35.json 36.json 37.json 38.json 39.json 4.json 5.json 6.json 7.json 8.json 9.json hardhat.config.js hardhat.config.ts package-lock.json package.json scripts config.json deploy.ts metadata.js verify.ts tsconfig.json chainlink_functions API-request-example.js Functions-request-config-chatgpt.js Functions-request-config-nftmetadataapi.js Functions-request-config.js FunctionsSandboxLibrary Functions.js Log.js Sandbox.js Validator.js buildRequest.js encryptSecrets.js getRequestConfig.js handler.js index.js simulateRequest.js NFTTokenMetadata-api.js OpenAIChatGPT-api.js OpenAIDALLE-api.js README.md build artifacts @chainlink contracts src v0.4 ERC677Token.sol ERC677Token.dbg.json ERC677Token.json LinkToken.sol LinkToken.dbg.json LinkToken.json interfaces ERC20.sol ERC20.dbg.json ERC20.json ERC20Basic.sol ERC20Basic.dbg.json ERC20Basic.json ERC677.sol ERC677.dbg.json ERC677.json ERC677Receiver.sol ERC677Receiver.dbg.json ERC677Receiver.json vendor BasicToken.sol BasicToken.dbg.json BasicToken.json SafeMathChainlink.sol SafeMathChainlink.dbg.json SafeMathChainlink.json StandardToken.sol StandardToken.dbg.json StandardToken.json v0.8 AutomationBase.sol AutomationBase.dbg.json AutomationBase.json AutomationCompatible.sol AutomationCompatible.dbg.json AutomationCompatible.json ConfirmedOwner.sol ConfirmedOwner.dbg.json ConfirmedOwner.json ConfirmedOwnerWithProposal.sol ConfirmedOwnerWithProposal.dbg.json ConfirmedOwnerWithProposal.json dev ocr2 OCR2Abstract.sol OCR2Abstract.dbg.json OCR2Abstract.json interfaces AggregatorV3Interface.sol AggregatorV3Interface.dbg.json AggregatorV3Interface.json AutomationCompatibleInterface.sol AutomationCompatibleInterface.dbg.json AutomationCompatibleInterface.json ERC677ReceiverInterface.sol ERC677ReceiverInterface.dbg.json ERC677ReceiverInterface.json LinkTokenInterface.sol LinkTokenInterface.dbg.json LinkTokenInterface.json OwnableInterface.sol OwnableInterface.dbg.json OwnableInterface.json TypeAndVersionInterface.sol TypeAndVersionInterface.dbg.json TypeAndVersionInterface.json vendor BufferChainlink.sol BufferChainlink.dbg.json BufferChainlink.json CBORChainlink.sol CBORChainlink.dbg.json CBORChainlink.json @openzeppelin contracts-upgradeable proxy utils Initializable.sol Initializable.dbg.json Initializable.json security PausableUpgradeable.sol PausableUpgradeable.dbg.json PausableUpgradeable.json utils AddressUpgradeable.sol AddressUpgradeable.dbg.json AddressUpgradeable.json ContextUpgradeable.sol ContextUpgradeable.dbg.json ContextUpgradeable.json contracts access Ownable.sol Ownable.dbg.json Ownable.json interfaces draft-IERC1822.sol IERC1822Proxiable.dbg.json IERC1822Proxiable.json proxy ERC1967 ERC1967Proxy.sol ERC1967Proxy.dbg.json ERC1967Proxy.json ERC1967Upgrade.sol ERC1967Upgrade.dbg.json ERC1967Upgrade.json Proxy.sol Proxy.dbg.json Proxy.json beacon IBeacon.sol IBeacon.dbg.json IBeacon.json transparent ProxyAdmin.sol ProxyAdmin.dbg.json ProxyAdmin.json TransparentUpgradeableProxy.sol TransparentUpgradeableProxy.dbg.json TransparentUpgradeableProxy.json utils Address.sol Address.dbg.json Address.json Context.sol Context.dbg.json Context.json StorageSlot.sol StorageSlot.dbg.json StorageSlot.json build-info 2b652466804e49120613e4a56c4fa475.json contracts AutomatedFunctionsConsumer.sol AutomatedFunctionsConsumer.dbg.json AutomatedFunctionsConsumer.json FunctionsConsumer.sol FunctionsConsumer.dbg.json FunctionsConsumer.json dev AuthorizedReceiver.sol AuthorizedReceiver.dbg.json AuthorizedReceiver.json functions AuthorizedOriginReceiver.sol AuthorizedOriginReceiver.dbg.json AuthorizedOriginReceiver.json AuthorizedOriginReceiverUpgradeable.sol AuthorizedOriginReceiverUpgradeable.dbg.json AuthorizedOriginReceiverUpgradeable.json ConfirmedOwnerUpgradeable.sol ConfirmedOwnerUpgradeable.dbg.json ConfirmedOwnerUpgradeable.json Functions.sol Functions.dbg.json Functions.json FunctionsBillingRegistry.sol FunctionsBillingRegistry.dbg.json FunctionsBillingRegistry.json FunctionsClient.sol FunctionsClient.dbg.json FunctionsClient.json FunctionsOracle.sol FunctionsOracle.dbg.json FunctionsOracle.json interfaces AuthorizedOriginReceiverInterface.sol AuthorizedOriginReceiverInterface.dbg.json AuthorizedOriginReceiverInterface.json AuthorizedReceiverInterface.sol AuthorizedReceiverInterface.dbg.json AuthorizedReceiverInterface.json FunctionsBillingRegistryInterface.sol FunctionsBillingRegistryInterface.dbg.json FunctionsBillingRegistryInterface.json FunctionsClientInterface.sol FunctionsClientInterface.dbg.json FunctionsClientInterface.json FunctionsOracleInterface.sol FunctionsOracleInterface.dbg.json FunctionsOracleInterface.json ocr2 OCR2Base.sol OCR2Base.dbg.json OCR2Base.json OCR2BaseUpgradeable.sol OCR2BaseUpgradeable.dbg.json OCR2BaseUpgradeable.json vendor openzeppelin-solidity v.4.8.0 contracts security Pausable.sol Pausable.dbg.json Pausable.json utils Context.sol Context.dbg.json Context.json SafeCast.sol SafeCast.dbg.json SafeCast.json structs EnumerableSet.sol EnumerableSet.dbg.json EnumerableSet.json v4.3.1 contracts utils Address.sol Address.dbg.json Address.json cache solidity-files-cache.json validations.json calculation-example.js contract-diff.sh hardhat.config.js helper-functions.js helper-hardhat-config.js network-config.js package-lock.json package.json scripts generateKeypair.js simulateFunctionsJavaScript.js tasks Functions-billing accept.js add.js cancel.js create.js fund.js index.js info.js remove.js timeoutRequest.js transfer.js Functions-client buildOffchainSecrets.js buildRequestJSON.js checkUpkeep.js deployAutoClient.js deployClient.js index.js performManualUpkeep.js readResultAndError.js request.js setAutoRequest.js setOracleAddr.js simulate.js accounts.js balance.js block-number.js index.js test staging APIConsumer.spec.js RandomNumberConsumer.spec.js RandomNumberDirectFundingConsumer.spec.js unit APIConsumer.spec.js AutomationCounter.spec.js PriceConsumerV3.spec.js RandomNumberConsumer.spec.js RandomNumberDirectFundingConsumer.spec.js | frontend abi nft_contract.json components walletInteract.js next.config.js package-lock.json package.json pages _app.js api getImagePrompt.js getNFTDetails.js getNftContractMetadata.js getNftImage.js getNftTokenMetadata.js getNftTokenMetadataCovalent.js getNftTokenMetadataInfura.js getNftsForCollection.js getNftsForOwner.js getOpenaiAPIs.js uploadImgFile.js uploadMetadataJson.js postcss.config.js styles Home.module.css InstructionsComponent.module.css Modal.module.css Navbar.module.css NftCollectionInfoDisplay.module.css NftGallery.module.css NftMinter.module.css globals.css tailwind.config.js utils interact.js notebook connected_wallet_data.json nft_ai_mixer_app.py package-lock.json package.json subgraph abis ERC721.json package.json src nft_hot_pot.ts
# Chainlink Functions Starter Kit - [Chainlink Functions Starter Kit](#chainlink-functions-starter-kit) - [Overview](#overview) - [Quickstart](#quickstart) - [Requirements](#requirements) - [Steps](#steps) - [Command Glossary](#command-glossary) - [Functions Commands](#functions-commands) - [Functions Subscription Management Commands](#functions-subscription-management-commands) - [Request Configuration](#request-configuration) - [JavaScript Code](#javascript-code) - [Functions Library](#functions-library) - [Modifying Contracts](#modifying-contracts) - [Simulating Requests](#simulating-requests) - [Off-chain Secrets](#off-chain-secrets) - [Automation Integration](#automation-integration) # Overview <p><b>This project is currently in a closed beta. Request access to send on-chain requests here <a href="https://functions.chain.link/">https://functions.chain.link/</a></b></p> <p>Chainlink Functions allows users to request data from almost any API and perform custom computation using JavaScript.</p> <p>It works by using a <a href="https://chain.link/education/blockchain-oracles#decentralized-oracles">decentralized oracle network</a> (DON).<br>When a request is initiated, each node in the DON executes the user-provided JavaScript code simultaneously. Then, nodes use the <a href="https://docs.chain.link/architecture-overview/off-chain-reporting/">Chainlink OCR</a> protocol to come to consensus on the results. Finally, the median result is returned to the requesting contract via a callback function.</p> <p>Chainlink Functions also enables users to share encrypted secrets with each node in the DON. This allows users to access APIs that require authentication, without exposing their API keys to the general public. # Quickstart ## Requirements - Node.js version [18](https://nodejs.org/en/download/) ## Steps 1. Clone this repository to your local machine<br><br> 2. Open this directory in your command line, then run `npm install` to install all dependencies.<br><br> 3. Set the required environment variables. 1. This can be done by copying the file *.env.example* to a new file named *.env*. (This renaming is important so that it won't be tracked by Git.) Then, change the following values: - *PRIVATE_KEY* for your development wallet - *MUMBAI_RPC_URL* or *SEPOLIA_RPC_URL* for the network that you intend to use 2. If desired, the *ETHERSCAN_API_KEY* or *POLYGONSCAN_API_KEY* can be set in order to verify contracts, along with any values used in the *secrets* object in *Functions-request-config.js* such as *COINMARKETCAP_API_KEY*.<br><br> 4. There are two files to notice that the default example will use: - *contracts/FunctionsConsumer.sol* contains the smart contract that will receive the data - *calculation-example.js* contains JavaScript code that will be executed by each node of the DON<br><br> 5. Test an end-to-end request and fulfillment locally by simulating it using:<br>`npx hardhat functions-simulate`<br><br> 6. Deploy and verify the client contract to an actual blockchain network by running:<br>`npx hardhat functions-deploy-client --network network_name_here --verify true`<br>**Note**: Make sure *ETHERSCAN_API_KEY* or *POLYGONSCAN_API_KEY* are set if using `--verify true`, depending on which network is used.<br><br> 7. Create, fund & authorize a new Functions billing subscription by running:<br> `npx hardhat functions-sub-create --network network_name_here --amount LINK_funding_amount_here --contract 0xDeployed_client_contract_address_here`<br>**Note**: Ensure your wallet has a sufficient LINK balance before running this command. Testnet LINK can be obtained at <a href="https://faucets.chain.link/">faucets.chain.link</a>.<br><br> 8. Make an on-chain request by running:<br>`npx hardhat functions-request --network network_name_here --contract 0xDeployed_client_contract_address_here --subid subscription_id_number_here` # Command Glossary Each of these commands can be executed in the following format: `npx hardhat command_here --parameter1 parameter_1_value_here --parameter2 parameter_2_value_here` Example: `npx hardhat functions-read --network mumbai --contract 0x787Fe00416140b37B026f3605c6C72d096110Bb8` ### Functions Commands | Command | Description | Parameters | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `compile` | Compiles all smart contracts | | | `functions-simulate` | Simulates an end-to-end fulfillment locally for the *FunctionsConsumer* contract | `gaslimit` (optional): Maximum amount of gas that can be used to call *fulfillRequest* in the client contract (defaults to 100,000 & must be less than 300,000) | | `functions-deploy-client` | Deploys the *FunctionsConsumer* contract | `network`: Name of blockchain network, `verify` (optional): Set to `true` to verify the deployed *FunctionsConsumer* contract (defaults to `false`) | | `functions-request` | Initiates a request from a *FunctionsConsumer* client contract using data from *Functions-request-config.js* | `network`: Name of blockchain network, `contract`: Address of the client contract to call, `subid`: Billing subscription ID used to pay for the request, `gaslimit` (optional): Maximum amount of gas that can be used to call *fulfillRequest* in the client contract (defaults to 100,000 & must be less than 300,000), `requestgas` (optional): Gas limit for calling the *executeRequest* function (defaults to 1,500,000), `simulate` (optional): Flag indicating if simulation should be run before making an on-chain request (defaults to true) | | `functions-read` | Reads the latest response (or error) returned to a *FunctionsConsumer* or *AutomatedFunctionsConsumer* client contract | `network`: Name of blockchain network, `contract`: Address of the client contract to read | | `functions-deploy-auto-client` | Deploys the *AutomatedFunctionsConsumer* contract and sets the Functions request using data from *Functions-request-config.js* | `network`: Name of blockchain network, `subid`: Billing subscription ID used to pay for Functions requests, `gaslimit` (optional): Maximum amount of gas that can be used to call *fulfillRequest* in the client contract (defaults to 250000), `interval` (optional): Update interval in seconds for Chainlink Automation to call *performUpkeep* (defaults to 300), `verify` (optional): Set to `true` to verify the deployed *AutomatedFunctionsConsumer* contract (defaults to `false`), `simulate` (optional): Flag indicating if simulation should be run before making an on-chain request (defaults to true) | | `functions-check-upkeep` | Checks if *checkUpkeep* returns true for an Automation compatible contract | `network`: Name of blockchain network, `contract`: Address of the contract to check, `data` (optional): Hex string representing bytes that are passed to the *checkUpkeep* function (defaults to empty bytes) | | `functions-perform-upkeep` | Manually call *performUpkeep* in an Automation compatible contract | `network`: Name of blockchain network, `contract`: Address of the contract to call, `data` (optional): Hex string representing bytes that are passed to the *performUpkeep* function (defaults to empty bytes) | | `functions-set-auto-request` | Updates the Functions request in deployed *AutomatedFunctionsConsumer* contract using data from *Functions-request-config.js* | `network`: Name of blockchain network, `contract`: Address of the contract to update, `subid`: Billing subscription ID used to pay for Functions requests, `interval` (optional): Update interval in seconds for Chainlink Automation to call *performUpkeep* (defaults to 300), `gaslimit` (optional): Maximum amount of gas that can be used to call *fulfillRequest* in the client contract (defaults to 250,000) | | `functions-set-oracle-addr` | Updates the oracle address for a client contract using the *FunctionsOracle* address from *network-config.js* | `network`: Name of blockchain network, `contract`: Address of the client contract to update | | `functions-build-request` | Creates a JSON file with Functions request parameters including encrypted secrets, using data from *Functions-request-config.js* | `network`: Name of blockchain network, `output` (optional): Output JSON file name (defaults to *Functions-request.json*), `simulate` (optional): Flag indicating if simulation should be run before building the request JSON file (defaults to true) | | `functions-build-offchain-secrets` | Builds an off-chain secrets object that can be uploaded and referenced via URL | `network`: Name of blockchain network, `output` (optional): Output JSON file name (defaults to *offchain-secrets.json*) | ### Functions Subscription Management Commands | Command | Description | Parameters | | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `functions-sub-create` | Creates a new Functions billing subscription for Functions client contracts | `network`: Name of blockchain network, `amount` (optional): Initial amount used to fund the subscription in LINK (decimals are accepted), `contract` (optional): Address of the client contract to add to the subscription | | `functions-sub-info` | Gets the Functions billing subscription balance, owner, and list of authorized client contract addresses | `network`: Name of blockchain network, `subid`: Subscription ID | | `functions-sub-fund` | Funds a Functions billing subscription with LINK | `network`: Name of blockchain network, `subid`: Subscription ID, `amount`: Amount to fund subscription in LINK (decimals are accepted) | | `functions-sub-cancel` | Cancels a Functions billing subscription and refunds the unused balance. Cancellation is only possible if there are no pending requests. | `network`: Name of blockchain network, `subid`: Subscription ID, `refundaddress` (optional): Address where the remaining subscription balance is sent (defaults to caller's address) | | `functions-sub-add` | Authorizes a client contract to use the Functions billing subscription | `network`: Name of blockchain network, `subid`: Subscription ID, `contract`: Address of the client contract to authorize for billing | | `functions-sub-remove` | Removes a client contract from a Functions billing subscription | `network`: Name of blockchain network, `subid`: Subscription ID, `contract`: Address of the client contract to remove from billing subscription | | `functions-sub-transfer` | Request ownership of a Functions subscription be transferred to a new address | `network`: Name of blockchain network, `subid`: Subscription ID, `newowner`: Address of the new owner | | `functions-sub-accept` | Accepts ownership of a Functions subscription after a transfer is requested | `network`: Name of blockchain network, `subid`: Subscription ID | | `functions-timeout-requests` | Times out expired requests | `network`: Name of blockchain network, `requestids`: 1 or more request IDs to timeout separated by commas | # Request Configuration Chainlink Functions requests can be configured by modifying values in the `requestConfig` object found in the *Functions-request-config.js* file located in the root of this repository. | Setting Name | Description | | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `codeLocation` | This specifies where the JavaScript code for a request is located. Currently, only the `Location.Inline` option is supported (represented by the value `0`). This means the JavaScript string is provided directly in the on-chain request instead of being referenced via a URL. | | `secretsLocation` | This specifies where the encrypted secrets for a request are located. `Location.Inline` (represented by the value `0`) means encrypted secrets are provided directly on-chain, while `Location.Remote` (represented by `1`) means secrets are referenced via encrypted URLs. | | `codeLanguage` | This specifies the language of the source code which is executed in a request. Currently, only `JavaScript` is supported (represented by the value `0`). | | `source` | This is a string containing the source code which is executed in a request. This must be valid JavaScript code that returns a Buffer. See the [JavaScript Code](#javascript-code) section for more details. | | `secrets` | This is a JavaScript object which contains secret values that are injected into the JavaScript source code and can be accessed using the name `secrets`. This object will be automatically encrypted by the tooling using the DON public key before making an on-chain request. This object can only contain string values. | | `walletPrivateKey` | This is the EVM private key. It is used to generate a signature for the encrypted secrets such that the secrets cannot be reused by an unauthorized 3rd party. | | `args` | This is an array of strings which contains values that are injected into the JavaScript source code and can be accessed using the name `args`. This provides a convenient way to set modifiable parameters within a request. | | `expectedReturnType` | This specifies the expected return type of a request. It has no on-chain impact, but is used by the CLI to decode the response bytes into the specified type. The options are `uint256`, `int256`, `string`, or `Buffer`. | | `secretsURLs` | This is an array of URLs where encrypted off-chain secrets can be fetched when a request is executed if `secretsLocation` == `Location.Remote`. This array is converted into a space-separated string, encrypted using the DON public key, and used as the `secrets` parameter on-chain. | | `perNodeOffchainSecrets` | This is an array of `secrets` objects that enables the optional ability to assign a separate set of secrets for each node in the DON if `secretsLocation` == `Location.Remote`. It is used by the `functions-build-offchain-secret` command. See the [Off-chain Secrets](#off-chain-secrets) section for more details. | | `globalOffchainSecrets` | This is a default `secrets` object that can be used by DON members to process a request. It is used by the `functions-build-offchain-secret` command. See the [Off-chain Secrets](#off-chain-secrets) section for more details. | ## JavaScript Code The JavaScript source code for a Functions request can use vanilla Node.js features, but *cannot* use any `require` statements or imported modules other than the built-in modules `buffer`, `crypto`, `querystring`, `string_decoder`, `url`, and `util`. It must return a JavaScript Buffer which represents the response bytes that are sent back to the requesting contract. Encoding functions are provided in the [Functions library](#functions-library). Additionally, the script must return in **less than 10 seconds** or it will be terminated and send back an error to the requesting contract. In order to make HTTP requests, the source code must use the `Functions.makeHttpRequest` function from the exposed [Functions library](#functions-library). Asynchronous code with top-level `await` statements is supported, as shown in the file *API-request-example.js*. ### Functions Library The `Functions` library is injected into the JavaScript source code and can be accessed using the name `Functions`. In order to make HTTP requests, only the `Functions.makeHttpRequest` function can be used. All other methods of accessing the Internet are restricted. The function takes an object with the following parameters. ``` { url: String with the URL to which the request is sent, method (optional): String specifying the HTTP method to use which can be either 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', or 'OPTIONS' (defaults to 'GET'), headers (optional): Object with headers to use in the request, params (optional): Object with URL query parameters, data (optional): Object which represents the body sent with the request, timeout (optional): Number with the maximum request duration in ms (defaults to 5000 ms), responseType (optional): String specifying the expected response type which can be either 'json', 'arraybuffer', 'document', 'text' or 'stream' (defaults to 'json'), } ``` The function returns a promise that resolves to either a success response object or an error response object. A success response object will have the following parameters. ``` { error: false, data: Response data sent by the server, status: Number representing the response status, statusText: String representing the response status, headers: Object with response headers sent by the server, } ``` An error response object will have the following parameters. ``` { error: true, message (may be undefined): String containing error message, code (may be undefined): String containing an error code, response (may be undefined): Object containing response sent from the server, } ``` This library also exposes functions for encoding JavaScript values into Buffers which represent the bytes that a returned on-chain. - `Functions.encodeUint256` takes a positive JavaScript integer number and returns a Buffer of 32 bytes representing a `uint256` type in Solidity. - `Functions.encodeInt256` takes a JavaScript integer number and returns a Buffer of 32 bytes representing a `int256` type in Solidity. - `Functions.encodeString` takes a JavaScript string and returns a Buffer representing a `string` type in Solidity. Remember, it is not required to use these encoding functions. The JavaScript code must only return a Buffer which represents the `bytes` array that is returned on-chain. ## Modifying Contracts Client contracts which initiate a request and receive a fulfillment can be modified for specific use cases. The only requirements are that the contract successfully calls *sendRequest* in the *FunctionsOracle* contract and correctly implements their own *handleOracleFulfillment* function. At this time, the maximum amount of gas that *handleOracleFulfillment* can use is 300,000. See *FunctionsClient.sol* for details. ## Simulating Requests An end-to-end request initiation and fulfillment can be simulated for the default *FunctionsConsumer* contract using the `functions-simulate` command. This command will report the total estimated gas use. If the *FunctionsConsumer* client contract is modified, this task must also be modified to accomodate the changes. See `tasks/Functions-client/simulate` for details. **Note:** The actual gas use on-chain can vary, so it is recommended to set a higher fulfillment gas limit when making a request to account for any differences. ## Off-chain Secrets Instead of using encrypted secrets stored directly on the blockchain, encrypted secrets can also be hosted off-chain and be fetched by DON nodes via HTTP when a request is initiated. Off-chain secrets also enable a separate set of secrets to be assigned to each node in the DON. Each node will not be able to decrypt the set of secrets belonging to another node. Optionally, a set of default secrets encrypted with the DON public key can be used as a fallback by any DON member who does not have a set of secrets assigned to them. This handles the case where a new member is added to the DON, but the assigned secrets have not yet been updated. To use per-node assigned secrets, enter a list of secrets objects into `perNodeOffchainSecrets` in *Functions-request-config.js* before running the `functions-build-offchain-secrets` command. The number of objects in the array must correspond to the number of nodes in the DON. Default secrets can be entered into the `globalOffchainSecrets` parameter of `Functions-request-config.js`. Each secrets object must have the same set of entries, but the values for each entry can be different (ie: `[ { apiKey: '123' }, { apiKey: '456' }, ... ]`). If the per-node secrets feature is not desired, `perNodeOffchainSecrets` can be left empty and a single set of secrets can be entered for `globalOffchainSecrets`. To generate the encrypted secrets JSON file, run the command `npx hardhat functions-build-offchain-secrets --network network_name_here`. This will output the file *offchain-secrets.json* which can be uploaded to S3, Github, or another hosting service that allows the JSON file to be fetched via URL. Once the JSON file is uploaded, set `secretsLocation` to `Location.Remote` in *Functions-request-config.js* and enter the URL(s) where the JSON file is hosted into `secretsURLs`. Multiple URLs can be entered as a fallback in case any of the URLs are offline. Each URL should host the exact same JSON file. The tooling will automatically pack the secrets URL(s) into a space-separated string and encrypt the string using the DON public key so no 3rd party can view the URLs. Finally, this encrypted string of URLs is used in the `secrets` parameter when making an on-chain request. URLs which host secrets must be available every time a request is executed by DON nodes. For optimal security, it is recommended to expire the URLs when the off-chain secrets are no longer in use. # Automation Integration Chainlink Functions can be used with Chainlink Automation in order to automatically trigger a Functions request. 1. Create & fund a new Functions billing subscription by running:<br>`npx hardhat functions-sub-create --network network_name_here --amount LINK_funding_amount_here`<br>**Note**: Ensure your wallet has a sufficient LINK balance before running this command.<br><br> 2. Deploy the *AutomationFunctionsConsumer* client contract by running:<br>`npx hardhat functions-deploy-auto-client --network network_name_here --subid subscription_id_number_here --interval time_between_requests_here --verify true`<br>**Note**: Make sure `ETHERSCAN_API_KEY` or `POLYGONSCAN_API_KEY` environment variables are set. API keys for these services are freely available to anyone who creates an EtherScan or PolygonScan account.<br><br> 3. Register the contract for upkeep via the Chainlink Automation web app here: [https://automation.chain.link/](https://automation.chain.link/) - Be sure to set the `Gas limit` for the *performUpkeep* function to a high enough value. The recommended value is 1,000,000. - Find further documentation for working with Chainlink Automation here: [https://docs.chain.link/chainlink-automation/introduction](https://docs.chain.link/chainlink-automation/introduction) Once the contract is registered for upkeep, check the latest response or error with the commands `npx hardhat functions-read --network network_name_here --contract contract_address_here`. For debugging, use the command `npx hardhat functions-check-upkeep --network network_name_here --contract contract_address_here` to see if Automation needs to call *performUpkeep*. To manually trigger a request, use the command `npx hardhat functions-perform-upkeep --network network_name_here --contract contract_address_here`. # NFT Hot Pot: On-Chain AI Gen Platform [ETHDenver Presentation](https://docs.google.com/presentation/d/1qgnQlnpZBb8RAfWI0yK9XUZrxenIdtdG8moeLtU4OQg/edit?usp=sharing) [Deployed Web App](https://nft-hot-pot-poc.vercel.app/) NFT Hot Pot is an on-chain NFT AI generator that enables a user to select existing NFTs as inputs and generate a new unique NFT that mixes the artistic features of the inputed NFT’s. The created NFT can be dynamically updated by being added to the mixer again. The metadata of the input NFT's are extracted using the Covalent and Alchemy NFT API. The metadata text is then used as input for ChatGPT to generate a DALL-E image prompt which is fed into DALL-E to generate an image. Both the ChatGPT and DALL-E API's are called by Chainlink Functions. The tool is available on the Ethereum, Polygon, Scroll, and NEAR Aurora chains with possibilities of other chains down the line. NFT Hot Pot provides a unique opportunity to combine and collaborate NFT’s across different collections. # **Problem Statement** - It is the stepping stone for AI Gen tools on chain, where the use of NFT’s can create an creditable development platform and tracking system for generated art - Collaboration Between NFT Projects: Foster friendship instead of hostility across NFT collections as there are few ways to have different NFT’s projects interact or integrate with each other - Increased Exposure: Collaboration between NFT collections can help to increase exposure and visibility for all the collections involved. By pooling audiences and cross-promoting each other's work, collections can reach a wider audience and attract new collectors and investors. - Incentivize artists to move art on-chain to collect royalties if their art is used for generative creations - Finally, this will help fill a gap in the NFT space regarding the lack of dynamic NFT’s, as generated NFT’s can be changed further by being thrown back into the mixer, adding a whole slew of potential art and gamification possibilities. - Prompt engineering can be challenging for generative Art. We come up with an innovative approach to automatically suggest a "creative" prompt from chatGPT by synthesizing the NFT metadata with a pre-defined prompt. This helps lower the barriers for normal users to onboard and experient with web3 dApp. # Smart contract Deployment | Chain/Protocol | Contract/Function Name | Contract Address | Code File | Note | |----------------|---------------|--------------------------------------------------------------------------------------------------------------------------------------|---------------------------------|-----------------------------| | Polygon Mumbai | NFTAIMixer | [0xe15560062F770d3fc89A8eFc0E4774dF8Be7F99b](https://mumbai.polygonscan.com/address/0xe15560062F770d3fc89A8eFc0E4774dF8Be7F99b#code) | backend/contract/NFTAIMixer.sol | ERC721 with royalty | | Base Testnet | NFTAIMixer | [0x098914A6Cc4A2F5Cb0A626F2D0998F50A0b9504a](https://base-goerli.blockscout.com/address/0x098914A6Cc4A2F5Cb0A626F2D0998F50A0b9504a) | backend/contract/NFTAIMixer.sol | `yarn deploy:baseTestnet` | | Aurora Testnet | NFTAIMixer | [0x378c52E95d11fa6F78E3B948936DefdF5981cfc8](https://explorer.testnet.aurora.dev/address/0x378c52E95d11fa6F78E3B948936DefdF5981cfc8) | backend/contract/NFTAIMixer.sol | `yarn deploy:auroraTestnet` | | Scroll Testnet | NFTAIMixer | [0x378c52E95d11fa6F78E3B948936DefdF5981cfc8](https://blockscout.scroll.io/address/0x378c52E95d11fa6F78E3B948936DefdF5981cfc8) | backend/contract/NFTAIMixer.sol | `yarn deploy:scrollTestnet` | | Chainlink Functions | OpenAIChatGPT-api | OxC5dd70292f94C9EA88a856d455C43974BA756824 | chainlink_functions/OpenAIChatGPT-api.js | Subscription ID: 272 | | Chainlink Functions | OpenAIDALLE-api | 0x454bf2056d13Aa85e24D9c0886083761dbE64965 | chainlink_functions/OpenAIDALLE-api.js | Subscription ID: 279 | Since the workflow depends on the Chainlink Functions which only supports Eth and Polygon networks, the frontend UI focuses on the polygon mumbai integration. # Workflow ## Mint Workflow - Mint Workflow: A generative AI algorithm that creates a generated NFT based on NFTs selected by the user ### Beginning User Interaction - User enters NFT Hot Pot Dapp - User connects wallet using ‘Connect’ button in top right of screen - User selects network and address - User’s wallet NFT’s are listed in the Dapp - User selects any number of NFT’s, ideally multiple ### Auto-Prompt Creation - Interface populates prompt field using ChatGPT with the description of each NFT in an image prompt - Prompt created is an ask to create a DALL-E image prompt containing the two character's metadata - Future developments to contain more rich image generation capabilities not yet live - Example: - Based on a description of the below characters, can you please provide a DALL-E image prompt detailing a picture involving the two? Character 1: Blue cloak Azuki female with rings. Character 2: Golden Bored Ape with pirate hat - User can edit prompt Note that the success is depending on the availability and quality of the NFT metadata, which supports the value and promise of bringing the creative art process on-chain. ### Image Generation - User generates NFT by clicking ‘Generate’ button - Image generated by DALL-E appears on Dapp - NFT image has 'prompt', 'temperature', 'model', ‘news’ metadata fields, in addition to its descriptive metadata fields - User has option to rerun image generation or edit prompt - User can then mint NFT to wallet ## Dynamic Workflow: - User selects any number of NFT’s and any original ‘NFT Hot Pot’ generated NFT from wallet - Interface populates prompt field using ChatGPT with the description of each NFT in an image prompt - Prompt should be an ask to create a DALL-E prompt that will create an image containing the two character's metadata - Future developments to contain more rich image generation capabilities - User has option to rerun image generation or edit prompt - User updates NFT (permanently) # Video Demo [Video Demo](https://www.youtube.com/watch?v=LB0xvEnllxI) # Future Improvements - **NFT upload as input:** Image uploading would allow for more accurate generated images, enriching the resulting art. - **NFT inpainting and outpainting:** DALL-E editor would enable more user control and customization over the generated image. Tools such as Midjourney Blend (no API currently) would allow for further flexibility - **Dynamic theft security:** The NFT can be dynamically updated to blackout if stolen - **Platform for the on-chain AI gen NFTs:** Create a valuable resource for developer to being transitioning AI technologies onto the blockchain - **Marketplace for AI gen mixed art:** Carve out a niche space in the market for combined art - **Gameification** enable competitive incentive system for generating dynamic art metadata # Primary Users - Any NFT holder, enthusiast, or fanatic that would like to explore further creativity for their interactions across collections. This includes gamers, collectors, and just about any NFT user. In addition, this provides an opportunity for like minded people to share their unique art with each other and allow users to indirectly own other collections - NFT artists who would like to receive credit and royalties for art used in AI image generators. There is an additional incentive of additional royalties when the NFT is returned to NFT Hot Pot to be dynamically updated. - Developers, who want to experiment with decentralized on-chain AI tools that can be incorporated into the generative workflow. Furthermore, an AI workflow that can synthesize from multiple images using on-chain NFT metadata when there exists no end-to-end image AI mixer algorithm in the market can be utilized as a development tool. # Challenges Faces By Project - Creating aesthetically pleasing art with the correct prompt: At the moment, NFT Hot Pot is limited by the metadata available from each NFT. Current limitations in the DALL-E API and Hackathon time limits prevent us from adding novel AI techniques such as inpainting, outpainting, 3D creations, and blending. Furthermore, limitations in current generative AI API's prevent two or more specific images to show up as near exact copies within a generative image. This level of accuracy would create a stronger affinity for the art from NFT users as the input NFT's would be less modified from their original state. - Legality of using someone else’s art: There is always an issue of legality when it comes to using other's art for inspiration, as it generally is accompanied by potential accusations of plagiarism. The royalty system and chain ledger seeks to address this problem, but is in no way a perfect and still subject to legal action. - Creating a healthy ecosystem to excite users to generate NFT’s: Like any NFT project, obtaining traction and market is one of the most difficult challenges. Beyond traditional means of marketing, creating momentum and community is a competitive environment with other NFT collections vying for the same attention from NFT collectors. Reputation and popularity are further challenges that all NFT’s must face in this market. # Bounties - Chainlink Bounty: Chainlink Functions is used to integrate OpenAI API’s such as ChatGPT for auto-test prompt generation and DALL-E for image generation. The enablement of the dapp to reach web2 API’s quickly and conveniently is a huge saver for the dev team. In addition, Chainlink Functions was able to provide the most rich NFT metadata in order to enhance the robustness and data quality of NFT metadata. However, we were not able to fully integrate this functionality without further testing. In addition, we could not access the Infura API key which prevented the full development of the feature, however this is a promising use case for future development - ETHStorage: ETHStorage was easy and straightforward to use in storing NFT metadata. The dapp could be defined as a dynamic on-chain dapp that uses the web3:// Access Protocol - Covalent: We primarily used Covalent to synthesize multiple images for analysis in addition to Node.js API integration testing, proving the API to be useful in multiple facets of integration. But we also noticed that the data coverage of metadata from Covalent was lacking compared to the Alchemy API. - Graph: The build and deployment of a custom subgraph using the GraphQL API was successfully used to index data from a smart contract. The blockchain data was queried to the dapp. - Infura: The Infura API key was not available to hackathon users the past few days. We had requested the key to be released in the official ETHDenver discord to no avail. As such, Infura was not implemented into the app. - Near Aurora: Near Aurora was added as a layer. The online documentation was easy to follow for the hardhat implementation. - Polygon: We not only decided to deploy to Polygon, but we deployed there first based on Polygon’s growing reputation and low fees in the space. - Base: Base also proved to be an easy later to add, with minimal additions to the config file. - Stellar: TBD - Scroll: Scroll layer was also an easy add. A challenge was that one of the docs on the bounty description was a dead URL. We were still able to find resources online and add the network. - Lens: The Lens protocol share button was easily implemented into the front end, thanks to the html snippet provided in the tutorial. The button worked as intended and highlighted the important of having easy to use buttons/widgets/attachments to pages when wanting to expand a protocol such as Lens.
iamfortune_NCD-01--dice
README.md babel.config.js contract Cargo.toml README.md build.sh compile.js src lib.rs tests test_utils.rs copy-dev-account.js jest.config.js package.json src __mocks__ fileMock.js assets logo-black.svg logo-white.svg config.js global.css jest.init.js main.js main.test.js utils.js wallet login index.html tests unit Notification.spec.js SignedIn.spec.js SignedOut.spec.js
NCD-GroupA-Demo Smart Contract ================== A demo contract for NCD Pojrect Phase-1. Play with this contract ======================== the contract is deployed at testnet with the name `dev-1614240595058-5266655` you can set it to env for later use: ```shell export CONTRACTID=dev-1614240595058-5266655 ``` ## Look around ```shell # return playground info near view $CONTRACTID get_contract_info '' # return winner tip rate near view $CONTRACTID get_reward_fee_fraction '' # return win history list near view $CONTRACTID get_win_history '{"from_index": 0, "limit": 100}' # return dice count that alice has near view $CONTRACTID get_account_dice_count '{"account_id": "alice.testnet"}' ``` ## Let's play ```shell # attached 3 Near to buy 3 dices near call $CONTRACTID buy_dice '' --amount=3 --account_id=alice.testnet #check user's dice, would return 3 here near view $CONTRACTID get_account_dice_count '{"account_id": "alice.testnet"}' # roll dice 3 times, say how luck you are near call $CONTRACTID roll_dice '{"target": 1}' --account_id=alice.testnet near call $CONTRACTID roll_dice '{"target": 3}' --account_id=alice.testnet near call $CONTRACTID roll_dice '{"target": 4}' --account_id=alice.testnet ``` Build Deploy and Init ====================== Before you compile this code, you will need to install Rust with [correct target] ```shell # building it srouce ./build.sh ``` ```shell # dev-deploy or deploy it near dev-deploy res/neardice.wasm # say it was deploy at $CONTRACTID, then init it near call $CONTRACTID new \ '{"owner_id": "boss.testnet", "dice_number": 1, "rolling_fee": "1000000000000000000000000", "reward_fee_fraction": {"numerator": 5, "denominator": 100}}' \ --account_id=$CONTRACTID ``` ```shell # last step to open the playgroud is # to deposit to the jackpod the very first time near call $CONTRACTID deposit_jackpod '' --amount=50 --account_id=boss.testnet ``` 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 NCD-GroupA-Demo ================== This is a homework demo project for NCD program phase-1. Rolling Dice On NEAR ==================== Guys, let's roll dice on NEAR. ## Why dice Randomness is always a key focus on any blockchain. We wanna show you how convenient that a random number can get on NEAR blockchain. To achieve that, it is hard to believe there is a better way than to make a dice dapp. Beyond what you can see in this demo, NEAR can even generate independent randomness not per block, but per receipt! ## How to play On home page, user can see the whole status of playground without login, i.e. an NEAR account is not necessary. He would have full imformation about owner account of this contract, dice price, commission fee rate, the size of current jackpod and etc. Then, user can login with NEAR account and buy several dices. With dices bought, he can guess a number and roll dice again and again. If the dice point is equal to his guess, half of jackpod would belong to him. Otherwise the amount he paid for the dice would belong to the jackpod. During playing, the latest 20 win records would appear and be auto refreshed on screen too. About Contract ==================== It's need to be mentioned that it is a pure dapp project, which means there is no centralized backend nor data server, all persistent information is stored and mananged on NEAR chain by a contract. ## Contract Structure ```rust /// This structure describe a winning event #[derive(BorshDeserialize, BorshSerialize)] pub struct WinnerInfo { pub user: AccountId, // winner accountId pub amount: Balance, // how much he got as win reward pub height: BlockHeight, // the block hight this event happened pub ts: u64, // the timestamp this event happened } /// main structure of this contract #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct NearDice { pub owner_id: AccountId, // owner can adjust params of this playground pub dice_number: u8, // how many dices one rolling event uses pub rolling_fee: Balance, // how much a dice costs when user buys it pub jack_pod: Balance, // as name shows and half of it would belong to the winner pub owner_pod: Balance, // winner would share a tip to the playground, this is where those tips go pub reward_fee_fraction: RewardFeeFraction, // a fraction defines tip rate // an always grow vector records all win event, // as a demo, we ignore the management of its size, // but in real project, it must be taken care of, // maybe has a maximum length and remove the oldest item when exceeds. pub win_history: Vector<WinnerInfo>, // records dice user bought by his payment amount. // This map has a mechanism to shrink, // when a user's balance is reduce to zero, the entry would be removed. pub accounts: LookupMap<AccountId, Balance>, } ``` ## Contract Interface ```rust /// winner's tip rate pub struct RewardFeeFraction { pub numerator: u32, pub denominator: u32, } /// a human readable version for win event struct, used in return value to caller pub struct HumanReadableWinnerInfo { pub user: AccountId, // winner accountId pub amount: U128, // the reward he got pub height: U64, // block height the event happens pub ts: U64, // timestamp the event happens } /// status of this playground, as return value of get_contract_info pub struct HumanReadableContractInfo { pub owner: AccountId, // who runs this playground, if you feel bad, just sue him :) pub jack_pod: U128, // you know what it means pub owner_pod: U128, // winner's tip goes to here, owner can withdraw pub dice_number: u8, // how many dice we use in one rolling event pub rolling_fee: U128, // how much a dice costs when user wanna buy it } /// every roll_dice event would return this info pub struct HumanReadableDiceResult { pub user: AccountId, // who rolls pub user_guess: u8, // the number he guess pub dice_point: u8, // the number dice shows pub reward_amount: U128, // reward he got pub jackpod_left: U128, // jackpod after this event pub height: U64, // the block height when he rolls pub ts: U64, // the timestamp when he rolls } //****************/ //***** INIT *****/ //****************/ /// initialization of this contract #[init] pub fn new( owner_id: AccountId, dice_number: u8, rolling_fee: U128, reward_fee_fraction: RewardFeeFraction, ) -> Self; //***************************/ //***** OWNER FUNCTIONS *****/ //***************************/ /// deposit to jackpod, used for initalizing the very first jackpod, /// otherwise, the jackpod is initialized as 0. #[payable] pub fn deposit_jackpod(&mut self); /// withdraw ownerpod to owner's account pub fn withdraw_ownerpod(&mut self, amount: U128); /// Updates current reward fee fraction to the new given fraction. pub fn update_reward_fee_fraction(&mut self, reward_fee_fraction: RewardFeeFraction); /// Updates current dice number used in one rolling event. pub fn update_dice_number(&mut self, dice_number: u8); /// Updates current dice price. pub fn update_rolling_fee(&mut self, rolling_fee: U128); //**************************/ //***** USER FUNCTIONS *****/ //**************************/ /// user deposit near to buy dice. /// he can buy multiple dices, /// any leftover amount would refund /// eg: rolling_fee is 1 Near, he can buy_dice with 4.4 Near and got 4 dices and 0.4 Near refund. #[payable] pub fn buy_dice(&mut self); /// user roll dice once, then his available dice count would reduce by one. pub fn roll_dice(&mut self, target: u8) -> HumanReadableDiceResult; //**************************/ //***** VIEW FUNCTIONS *****/ //**************************/ /// get a list of winn events in LIFO order /// best practise is set from_index to 0, and limit to 20, /// that means to get latest 20 win events information with latest first order. pub fn get_win_history(&self, from_index: u64, limit: u64) -> Vec<HumanReadableWinnerInfo>; /// get current playground status pub fn get_contract_info(&self) -> HumanReadableContractInfo; /// get current winner tip rate pub fn get_reward_fee_fraction(&self) -> RewardFeeFraction; /// get account's available dice count pub fn get_account_dice_count(&self, account_id: String) -> u8; ``` 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/main.js` is a great place to start exploring. 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 `NCD-GroupA-Demo.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `NCD-GroupA-Demo.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 NCD-GroupA-Demo.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 || 'NCD-GroupA-Demo.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. [Vue]: https://vuejs.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
mukuls9971_NEAR-bicycle-borrow
README.md bicycle-shop-contract Cargo.toml build.sh src callbacks.rs external.rs internal.rs lib.rs offer_new.rs offer_views.rs frontend App.js config.js index.html index.js ft Cargo.toml README.md build.sh src fungible_token_core.rs fungible_token_metadata.rs internal.rs lib.rs storage_manager.rs nft-contract Cargo.toml build.sh src approval.rs enumeration.rs events.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs royalty.rs package.json
# Bicycle Borrowing Shop - Alice and Bob are two users - One Fungible token bift is used as medium of exchange for the shop - Both Alice and Bob already have 10000 tokens for both - Alice wants to lend her bicycle, so she mints an NFT with info(type: bicycle, model: 2016, owner:alice) - Alice put this NFT into shop as an offer with rent per second: 1, guarantee: 5000, max_expiry(in seconds) - Bob gets the list of NFTs in the shop and put buys it by sending the guarantee money - Bicycle shop add the borrowerID, change the status and expiry to the NFT, and save the guarantee into escrew - NFT will have two status: OFFER/ONRENT - The owner can reclaim the escrow, after expiry period of NFT.(liquidation) - The borrower can withdraw_guarantee. Bob returns the bicycle and is charged for the amount equal to days*rent. Pending amount of guarantee is returned to him. # Contracts Involved 1. Create an FT token bift 2. Create an NFT contract binft 3. Create a shop contract bi 4. Setup frontend to mint NFT and exchange NFT ## Use Makefile to setup contracts and test the execution ### test scenario: `make test` ## Creating and setting up ft accounts ## Minting token on nft ## Putting offer on shop ## Modifying offer ## borrowing on shop ## Withdraw Guarantee and return on shop ## Liquidation on shop ## Online test - Use `npm build:web && npm start` to setup basic frontend and try out the same - Change the Makefile to add appropriate accounts and call `make setupOnline` ### Actions - MintAndOffer - Alice mints an NFT token after providing the details and put it on offer - ViewOffers - Bob view the available offers - BorrowsToken - Bob applies for one of the offer providing NFT tokenID - Liquidation - Alice tries to liquidate it providing NFT tokenID - WithDrawGuarantee - Bob withdraws_guarantee by providing NFT tokenID ### Corresponding JSON Minting: `{"token_id": "hero2017","receiver_id":"alice1.testnet", "metadata": {"title": "Hero-2016 model"} }` Approval: `{"token_id": "hero2017","account_id":"shop.testkrishu.testnet", "msg": "{\"rent\": 1, \"guarantee\": 5000, \"max_duration\": 2500}" }` Borrow: `{"receiver_id":"shop.testkrishu.testnet","amount":"5000","msg": "{\"nft_contract\":\"nft.testkrishu.testnet\",\"token_id\":\"hero2017\",\"expiry\":100}","memo":"rent a bicycle"}` Liquidation: `{"nft_contract_id":"nft.testkrishu.testnet", "token_id":"hero2017"}` Withdraw: `{"nft_contract_id":"nft.testkrishu.testnet", "token_id":"hero2017"}` Minimal NEP141 + Metadata Token Launcher TBD Fork of: https://github.com/mikedotexe/nep-141-examples (basic)
mdy123_mdy123.github.io
AWS_P2 README.md cloud-cdnd-c2-final.postman_collection.json package.json src server.ts util util.ts tsconfig.json tslint.json css bootstrap.min.css face_generation helper.py problem_unittests.py first_neural_network Your_first_neural_network.html bias_generator_on_gate.py flutter caltrain_station README.md firebase_login_firestore README.md google_sheets README.md web assets AssetManifest.json FontManifest.json assets labels.txt flutter_service_worker.js index.html manifest.json one.txt image_to_text README.md insulin_dose README.md ios privacy_policy.html support.html web_scraping README.md image_classification dlnd_image_classification.html helper.py problem_unittests.py js bootstrap.min.js jquery-2.1.4.min.js language_translation dlnd_language_translation.html helper.py problem_unittests.py project.0 css project.0.css images udacity_logo.svg project.0.html project.1 css project.1.css images aa.svg codeimg.html js project.1.js project.1.html project.2 css project.2.css images aa.svg js helper.js json-data.js project.2.js project.2.html project.3 README.md css style.css index.html js app.js engine.js resources.js Collision Player project.4 README.md index.html js perfmatters.js project-2048.html project-mobile.html project-webperf.html views js main.js pizza.html project.5-1 README.md css bootstrap.min.css js bootstrap.min.js caltrain-stations.js jquery-2.1.4.min.js knockout.js map.js menu-search.js map.html project.6 README.md css icomoon.css normalize.css style.css fonts icomoon.svg index.html jasmine lib jasmine-2.1.2 boot.js console.js jasmine-html.js jasmine.css jasmine.js spec feedreader.js js app.js smart_contracts escrow_contract README.md escrow_contract.rs Escrow Contract on Near blockchain Near-SDK 4.0.0 tv_script_generation dlnd_tv_script_generation.html helper.py problem_unittests.py
# Insulin Dose Calculator ### Dart Packages - Flutter material design package <br /> https://api.flutter.dev/flutter/material/material-library.html ### Features ![image](./two_1.jpg) ```sh Data Validating - no zero value at Carb and Target G.B data fields. - only number at Carb and Target G.B data fields. ``` ![image](./one_1.jpg) ```sh The Result changes instanltly depened on the inputs. ``` # Web Scraping App ### Dart Packages - html &nbsp;&nbsp;(parsing html page)<br /> https://pub.dev/packages/html - webview_flutter &nbsp;&nbsp;(launch web page in the app)<br /> https://pub.dev/packages/webview_flutter ### Features ![image](./ws_1.jpg) ```sh Pull 100 records of data from web page each time. ``` ![image](./ws_2.jpg) ```sh Show totally of Puchase or Sell amount and company name from each record ``` ![image](./ws_3.jpg) ```sh When select the item from the list, it opens new window with three tabs (yahoo,sec and google ) for more information about that company. ``` # CalTrain Station Map App ### Dart Packages - google_maps_flutter &nbsp;&nbsp;(show google map with marker of the stations )<br /> https://pub.dev/packages/google_maps_flutter - url_launcher &nbsp;&nbsp;(launch google map on the browser from the station list)<br /> https://pub.dev/packages/url_launcher ### Features ![image](./cs_1.jpg) ```sh Show the list of stations and station markers on the map. ``` ![image](./cs_2.jpg) ```sh Marker moves to the middle of map and shows the name when you touch it on the map. ``` ![image](./cs_3.jpg) ```sh Show the map location on the browser when you touch the station from the list. ``` # Image to Text App ### Dart Packages - firebase_ml_vision &nbsp;&nbsp;( convert the image to text )<br /> https://pub.dev/packages/firebase_ml_vision - image_picker &nbsp;&nbsp;( select the image from local storage or directly from camera )<br /> https://pub.dev/packages/image_picker - url_launcher &nbsp;&nbsp;( google search the text on the browser)<br /> https://pub.dev/packages/url_launcher ### Features ![image](./it_1.jpg) ```sh Select the image from local storage or take the image directly from camera. ``` ![image](./it_2.jpg) ```sh Convert the image to text using Google firebase_ml_vision package. ``` ![image](./it_3.jpg) ```sh Google search the text translated from the image when pressed the search icon. ``` # Insulin Dose Calculator ### Dart Packages - Flutter material design package <br /> https://api.flutter.dev/flutter/material/material-library.html - HTML flutter package <br /> https://pub.dev/packages/html ### Link to the Web Version Of this App. http://mdy123.github.io/flutter/google_sheets/web/#/ ```sh - Swipe left or right to delete data - Form with data validations to input data ``` ### App Features ![image](./sheet1.jpg) ```sh Pull the data from Google Sheet. ``` ![image](./sheet2.jpg) ```sh Swipe left or right to delete data. ``` ![image](./sheet3.jpg) ```sh Data Validation before sending to Google Sheet - Null data validation - Number data validation for age - Email format data validation for email ``` ### Escrow smart contract on Near blockchain using Rust language. * [Near Blockchain](https://near.org/) * [Rust Language](https://www.rust-lang.org/) &nbsp; It has four states to complete this escrow contract. &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 1. NotInitiated, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2. AwaitingPayment, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 3. AwaitingDelivery, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 4. Complete, &nbsp; Functon "new" initializes the smart contract by assigning Buyer's Near id, Seller's Near Id and agreed Price. > * near deploy --account-id owner.escrow.testnet --wasmFile target/wasm32-unknown-unknown/release/escrow.wasm --initFunction new --initArgs '{"buyer": "buyer.escrow.testnet", "seller": "seller.escrow.testnet", "price": "5"}' &nbsp; Buyer and Seller use "init_escrow" function to sign in and change the state from "NotInitiated" to "AwaitingPayment". > * near call owner.escrow.testnet init_escrow '{}' --account-id buyer.escrow.testnet > * near call owner.escrow.testnet init_escrow '{}' --account-id seller.escrow.testnet &nbsp; Buyer uses "deposite" function to tranfer the tokens to this smart contract and changes the state from "AwaitingPayment" to "AwaitingDelivery". > * near call owner.escrow.testnet deposite '{}' --account-id buyer.escrow.testnet --amount 5 &nbsp; Buyer uses "confirm_delivery" function to transfer the tokens from this contract to seller and changes the state from "AwaitingDelivery" to "Complete". > * near call owner.escrow.testnet confirm_delivery '{}' --account-id buyer.escrow.testnet &nbsp; Owner of this contract uses "withdraw" function to canel this transaction. > * near call owner.escrow.testnet withdraw '{}' --account-id owner.escrow.testnet &nbsp; Owner of this contract uses "reset" function to reset Buyer id, Seller id, agreed Price and the state back to NotInitiated. > * near call owner.escrow.testnet reset '{}' --account-id owner.escrow.testnet &nbsp; Function "get_all_data" returns all the data of this contract. > * near view owner.escrow.testnet get_all_data '{}' --account-id buyer.escrow.testnet Project 4 - Website Performance Optimization ============================================ ### Modifications for **_index.html_** to get speed test score 90 * convert jpg to webp format. [WebP converter](https://developers.google.com/speed/webp/?hl=en) * inline css into html page. * inline google api font into html page. * asynchronously load js file. ### Modifications for **_pizza.html_** * convert jpg and png to webp format. [WebP converter](https://developers.google.com/speed/webp/?hl=en) * delete all unused css using Audit function of Chrome Dev tool. * inline css into html page. * asynchronously load js file. ###For 60 fps scrolling * ***I use the img template string (elemTemplate) and replace 'sTop' with top pixiel number,*** ***then add it to the black string (elem),*** ***and then assign that string (elem) as inner text to the parent node after the loop.*** ``` // Generates the sliding pizzas when the page loads. var basicLeft = []; document.addEventListener('DOMContentLoaded', function() { var cols = 8; var s = 256; var elemTemplate = '<img class="mover"; src="images/pizza.webp"; style="width:73.33px; height:100px; top:sTop";>'; var elem = ''; var pElem = document.querySelector("#movingPizzas1"); for (var i = 0; i < 35; i++) { basicLeft.push((i % cols) * s); elem = elem + elemTemplate.replace('sTop', ((Math.floor(i / cols) * s) + 'px')); } pElem.innerHTML = elem; updatePositions(); }); ``` * ***I move unessential items out of the movement creation loop.*** ***Then just change the margin left of pizza item to make the movement.*** ``` function updatePositions() { frame++; window.performance.mark("mark_start_frame"); var scrollTop =(document.body.scrollTop / 1250); var pizzaElem = document.querySelectorAll(".mover"); for (var i = 0; i < basicLeft.length; i++) { pizzaElem[i].style.left= basicLeft[i] + (100 * (Math.sin(scrollTop + (i % 5))) ) + 'px'; } // User Timing API to the rescue again. Seriously, it's worth learning. // Super easy to create custom metrics. window.performance.mark("mark_end_frame"); window.performance.measure("measure_frame_duration", "mark_start_frame", "mark_end_frame"); if (frame % 10 === 0) { var timesToUpdatePosition = window.performance.getEntriesByName("measure_frame_duration"); logAverageFrame(timesToUpdatePosition); } } ``` * ***I also use the same string method to generate different pizza types to increase loding time.*** ``` // This for-loop actually creates and appends all of the pizzas when the page loads var htmlStr = ''; htmlStr = htmlStr + '<div id="pizza0" class="randomPizzaContainer" style="height: 325px;"><div class="col-md-6"><img src="images/pizza.webp" class="img-responsive"> </div><div class="col-md-6"><h4>The Udacity Special</h4><ul><li>Turkey</li><li>Tofu</li><li>Cauliflower</li><li>Sun Dried Tomatoes</li><li>Velveeta Cheese </li><li>Red Sauce</li><li>Whole Wheat Crust</li></ul></div></div> '; htmlStr = htmlStr + '<div id="pizza1" class="randomPizzaContainer" style="height: 325px;"><div class="col-md-6"><img src="images/pizza.webp" class="img-responsive"> </div><div class="col-md-6"><h4>The Cameron Special</h4><ul><li>Chicken</li><li>Hot Sauce</li><li>White Crust</li></ul></div></div>'; for (var i = 2; i < 100; i++) { htmlStr = htmlStr + '<div class="randomPizzaContainer" id="pizza' + i + '" style="height: 325px;"><div class="col-md-6"><img src="images/pizza.webp" class="img-responsive"></div><div class="col-md-6"><h4>' + randomName() + '</h4><ul>' + makeRandomPizza() + '</ul></div></div>'; } document.getElementById("randomPizzas").innerHTML = htmlStr; ``` ###For <5ms resize pizza image. * ***change the css width of the pizza image class*** **_'randomPizzaContainer'_** ***instead of changing the width individually.*** ``` function changePizzaSizes(size) { var dx = determineDx(document.querySelectorAll(".randomPizzaContainer")[0], size); var newwidth = (document.querySelectorAll(".randomPizzaContainer")[0].offsetWidth + dx) + 'px'; document.styleSheets[0].cssRules[0].style.width = newwidth; } ``` Project 5-1 - Neighborhood Map ============================================ ### [Caltrain Station Map](http://www.caltrain.com/stations/systemmap.html) ### Instructions * show all the stations on the map when first load the **_map.html_**. * press **Caltrain** button on the upper left corner to show drop down list and searh input box. * when click any station on the drop down list, that station marker on the map will animate and show info window. * the marker will also animate and show info window when click it on the map directly. * marker info window include station name , address and image from Flickr. * when input any character into search box, all the matched stations will listed. * all the stations will reappear when you delete all the characters in the search box. ### Files * ./project.5-1/map.html (main html page) * ./porject.5-1/caltrain-stations.js (caltrain station json data file) * ./project.5-1/map.js (view model for map) * ./project.5-1/menu-search.js (view model for search menu) ### Frameworks * KnockoutJS * BootStrap * JQuery ### API * Google Map * Flickr (image for Marker) # Firebase Autentication and Firestore NoSql Database ### Dart Packages - firebase authentication &nbsp;&nbsp;( google cloud firebase autentication service )<br /> https://pub.dev/packages/firebase_auth - google sign-in &nbsp;&nbsp;( authenticate user using google sign-in )<br /> https://pub.dev/packages/google_sign_in - firestore nosql database &nbsp;&nbsp;( google cloud firestore database to store user information)<br /> https://pub.dev/packages/cloud_firestore ### Features ![image](./sign_in.png) ```sh Google sign-in using Google Cloud Firebase authentication service. ``` ![image](./new_user.png) ```sh New user information is saved into Firestore after successsfully sign in through Google sign-in. ``` ![image](./old_user.png) ```sh After old user successsfully sign in through Google sign-in using Firebase cloud authentication. ``` Project 6 - Feed Reader Testing ============================================ ## Testing the Feed Reader using Jasmine ### Files * ./project.6/index.html (main html page) * ./porject.6/jasmine/spec/feedreader.js (specification file) * ./project.6/js/app.js (main js file) ### Frameworks * jasmine # Udagram Image Filtering Microservice Udagram is a simple cloud application developed alongside the Udacity Cloud Engineering Nanodegree. It allows users to register and log into a web client, post photos to the feed, and process photos using an image filtering microservice. The project is split into three parts: 1. [The Simple Frontend](https://github.com/udacity/cloud-developer/tree/master/course-02/exercises/udacity-c2-frontend) A basic Ionic client web application which consumes the RestAPI Backend. [Covered in the course] 2. [The RestAPI Backend](https://github.com/udacity/cloud-developer/tree/master/course-02/exercises/udacity-c2-restapi), a Node-Express server which can be deployed to a cloud service. [Covered in the course] 3. [The Image Filtering Microservice](https://github.com/udacity/cloud-developer/tree/master/course-02/project/image-filter-starter-code), the final project for the course. It is a Node-Express application which runs a simple script to process images. [Your assignment] ## Tasks ### Setup Node Environment You'll need to create a new node server. Open a new terminal within the project directory and run: 1. Initialize a new project: `npm i` 2. run the development server with `npm run dev` ### Create a new endpoint in the server.ts file The starter code has a task for you to complete an endpoint in `./src/server.ts` which uses query parameter to download an image from a public URL, filter the image, and return the result. We've included a few helper functions to handle some of these concepts and we're importing it for you at the top of the `./src/server.ts` file. ```typescript import {filterImageFromURL, deleteLocalFiles} from './util/util'; ``` ### Deploying your system Follow the process described in the course to `eb init` a new application and `eb create` a new environment to deploy your image-filter service! Don't forget you can use `eb deploy` to push changes. ## Stand Out (Optional) ### Refactor the course RESTapi If you're feeling up to it, refactor the course RESTapi to make a request to your newly provisioned image server. ### Authentication Prevent requests without valid authentication headers. > !!NOTE if you choose to submit this, make sure to add the token to the postman collection and export the postman collection file to your submission so we can review! ### Custom Domain Name Add your own domain name and have it point to the running services (try adding a subdomain name to point to the processing server) > !NOTE: Domain names are not included in AWS’ free tier and will incur a cost. Project 3 - Arcade Game Clone ============================= ###[My Github link to play](http://mdy123.github.io/project.3/index.html) ###Instructions 1. Run * load **_index.html_** on your browser. 2. Play * use arrow keys to move around. * avoid collision with enemy bug. * score increase when the player reach the water. * score decrease when collide with enemy bug. ###contents 1. **index.html** 2. **css/style.css** 3. **js/app.js** 4. **js/engine.js** 5. **js/resources.js** 6. **images/char-boy.png** 7. **images/enemy-bug.png**
nategeier_alpha-me-bd
README.md config paths.js presets loadPreset.js webpack.analyze.js webpack.development.js webpack.production.js package.json public index.html manifest.json robots.txt src App.js components Editor AddModal.js CreateModal.js OpenModal.js RenameModal.js VsCodeBanner.js SaveDraft.js common buttons BlueButton.js Button.js GrayBorderButton.js icons ArrowUpRight.js Book.js Close.js Code.js Fork.js Home.js LogOut.js NearSocialLogo.js Pretend.js StopPretending.js User.js UserCircle.js Withdraw.js navigation Logotype.js NavigationButton.js NavigationWrapper.js NotificationWidget.js PretendModal.js SignInButton.js alpha NavigationButton.js NavigationWrapper.js NotificationWidget.js SignInButton.js desktop DesktopNavigation.js DevActionsDropdown.js NavDropdownButton.js UserDropdown.js nav_dropdown NavDropdownMenu.js NavDropdownMenuLinkList.js icons AvatarPlaceholder.js Bell.js Community.js Components.js Editor.js Education.js HouseLine.js LogOut.js Logo.js MagnifyingGlass.js Notebook.js Return.js User.js UserLarge.js Withdraw.js apps.svg code-small.svg code.svg education.svg logo-black.svg notebook.svg search.svg user-circle.svg users.svg mobile BottomNavigation.js MenuLeft.js MenuRight.js MobileNavigation.js TopNavigation.js desktop DesktopNavigation.js DevActionsDropdown.js UserDropdown.js mobile Menu.js MobileMenuButton.js MobileNavigation.js Navigation.js data links.js widgets.js hooks useHashUrlBackwardsCompatibility.js useQuery.js useScrollBlock.js images near_social_combo.svg near_social_icon.svg vs_code_icon.svg index.css index.js pages EditorPage.js EmbedPage.js ViewPage.js vercel.json webpack.config.js
# NEAR Discovery (BOS) ## Setup & Development Initialize repo: ``` yarn ``` Start development version: ``` yarn start ``` ## Component example Profile view ```jsx let accountId = props.accountId || "eugenethedream"; let profile = socialGetr(`${accountId}/profile`); <div> <img src={profile.image.url} /> <span>{profile.name}</span> <span>(@{accountId})</span> </div>; ``` Profile editor ```jsx let accountId = context.accountId; if (!accountId) { return "Please sign in with NEAR wallet"; } const profile = socialGetr(`${accountId}/profile`); if (profile === null) { return "Loading"; } initState({ name: profile.name, url: profile.image.url, }); const data = { profile: { name: state.name, image: { url: state.url, }, }, }; return ( <div> <div>account = {accountId}</div> <div> Name: <input type="text" value={state.name} /> </div> <div> Image URL: <input type="text" value={state.url} /> </div> <div>Preview</div> <div> <img src={state.url} alt="profile image" /> {state.name} </div> <div> <CommitButton data={data}>Save profile</CommitButton> </div> </div> ); ``` ## Local VM Development If you need to make changes to the VM and test locally, you can easily link your local copy of the VM: 1. Clone the viewer repo as a sibling of `near-discovery-alpha`: ``` git clone [email protected]:NearSocial/VM.git ``` Folder Structure: ``` /near-discovery-alpha /VM ``` 2. Initialize the `VM` repo and run the link command: ``` cd VM yarn yarn link yarn build ``` 3. Run the link command inside `near-discovery-alpha` and start the app: ``` cd ../near-discovery-alpha yarn link "near-social-vm" yarn start ``` 4. Any time you make changes to the `VM`, run `yarn build` inside the `VM` project in order for the viewer project to pick up the changes.
Prachi143_Polling-system-using-solidity
.gitpod.yml App.js Home.js NewPoll.js PollingStation.js README.md as-pect.config.js as-pect.d.ts as_types.d.ts asconfig.json babel.config.js blockvotelogo.svg compile.js config.js fileMock.js global.css index.html index.js index.ts jest.init.js loadingcircles.svg logo-black.svg logo-white.svg main.spec.ts main.test.js package.json tsconfig.json utils.js
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
influx6_dapp-learn
.idea aws.xml codeStyles Project.xml codeStyleConfig.xml misc.xml modules.xml vcs.xml Chapter5 README.md hardhat.config.js package-lock.json package.json scripts deploy.js tasks block-number.js test simple-storage-test.js Chapter6 artifacts @chainlink contracts src v0.6 interfaces AggregatorInterface.sol AggregatorInterface.dbg.json AggregatorInterface.json AggregatorV2V3Interface.sol AggregatorV2V3Interface.dbg.json AggregatorV2V3Interface.json AggregatorV3Interface.sol AggregatorV3Interface.dbg.json AggregatorV3Interface.json tests MockV3Aggregator.sol MockV3Aggregator.dbg.json MockV3Aggregator.json v0.8 interfaces AggregatorV3Interface.sol AggregatorV3Interface.dbg.json AggregatorV3Interface.json build-info 17d1b92d7a0f97a2e3085a34adc3f08a.json 1b8135eb034eb59d0e5b41bdbc2ae27e.json d58721367af6e07422bc3fe804d648ec.json contracts FundMe.sol FundMe.dbg.json FundMe.json PriceConverter.sol PriceConverter.dbg.json PriceConverter.json cache solidity-files-cache.json deploy 00-deploy-mocks.js o1-deploy-fund-me.js gas_report.txt hardhat.config.js helpers helper-hardhat-config.js package-lock.json package.json scripts fund.js fundMeStorage.js withdraw.js test staging fundme.staging.test.js unit fundme.test.js utils eth-verify.js web constants.js ethers-5.6.esm.min.js index.html index.js Chapter7 .solhint.json deploy 00-deploy-mocks.js o1-deploy-raffle.js gas_report.txt hardhat.config.js package.json test staging raffle.staging.test.js unit raffle.unit.test.js utils eth-verify.js helper-hardhat-config.js chapter-10 .solhint.json deploy 00-deploy-mocks.js gas_report.txt hardhat.config.js package.json scripts aaveBorrow.js getWeth.js test staging mica20.staging.test.js unit mica20.unit.test.js utils eth-verify.js helper-hardhat-config.js chapter-11 .solhint.json deploy 00-deploy-mocks.js 01-deploy-basic-nft.js 03-deploy-dynamic-nft.js 04-deploy-random-nft.js 05-deploy-nft-marketplace.js gas_report.txt hardhat.config.js images dynamicNft frown.svg happy.svg package.json scripts buy-item.js cancel-item.js mine.js mint-and-list-item.js mint.js test unit basicnft.unit.test.js randomnft.unit.test.js utils eth-verify.js helper-hardhat-config.js move-blocks.js uploadToNftStorage.js uploadToPinata.js chapter-12 .solhint.json deploy 00-deploy-box.js 00-deploy-boxv2.js 00-deploy-mocks.js gas_report.txt hardhat.config.js package.json scripts mine.js otherUpgradeExamples deploy.js prepare-upgrade.js transfer-ownership.js upgrade.js upgrade-box-manual.js test staging mica20.staging.test.js unit mica20.unit.test.js utils eth-verify.js helper-hardhat-config.js move-blocks.js uploadToNftStorage.js uploadToPinata.js chapter-13 .solhint.json deploy 00-deploy-mocks.js 01-deploy-governor-token.js 02-deploy-time-lock.js 03-deploy-governor-contract.js 04-setup-governance-contracts.js 05-deploy-box.js gas_report.txt hardhat.config.js package.json scripts mine.js propose.ts queue-and-execute.ts vote.ts test staging mica20.staging.test.js testflow.test.ts unit mica20.unit.test.js utils eth-verify.js helper-hardhat-config.js move-blocks.js move-blocks.ts move-time.ts uploadToNftStorage.js uploadToPinata.js chapter-8 .eslintrc.json README.md constants abi.json index.js next.config.js package.json pages _app.js api hello.js index.js postcss.config.js public vercel.svg styles Home.module.css globals.css tailwind.config.js chapter-9 .solhint.json deploy 00-deploy-mocks.js o1-deploy-mica20.js gas_report.txt hardhat.config.js package.json test staging mica20.staging.test.js unit mica20.unit.test.js utils eth-verify.js helper-hardhat-config.js chapter-example .solhint.json deploy 00-deploy-mocks.js gas_report.txt hardhat.config.js package.json scripts mine.js test staging mica20.staging.test.js unit mica20.unit.test.js utils eth-verify.js helper-hardhat-config.js move-blocks.js uploadToNftStorage.js uploadToPinata.js chapter4 deploy.js encryptKey.js encrypt_key.json package-lock.json package.json sources .github ISSUE_TEMPLATE code_mistake.yml config.yml repo_enhancement.yml video_mistake.yml README.md chronological-updates.md dao-template .gitpod.yml .solhint.json README.md deploy 01-deploy-governor-token.ts 02-deploy-time-lock.ts 03-deploy-governor-contract.ts 04-setup-governance-contracts.ts 05-deploy-box.ts hardhat.config.ts helper-functions.ts helper-hardhat-config.ts package.json scripts propose.ts queue-and-execute.ts vote.ts test unit testflow.test.ts tsconfig.json utils move-blocks.ts move-time.ts dapp-examples Call-Delegate-Call-and-MultiCall-master ._README.md ._hardhat.config.js ._package-lock.json ._package.json README.md hardhat.config.js package-lock.json package.json scripts ._sample-script.js sample-script.js test ._sample-test.js sample-test.js Dex-Aggregator-master ._README.md ._hardhat.config.js ._package-lock.json ._package.json README.md hardhat.config.js package.json public ._index.html ._manifest.json ._robots.txt index.html manifest.json robots.txt scripts ._deploy.js deploy.js src ._App.css ._App.js ._App.test.js ._index.css ._index.js ._logo.svg ._reportWebVitals.js ._setupTests.js ABIs ._USDCContract.json ._WETHContract.json USDCContract.json WETHContract.json App.css App.js App.test.js components ._Navbar.js ._Swap.css ._Swap.js Navbar.js Swap.css Swap.js index.css index.js logo.svg reportWebVitals.js setupTests.js test ._testDexAggregator.js testDexAggregator.js Opensea-NFT-Visualizer-master ._README.md ._package-lock.json ._package.json README.md package.json public ._index.html ._manifest.json ._robots.txt index.html manifest.json robots.txt src ._App.css ._App.js ._App.test.js ._index.css ._index.js ._logo.svg ._reportWebVitals.js ._setupTests.js App.css App.js App.test.js index.css index.js logo.svg reportWebVitals.js setupTests.js art_generator-master ._README.md ._package-lock.json ._package.json README.md helpers ._attributes.js ._metadata.js attributes.js metadata.js package-lock.json package.json scripts ._create.js ._generateRarityConfig.js ._regenerateMetadata.js create.js generateRarityConfig.js regenerateMetadata.js settings ._config.json config.json crypto-token-index-fund-master ._README.md ._hardhat.config.js ._package-lock.json ._package.json README.md hardhat.config.js package-lock.json package.json public ._index.html ._manifest.json ._robots.txt index.html manifest.json robots.txt scripts ._deploy.js deploy.js src ._App.css ._App.js ._App.test.js ._index.css ._index.js ._logo.svg ._reportWebVitals.js ._setupTests.js App.css App.js App.test.js artifacts @chainlink contracts src v0.8 interfaces AggregatorV3Interface.sol ._AggregatorV3Interface.dbg.json ._AggregatorV3Interface.json AggregatorV3Interface.dbg.json AggregatorV3Interface.json build-info ._b54754c1e0a9a41dac69d6a53bfbb84a.json b54754c1e0a9a41dac69d6a53bfbb84a.json src contracts IndexFund.sol ._IndexFund.dbg.json ._IndexFund.json IndexFund.dbg.json IndexFund.json cache ._solidity-files-cache.json hardhat-network-fork ._recommendations-already-shown.json recommendations-already-shown.json solidity-files-cache.json index.css index.js logo.svg reportWebVitals.js setupTests.js test ._sample-test.js sample-test.js dapp-examples.sb-e932c94d-Gut0DG juicyswap-frontend-master ._README.md ._package-lock.json ._package.json ._tsconfig.json README.md package-lock.json package.json public ._index.html ._manifest.json ._robots.txt index.html manifest.json robots.txt src ._setupTests.js assets img metamask-fox.svg wallet-connect.svg components Button index.ts Card index.ts CardContent index.ts CardIcon index.ts CardTitle index.ts Container index.ts Dial index.ts DisclaimerModal index.ts Footer index.ts Icon index.ts IconButton index.ts Input index.ts Label index.ts Loader index.ts Logo index.ts MobileMenu index.ts Modal index.ts ModalActions index.ts ModalContent index.ts ModalTitle index.ts Page index.ts PageHeader index.ts Separator index.ts Spacer index.ts SushiIcon index.ts TokenInput index.ts TopBar index.ts Value index.ts WalletProviderModal index.ts icons index.ts constants abi ERC20.json tokenAddresses.ts contexts Farms ._index.ts context.ts index.ts types.ts Modals index.ts SushiProvider index.ts Transactions ._context.ts ._index.ts ._reducer.ts ._types.ts context.ts index.ts reducer.ts types.ts hooks useAllEarnings.ts useAllStakedValue.ts useAllowance.ts useAllowanceStaking.ts useApprove.ts useApproveStaking.ts useBlock.ts useEarnings.ts useEnter.ts useFarm.ts useFarms.ts useLeave.ts useModal.ts usePendingTransactions.ts useRedeem.ts useReward.ts useStake.ts useStakedBalance.ts useSushi.ts useTokenBalance.ts useTransactionAdder.ts useUnharvested.ts useUnstake.ts index.css logo.svg react-app-env.d.ts setupTests.js sushi Sushi.js index.js lib abi erc20.json masterchef.json sushi.json uni_v2_lp.json weth.json xsushi.json accounts.js constants.js contracts.js evm.js types.js utils.js theme colors.ts index.ts utils erc20.ts formatAddress.ts formatBalance.ts index.ts views Farm index.ts Farms index.ts Home index.ts types.ts StakeXSushi index.ts Staking index.ts tsconfig.json workers-site ._index.js ._package-lock.json ._package.json index.js package-lock.json package.json dapp-examples.sb-e932c94d-j71idV Foundry-Overview-master .github workflows test.yml README.md foundry.toml lib forge-std .github workflows tests.yml README.md openzeppelin-contracts ._.codecov.yml ._.mocharc.js ._.solcover.js ._.solhint.json ._CHANGELOG.md ._CODE_OF_CONDUCT.md ._CONTRIBUTING.md ._DOCUMENTATION.md ._GUIDELINES.md ._README.md ._RELEASING.md ._SECURITY.md ._hardhat.config.js ._netlify.toml ._package-lock.json ._package.json ._renovate.json ._slither.config.json .codecov.yml .github ._PULL_REQUEST_TEMPLATE.md ISSUE_TEMPLATE ._bug_report.md ._config.yml ._feature_request.md bug_report.md config.yml feature_request.md PULL_REQUEST_TEMPLATE.md actions setup ._action.yml action.yml workflows ._checks.yml ._docs.yml ._upgradeable.yml checks.yml docs.yml upgradeable.yml .mocharc.js .solcover.js .solhint.json CHANGELOG.md CODE_OF_CONDUCT.md CONTRIBUTING.md DOCUMENTATION.md GUIDELINES.md README.md RELEASING.md SECURITY.md audit ._2017-03.md 2017-03.md certora ._README.md README.md scripts ._Governor.sh ._GovernorCountingSimple-counting.sh ._WizardControlFirstPriority.sh ._WizardFirstTry.sh ._sanity.sh ._verifyAll.sh Governor.sh GovernorCountingSimple-counting.sh WizardControlFirstPriority.sh WizardFirstTry.sh sanity.sh verifyAll.sh contracts package.json token ERC1155 presets README.md ERC20 presets README.md ERC721 presets README.md docs ._antora.yml ._helpers.js antora.yml helpers.js hardhat.config.js hardhat env-contract.js logo.svg netlify.toml package.json renovate.json scripts ._gen-nav.js ._git-user-config.sh ._helpers.js ._migrate-imports.js ._prepack.sh ._prepare-contracts-package.sh ._prepare-docs-solc.js ._prepare-docs.sh ._prepare.sh ._remove-ignored-artifacts.js ._update-docs-branch.js checks ._generation.sh ._inheritance-ordering.js generation.sh inheritance-ordering.js gen-nav.js generate ._format-lines.js ._run.js format-lines.js run.js templates ._SafeCast.js ._SafeCastMock.js SafeCast.js SafeCastMock.js git-user-config.sh helpers.js migrate-imports.js prepack.sh prepare-contracts-package.sh prepare-docs-solc.js prepare-docs.sh prepare.sh release ._release.sh ._synchronize-versions.js ._update-changelog-release-date.js ._update-comment.js ._version.sh release.sh synchronize-versions.js update-changelog-release-date.js update-comment.js version.sh remove-ignored-artifacts.js update-docs-branch.js slither.config.json test ._TESTING.md ._migrate-imports.test.js TESTING.md access ._AccessControl.behavior.js ._AccessControl.test.js ._AccessControlCrossChain.test.js ._AccessControlEnumerable.test.js ._Ownable.test.js AccessControl.behavior.js AccessControl.test.js AccessControlCrossChain.test.js AccessControlEnumerable.test.js Ownable.test.js crosschain ._CrossChainEnabled.test.js CrossChainEnabled.test.js finance PaymentSplitter.test.js VestingWallet.behavior.js VestingWallet.test.js governance ._Governor.test.js ._TimelockController.test.js Governor.test.js TimelockController.test.js compatibility ._GovernorCompatibilityBravo.test.js GovernorCompatibilityBravo.test.js extensions ._GovernorComp.test.js ._GovernorERC721.test.js ._GovernorPreventLateQuorum.test.js ._GovernorTimelockCompound.test.js ._GovernorTimelockControl.test.js ._GovernorWeightQuorumFraction.test.js ._GovernorWithParams.test.js GovernorComp.test.js GovernorERC721.test.js GovernorPreventLateQuorum.test.js GovernorTimelockCompound.test.js GovernorTimelockControl.test.js GovernorWeightQuorumFraction.test.js GovernorWithParams.test.js utils ._Votes.behavior.js ._Votes.test.js Votes.behavior.js Votes.test.js helpers ._create2.js ._crosschain.js ._customError.js ._eip712.js ._enums.js ._erc1967.js ._governance.js ._sign.js ._txpool.js create2.js crosschain.js customError.js eip712.js enums.js erc1967.js governance.js sign.js txpool.js metatx ._ERC2771Context.test.js ._MinimalForwarder.test.js ERC2771Context.test.js MinimalForwarder.test.js migrate-imports.test.js proxy ._Clones.behaviour.js ._Clones.test.js ._Proxy.behaviour.js Clones.behaviour.js Clones.test.js ERC1967 ._ERC1967Proxy.test.js ERC1967Proxy.test.js Proxy.behaviour.js beacon ._BeaconProxy.test.js ._UpgradeableBeacon.test.js BeaconProxy.test.js UpgradeableBeacon.test.js transparent ._ProxyAdmin.test.js ._TransparentUpgradeableProxy.behaviour.js ._TransparentUpgradeableProxy.test.js ProxyAdmin.test.js TransparentUpgradeableProxy.behaviour.js TransparentUpgradeableProxy.test.js utils ._Initializable.test.js ._UUPSUpgradeable.test.js Initializable.test.js UUPSUpgradeable.test.js security ._Pausable.test.js ._PullPayment.test.js ._ReentrancyGuard.test.js Pausable.test.js PullPayment.test.js ReentrancyGuard.test.js token ERC1155 ERC1155.behavior.js ERC1155.test.js extensions ._ERC1155Burnable.test.js ._ERC1155Pausable.test.js ._ERC1155Supply.test.js ERC1155Burnable.test.js ERC1155Pausable.test.js ERC1155Supply.test.js ERC1155URIStorage.test.js presets ERC1155PresetMinterPauser.test.js utils ERC1155Holder.test.js ERC20 ._ERC20.behavior.js ._ERC20.test.js ERC20.behavior.js ERC20.test.js extensions ._ERC20Burnable.behavior.js ._ERC20Burnable.test.js ._ERC20Capped.behavior.js ._ERC20Capped.test.js ._ERC20FlashMint.test.js ._ERC20Pausable.test.js ._ERC20Snapshot.test.js ._ERC20Votes.test.js ._ERC20VotesComp.test.js ._ERC20Wrapper.test.js ._ERC4626.test.js ._draft-ERC20Permit.test.js ERC20Burnable.behavior.js ERC20Burnable.test.js ERC20Capped.behavior.js ERC20Capped.test.js ERC20FlashMint.test.js ERC20Pausable.test.js ERC20Snapshot.test.js ERC20Votes.test.js ERC20VotesComp.test.js ERC20Wrapper.test.js ERC4626.test.js draft-ERC20Permit.test.js presets ._ERC20PresetFixedSupply.test.js ._ERC20PresetMinterPauser.test.js ERC20PresetFixedSupply.test.js ERC20PresetMinterPauser.test.js utils ._SafeERC20.test.js ._TokenTimelock.test.js SafeERC20.test.js TokenTimelock.test.js ERC721 ._ERC721.behavior.js ._ERC721.test.js ._ERC721Enumerable.test.js ERC721.behavior.js ERC721.test.js ERC721Enumerable.test.js extensions ._ERC721Burnable.test.js ._ERC721Pausable.test.js ._ERC721Royalty.test.js ._ERC721URIStorage.test.js ._ERC721Votes.test.js ERC721Burnable.test.js ERC721Pausable.test.js ERC721Royalty.test.js ERC721URIStorage.test.js ERC721Votes.test.js presets ._ERC721PresetMinterPauserAutoId.test.js ERC721PresetMinterPauserAutoId.test.js utils ._ERC721Holder.test.js ERC721Holder.test.js ERC777 ERC777.behavior.js ERC777.test.js presets ERC777PresetFixedSupply.test.js common ._ERC2981.behavior.js ERC2981.behavior.js utils ._Address.test.js ._Arrays.test.js ._Base64.test.js ._Checkpoints.test.js ._Context.behavior.js ._Context.test.js ._Counters.test.js ._Create2.test.js ._Multicall.test.js ._StorageSlot.test.js ._Strings.test.js ._TimersBlockNumberImpl.test.js ._TimersTimestamp.test.js Address.test.js Arrays.test.js Base64.test.js Checkpoints.test.js Context.behavior.js Context.test.js Counters.test.js Create2.test.js Multicall.test.js StorageSlot.test.js Strings.test.js TimersBlockNumberImpl.test.js TimersTimestamp.test.js cryptography ._ECDSA.test.js ._MerkleProof.test.js ._SignatureChecker.test.js ._draft-EIP712.test.js ECDSA.test.js MerkleProof.test.js SignatureChecker.test.js draft-EIP712.test.js escrow ._ConditionalEscrow.test.js ._Escrow.behavior.js ._Escrow.test.js ._RefundEscrow.test.js ConditionalEscrow.test.js Escrow.behavior.js Escrow.test.js RefundEscrow.test.js introspection ._ERC165.test.js ._ERC165Checker.test.js ._ERC165Storage.test.js ._ERC1820Implementer.test.js ._SupportsInterface.behavior.js ERC165.test.js ERC165Checker.test.js ERC165Storage.test.js ERC1820Implementer.test.js SupportsInterface.behavior.js math ._Math.test.js ._SafeCast.test.js ._SafeMath.test.js ._SignedMath.test.js ._SignedSafeMath.test.js Math.test.js SafeCast.test.js SafeMath.test.js SignedMath.test.js SignedSafeMath.test.js structs ._BitMap.test.js ._DoubleEndedQueue.test.js ._EnumerableMap.behavior.js ._EnumerableMap.test.js ._EnumerableSet.behavior.js ._EnumerableSet.test.js BitMap.test.js DoubleEndedQueue.test.js EnumerableMap.behavior.js EnumerableMap.test.js EnumerableSet.behavior.js EnumerableSet.test.js defi_arb-master ._README.md ._package.json ._truffle.js README.md migrations ._1_initial_migrations.js ._2_deploy.js 1_initial_migrations.js 2_deploy.js package.json scripts ._arb.js arb.js src abis ._Account.json ._Actions.json ._Arb.json ._Decimal.json ._DydxFlashloanBase.json ._ICallee.json ._ICurveFiCurve.json ._IERC20.json ._ISoloMargin.json ._IUniswapV2Router02.json ._Interest.json ._Migrations.json ._Monetary.json ._SafeMath.json ._Storage.json ._Types.json Account.json Actions.json Arb.json Decimal.json DydxFlashloanBase.json ICallee.json ICurveFiCurve.json IERC20.json ISoloMargin.json IUniswapV2Router02.json Interest.json Migrations.json Monetary.json SafeMath.json Storage.json Types.json truffle.js defi_mc-master 2 backend ._README.md ._package.json ._truffle.js README.md migrations ._1_initial_migration.js ._2_deploy.js 1_initial_migration.js 2_deploy.js package.json scripts ._create_lp.js create_lp.js truffle.js frontend ._README.md ._package.json ._tsconfig.json README.md package.json public ._index.html ._manifest.json ._robots.txt index.html manifest.json robots.txt src ._index.css ._logo.svg ._react-app-env.d.ts ._setupTests.js assets img ._metamask-fox.svg ._wallet-connect.svg metamask-fox.svg wallet-connect.svg components Button ._index.ts index.ts Card ._index.ts index.ts CardContent ._index.ts index.ts CardIcon ._index.ts index.ts CardTitle ._index.ts index.ts Container ._index.ts index.ts Dial ._index.ts index.ts DisclaimerModal ._index.ts index.ts Footer ._index.ts index.ts Icon ._index.ts index.ts IconButton ._index.ts index.ts Input ._index.ts index.ts Label ._index.ts index.ts Loader ._index.ts index.ts Logo ._index.ts index.ts MobileMenu ._index.ts index.ts Modal ._index.ts index.ts ModalActions ._index.ts index.ts ModalContent ._index.ts index.ts ModalTitle ._index.ts index.ts Page ._index.ts index.ts PageHeader ._index.ts index.ts Separator ._index.ts index.ts Spacer ._index.ts index.ts SushiIcon ._index.ts index.ts TokenInput ._index.ts index.ts TopBar ._index.ts index.ts Value ._index.ts index.ts WalletProviderModal ._index.ts index.ts icons ._index.ts index.ts constants ._tokenAddresses.ts abi ._ERC20.json ERC20.json tokenAddresses.ts contexts Farms ._context.ts ._index.ts ._types.ts context.ts index.ts types.ts Modals ._index.ts index.ts SushiProvider ._index.ts index.ts Transactions ._context.ts ._index.ts ._reducer.ts ._types.ts context.ts index.ts reducer.ts types.ts hooks ._useAllEarnings.ts ._useAllStakedValue.ts ._useAllowance.ts ._useAllowanceStaking.ts ._useApprove.ts ._useApproveStaking.ts ._useBlock.ts ._useEarnings.ts ._useEnter.ts ._useFarm.ts ._useFarms.ts ._useLeave.ts ._useModal.ts ._usePendingTransactions.ts ._useRedeem.ts ._useReward.ts ._useStake.ts ._useStakedBalance.ts ._useSushi.ts ._useTokenBalance.ts ._useTransactionAdder.ts ._useUnharvested.ts ._useUnstake.ts useAllEarnings.ts useAllStakedValue.ts useAllowance.ts useAllowanceStaking.ts useApprove.ts useApproveStaking.ts useBlock.ts useEarnings.ts useEnter.ts useFarm.ts useFarms.ts useLeave.ts useModal.ts usePendingTransactions.ts useRedeem.ts useReward.ts useStake.ts useStakedBalance.ts useSushi.ts useTokenBalance.ts useTransactionAdder.ts useUnharvested.ts useUnstake.ts index.css logo.svg react-app-env.d.ts setupTests.js sushi ._Sushi.js ._index.js ._utils.js Sushi.js index.js lib ._accounts.js ._constants.js ._contracts.js ._evm.js ._types.js abi ._erc20.json ._masterchef.json ._sushi.json ._uni_v2_lp.json ._weth.json ._xsushi.json erc20.json masterchef.json sushi.json uni_v2_lp.json weth.json xsushi.json accounts.js constants.js contracts.js evm.js types.js utils.js theme ._colors.ts ._index.ts colors.ts index.ts utils ._erc20.ts ._formatAddress.ts ._formatBalance.ts ._index.ts erc20.ts formatAddress.ts formatBalance.ts index.ts views Farm ._index.ts index.ts Farms ._index.ts index.ts Home ._index.ts ._types.ts index.ts types.ts StakeXSushi ._index.ts index.ts Staking ._index.ts index.ts tsconfig.json workers-site ._index.js ._package-lock.json ._package.json index.js package-lock.json package.json defi_mc-master backend ._README.md ._package.json ._truffle.js README.md migrations ._1_initial_migration.js ._2_deploy.js 1_initial_migration.js 2_deploy.js package.json scripts ._create_lp.js create_lp.js truffle.js frontend ._README.md ._package.json ._tsconfig.json README.md package.json public ._index.html ._manifest.json ._robots.txt index.html manifest.json robots.txt src ._index.css ._logo.svg ._react-app-env.d.ts ._setupTests.js assets img ._metamask-fox.svg ._wallet-connect.svg metamask-fox.svg wallet-connect.svg components Button ._index.ts index.ts Card ._index.ts index.ts CardContent ._index.ts index.ts CardIcon ._index.ts index.ts CardTitle ._index.ts index.ts Container ._index.ts index.ts Dial ._index.ts index.ts DisclaimerModal ._index.ts index.ts Footer ._index.ts index.ts Icon ._index.ts index.ts IconButton ._index.ts index.ts Input ._index.ts index.ts Label ._index.ts index.ts Loader ._index.ts index.ts Logo ._index.ts index.ts MobileMenu ._index.ts index.ts Modal ._index.ts index.ts ModalActions ._index.ts index.ts ModalContent ._index.ts index.ts ModalTitle ._index.ts index.ts Page ._index.ts index.ts PageHeader ._index.ts index.ts Separator ._index.ts index.ts Spacer ._index.ts index.ts SushiIcon ._index.ts index.ts TokenInput ._index.ts index.ts TopBar ._index.ts index.ts Value ._index.ts index.ts WalletProviderModal ._index.ts index.ts icons ._index.ts index.ts constants ._tokenAddresses.ts abi ._ERC20.json ERC20.json tokenAddresses.ts contexts Farms ._context.ts ._index.ts ._types.ts context.ts index.ts types.ts Modals ._index.ts index.ts SushiProvider ._index.ts index.ts Transactions ._context.ts ._index.ts ._reducer.ts ._types.ts context.ts index.ts reducer.ts types.ts hooks ._useAllEarnings.ts ._useAllStakedValue.ts ._useAllowance.ts ._useAllowanceStaking.ts ._useApprove.ts ._useApproveStaking.ts ._useBlock.ts ._useEarnings.ts ._useEnter.ts ._useFarm.ts ._useFarms.ts ._useLeave.ts ._useModal.ts ._usePendingTransactions.ts ._useRedeem.ts ._useReward.ts ._useStake.ts ._useStakedBalance.ts ._useSushi.ts ._useTokenBalance.ts ._useTransactionAdder.ts ._useUnharvested.ts ._useUnstake.ts useAllEarnings.ts useAllStakedValue.ts useAllowance.ts useAllowanceStaking.ts useApprove.ts useApproveStaking.ts useBlock.ts useEarnings.ts useEnter.ts useFarm.ts useFarms.ts useLeave.ts useModal.ts usePendingTransactions.ts useRedeem.ts useReward.ts useStake.ts useStakedBalance.ts useSushi.ts useTokenBalance.ts useTransactionAdder.ts useUnharvested.ts useUnstake.ts index.css logo.svg react-app-env.d.ts setupTests.js sushi ._Sushi.js ._index.js ._utils.js Sushi.js index.js lib ._accounts.js ._constants.js ._contracts.js ._evm.js ._types.js abi ._erc20.json ._masterchef.json ._sushi.json ._uni_v2_lp.json ._weth.json ._xsushi.json erc20.json masterchef.json sushi.json uni_v2_lp.json weth.json xsushi.json accounts.js constants.js contracts.js evm.js types.js utils.js theme ._colors.ts ._index.ts colors.ts index.ts utils ._erc20.ts ._formatAddress.ts ._formatBalance.ts ._index.ts erc20.ts formatAddress.ts formatBalance.ts index.ts views Farm ._index.ts index.ts Farms ._index.ts index.ts Home ._index.ts ._types.ts index.ts types.ts StakeXSushi ._index.ts index.ts Staking ._index.ts index.ts tsconfig.json workers-site ._index.js ._package-lock.json ._package.json index.js package-lock.json package.json dodo_flashloan-master ._README.md ._hardhat.config.js ._package-lock.json ._package.json README.md hardhat.config.js package-lock.json package.json scripts ._1_deploy.js ._2_execute-flashloan.js 1_deploy.js 2_execute-flashloan.js test ._Flashloan.js Flashloan.js erc20_deploy_arbitrum_truffle-main ._README.md ._package.json ._truffle-config.arbitrum.js ._truffle-config.js README.md migrations_arbitrum ._1_deploy_contracts.js 1_deploy_contracts.js migrations_ethereum ._1_deploy_contracts.js 1_deploy_contracts.js package.json public ._index.html ._manifest.json index.html manifest.json src ._index.js ._serviceWorker.js build arbitrum-contracts ._SafeMath.json ._Token.json SafeMath.json Token.json ethereum-contracts ._SafeMath.json ._Token.json SafeMath.json Token.json components ._App.css ._App.js App.css App.js index.js serviceWorker.js test ._Token.test.js Token.test.js test_arbitrum ._Token.test.js Token.test.js truffle-config.arbitrum.js truffle-config.js erc20_optimism_hardhat-main ._README.md ._hardhat.config.js ._package-lock.json ._package.json README.md hardhat.config.js package.json public ._index.html ._manifest.json index.html manifest.json src ._index.js ._serviceWorker.js backend scripts ._deploy.js deploy.js test ._Token.js Token.js frontend components ._App.css ._App.js App.css App.js contractsData ._Token.json ._contract-address.json Token.json contract-address.json index.js serviceWorker.js erc20_optimism_truffleBox-main ._README.md ._package-lock.json ._package.json ._truffle-config.js ._truffle-config.ovm.js README.md migrations ._1_deply_contracts.js 1_deply_contracts.js package.json public ._index.html ._manifest.json index.html manifest.json src ._index.js ._serviceWorker.js components ._App.css ._App.js App.css App.js index.js serviceWorker.js test ._Token.test.js Token.test.js test_evm ._Token.test.js Token.test.js truffle-config.js truffle-config.ovm.js flash_mint-main ._README.md ._package.json ._truffle.js README.md abis ._Borrower.json ._Context.json ._ERC20.json ._FlashMintMockWETH.json ._IBorrower.json ._IERC20.json ._Migrations.json ._Ownable.json ._SafeMath.json Borrower.json Context.json ERC20.json FlashMintMockWETH.json IBorrower.json IERC20.json Migrations.json Ownable.json SafeMath.json migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js package.json scripts ._flashMint.js flashMint.js truffle.js flashloan_masterclass-master ._README.md ._package-lock.json ._package.json ._truffle-config.js README.md migrations ._1_initial_migration.js 1_initial_migration.js package-lock.json package.json test ._FlashLoanTemplate.test.js ._LeveragedYieldFarm.test.js FlashLoanTemplate.test.js LeveragedYieldFarm.test.js truffle-config.js fractional_nfts-master ._README.md ._package-lock.json ._package.json ._truffle-config.js README.md migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js package-lock.json package.json scripts ._distribute_tokens.js distribute_tokens.js test ._NFT.test.js NFT.test.js truffle-config.js governance-master ._README.md ._package-lock.json ._package.json ._truffle-config.js README.md migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js package-lock.json package.json scripts ._1_create_proposal.js 1_create_proposal.js truffle-config.js hack_smart_contracts-main ._README.md ._hardhat.config.js ._package-lock.json ._package.json README.md hardhat.config.js package-lock.json package.json test ._execute-attack.js execute-attack.js juicyswap-frontend-master ._README.md ._package-lock.json ._package.json ._tsconfig.json README.md package-lock.json package.json public ._index.html ._manifest.json ._robots.txt index.html manifest.json robots.txt src ._index.css ._logo.svg ._react-app-env.d.ts ._setupTests.js assets img ._metamask-fox.svg ._wallet-connect.svg metamask-fox.svg wallet-connect.svg components Button ._index.ts index.ts Card ._index.ts index.ts CardContent ._index.ts index.ts CardIcon ._index.ts index.ts CardTitle ._index.ts index.ts Container ._index.ts index.ts Dial ._index.ts index.ts DisclaimerModal ._index.ts index.ts Footer ._index.ts index.ts Icon ._index.ts index.ts IconButton ._index.ts index.ts Input ._index.ts index.ts Label ._index.ts index.ts Loader ._index.ts index.ts Logo ._index.ts index.ts MobileMenu ._index.ts index.ts Modal ._index.ts index.ts ModalActions ._index.ts index.ts ModalContent ._index.ts index.ts ModalTitle ._index.ts index.ts Page ._index.ts index.ts PageHeader ._index.ts index.ts Separator ._index.ts index.ts Spacer ._index.ts index.ts SushiIcon ._index.ts index.ts TokenInput ._index.ts index.ts TopBar ._index.ts index.ts Value ._index.ts index.ts WalletProviderModal ._index.ts index.ts icons ._index.ts index.ts constants ._tokenAddresses.ts abi ._ERC20.json ERC20.json tokenAddresses.ts contexts Farms ._context.ts ._index.ts ._types.ts context.ts index.ts types.ts Modals ._index.ts index.ts SushiProvider ._index.ts index.ts Transactions ._context.ts ._index.ts ._reducer.ts ._types.ts context.ts index.ts reducer.ts types.ts hooks ._useAllEarnings.ts ._useAllStakedValue.ts ._useAllowance.ts ._useAllowanceStaking.ts ._useApprove.ts ._useApproveStaking.ts ._useBlock.ts ._useEarnings.ts ._useEnter.ts ._useFarm.ts ._useFarms.ts ._useLeave.ts ._useModal.ts ._usePendingTransactions.ts ._useRedeem.ts ._useReward.ts ._useStake.ts ._useStakedBalance.ts ._useSushi.ts ._useTokenBalance.ts ._useTransactionAdder.ts ._useUnharvested.ts ._useUnstake.ts useAllEarnings.ts useAllStakedValue.ts useAllowance.ts useAllowanceStaking.ts useApprove.ts useApproveStaking.ts useBlock.ts useEarnings.ts useEnter.ts useFarm.ts useFarms.ts useLeave.ts useModal.ts usePendingTransactions.ts useRedeem.ts useReward.ts useStake.ts useStakedBalance.ts useSushi.ts useTokenBalance.ts useTransactionAdder.ts useUnharvested.ts useUnstake.ts index.css logo.svg react-app-env.d.ts setupTests.js sushi ._Sushi.js ._index.js ._utils.js Sushi.js index.js lib ._accounts.js ._constants.js ._contracts.js ._evm.js ._types.js abi ._erc20.json ._masterchef.json ._sushi.json ._uni_v2_lp.json ._weth.json ._xsushi.json erc20.json masterchef.json sushi.json uni_v2_lp.json weth.json xsushi.json accounts.js constants.js contracts.js evm.js types.js utils.js theme ._colors.ts ._index.ts colors.ts index.ts utils ._erc20.ts ._formatAddress.ts ._formatBalance.ts ._index.ts erc20.ts formatAddress.ts formatBalance.ts index.ts views Farm ._index.ts index.ts Farms ._index.ts index.ts Home ._index.ts ._types.ts index.ts types.ts StakeXSushi ._index.ts index.ts Staking ._index.ts index.ts tsconfig.json workers-site ._index.js ._package-lock.json ._package.json index.js package-lock.json package.json juicyswap-master ._README.md ._package-lock.json ._package.json ._setup.sh ._truffle-config.js README.md migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js package-lock.json package.json setup.sh truffle-config.js mini_defi_lending_aggregator-master ._README.md ._package.json ._truffle.js README.md package.json scripts ._0_get_dai.js ._1_deposit.js ._2_rebalance.js ._3_withdraw.js ._library.js 0_get_dai.js 1_deposit.js 2_rebalance.js 3_withdraw.js library.js truffle.js multisig_remix-main ._README.md README.md nft_farm-main ._README.md ._package-lock.json ._package.json ._truffle-config.js README.md migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js package.json public ._index.html ._manifest.json index.html manifest.json src ._index.js ._serviceWorker.js abis ._Address.json ._Context.json ._Crops.json ._DaiToken.json ._ERC1155.json ._ERC1155Holder.json ._ERC1155Receiver.json ._ERC165.json ._ERC20.json ._IERC1155.json ._IERC1155MetadataURI.json ._IERC1155Receiver.json ._IERC165.json ._IERC20.json ._IERC20Metadata.json ._Migrations.json ._NFTFarm.json ._Ownable.json ._ReentrancyGuard.json Address.json Context.json Crops.json DaiToken.json ERC1155Holder.json ERC1155Receiver.json ERC165.json ERC20.json IERC1155.json IERC1155MetadataURI.json IERC1155Receiver.json IERC165.json IERC20.json IERC20Metadata.json Migrations.json Ownable.json ReentrancyGuard.json components ._App.css ._App.js ._Main.js ._Navbar.js App.css App.js Main.js Navbar.js index.js serviceWorker.js test ._NFTFarm.test.js NFTFarm.test.js truffle-config.js open_punks-master ._README.md ._config-overrides.js ._package-lock.json ._package.json ._truffle-config.js README.md config-overrides.js migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js package.json public ._index.html ._manifest.json ._robots.txt index.html manifest.json robots.txt src ._App.css ._config.json ._index.js ._reportWebVitals.js ._setupTests.js App.css abis ._Address.json ._Context.json ._ERC165.json ._ERC721.json ._ERC721Enumerable.json ._IERC165.json ._IERC721.json ._IERC721Enumerable.json ._IERC721Metadata.json ._IERC721Receiver.json ._Migrations.json ._OpenPunks.json ._Ownable.json ._Strings.json Migrations.json components ._App.js ._Navbar.js App.js Navbar.js config.json images socials ._instagram.svg ._opensea.svg ._twitter.svg instagram.svg opensea.svg twitter.svg index.js reportWebVitals.js setupTests.js test ._OpenPunks.test.js OpenPunks.test.js truffle-config.js signing_messages-main ._README.md ._package.json ._truffle-config.js README.md migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js package.json public ._index.html ._manifest.json index.html manifest.json src ._index.js ._serviceWorker.js abis ._Migrations.json ._Verification.json Migrations.json Verification.json components ._App.css ._App.js App.css App.js index.js serviceWorker.js truffle-config.js test_forked_mainnet-master ._README.md ._package.json ._truffle.js README.md migrations ._1_initial_migration.js 1_initial_migration.js package.json test ._test.js test.js truffle.js token_bridge-master ._README.md ._package-lock.json ._package.json ._truffle-config.js README.md migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js package-lock.json package.json public ._index.html ._manifest.json ._robots.txt index.html manifest.json robots.txt src ._index.js ._reportWebVitals.js abis ._BSCBridge.json ._BSCToken.json ._Bridge.json ._Context.json ._ECDSA.json ._ERC20.json ._ETHBridge.json ._ETHToken.json ._IERC20.json ._IERC20Metadata.json ._Migrations.json ._Ownable.json ._Strings.json ._Token.json BSCBridge.json BSCToken.json Bridge.json Context.json ECDSA.json ERC20.json ETHBridge.json ETHToken.json IERC20.json IERC20Metadata.json Migrations.json Ownable.json Strings.json Token.json components ._App.css ._App.js ._Navbar.js App.css App.js Navbar.js index.js reportWebVitals.js test ._Bridge.test.js ._Token.test.js Bridge.test.js Token.test.js truffle-config.js token_curated_registry-master ._README.md ._package-lock.json ._package.json ._truffle-config.js README.md migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js package-lock.json package.json scripts ._1_propose_and_approve.js ._2_propose_and_reject.js 1_propose_and_approve.js 2_propose_and_reject.js test ._Registry.test.js Registry.test.js truffle-config.js token_sniping_bot-master ._README.md ._bot.js ._package-lock.json ._package.json ._truffle-config.js README.md bot.js migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js package-lock.json package.json scripts ._1_fund.js ._2_create_pool.js 1_fund.js 2_create_pool.js truffle-config.js trading_bot-master ._README.md ._bot.js ._config.json ._package-lock.json ._package.json ._truffle-config.js README.md bot.js config.json helpers ._helpers.js ._initialization.js ._server.js helpers.js initialization.js server.js migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js package-lock.json package.json scripts ._manipulatePrice.js manipulatePrice.js truffle-config.js yield-aggregator-master ._README.md ._package-lock.json ._package.json ._truffle-config.js README.md migrations ._1_initial_migration.js ._2_deploy_contracts.js 1_initial_migration.js 2_deploy_contracts.js mint-dai ._dai-abi.json ._dai.js dai-abi.json dai.js package.json public ._index.html ._manifest.json index.html manifest.json src ._index.js ._serviceWorker.js abis ._AaveLendingPool.json ._Aggregator.json ._DAI.json ._Migrations.json ._SafeMath.json ._aDAI.json ._cDAI.json AaveLendingPool.json Aggregator.json DAI.json Migrations.json SafeMath.json aDAI.json cDAI.json components ._App.css ._App.js ._Navbar.js App.css App.js Navbar.js helpers ._aaveLendingPool-abi.json ._cDai-abi.json ._calculateAPY.js ._dai-abi.json aaveLendingPool-abi.json cDai-abi.json calculateAPY.js dai-abi.json index.js serviceWorker.js test ._Aggregator.test.js Aggregator.test.js truffle-config.js ethers-simple-storage-fcc .gitpod.yml README.md deploy.js encryptKey.js package.json full-stack-web3-metamask-connectors README.md fund-me-fcc README.md graph-nft-marketplace-fcc README.md abis NftMarketplace.json generated NftMarketplace NftMarketplace.ts schema.ts package.json src mapping.ts subgraphQueries.ts tsconfig.json hardhat-dao-fcc .solhint.json README.md deploy 01-deploy-governor-token.ts 02-deploy-time-lock.ts 03-deploy-governor-contract.ts 04-setup-governance-contracts.ts 05-deploy-box.ts hardhat.config.ts helper-functions.ts helper-hardhat-config.ts package.json scripts propose.ts queue-and-execute.ts vote.ts test unit testflow.test.ts tsconfig.json utils move-blocks.ts move-time.ts hardhat-defi-fcc .solhint.json README.md hardhat.config.js helper-hardhat-config.js package.json scripts aaveBorrow.js getWeth.js hardhat-erc20-fcc .solhint.json README.md deploy 01-deploy-token.js hardhat.config.js helper-functions.js helper-hardhat-config.js package.json test unit ourToken-unit.test.js hardhat-fund-me-fcc README.md deploy 00-deploy-mocks.js 01-deploy-fund-me.js 99-deploy-storage-fun.js hardhat.config.js helper-hardhat-config.js package.json scripts exampleScript fundMeStorage.js fund.js withdraw.js test staging FundMe.staging.test.js unit FundMe.test.js utils verify.js hardhat-fund-me-forked-fcc README.md deploy-helpers verify.js deploy 00-deploy-fund-me.js deployments kovan FundMe.json solcInputs 688baeaa7cd8ac36e6c3fab95a683109.json localhost FundMe.json MockV3Aggregator.json solcInputs 9577bda3f76f4ac030a71a5f791015b9.json c3aba118db4b62025d5a7b53eec5c8cd.json hardhat.config.js helper-hardhat-config.js package.json scripts fund.js withdraw.js test unit FundMe.test.js hardhat-metamorphic-upgrades-fcc .solhint.json README.md deploy 01-deploy-box.js 02-destroy-and-redeploy.js hardhat.config.js helper-functions.js helper-hardhat-config.js package.json hardhat-nft-fcc README.md deploy 00-deploy-mocks.js 01-deploy-basic-nft.js 02-deploy-dynamic-svg-nft.js 03-deploy-random-ipfs-nft.js 04-mint.js hardhat.config.js helper-hardhat-config.js images dynamicNft frown.svg happy.svg package.json test unit basicNft.test.js dynamicSvg.test.js randomIpfs.test.js utils uploadToNftStorage.js uploadToPinata.js verify.js hardhat-nft-marketplace-fcc .solhint.json README.md deploy 01-deploy-nft-marketplace.js 02-deploy-basic-nft.js 03-update-front-end.js hardhat.config.js helper-hardhat-config.js package.json scripts buy-item.js cancel-item.js mine.js mint-and-list-item.js mint.js test unit NftMarketplace.test.js utils move-blocks.js verify.js hardhat-security-fcc .solhint.json README.md hardhat.config.js helper-functions.js helper-hardhat-config.js package.json hardhat-simple-storage-fcc .gitpod.yml README.md hardhat.config.js package.json scripts deploy.js tasks block-number.js test test-deploy.js hardhat-smartcontract-lottery-fcc .solhint.json README.md deploy 00-deploy-mocks.js 01-deploy-raffle.js 02-update-front-end.js hardhat.config.js helper-hardhat-config.js package.json scripts enter.js mockOffchain.js test staging Raffle.staging.test.js unit Raffle.test.js utils verify.js hardhat-starter-kit .gitpod.yml .solcover.js .solhint.json README.md deploy 00_Deploy_Mocks.js 01_Deploy_PriceConsumerV3.js 02_Deploy_APIConsumer.js 03_Deploy_RandomNumberConsumer.js 04_Deploy_KeepersCounter.js hardhat.config.js helper-functions.js helper-hardhat-config.js package.json scripts readPrice.js tasks accounts.js api-consumer index.js read-data.js request-data.js balance.js block-number.js index.js keepers index.js read-keepers-counter.js price-consumer index.js read-price-feed-ens.js read-price-feed.js random-number-consumer index.js read-random-number.js request-random-number.js withdraw-link.js test staging APIConsumer_int_test.js RandomNumberConsumerV2_int_test.js unit APIConsumer_unit_test.js KeepersCounter_unit_test.js PriceConsumerV3_unit_test.js RandomNumberConsumerV2_unit_test.js hardhat-upgrades-fcc .solhint.json README.md deploy 01-deploy-box.js 02-deploy-box2.js hardhat.config.js helper-functions.js helper-hardhat-config.js package.json scripts otherUpgradeExamples deploy.js prepare-upgrade.js transfer-ownership.js upgrade.js upgrade-box-manual.js test unit boxUpgrades.test.js how-to-answer-a-question.md how-to-ask-a-question.md html-fund-me-fcc README.md constants.js ethers-5.6.esm.min.js index.html index.js package.json learn-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 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 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 nextjs-ethers-introduction-fcc README.md constants constants.js next.config.js package.json pages _app.js api hello.js index.js postcss.config.js public vercel.svg styles Home.module.css globals.css tailwind.config.js nextjs-nft-marketplace-moralis-fcc README.md addEvents.js cloudFunctions updateActiveItems.js components Header.js NFTBox.js UpdateListingModal.js constants BasicNft.json NftMarketplace.json networkMapping.json next.config.js package.json pages _app.js api hello.js index.js sell-nft.js postcss.config.js public vercel.svg styles Home.module.css globals.css tailwind.config.js nextjs-nft-marketplace-thegraph-fcc README.md addEvents.js components Header.js NFTBox.js UpdateListingModal.js constants BasicNft.json NftMarketplace.json networkMapping.json subgraphQueries.js next.config.js package.json pages _app.js api hello.js graphExample.js index.js sell-nft.js postcss.config.js public vercel.svg styles Home.module.css globals.css tailwind.config.js nextjs-smartcontract-lottery-fcc .eslintrc.json .vscode settings.json README.md components Header.js LotteryEntrance.js ManualHeader.js constants abi.json contractAddresses.json index.js next.config.js package.json pages _app.js api hello.js index.js postcss.config.js public vercel.svg styles Home.module.css globals.css tailwind.config.js sc-language-comparison README.md compare_contract_creation.py differences.txt foundry.toml gas-deployed.md requirements.txt simple_storage_abi.json simple-storage-fcc README.md storage-factory-fcc README.md | | n : |
# Foundry Overview Learn everything you need to know to get started with Foundry ## Technology Stack & Dependencies - Solidity (Writing Smart Contract) - [Infura](https://www.alchemy.com/) As a node provider https://infura.io/ ### 1. Clone/Download the Repository ### 2. Compile Smart Contracts ``` forge build ``` ### 3. Test and Debug(console.log) Smart Contracts ``` forge test ``` ### 6. Deploy Contract to public testnet ``` forge create --rpc-url <infuraRpc> --private-key <yourPrivateKey> src/Contract.sol:Contract ``` # NFT Farm ### About Full stack Dapp that allows users to stake their tokens and earn points for doing so. They can use these points to redeem crop themed ERC-1155 NFTs. ## Technology Stack & Tools - Solidity (Writing Smart Contract) - Javascript (React & Testing) - [Ethers](https://docs.ethers.io/v5/) (Blockchain Interaction) - [Truffle](https://www.trufflesuite.com/docs/truffle/overview) (Development Framework) - [Ganache](https://www.trufflesuite.com/ganache) (For Local Blockchain) - [Open Zeppelin](https://docs.openzeppelin.com/) (smart contract libraries) ## Requirements For Initial Setup - Install [NodeJS](https://nodejs.org/en/), should work with any node version below 16.5.0 - Install [Truffle](https://www.trufflesuite.com/docs/truffle/overview), In your terminal, you can check to see if you have truffle by running `truffle version`. To install truffle run `npm i -g truffle`. Ideal to have truffle version 5.4 to avoid dependency issues. - Install [Ganache](https://www.trufflesuite.com/ganache). ## Setting Up ### 1. Clone/Download the Repository ### 2. Install Dependencies: ``` $ cd nft_farm $ npm install ``` ### 3. Start Ganache ### 4. Connect you ganache addresses to Metamask - Copy private key of the addresses in ganache and import to Metamask - Connect you metamask to ganache, network 127.0.0.1:7545. - If you have not added ganache to the list of networks on your metamask, open up a browser, click the fox icon, then click the top center dropdown button that lists all the available networks then click add networks. A form should pop up. For the "Network Name" field enter "ganache". For the "New RPC URL" field enter "http://127.0.0.1:8545". For the chain ID enter "1337". Then click save. ### 5. Migrate Smart Contracts `truffle migrate --reset` ### 6. Run Tests `$ truffle test` ### 7. Launch Frontend `$ npm run start` License ---- MIT This is part of the FreeCodeCamp Solidity & Javascript Blockchain Course. *[⌨️ (03:05:34) Lesson 3: Remix Storage Factory](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=11134s)* ## Getting Started 1. Go to [Remix](https://remix.ethereum.org/) 2. Paste the code from `SimpleStorage.sol`, `StorageFactory.sol`, and `ExtraStorage.sol` into a new file in Remix 3. Hit `Compile` 4. Hit `Deploy` for whatever contract you want. For a more in depth blog on working with remix, [read here](https://docs.chain.link/docs/deploy-your-first-contract/) # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) # Governance and DAO's ## Technology Stack & Tools - Solidity (Writing Smart Contract) - Javascript (React & Testing) - [Web3](https://web3js.readthedocs.io/en/v1.5.2/) (Blockchain Interaction) - [Truffle](https://www.trufflesuite.com/docs/truffle/overview) (Development Framework) - [Ganache](https://www.trufflesuite.com/ganache) (For Local Blockchain) ## Requirements For Initial Setup - Install [NodeJS](https://nodejs.org/en/), should work with any node version below 16.5.0 - Install [Truffle](https://www.trufflesuite.com/docs/truffle/overview), In your terminal, you can check to see if you have truffle by running `truffle version`. To install truffle run `npm i -g truffle`. Ideal to have truffle version 5.4 to avoid dependency issues. - Install [Ganache](https://www.trufflesuite.com/ganache). ## Setting Up ### 1. Clone/Download the Repository ### 2. Install Dependencies: `$ npm install` ### 3. Start Ganache ### 4. Migrate Smart Contracts `$ truffle migrate --reset` ### 5. Run 1st script `$ truffle exec .\scripts\1_create_proposal.js` - [Full-Stack Setup](#full-stack-setup) - [1. Git clone the contracts repo](#1-git-clone-the-contracts-repo) - [2. Start your node](#2-start-your-node) - [3. Connect your codebase to your moralis server](#3-connect-your-codebase-to-your-moralis-server) - [4. Globally install the `moralis-admin-cli`](#4-globally-install-the-moralis-admin-cli) - [5. Setup your Moralis reverse proxy](#5-setup-your-moralis-reverse-proxy) - [IMPORTANT](#important) - [6. Setup your Cloud functions](#6-setup-your-cloud-functions) - [7. Add your event listeners](#7-add-your-event-listeners) - [You can do this programatically by running:](#you-can-do-this-programatically-by-running) - [Or, if you want to do it manually](#or-if-you-want-to-do-it-manually) - [8. Mint and List your NFT](#8-mint-and-list-your-nft) - [9. Start your front end](#9-start-your-front-end) - [Minimal Quickstart](#minimal-quickstart) # Full-Stack Setup ## 1. Git clone the contracts repo In it's own terminal / command line, run: ``` git clone https://github.com/PatrickAlphaC/hardhat-nft-marketplace-fcc cd hardhat-nextjs-nft-marketplace-fcc yarn ``` ## 2. Start your node After installing dependencies, start a node on it's own terminal with: ``` yarn hardhat node ``` ## 3. Connect your codebase to your moralis server Setup your event [moralis](https://moralis.io/). You'll need a new moralis server to get started. Sign up for a [free account here](https://moralis.io/). Once setup, update / create your `.env` file. You can use `.env.example` as a boilerplate. ``` NEXT_PUBLIC_APP_ID=XXXX NEXT_PUBLIC_SERVER_URL=XXXX moralisApiKey=XXX moralisSubdomain=XXX masterKey=XXX chainId=31337 ``` With the values from your account. Then, in your `./package.json` update the following lines: ``` "moralis:sync": "moralis-admin-cli connect-local-devchain --chain hardhat --moralisSubdomain XXX.usemoralis.com --frpcPath ./frp/frpc", "moralis:cloud": "moralis-admin-cli watch-cloud-folder --moralisSubdomain XXX.usemoralis.com --autoSave 1 --moralisCloudfolder ./cloudFunctions", "moralis:logs": "moralis-admin-cli get-logs --moralisSubdomain XXX.usemoralis.com" ``` Replace the `XXX.usemoralis.com` with your subdomain, like `4444acatycat.usemoralis.com` and update the `moralis:sync` script's path to your instance of `frp` (downloaded as part of the Moralis "Devchain Proxy Server" instructions mentioned above) ## 4. Globally install the `moralis-admin-cli` ``` yarn global add moralis-admin-cli ``` ## 5. Setup your Moralis reverse proxy > Optionally: On your server, click on "View Details" and then "Devchain Proxy Server" and follow the instructions. You'll want to use the `hardhat` connection. - Download the latest reverse proxy code from [FRP](https://github.com/fatedier/frp/releases) and add the binary to `./frp/frpc`. - Replace your content in `frpc.ini`, based on your devchain. You can find the information on the `DevChain Proxy Server` tab of your moralis server. In some Windows Versions, FRP could be blocked by firewall, just use a older release, for example frp_0.34.3_windows_386 Mac / Windows Troubleshooting: https://docs.moralis.io/faq#frpc Once you've got all this, you can run: ``` yarn moralis:sync ``` You'll know you've done it right when you can see a green `connected` button after hitting the refresh symbol next to `DISCONNECTED`. *You'll want to keep this connection running*. <img src="./img/connected.png" width="200" alt="Connected to Moralis Reverse Proxy"> ### IMPORTANT Anytime you reset your hardhat node, you'll need to press the `RESET LOCAL CHAIN` button on your UI! ## 6. Setup your Cloud functions In a separate terminal (you'll have a few up throughout these steps) Run `yarn moralis:cloud` in one terminal, and run `yarn moralis:logs` in another. If you don't have `moralis-admin-cli` installed already, install it globally with `yarn global add moralis-admin-cli`. > Note: You can stop these after running them once if your server is at max CPU capactity. If you hit the little down arrow in your server, then hit `Cloud Functions` you should see text in there. <img src="./img/down-arrow.png" width="500" alt="Cloud Functions Up"> <img src="./img/functions.png" width="250" alt="Cloud Functions Up"> Make sure you've run `yarn moralis:sync` from the previous step to connect your local Hardhat devchain with your Moralis instance. You'll need these 3 moralis commands running at the same time. ## 7. Add your event listeners ### You can do this programatically by running: ``` node watchEvents.js ``` ### Or, if you want to do it manually Finally, go to `View Details` -> `Sync` and hit `Add New Sync` -> `Sync and Watch Contract Events` Add all 3 events by adding it's information, like so: 1. ItemListed: 1. Description: ItemListed 2. Sync_historical: True 3. Topic: ItemListed(address,address,uint256,uint256) 4. Abi: ``` { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "seller", "type": "address" }, { "indexed": true, "internalType": "address", "name": "nftAddress", "type": "address" }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256" }, { "indexed": false, "internalType": "uint256", "name": "price", "type": "uint256" } ], "name": "ItemListed", "type": "event" } ``` 5. Address: <YOUR_NFT_MARKETPLACE_DEPLOYED_ADDRESS_FROM_HARDHAT> 6. TableName: ItemListed You can add the canceled and bought events later. ## 8. Mint and List your NFT Back in the main directory, run: ``` yarn hardhat run scripts/mint-and-list-item.js --network localhost ``` And you'll now have an NFT listed on your marketplace. ## 9. Start your front end At this point, you'll have a few terminals running: - Your Hardhat Node - Your Hardhat Node syncing with your moralis server - Your Cloud Functions syncing - Your Moralis Logging And you're about to have one more for your front end. ``` yarn run dev ``` And you'll have your front end, indexing service running, and blockchain running. # Minimal Quickstart 1. Clone the backend repo ``` git clone https://github.com/PatrickAlphaC/hardhat-nft-marketplace-fcc cd hardhat-nextjs-nft-marketplace-fcc yarn yarn hardhat node ``` Leave that terminal running^ 2. Clone the frontend ``` git clone https://github.com/PatrickAlphaC/nextjs-nft-marketplace-moralis-fcc cd nextjs-nft-marketplace-moralis-fcc yarn ``` Setup your `.env` with moralis info and update your `package.json` with moralis subdomain. 3. Sync your hardhat node with moralis Update your `frpc.ini` file with what you see in the moralis UI. Leave this terminal running: ``` yarn moralis:sync ``` 4. Watch for events && Update cloud functions Run once: ``` yarn moralis:cloud ``` ``` node watchEvents.js ``` 5. Emit an event Back in your hardhat project, run: ``` yarn hardhat run scripts/mint-and-list-item.js --network localhost ``` And you should see it updated in the database [Content not decodable] # Hack Smart Contracts ## About - Learn about smart contract security by hacking flash loan contracts! - Goal: Steal all the ether in the lender pool and flash loan reciever contracts in a single transaction. - PLEASE DO NOT USE THESE CONTRACTS IN PRODUCTION ## Technology Stack & Tools - Solidity (Writing Smart Contract) - Javascript (Testing) - [Ethers](https://docs.ethers.io/v5/) (Blockchain Interaction) - [Hardhat](https://hardhat.org/) (Development Framework) ## Requirements For Initial Setup - Install [NodeJS](https://nodejs.org/en/), should work with any node version below 16.5.0 - Install [Hardhat](https://hardhat.org/) ## Setting Up ### 1. Clone/Download the Repository ### 2. Install Dependencies: ``` $ cd hack_smart_contracts $ npm install ``` ### 3. Run Exploit `$ npx hardhat test` [Content not decodable] # SushiSwap 🍣 https://app.sushiswap.org. Feel free to read the code. More details coming soon. ## Deployed Contracts / Hash - SushiToken - https://etherscan.io/token/0x6b3595068778dd592e39a122f4f5a5cf09c90fe2 - MasterChef - https://etherscan.io/address/0xc2edad668740f1aa35e4d8f227fb8e17dca888cd - (Uni|Sushi)swapV2Factory - https://etherscan.io/address/0xc0aee478e3658e2610c5f7a4a2e1777ce9e4f2ac - (Uni|Sushi)swapV2Router02 - https://etherscan.io/address/0xd9e1ce17f2641f24ae83637ab66a2cca9c378b9f - (Uni|Sushi)swapV2Pair init code hash - `e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303` - SushiBar - https://etherscan.io/address/0x8798249c2e607446efb7ad49ec89dd1865ff4272 - SushiMaker - https://etherscan.io/address/0x54844afe358ca98e4d09aae869f25bfe072e1b1a ## License WTFPL # The Ultimate NFT Repo *[⌨️ (20:28:51) Lesson 14: Hardhat NFTs ](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=73731s)* <br/> <p align="center"> <img src="./images/randomNft/pug.png" width="225" alt="NFT Pug"> <img src="./images/dynamicNft/happy.svg" width="225" alt="NFT Happy"> <img src="./images/randomNft/shiba-inu.png" width="225" alt="NFT Shiba"> <img src="./images/dynamicNft/frown.svg" width="225" alt="NFT Frown"> <img src="./images/randomNft/st-bernard.png" width="225" alt="NFT St.Bernard"> </p> <br/> We go through creating 3 different kinds of NFTs. 1. A Basic NFT 2. IPFS Hosted NFT 1. That uses Randomness to generate a unique NFT 3. SVG NFT (Hosted 100% on-chain) 1. Uses price feeds to be dynamic # Getting Started ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an ouput like: `vx.x.x` - [Yarn](https://yarnpkg.com/getting-started/install) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` and get an output like: `x.x.x` - You might need to [install it with `npm`](https://classic.yarnpkg.com/lang/en/docs/install/) or `corepack` ## Quickstart ``` git clone https://github.com/PatrickAlphaC/hardhat-nft-fcc cd hardhat-nft-fcc yarn ``` ## Typescript If you want to get to typescript and you cloned the javascript version, just run: ``` git checkout typescript ``` # Useage Deploy: ``` yarn hardhat deploy ``` ## Testing ``` yarn hardhat test ``` ### Test Coverage ``` yarn hardhat coverage ``` # Deployment to a testnet or mainnet 1. Setup environment variabltes You'll want to set your `RINKEBY_RPC_URL` and `PRIVATE_KEY` as environment variables. You can add them to a `.env` file, similar to what you see in `.env.example`. - `PRIVATE_KEY`: The private key of your account (like from [metamask](https://metamask.io/)). **NOTE:** FOR DEVELOPMENT, PLEASE USE A KEY THAT DOESN'T HAVE ANY REAL FUNDS ASSOCIATED WITH IT. - You can [learn how to export it here](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key). - `RINKEBY_RPC_URL`: This is url of the rinkeby testnet node you're working with. You can get setup with one for free from [Alchemy](https://alchemy.com/?a=673c802981) 2. Get testnet ETH Head over to [faucets.chain.link](https://faucets.chain.link/) and get some tesnet ETH & LINK. You should see the ETH and LINK show up in your metamask. [You can read more on setting up your wallet with LINK.](https://docs.chain.link/docs/deploy-your-first-contract/#install-and-fund-your-metamask-wallet) 3. Setup a Chainlink VRF Subscription ID Head over to [vrf.chain.link](https://vrf.chain.link/) and setup a new subscription, and get a subscriptionId. You can reuse an old subscription if you already have one. [You can follow the instructions](https://docs.chain.link/docs/get-a-random-number/) if you get lost. You should leave this step with: 1. A subscription ID 2. Your subscription should be funded with LINK 3. Deploy In your `helper-hardhat-config.ts` add your `subscriptionId` under the section of the chainId you're using (aka, if you're deploying to rinkeby, add your `subscriptionId` in the `subscriptionId` field under the `4` section.) Then run: ``` yarn hardhat deploy --network rinkeby --tags main ``` We only deploy the `main` tags, since we need to add our `RandomIpfsNft` contract as a consumer. 4. Add your contract address as a Chainlink VRF Consumer Go back to [vrf.chain.link](https://vrf.chain.link) and under your subscription add `Add consumer` and add your contract address. You should also fund the contract with a minimum of 1 LINK. 5. Mint NFTs Then run: ``` yarn hardhat deploy --network rinkeby --tags mint ``` ### Estimate gas cost in USD To get a USD estimation of gas cost, you'll need a `COINMARKETCAP_API_KEY` environment variable. You can get one for free from [CoinMarketCap](https://pro.coinmarketcap.com/signup). Then, uncomment the line `coinmarketcap: COINMARKETCAP_API_KEY,` in `hardhat.config.ts` to get the USD estimation. Just note, everytime you run your tests it will use an API call, so it might make sense to have using coinmarketcap disabled until you need it. You can disable it by just commenting the line back out. ## Verify on etherscan If you deploy to a testnet or mainnet, you can verify it if you get an [API Key](https://etherscan.io/myapikey) from Etherscan and set it as an environemnt variable named `ETHERSCAN_API_KEY`. You can pop it into your `.env` file as seen in the `.env.example`. In it's current state, if you have your api key set, it will auto verify kovan contracts! However, you can manual verify with: ``` yarn hardhat verify --constructor-args arguments.ts DEPLOYED_CONTRACT_ADDRESS ``` ### Typescript differences 1. `.js` files are now `.ts` 2. We added a bunch of typescript and typing packages to our `package.json`. They can be installed with: 1. `yarn add @typechain/ethers-v5 @typechain/hardhat @types/chai @types/node ts-node typechain typescript` 3. The biggest one being [typechain](https://github.com/dethcrypto/TypeChain) 1. This gives your contracts static typing, meaning you'll always know exactly what functions a contract can call. 2. This gives us `factories` that are specific to the contracts they are factories of. See the tests folder for a version of how this is implemented. 4. We use `imports` instead of `require`. Confusing to you? [Watch this video](https://www.youtube.com/watch?v=mK54Cn4ceac) 5. Add `tsconfig.json` # Linting To check linting / code formatting: ``` yarn lint ``` or, to fix: ``` yarn lint:fix ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) [Content not decodable] # Running the certora verification tool These instructions detail the process for running CVT on the OpenZeppelin (Wizard/Governor) contracts. Documentation for CVT and the specification language are available [here](https://certora.atlassian.net/wiki/spaces/CPD/overview) ## Running the verification The scripts in the `certora/scripts` directory are used to submit verification jobs to the Certora verification service. After the job is complete, the results will be available on [the Certora portal](https://vaas-stg.certora.com/). These scripts should be run from the root directory; for example by running ``` sh certora/scripts/verifyAll.sh <meaningful comment> ``` The most important of these is `verifyAll.sh`, which checks all of the harnessed contracts (`certora/harness/Wizard*.sol`) against all of the specifications (`certora/spec/*.spec`). The other scripts run a subset of the specifications or the contracts. You can verify different contracts or specifications by changing the `--verify` option, and you can run a single rule or method with the `--rule` or `--method` option. For example, to verify the `WizardFirstPriority` contract against the `GovernorCountingSimple` specification, you could change the `--verify` line of the `WizardControlFirstPriortity.sh` script to: ``` --verify WizardFirstPriority:certora/specs/GovernorCountingSimple.spec \ ``` ## Adapting to changes in the contracts Some of our rules require the code to be simplified in various ways. Our primary tool for performing these simplifications is to run verification on a contract that extends the original contracts and overrides some of the methods. These "harness" contracts can be found in the `certora/harness` directory. This pattern does require some modifications to the original code: some methods need to be made virtual or public, for example. These changes are handled by applying a patch to the code before verification. When one of the `verify` scripts is executed, it first applies the patch file `certora/applyHarness.patch` to the `contracts` directory, placing the output in the `certora/munged` directory. We then verify the contracts in the `certora/munged` directory. If the original contracts change, it is possible to create a conflict with the patch. In this case, the verify scripts will report an error message and output rejected changes in the `munged` directory. After merging the changes, run `make record` in the `certora` directory; this will regenerate the patch file, which can then be checked into git. # Trading Bot Demo ## Technology Stack & Tools - Solidity (Writing Smart Contract) - Javascript (React & Testing) - [Web3](https://web3js.readthedocs.io/en/v1.5.2/) (Blockchain Interaction) - [Truffle](https://trufflesuite.com/docs/truffle/) (Development Framework) - [Ganache-CLI](https://github.com/trufflesuite/ganache) (For Local Blockchain) - [Alchemy](https://www.alchemy.com/) (For forking the Ethereum mainnet) ## Requirements For Initial Setup - Install [NodeJS](https://nodejs.org/en/), I recommend using node version 16.14.2 to avoid any potential dependency issues - Install [Truffle](https://github.com/trufflesuite/truffle), In your terminal, you can check to see if you have truffle by running `truffle --version`. To install truffle run `npm i -g truffle`. - Install [Ganache-CLI](https://github.com/trufflesuite/ganache). To see if you have ganache-cli installed, in your command line type `ganache --version`. To install, in your command line type `npm install ganache --global` ## Setting Up ### 1. Clone/Download the Repository ### 2. Install Dependencies: `$ npm install` ### 3. Start Ganache CLI In your terminal run: ``` ganache -f -m <Your-Mnemonic-Phrase> -u 0xdEAD000000000000000042069420694206942069 -p 7545 ``` Alternatively you can start ganache with your own RPC URL such as the one provided from Alchemy: ``` ganache -f wss://eth-mainnet.alchemyapi.io/v2/<Your-App-Key> -m <Your-Mnemonic-Phrase> -u 0xdEAD000000000000000042069420694206942069 -p 7545 ``` For the -m parameter you can get away by using a 1 word mnemonic, remember these are only development accounts and are not to be used in production. For the -u parameter in the command, we are unlocking an address with SHIB tokens to manipulate price of SHIB/WETH in our scripts. If you plan to use a different ERC20 token, you'll need to unlock an account holding that specific ERC20 token. Once you've started ganache-cli, copy the address of the first account as you'll need to paste it in your .env file in the next step. ### 4. Create and Setup .env Before running any scripts, you'll want to create a .env file with the following values (see .env.example): - **ALCHEMY_API_KEY=""** - **ARB_FOR="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"** (By default we are using WETH) - **ARB_AGAINST="0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE"** (By default we are using SHIB) - **PRIVATE_KEY=""** (Private key of the account to recieve profit/execute arbitrage contract) - **PRICE_DIFFERENCE=0.50** (Difference in price between Uniswap & Sushiswap, default is 0.50%) - **UNITS=0** (Only used for price reporting) - **GAS_LIMIT=600000** (Currently a hardcoded value, may need to adjust during testing) - **GAS_PRICE=0.0093** (Currently a hardcoded value, may need to adjust during testing) ### 5. Migrate Smart Contracts In a seperate terminal run: `$ truffle migrate --reset` ### 6. Start the Bot `$ node ./bot.js` ### 7. Manipulate Price In another terminal run: `$ node ./scripts/manipulatePrice.js` ## About config.json Inside the *config.json* file, under the PROJECT_SETTINGS object, there are 2 keys that hold a boolean value: - isLocal - isDeployed Both options depend on how you wish to test the bot. By default both values are set to true. If you set isLocal to false, and then run the bot this will allow the bot to monitor swap events on the actual mainnet, instead of locally. isDeployed's value can be set on whether you wish for the abritrage contract to be called if a potential trade is found. By default isDeployed is set to true for local testing. Ideally this is helpful if you want to monitor swaps on mainnet and you don't have a contract deployed. This will allow you to still experiment with finding potential abitrage opportunites. ## Testing Bot on Mainnet For monitoring prices and detecting potential arbitrage opportunities, you do not need to deploy the contract. ### 1. Edit config.json Inside the *config.json* file, set **isDeployed** to **false**. ### 2. Create and Setup .env See step #4 in **Setting Up** ### 3. Run the bot `$ node ./bot.js` Keep in mind you'll need to wait for an actual swap event to be triggered before it checks the price. ## Anatomy of bot.js The bot is essentially composed of 5 functions. - *main()* - *checkPrice()* - *determineDirection()* - *determineProfitability()* - *executeTrade()* The *main()* function monitors swap events from both Uniswap & Sushiswap. When a swap event occurs, it calls *checkPrice()*, this function will log the current price of the assets on both Uniswap & Sushiswap, and return the **priceDifference** Then *determineDirection()* is called, this will determine where we would need to buy first, then sell. This function will return an array called **routerPath** in *main()*. The array contains Uniswap & Sushiswap's router contracts. If no array is returned, this means the **priceDifference** returned earlier is not higher than **difference** If **routerPath** is not null, then we move into *determineProfitability()*. This is where we set our conditions on whether there is a potential arbitrage or not. This function returns either true or false. If true is returned from *determineProfitability()*, then we call *executeTrade()* where we make our call to our arbitrage contract to perform the trade. Afterwards a report is logged, and the bot resumes to monitoring for swap events. ### Modifying & Testing the Scripts Both the *manipulatePrice.js* and *bot.js* has been setup to easily make some modifications easy. Before the main() function in *manipulatePrice.js*, there will be a comment: **// -- CONFIGURE VALUES HERE -- //**. Below that will be some constants you'll be able to modify such as the unlocked account, and the amount of tokens you'll want that account to spent in order to manipulate price (You'll need to adjust this if you are looking to test different pairs). For *bot.js*, you'd want to take a look at the function near line 132 called *determineProfitability()*. Inside this function we can set our conditions and do our calculations to determine whether we may have a potential profitable trade on our hands. This function is to return **true** if a profitable trade is possible, and **false** if not. Note if you are doing an arbitrage for a different ERC20 token than the one in the provided example (WETH), then you may also need to adjust profitability reporting in the *executeTrade()* function. Keep in mind, after running the scripts, specifically *manipulatePrice.js*, you may need to restart your ganache cli, and re-migrate contracts to properly retest. ### Additional Information The *bot.js* script uses helper functions for fetching token pair addresses, calculating price of assets, and calculating estimated returns. These functions can be found in the *helper.js* file inside of the helper folder. The helper folder also has *server.js* which is responsible for spinning up our local server, and *initialization.js* which is responsible for setting up our web3 connection, configuring Uniswap/Sushiswap contracts, etc. As you customize parts of the script it's best to refer to [Uniswap documentation](https://docs.uniswap.org/protocol/V2/introduction) for a more detail rundown on the protocol and interacting with the V2 exchange. ### Strategy Overview and Potential Errors The current strategy implemented is only shown as an example alongside with the *manipulatePrice.js* script. Essentially, after we manipulate price on Uniswap, we look at the reserves on Sushiswap and determine how much SHIB we need to buy on Uniswap to 'clear' out reserves on Sushiswap. Therefore the arbitrage direction is Uniswap -> Sushiswap. This works because Sushiswap has lower reserves than Uniswap. However, if the arbitrage direction was swapped: Sushiswap -> Uniswap, this will sometimes error out if monitoring swaps on mainnet. This error occurs in the *determineProfitability()* function inside of *bot.js*. Currently a try/catch is implemented, so if it errors out, the bot will just resume monitoring price. Other solutions to this may be to implement a different strategy, use different ERC20 tokens, or reversing the order. ## Using other EVM chains If you are looking to test on an EVM compatible chain, you can follow these steps: ### 1. Update .env - **ARB_FOR=""** - **ARB_AGAINST=""** Token addresses will be different on different chains, you'll want to reference blockchain explorers such as [Polyscan](https://polygonscan.com/) for Polygon for token addresses you want to test. ### 2. Update config.json - **V2_ROUTER_02_ADDRESS=""** - **FACTORY_ADDRESS=""** You'll want to update the router and factory addresses inside of the *config.json* file with the V2 exchanges you want to use. Based on the exchange you want to use, refer to the documentation for it's address. ### 3. Change RPC URL Inside of *initialization.js* and *helpers.js*, you'll want to update the Web3 provider RPC URL. Example of Polygon: ``` web3 = new Web3(`wss://polygon-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`) ``` ### 4. Changing Arbitrage.sol You may also need to change the flashloan provider used in the contract to one that is available on your chain of choice. ### Additional Notes - When starting ganache CLI, you'll want to fork using your chain's RPC URL and perhaps update the address of the account you want to unlock. - If testing out the *manipulatePrice.js* script, you'll also want to update the **UNLOCKED_ACCOUNT** variable and adjust **AMOUNT** as needed. # Flash-mintable Asset-backed Tokens Flash-mintable tokens allow you to mint tokens that can be considered as a loan/credit much like Flashloans, the tokens received are burned before the end of the same transaction. Flash Tokens are considered by some better than Flashloans as they dont involve high fees, need for there to be liquidity at the lending platform. Contracts simply need to implement an IBorrower interface to mint as many of the Mintable tokens and have them burned at end of transaction. The following code shows a simple example of an Asset Backed Flash Mintable token, an Example of a Borrower contract making use of the Flash minting on the token. This example uses a Mock WETH Token which is Flash Mintable to borrow an amount. [Code adopted from Austin Williams Github repo on Flash Mintable Tokens](https://github.com/Austin-Williams/flash-mintable-tokens) ### Technology Stack and Tools * [Node Version Manager](https://heynode.com/tutorial/install-nodejs-locally-nvm) - node version manager * [Yarn](https://yarnpkg.com/) - Alternative package manager to NPM * [Truffle](https://www.trufflesuite.com/) - development framework * [Solidity](https://docs.soliditylang.org/en/v0.7.4/) - ethereum smart contract language * [Ganache](https://www.trufflesuite.com/ganache) - local blockchain development * [Web3](https://web3js.readthedocs.io/en/v1.3.0/) - library interact with ethereum nodes * [JavaScript](https://www.javascript.com/) - logic front end and testing smart contracts * [Infura](https://infura.io/) - connection to ethereum networks * [Flash Mintable Tokens](https://blog.openzeppelin.com/flash-mintable-asset-backed-tokens/ ) - For background and what Asset Back Tokens and Flash Mintable Tokens are * [ERC20](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20) - ERC20 Token standards ##### Folder / Directory Structure (key folders and files) * Flash_Mint * contracts * Migrations.sol * IBorrower.sol * MockWETH.sol * FlashMintMockWETH.sol * Borrower.sol * migrations * node_modules * scripts * flashMint.js * truffle.js * package.json * .gitignore * README.md * yarn.lock ### Machine set up (Optional if you have not setup before or having challenges on your system) 1. Mac & Linux - Have python 2.7 installed Check if installed using command below ```sh python -V ``` If not installed download from python [Python Download](https://www.python.org/downloads/) version 2.7 related to your system - Download Ganache Graphical User Interface (GUI ) from [Truffle Framework Site](https://www.trufflesuite.com/ganache) choose related to your system - Have node-gyp installed If not installed, install using command below ```sh npm i -g node-gyp ``` 2. Windows machine Ignore Step 7 in the document below (document for bootcamp setup but applies to setup ubuntu environment) - You may need to [Follow the Windows setup steps in this document](https://www.evernote.com/shard/s584/client/snv?noteGuid=960efc37-4e96-f95a-8c19-cc3b39b54836&noteKey=fd3fd7c99f629eb72a29552f16e4c9e8&sn=https%3A%2F%2Fwww.evernote.com%2Fshard%2Fs584%2Fsh%2F960efc37-4e96-f95a-8c19-cc3b39b54836%2Ffd3fd7c99f629eb72a29552f16e4c9e8&title=B00tc%2540mp%2Bwin10%2Benv.) ### Preconfiguration, Installation 1. You will need nvm if not laready installed; so you can use specific version node version 14 and above ```sh $ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash $ source ~/.nvm/nvm.sh ``` Restart your terminal 2. Install node v12.0.0 or versions above e.g node v14.16.0 ```sh $ nvm install 14.16.0 $ nvm alias default 14.16.0 $ nvm use default ``` 3. Install truffle globally if not installed. Check if installed using ```sh truffle version ``` If not installed install with below ```sh $ npm install -g truffle ``` 4. Ignore if either installed already! If opting to use ganache-cli vs [Ganache GUI](https://www.trufflesuite.com/ganache), install ganache-cli globally. Note that ganache-cli rus on port 8545 and ganache-gui runs on port 7545 as placced in truffle-config.js. Check if ganache-cli installed first with ```sh ganache-cli --version ``` If not installed install with below ```sh $ npm install -g ganache-cli $ ganache-cli ``` Run ganache-cli in different terminal and keep running when compiling,testing, migrating, running app etc 6. Install yarn if not installed. Check if installed using ```sh yarn --version ``` If not installed install with below ```sh $ npm install --global yarn ``` 7. Enter project directory and install dependancies ```sh $ cd nft_collectibles_masterclass $ yarn install ``` ## Running the project Make sure you are in project directory ```sh $ cd flash_mint ``` 1. Run Ganache ```sh $ ganache-cli ``` 2. Compile contracts to check all is working well ```sh $ ganache-cli ``` 3. Migrate contracts to local blockchain Open a new terminal and run ```sh $ truffle migrate --reset ``` 4. Check deployments ```sh $ truffle networks ``` 5. Execute scripts to borrow/mint amounts on FlashToken ```sh $ truffle exec scripts/flashMint.js ``` [Content not decodable] [Content not decodable] [Content not decodable] # Hardhat DeFi This is a section of the Javascript Blockchain/Smart Contract FreeCodeCamp Course. *[⌨️ (19:16:13) Lesson 13: Hardhat DeFi & Aave](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=69373s)* [Full Repo](https://github.com/smartcontractkit/full-blockchain-solidity-course-js) - [Hardhat DeFi](#hardhat-defi) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Typescript](#typescript) - [Optional Gitpod](#optional-gitpod) - [Usage](#usage) - [Testing](#testing) - [Running on a testnet or mainnet](#running-on-a-testnet-or-mainnet) - [Linting](#linting) - [Formatting](#formatting) - [Thank you!](#thank-you) # Getting Started ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an ouput like: `vx.x.x` - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` and get an output like:`x.x.x` - You might need to install it with npm ## Quickstart ``` git clone https://github.com/PatrickAlphaC/hardhat-defi-fcc cd hardhat-defi-fcc yarn ``` ## Typescript For the typescript edition, run: ``` git checkout typescript ``` ### Optional Gitpod If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the `clone this repo` part. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#github.com/PatrickAlphaC/hardhat-defi-fcc) # Usage This repo requires a mainnet rpc provider, but don't worry! You won't need to spend any real money. We are going to be `forking` mainnet, and pretend as if we are interacting with mainnet contracts. All you'll need, is to set a `MAINNET_RPC_URL` environment variable in a `.env` file that you create. You can get setup with one for free from [Alchemy](https://alchemy.com/?a=673c802981) Run: ``` yarn hardhat run scripts/aaveBorrow.js ``` ## Testing We didn't write any tests for this, sorry! # Running on a testnet or mainnet 1. Setup environment variabltes You'll want to set your `KOVAN_RPC_URL` and `PRIVATE_KEY` as environment variables. You can add them to a `.env` file, similar to what you see in `.env.example`. - `PRIVATE_KEY`: The private key of your account (like from [metamask](https://metamask.io/)). **NOTE:** FOR DEVELOPMENT, PLEASE USE A KEY THAT DOESN'T HAVE ANY REAL FUNDS ASSOCIATED WITH IT. - You can [learn how to export it here](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key). - `KOVAN_RPC_URL`: This is url of the kovan testnet node you're working with. You can get setup with one for free from [Alchemy](https://alchemy.com/?a=673c802981) 2. Get testnet ETH Head over to [faucets.chain.link](https://faucets.chain.link/) and get some tesnet ETH. You should see the ETH show up in your metamask. 3. Run ``` yarn hardhat run scripts/aaveBorrow.js --network kovan ``` # Linting To check linting / code formatting: ``` yarn lint ``` or, to fix: ``` yarn lint:fix ``` ## Formatting ``` yarn format ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.<br /> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br /> You will also see any lint errors in the console. ### `yarn test` Launches the test runner in the interactive watch mode.<br /> 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.<br /> 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.<br /> 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 ### Analyzing the Bundle Size This section has moved here: 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 ### Advanced Configuration This section has moved here: 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 ### `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 # html-fund-me-fcc *[⌨️ (12:32:57) Lesson 8: HTML / Javascript Fund Me (Full Stack / Front End)](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=45177s)* This is a minimalistic example what you can find in the [metamask docs](https://docs.metamask.io/guide/create-dapp.html#basic-action-part-1). # Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you've installed it right if you can run: - `git --version` - [Metamask](https://metamask.io/) - This is a browser extension that lets you interact with the blockchain. - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` And get an ouput like: `vx.x.x` - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` And get an output like: `x.x.x` - You might need to install it with npm Confused? You can run `git checkout nodejs-edition` if you'd like to see this with nodejs. ## Typescript For this demo project, we do not have a typescript edition. Please see the NextJS projects for a professional typescript front end. ### Optional Gitpod If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the `clone this repo` part. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#github.com/PatrickAlphaC/html-fund-me-fcc) # Quickstart 1. Clone the repo ``` git clone https://github.com/PatrickAlphaC/html-fund-me-fcc cd html-fund-me-fcc ``` 2. Run the file. You can usually just double click the file to "run it in the browser". Or you can right click the file in your VSCode and run "open with live server". Optionally: If you'd like to run with prettier formatting, or don't have a way to run your file in the browser, run: ``` yarn yarn http-server ``` And you should see a small button that says "connect". ![Connect](connect.png) Hit it, and you should see metamask pop up. # Execute a transaction If you want to execute a transaction follow this: Make sure you have the following installed: 1. You'll need to open up a second terminal and run: ``` git clone https://github.com/PatrickAlphaC/hardhat-fund-me-fcc cd hardhat-fund-me-fcc yarn yarn hardhat node ``` This will deploy a sample contract and start a local hardhat blockchain. 2. Update your `constants.js` with the new contract address. In your `constants.js` file, update the variable `contractAddress` with the address of the deployed "FundMe" contract. You'll see it near the top of the hardhat output. 3. Connect your [metamask](https://metamask.io/) to your local hardhat blockchain. > **PLEASE USE A METAMASK ACCOUNT THAT ISNT ASSOCIATED WITH ANY REAL MONEY.** > I usually use a few different browser profiles to separate my metamasks easily. In the output of the above command, take one of the private key accounts and [import it into your metamask.](https://metamask.zendesk.com/hc/en-us/articles/360015489331-How-to-import-an-Account) Additionally, add your localhost with chainid 31337 to your metamask. 5. Reserve the front end with `yarn http-server`, input an amount in the text box, and hit `fund` button after connecting # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) # Sample Hardhat Project This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, and a script that deploys that contract. Try running some of the following tasks: ```shell npx hardhat help npx hardhat test GAS_REPORT=true npx hardhat test npx hardhat node npx hardhat run scripts/deploy.js ``` [Content not decodable] [Content not decodable] # Hardhat MetaMorphic Upgrades This is a section of the Javascript Blockchain/Smart Contract FreeCodeCamp Course. This is not a complete repo, but a way to show users how to interact with metamorphic contracts that use create2. Video Coming soon... [Full Repo](https://github.com/smartcontractkit/full-blockchain-solidity-course-js) - [Hardhat MetaMorphic Upgrades](#hardhat-metamorphic-upgrades) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Typescript](#typescript) - [Version is: 1](#version-is-1) - [Version is: 2](#version-is-2) - [Resources](#resources) - [Thank you!](#thank-you) This project is apart of the Hardhat FreeCodeCamp video. Video coming soon... # Getting Started ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an ouput like: `vx.x.x` - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` and get an output like: `x.x.x` - You might need to install it with npm ## Quickstart ``` git clone https://github.com/PatrickAlphaC/hardhat-metamorphic-upgrades-fcc cd hardhat-metamorphic-upgrades-fcc yarn ``` ## Typescript COMING SOON... <!-- For the typescript edition, run: ``` git checkout typescript ``` --> # Usage Deploy: ``` yarn hardhat deploy ``` You should see an output similar to this: ``` ---------------------------------------------------- Box address is: 0x5FbDB2315678afecb367f032d93F642f64180aa3 Proxy address is: 0xa7D9Bf84f60248DfBb0ab5512e1eAbBf12c9a4b2 Value is: 77 Version is: 1 ---------------------------------------------------- ---------------------------------------------------- Box address is: 0x0165878A594ca255338adfa4d48449f69242Eb8F Proxy address is: 0xa7D9Bf84f60248DfBb0ab5512e1eAbBf12c9a4b2 Value is: 1 Version is: 2 ---------------------------------------------------- ``` The important thing to note, is that the `Proxy` address stayed the same, while the `Box` address changed. By deleting our proxy contract, we destroyed storage, and started over with our `BoxV2` contract, but kept the same address! You'll want to check for function and storage clashes when working with something like this! # Linting To check linting / code formatting: ``` yarn lint ``` or, to fix: ``` yarn lint:fix ``` # Formatting ``` yarn format ``` # Resources - [MetaMorphic Contracts](https://medium.com/@0age/the-promise-and-the-peril-of-metamorphic-contracts-9eb8b8413c5e) - [How do I read the implementation address of a proxy?](https://ethereum.stackexchange.com/questions/103143/how-do-i-get-the-implementation-contract-address-from-the-proxy-contract-address) - [Create2 Video](https://www.youtube.com/watch?v=883-koWrsO4) - [Function Selector](https://solidity-by-example.org/function-selector/) - [Understanding storage collisions in upgrades](https://docs.openzeppelin.com/upgrades-plugins/1.x/proxies#storage-collisions-between-implementation-versions) # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) # Token Bridge ## Technology Stack & Tools - Solidity (Writing Smart Contract) - Javascript (React & Testing) - [Web3](https://web3js.readthedocs.io/en/v1.5.2/) (Blockchain Interaction) - [Truffle](https://www.trufflesuite.com/docs/truffle/overview) (Development Framework) - [Ganache](https://www.trufflesuite.com/ganache) (For Local Blockchain) ## Requirements For Initial Setup - Install [NodeJS](https://nodejs.org/en/), should work with any node version below 16.5.0 - Install [Truffle](https://www.trufflesuite.com/docs/truffle/overview), In your terminal, you can check to see if you have truffle by running `truffle version`. To install truffle run `npm i -g truffle`. Ideal to have truffle version 5.4 to avoid dependency issues. - Install [Ganache](https://www.trufflesuite.com/ganache). ## Setting Up ### 1. Clone/Download the Repository ### 2. Install Dependencies: `$ npm install` ### 3. Add Binance Testnet to your MetaMask wallet 1. Log in to your MetaMask, and click the profile image in the top right. 2. Navigate to Settings -> Networks -> Add Network 3. Fill in the following: - **Network Name**: BSC - Testnet - **New RPC URL**: https://data-seed-prebsc-1-s1.binance.org:8545/ - **Chain ID**: 97 - **Currency Symbol**: BNB - **Block Explorer URL**: https://testnet.bscscan.com ### 4. Fund Your Wallet You'll need both ETH on Rinkeby & BNB on Binance Testnet in order to deploy your contracts. You'll also want to make sure you fund the same address! - You can get ETH from the chainlink faucet: [https://faucets.chain.link/rinkeby](https://faucets.chain.link/rinkeby) - You can get BNB from the binance faucet: [https://testnet.binance.org/faucet-smart](https://testnet.binance.org/faucet-smart) ### 5. Create .env file You'll want to create a .env file with the following values (see .env.example): - **INFURA_API_KEY=""** - **PRIVATE_KEY=""** (Private key for the account used in deploying) - **REACT_APP_INFURA_API_KEY=""** (Will need to connect to a node while on a different network) - **REACT_APP_PRIVATE_KEY=""** (Private key for the account used to call contract methods on behalf of the user) Note: The REACT_APP variables should/can be the same as your INFURA_API_KEY & PRIVATE_KEY. ### 6. Migrate Smart Contracts 1. `$ truffle migrate --reset --network rinkeby` 2. `$ truffle migrate --reset --network bsc_testnet` ### 7. Launch Frontend `$ npm start` ### 6. Verify Network & Add Token to MetaMask You'll want to make sure you are connected to Rinkeby, as this is the main network for the tokens we have deployed. On the frontend there will be a button called "Add Token to MetaMask". This will add the token we deployed to your MetaMask, you should see 1,000,000 tokens in your wallet. ### 7. Bridge Over Some Tokens In the input field, input how many tokens you want to "bridge" over, then click the button "Bridge to Binance". It's important to wait until the spinner stops to avoid losing tokens. ### 8. Switch to Binance After the completion, a new button should appear to switch networks. Click on that, connect your wallet, add the token to your MetaMask, and you should see the amount you bridged over now in your wallet. ### 9. Bridge over to Rinkeby Once on the Binance network, you can bridge over funds back to Rinkeby using the same steps as you did to bridge from Rinkeby. Contract presets are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com/) as a more powerful alternative. [Content not decodable] # 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 # Create and Deploy ERC20 Token to Arbitrum using Truffle, Web3 Stack Deploy ERC20 token to Arbitrum using Truffle to Arbitrum Layer2 Testnet only. Read up on our notes on [Arbitrum ](https://docs.google.com/document/d/14JUtFQvbWLeXYpTcSlvcOMZqLgC-SBqQT90LL_0W3_k/edit?usp=sharing) Project uses truffle arbitrum box in addition to create-react-app and places build folder in src to demonstrate a full stack app / dapp deployed to an Arbitrum network e.g Arbitrum Rinkeby and Arbitrum Mainnet in addition to normal Ethereum network deployments e.g local ganache, testnets kovan etc. The project makes use of the [Truffle Arbitrum Box](https://www.trufflesuite.com/boxes/arbitrum) To get started! First See below KEY SUMMARY SECTION from original READ.me for info on Arbitrum Box (Ignore ##Installation section on truffle unbox). Below is a summary of key points to compile, run, test, deploy ERC20 to networks Ethereum and Arbitrum Project makes some slight changes to original truffle box folder structure so as to help see Arbitrum side by side Ethereum networks on backend and frontend. ### VERY IMPORTANT!!!!!! In this example we will deploy ERC20 Token directly to Layer2 Arbitrum without a corresponding pair Token on the L1 Ethereum related network. This means that at this point it wont be possible to withdraw these tokens on Arbitrum Layer2 to Layer 1 network. These tokens will only work on Layer2 and is for learning purposes only. --------------------------------KEY SUMMARY----------------------------------------------------------------------- ### Machine set up (Optional if you have not setup before or having challenges on your system) 1. Mac & Linux - Have python 2.7 installed Check if installed using command below ```sh python -V ``` If not installed download from python [Python Download](https://www.python.org/downloads/) version 2.7 related to your system - Download Ganache Graphical User Interface (GUI ) from [Truffle Framework Site](https://www.trufflesuite.com/ganache) choose related to your system - Have node-gyp installed Check if installed using command below ```sh ``` If not installed, install using command below ```sh npm i -g node-gyp ``` 2. Windows machine Ignore Step 7 in the document below (document for bootcamp setup but applies to setup ubuntu environment) - You may need to [Follow the Windows setup steps in this document](https://www.evernote.com/shard/s584/client/snv?noteGuid=960efc37-4e96-f95a-8c19-cc3b39b54836&noteKey=fd3fd7c99f629eb72a29552f16e4c9e8&sn=https%3A%2F%2Fwww.evernote.com%2Fshard%2Fs584%2Fsh%2F960efc37-4e96-f95a-8c19-cc3b39b54836%2Ffd3fd7c99f629eb72a29552f16e4c9e8&title=B00tc%2540mp%2Bwin10%2Benv.) ### Preconfiguration, Installation and Running project locally 1. You will need nvm if not laready installed; so you can use specific version node version 14 and above ```sh $ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash $ source ~/.nvm/nvm.sh ``` Restart your terminal 2. Install node v14.16.0 or versions above ```sh $ nvm install 14.16.0 $ nvm alias default 14.16.0 $ nvm use default ``` 3. Install truffle globally if not installed. Check if installed using ```sh truffle version ``` If not installed install with below ```sh $ npm install -g truffle ``` 4. Ignore if either installed already! If opting to use ganache-cli vs [Ganache GUI](https://www.trufflesuite.com/ganache), install ganache-cli globally. Note that ganache-cli rus on port 8545 and ganache-gui runs on port 7545 as placced in truffle-config.js. Check if ganache-cli installed first with ```sh ganache-cli --version ``` If not installed install with below ```sh $ npm install -g ganache-cli $ ganache-cli ``` Run ganache-cli in different terminal and keep running when compiling,testing, migrating, running app etc 6. Install yarn if not installed. Check if installed using ```sh yarn --version ``` If not installed install with below ```sh $ npm install --global yarn ``` 7. Duplicate the .en.example file and rename it .env. Populate your environment variables .env see .env.example - Leave the MNEMONIC as is, it works with Local Arbitrum network, replace other variables with correct values from Infura and your Metamask Seed phrases. 8. Configure Metamask networks for Arbitrum Networks [You can read up on Arbitrum network configuration, bridge and other important contract accounts here](https://github.com/OffchainLabs/arbitrum/blob/master/docs/Public_Testnet.md) - Arbitrum network to be discuseed here is: Arbitrum Rinkeby. You can run Arbitrum Local Node by following truffle box instructions in later part of this READ.me file. Caution as testnet and mainnet networks are still in early stages at time of writing this document You may require your project to be whitelisted first to deploy on Arbitrum Mainnet. - Setup networks in Metamask, see images below <span><img src="./ImagesReadMe/rinkeby.png" alt="configure Arbitrum Rinkeby" width="200"/> </span> When you deploy Token to network you can copy its contract address and Add Asset to Metamask to play around with sending Token between various accounts. ### Migrating contracts and Testing Locally to Local Ethereum using Ganache 1. Compile,test, deploy, migrate Contracts to Etherem networks e.g Local Ganache Ensure ganache is running in seperate terminal ```sh ganache-cli npm run compile:ethereum npm run test:ethereum npm run migrate:ethereum ``` 2. Run app on localhost front-end ```sh $ yarn start ``` Enter dApp in browser at localhost:3000 ### Migrating contracts and Testing Arbitrum Rinkeby For now the gasPrice for Arbitrum_Testnet which is Arbitrum_Rinkeby is set at 0 {gasPrice: 0} so there is no need to bridge some Rinkeby ETH to Arbitrum ETH for deployment for now. However to bridge some value eg ETH to Arbitrum_Rinkey go to [https://bridge.arbitrum.io/](https://bridge.arbitrum.io/), ensure Metamask is on Rinkeby network and deposit some funds into Arbitrum_Rinkeby. - Setup Infura. If not already added arbitrum network as add-on, got to [infura.io](infura.io) under your account settings go to Billing. In Billing, Click Manage Add-Ons. Select Arbitrum Rollup and add with your card(there is no charge). You may have timeouts if so retry. - Test ```sh npm run test:arbitrum arbitrum_testnet ``` - Migrate ```sh npm run migrate:arbitrum arbitrum_testnet ``` [View on Arbitrum Testnet Scan here](https://rinkeby-explorer.arbitrum.io/#/) - Run app locally ```sh yarn start ``` Add as an Asset in Metamask the deployed token copying its address from the navbar follow [instructions here to add Asset to Metmask](https://metamask.zendesk.com/hc/en-us/articles/360015489031-How-to-view-see-your-tokens-custom-tokens-in-MetaMask) . Explore sending tokens between accounts on the Arbitrum Rinkeby Based Testnet. ### Migrating contracts to Arbitrum Mainnet - Migrate ```sh npm run migrate:arbitrum arbitrum_mainnet ``` - Run app locally ```sh yarn start ``` --------MORE DETAILED INFO _ SEE ORIGINAL TRUFFLE BOX READ.ME BELOW-------------------------------------- - [Requirements](#requirements) - [Installation](#installation) - [Setup](#setup) * [Using the .env File](#using-the-env-file) * [New Configuration File](#new-configuration-file) * [New Directory Structure for Artifacts](#new-directory-structure-for-artifacts) - [Arbitrum](#arbitrum) * [Compiling](#compiling) * [Migrating](#migrating) * [Basic Commands](#basic-commands) * [Testing](#testing) * [Communication Between Ethereum and Arbitrum Chains](#communication-between-ethereum-and-arbitrum-chains) - [Support](#support) <small><i><a href='http://ecotrust-canada.github.io/markdown-toc/'>Table of contents generated with markdown-toc</a></i></small> This Truffle Arbitrum Box provides you with the boilerplate structure necessary to start coding for Arbitrum's Ethereum Layer 2 solution. For detailed information on how Arbitrum works, please see the documentation [here](https://developer.offchainlabs.com/docs/developer_quickstart). As a starting point, this box contains only the SimpleStorage Solidity contract. Including minimal code was a conscious decision as this box is meant to provide the initial building blocks needed to get to work on Arbitrum without pushing developers to write any particular sort of application. With this box, you will be able to compile, migrate, and test Solidity code against a variety of Arbitrum test networks. Arbitrum's Layer 2 solution is almost fully compatible with the EVM. You do not need a separate compiler to compile your Solidity contracts. The main difference between the EVM and the Arbitrum chain that developers will notice is that some opcodes are different and concepts such as time and gas are handled a little differently. Developers can use their regular Solidity compiler to compile contracts for Arbitrum. You can see the complete list of differences between the Arbitrum L2 chain and Ethereum [here](https://developer.offchainlabs.com/docs/differences_overview). ## Requirements The Arbitrum Box has the following requirements: - [Node.js](https://nodejs.org/) 10.x or later - [NPM](https://docs.npmjs.com/cli/) version 5.2 or later - [docker](https://docs.docker.com/get-docker/), version 19.03.12 or later - [docker-compose](https://docs.docker.com/compose/install/), version 1.27.3 or later - Recommended Docker memory allocation of >=8 GB. - Windows, Linux or MacOS Helpful, but optional: - An [Infura](https://infura.io/) account and Project ID - A [MetaMask](https://metamask.io/) account ## Installation > Note that this installation command will only work once the box is published (in the interim you can use `truffle unbox https://github.com/truffle-box/arbitrum-box`). ```bash $ truffle unbox arbitrum ``` ## Setup ### Using the env File ou will need at least one mnemonic to use with the network. The `.dotenv` npm package has been installed for you, and you will need to create a `.env` file for storing your mnemonic and any other needed private information. The `.env` file is ignored by git in this project, to help protect your private data. In general, it is good security practice to avoid committing information about your private keys to github. The `truffle-config.arbitrum.js` file expects a `MNEMONIC` value to exist in `.env` for running commands on each of these networks, as well as a default `MNEMONIC` for the Arbitrum network we will run locally. If you are unfamiliar with using `.env` for managing your mnemonics and other keys, the basic steps for doing so are below: 1) Use `touch .env` in the command line to create a `.env` file at the root of your project. 2) Open the `.env` file in your preferred IDE 3) Add the following, filling in your own Infura project key and mnemonics: ``` MNEMONIC="jar deny prosper gasp flush glass core corn alarm treat leg smart" INFURA_KEY="<Your Infura Project ID>" RINKEBY_MNEMONIC="<Your Rinkeby Mnemonic>" MAINNET_MNEMONIC="<Your Arbitrum Mainnet Mnemonic>" ``` _Note: the value for the `MNEMONIC` above is the one you should use, as it is expected within the local arbitrum network we will run in this Truffle Box._ 4) As you develop your project, you can put any other sensitive information in this file. You can access it from other files with `require('dotenv').config()` and refer to the variable you need with `process.env['<YOUR_VARIABLE>']`. ### New Configuration File A new configuration file exists in this project: `truffle-config.arbitrum.js`. This file contains a reference to the new file location of the `contracts_build_directory` and `contracts_directory` for Arbitrum contracts and lists several networks for running the Arbitrum Layer 2 network instance (see [below](#migrating)). Please note, the classic `truffle-config.js` configuration file is included here as well, because you will eventually want to deploy contracts to Ethereum as well. All normal truffle commands (`truffle compile`, `truffle migrate`, etc.) will use this config file and save built files to `build/ethereum-contracts`. You can save Solidity contracts that you wish to deploy to Ethereum in the `contracts/ethereum` folder. ### New Directory Structure for Artifacts When you compile or migrate, the resulting `json` files will be at `build/arbitrum-contracts/`. This is to distinguish them from any Ethereum contracts you build, which will live in `build/ethereum-contracts`. As we have included the appropriate `contracts_build_directory` in each configuration file, Truffle will know which set of built files to reference! ## Arbitrum ### Compiling To compile your Arbitrum contracts, run the following in your terminal: ``` npm run compile:arbitrum ``` This script lets Truffle know to use the `truffle-config.arbitrum.js` configuration file, which tells Truffle where to store your build artifacts. When adding new contracts to compile, you may find some discrepancies and errors, so please remember to keep an eye on [differences between ethereum and Arbitrum](https://developer.offchainlabs.com/docs/differences_overview)! If you would like to recompile previously compiled contracts, you can manually run this command with `truffle compile --config truffle-config.arbitrum.js` and add the `--all` flag. ### Migrating To migrate on Arbitrum, run: ``` npm run migrate:arbitrum --network=(arbitrum_local | arbitrum_testnet | arbitrum_mainnet) ``` (remember to choose a network from these options!). You have several Arbitrum networks to choose from, prepackaged in this box (note: Layer 1 networks are included in the regular `truffle-config.js` file, to aid you with further development. But here we'll just go through the Layer 2 deployment options available): - `arbitrum_local`: This network is the default Layer 1/Layer 2 integration provided by Arbitrum for testing your Arbitrum-compatible code. Documentation about this setup can be found [here](https://developer.offchainlabs.com/docs/local_blockchain). * You will need to install the code for this network in this box in order to use the scripts associated with it. To install it, run `npm run installLocalArbitrum`. You should only need to run this initiation command once. It will create an `arbitrum` directory in this project that will house the repository you need. If at any point you want to update to the latest Arbitrum docker image, you can delete your `arbitrum` directory and run this command again. If you'd rather house the Arbitrum local blockchain outside of this box, see [these notes](https://developer.offchainlabs.com/docs/installation) for how to get started doing so. * If you wish to use this network, follow these steps, in this order: 1) In a new terminal tab, enter `npm run startLocalEthereum`. 2) Wait for step #1 to complete. The Arbitrum Layer 2 blockchain depends on the existence of a Layer 1 for proper interoperability. 3) In another new terminal tab, enter `npm run startLocalArbitrum`. Wait a little while, and you will see the Arbitrum blockchain running and interacting with the Layer 1 simulation from step #1! You are ready to try out deploying your contracts! - `arbitrum_testnet`: Arbitrum has deployed a testnet to the Rinkeby network. The RPC endpoint is https://arbitrum-rinkeby.infura.io/v3/. In order to access this node for testing, you will need to connect a wallet (we suggest [MetaMask](https://metamask.io/)). Save your seed phrase in a `.env` file as `RINKEBY_MNEMONIC`. Using an `.env` file for the mnemonic is safer practice because it is listed in `.gitignore` and thus will not be committed. * Currently, we have the gasPrice for transactions on Arbitrum Rinkeby set to zero. You should be able to use this network as configured at this time. * In order to set up your MetaMask wallet to connect to the Arbitrum Rinkeby network, you will need to create a custom RPC network in your wallet. You can find detailed steps for this process [here](https://metamask.zendesk.com/hc/en-us/articles/360043227612-How-to-add-custom-Network-RPC-and-or-Block-Explorer). You will need the following information: - RPC Url: `https://arbitrum-rinkeby.infura.io/v3/ + <your infura key>` - chain id: 421611 - `arbitrum_mainnet`: This is the mainnet for Arbitrum's Layer 2 solution. You will need to connect your wallet to the Arbitrum mainnet RPC network, located at https://arbitrum-mainnet.infura.io/v3/ Layer 1 networks are included in the `truffle-config.js` file, but it is not necessary to deploy your base contracts to Layer 1 right now. Eventually, you will likely have a Layer 2 contract that you want to connect with a Layer 1 contract. One example is an ERC20 contract that is deployed on an Arbitrum network. At some point the user will wish to withdraw their funds into Ethereum. There will need to be a contract deployed on Layer 1 that can receive the message from Layer 2 to mint the appropriate tokens on Layer 1 for the user. More information on this system can be found [here](https://developer.offchainlabs.com/docs/bridging_assets). If you would like to migrate previously migrated contracts on the same network, you can run `truffle migrate --config truffle-config.arbitrum.js --network=(arbitrum_local | arbitrum_testnet | arbitrum_mainnet)` and add the `--reset` flag. ## Basic Commands The code here will allow you to compile, migrate, and test your code against an Arbitrum instance. The following commands can be run (more details on each can be found in the next section): To compile: ``` npm run compile:arbitrum ``` To migrate: ``` npm run migrate:arbitrum --network=(arbitrum_local | arbitrum_testnet | arbitrum_mainnet) ``` To test: ``` npm run test:arbitrum --network=(arbitrum_local | arbitrum_testnet | arbitrum_mainnet) ``` ### Testing Currently, this box supports testing via Javascript/TypeScript tests. In order to run the test currently in the boilerplate, use the following command: ``` npm run test:arbitrum --network=(arbitrum_local | arbitrum_testnet | arbitrum_mainnet) ``` Remember that there are some differences between Arbitrum and Ethereum, and refer to the Arbitrum documentation if you run into test failures. ### Communication Between Ethereum and Arbitrum Chains The information above should allow you to deploy to an Arbitrum Layer 2 chain. This is only the first step! Once you are ready to deploy your own contracts to function on Layer 1 using Layer 2, you will need to be aware of the [ways in which Layer 1 and Layer 2 interact in the Arbitrum ecosystem](https://developer.offchainlabs.com/docs/bridging_assets). Keep an eye out for additional Truffle tooling and examples that elucidate this second step to full Arbitrum integration! ## Support Support for this box is available via the Truffle community available [here](https://www.trufflesuite.com/community). I need your confirm about the way to deploy a counterpart ERC20 contract in L2 (actually I followed this process and it works) [Content not decodable] # Simple ERC20 Token deployed to Optimistic Networks ### About ERC20 Token deployed to Optimism [Read accompanying document on Optimism & Optimistic Rollups](https://docs.google.com/document/d/1qJjz3rzGDKnVjs-qDdwDdGmDdtkLWmMjH4gUqrLP7Is/edit?usp=sharing) Stack used is Hardhat, Ethers, ### Technology Stack and Tools * [Node Version Manager](https://heynode.com/tutorial/install-nodejs-locally-nvm) - node version manager * [Optimism](https://optimism.io/) - Optimism Ethereum Scaling solution * [Docker](https://www.docker.com/) - leading containerization solution * [ERC721](https://docs.openzeppelin.com/contracts/3.x/erc721) - ERC721 Token standard (NFTs) * [Metamask Wallet](https://metamask.io/) - Metamask Wallet * [Hardhat](https://hardhat.org//) - development framework alternative to Truffle * [Ethers](https://docs.ethers.io/v5/) - library to interact with Ethereum alternative to Web3.js (supports human readable ABI's) * [Ethereum-Waffle](https://www.npmjs.com/package/ethereum-waffle) - testing framework for smart contracts * [React](https://reactjs.org/) - front end framework * [Solidity](https://docs.soliditylang.org/en/v0.7.4/) - ethereum smart contract language * [JavaScript](https://www.javascript.com/) - logic front end and testing smart contracts * [Infura](https://infura.io/) - connection to ethereum networks * [Open Zeppelin](https://infura.io/) - smart contract libraries ##### Folder / Directory Structure (key folders) * erc20_optimism_hardhhat * node_modules * public * index.html * src * backEnd * artifacts * cache * contracts * migrations * scripts * test * frontEnd * components * contractsData * index.js * .env * .env.example * hardhat.config.js * package.json ### Install packages 1. Enter project directory and install dependancies ```sh $ yarn install ``` ### Running project locally (Layer1 setups) - just to check all is okay and contracts can be deployed, tested, migrated 1. Run local blockchain with hardhat and keep running in seperate terminal ```sh npx hardhat node ``` 2. To compile contracts e.g you make changes to contracts ```sh $ npx hardhat compile --network hardhat ``` 3. To test contracts ```sh $ npx hardhat test --network hardhat ``` 4. Deploy contracts ```sh $ npx hardhat run src/backEnd/scripts/deploy.js --network hardhat $ ``` ### Deploying to Optimism networks [You can also lookup with Optimism Developer documentation here](https://community.optimism.io/docs/) or reference with [Github repository](https://github.com/ethereum-optimism/optimism-tutorial) '@eth-optimism/hardhat-ovm' is the package that brings OVM compiler support to Hardhat projects. 3 Optimism networks to be discuseed here are: local Optimism node, Optimistic Kovan(optimism-kovan) and Optimistic Ethereum(optimism-ethereum). Caution as testnet and mainnet networks are still in early stagesa at time of writing this document. - Setup networks in Metamask, see images below <span><img src="./ImagesReadMe/local8545.png" alt="configure Polygon Matic Mumbai Testne" width="200"/><img src="./ImagesReadMe/local9545.png" alt="configure Polygon Matic Mumbai Testne" width="200"/> <img src="./ImagesReadMe/kovanOptimism.png" alt="configure Polygon Matic Mainnet" width="200"/><img src="./ImagesReadMe/ethereumOptimism.png" alt="configure Polygon Matic Mainnet" width="200"/></span> - Setup your .env file. Duplicate .env.example and rename to .env Copy your Metamask Mnemonic Seed Phrase and replace the one in your .env file with the copied mnemonic - Fund accounts using a bridge from Kovan ETH to Optimistic Kovan and from Ethereum Mainnet to Optimistic Ethereum. Get Kovan testnet ETH into a Metamask account e.g use faucets like https://gitter.im/kovan-testnet/faucet or https://enjin.io/software/kovan-faucet or https://linkfaucet.protofire.io/kovan Ensure Metamask is setup correctly for Optimistic Kovan Network and Optimitic Ethereum Networks see earlier section [or read here](https://community.optimism.io/docs/developers/metamask.html#connecting-manually) [Bridge Kovan ETH to Optimistic Kovan ETH here](https://gateway.optimism.io/). Caution!!! When using mainnet bridign you are using your real funds from Ethereum mainnet to Optimism using the bridge. - If you switch between networks in Metamask you will have to redeploy to the network you swtiched to first. ## 1 => Deploy to Layer 2 Optimism LocalNode Copy and import the first addresses private key from Docker running Local Optimistic Node 1. Ensure you have Docker installed on your machine use this link [https://docs.docker.com/get-docker/](https://docs.docker.com/get-docker/) Check installaton using commands below ``sh docker --version docker-compose --version `` 2. Run Local Optimistic Ethereum Node Run and keep running a local Optimistic Ethereum node using Docker ```sh git clone https://github.com/ethereum-optimism/optimism.git cd optimism yarn install yarn build cd ops docker-compose build docker-compose up ``` 3. Test on local Optimistic Ethereum Node ```sh npx hardhat test --network optimistic_local ``` 4. Deploy Optimistic Ethereum Contract to local Optimism ```sh npx hardhat run src/backEnd/scripts/deploy.js --network optimistic_local ``` 5. Run app on localhost front-end and interact with app ```sh $ npm start ``` Add Token as an Asset in Metamask the deployed token copying its address e.g from the navbar follow [instructions here](https://metamask.zendesk.com/hc/en-us/articles/360015489031-How-to-view-see-your-tokens-custom-tokens-in-MetaMask) Use Decimal = 1 when setting deployed Token for this example Token ## 2 => Deploy to Layer 2 testnet Optimism Kovan 1. Deploy Optimistic Ethereum Contract to local Optimism ```sh npx hardhat run src/backEnd/scripts/deploy.js --network optimistic_kovan ``` 2. Run app on localhost front-end and interact with app ```sh $ npm start ``` Add Token as an Asset in Metamask the deployed token copying its address e.g from the navbar follow [instructions here](https://metamask.zendesk.com/hc/en-us/articles/360015489031-How-to-view-see-your-tokens-custom-tokens-in-MetaMask) Use Decimal = 1 when setting deployed Token for this example Token ## 3 => Deploy to Layer 2 mainnet Optimism Ethereum Caution!! You may need to use some real Ethereum to do deployment. See previous section on using bridge. 1. Deploy Optimistic Ethereum Contract to local Optimism ```sh npx hardhat run src/backEnd/scripts/deploy.js --network optimistic_ethereum ``` 2. Run app on localhost front-end and interact with app ```sh $ npm start ``` Add Token as an Asset in Metamask the deployed token copying its address e.g from the navbar follow [instructions here](https://metamask.zendesk.com/hc/en-us/articles/360015489031-How-to-view-see-your-tokens-custom-tokens-in-MetaMask) Use Decimal = 1 when setting deployed Token for this example Token [Content not decodable] # Ethers Simple Storage This is part of the FreeCodeCamp Solidity & Javascript Blockchain Course. Video Link : *[⌨️ (05:30:42) Lesson 5: Ethers.js Simple Storage](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=19842s)* # Getting Started ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an ouput like: `vx.x.x` - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` and get an output like: `x.x.x` - You might need to install it with npm - [ganache](https://trufflesuite.com/ganache/) - You'll know you did it right if you can run the application and see: <br> <img src="./img/ganache-picture.png" alt="ganache" width="200"/> - You can alternatively use [ganache-cli](https://www.npmjs.com/package/ganache-cli) or [hardhat](https://hardhat.org/) ### Optional Gitpod If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the `clone this repo` part. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#github.com/PatrickAlphaC/ethers-simple-storage-fcc) ## Setup Clone this repo ``` git clone https://github.com/PatrickAlphaC/ethers-simple-storage cd ethers-simple-storage ``` Then install dependencies ``` yarn ``` > Note: You'll notice in our `package.json` we are using `"solc": "0.8.7-fixed"`. Usually, you'll just be able to do `"solc": "0.8.7"` to get a specific version, but there was a bit of an issue with that one... You'll find out why we use 0.8.7 ### Typescript If you like `typescript`, run `git checkout typescript` then run `yarn` ## Usage 1. Run your ganache local chain, by hitting `quickstart` on your ganache application > Save the workspace. This way, next time you open ganache you can start the workspace you've created, otherwise you'll have to redo all the steps below. 2. Copy the `RPC SERVER` sting in your ganache CLI, and place it into your `.env` file similar to what's in `.env.example`. <img src="./img/ganache-http.png" alt="ganache" width="500"/> `.env` Example: ``` RPC_URL=http://0.0.0.0:8545 ``` 3. Hit the key on one of the accounts, and copy the key you see and place it into your `.env` file, similar to what you see in `.env.example`. <img src="./img/ganache-key.png" alt="ganache" width="500"/> <img src="./img/ganache-private-key.png" alt="ganache" width="500"/> `.env` Example: PRIVATE_KEY=11ee3108a03081fe260ecdc106554d09d9d1209bcafd46942b10e02943effc4a 4. Compile your code Run ``` yarn compile ``` You'll see files `SimpleStorage_sol_SimpleStorage.abi` and `SimpleStorage_sol_SimpleStorage.bin` be created. 5. Run your application ``` node deploy.js ``` ### For WSL users 1. Run ``` yarn add ganache ``` 2. Change Server settings in Ganache Settings > Server > Host Name Change Host Name to vEthernet (WSL) 3. Run your application ``` node deploy.js ``` ### Deploying to a testnet Make sure you have a [metamask](https://metamask.io/) or other wallet, and export the private key. **IMPORTANT** USE A METAMASK THAT DOESNT HAVE ANY REAL FUNDS IN IT. Just in case you accidentally push your private key to a public place. I _highly_ recommend you use a different metamask or wallet when developing. 1. [Export your private key](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key) and place it in your `.env` file, as done above. 2. Go to [Alchemy](https://alchemy.com/?a=673c802981) and create a new project on the testnet of choice (ie, Goerli) 3. Grab your URL associated with the testnet, and place it into your `.env` file. 4. Make sure you have [testnet ETH](https://faucets.chain.link/) in your account. You can [get some here](https://faucets.chain.link/). You should get testnet ETH for the same testnet that you made a project in Alchemy (ie, Goerli) 5. Run ``` node deploy.js ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.<br /> Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.<br /> You will also see any lint errors in the console. ### `yarn test` Launches the test runner in the interactive watch mode.<br /> 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.<br /> 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.<br /> 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 ### Analyzing the Bundle Size This section has moved here: 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 ### Advanced Configuration This section has moved here: 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 ### `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 # Token Curated Registry ## Technology Stack & Tools - Solidity (Writing Smart Contract) - Javascript (React & Testing) - [Web3](https://web3js.readthedocs.io/en/v1.5.2/) (Blockchain Interaction) - [Truffle](https://www.trufflesuite.com/docs/truffle/overview) (Development Framework) - [Ganache](https://www.trufflesuite.com/ganache) (For Local Blockchain) ## Requirements For Initial Setup - Install [NodeJS](https://nodejs.org/en/), should work with any node version below 16.5.0 - Install [Truffle](https://www.trufflesuite.com/docs/truffle/overview), In your terminal, you can check to see if you have truffle by running `truffle version`. To install truffle run `npm i -g truffle`. Ideal to have truffle version 5.4 to avoid dependency issues. - Install [Ganache](https://www.trufflesuite.com/ganache). ## Setting Up ### 1. Clone/Download the Repository ### 2. Install Dependencies: `$ npm install` ### 3. Start Ganache ### 4. Migrate Smart Contracts `$ truffle migrate --reset` ### 5. Run 1st script `$ truffle exec .\scripts\1_propose_and_approve.js` ### 6. Run 2nd script `$ truffle exec .\scripts\2_propose_and_reject.js` ### 7. Run Tests (Optional) `$ truffle test` [Content not decodable] [Content not decodable] # Dex Aggregator Swap coins at a cheaper exchange ## Technology Stack & Dependencies - Solidity (Writing Smart Contract) - Javascript (Game interaction) - [Alchemy](https://www.alchemy.com/) As a node provider - [NodeJS](https://nodejs.org/en/) To create hardhat project and install dependencis using npm ### 1. Clone/Download the Repository ### 2. Install Dependencies: ``` npm install ``` ### 4. Run Test ``` npx hardhat test test/testNumber.js ``` ### 5. Deploy Contract to blockchain ``` npx hardhat run scripts/deploy.js ``` ### 6. Interact with deployed contract on Hardhat network ``` npx hardhat console const MyContract = await ethers.getContractFactory("DexAggregator"); const contract = await MyContract.attach("addressOfContract"); await contract.sushiRate(["0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"], "1000000000000000000"); ``` ### 7. Fork ethereum and run the app ``` npx hardhat node --fork https://mainnet.infura.io/v3/<YourInfuraProjectId> ``` ``` npx hardhat run scripts/deploy.js ``` ``` npm start ``` [Content not decodable] [Content not decodable] # Hardhat Simple Storage This is a section of the Javascript Blockchain/Smart Contract FreeCodeCamp Course. *[⌨️ (08:20:17) Lesson 6: Hardhat Simple Storage](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=30017s)* *This repo has been updated for Goerli over Rinkeby.* [Full Repo](https://github.com/smartcontractkit/full-blockchain-solidity-course-js) - [Hardhat Simple Storage](#hardhat-simple-storage) - [- Usage](#--usage) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Typescript](#typescript) - [Optional Gitpod](#optional-gitpod) - [Usage](#usage) - [Testing](#testing) - [Test Coverage](#test-coverage) - [Estimate gas](#estimate-gas) - [Local Deployment](#local-deployment) - [Important localhost note](#important-localhost-note) - [Deployment to a testnet or mainnet](#deployment-to-a-testnet-or-mainnet) - [Verify on etherscan](#verify-on-etherscan) - [In it's current state, if you have your api key set, it will auto verify rinkeby contracts!](#in-its-current-state-if-you-have-your-api-key-set-it-will-auto-verify-rinkeby-contracts) - [Linting](#linting) - [Thank you!](#thank-you) <<<<<<< HEAD - [Usage](#usage) ======= - [Optional Gitpod](#optional-gitpod) - [Useage](#useage) >>>>>>> 4a00535 (goerli update) - [Testing](#testing) - [Test Coverage](#test-coverage) - [Estimate gas](#estimate-gas) - [Local Deployment](#local-deployment) - [Important localhost note](#important-localhost-note) - [Deployment to a testnet or mainnet](#deployment-to-a-testnet-or-mainnet) - [Verify on etherscan](#verify-on-etherscan) - [Linting](#linting) - [Thank you!](#thank-you) This project is apart of the Hardhat FreeCodeCamp video. # Getting Started ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an output like: `vx.x.x` - [Yarn](https://yarnpkg.com/getting-started/install) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` and get an output like: `x.x.x` - You might need to [install it with `npm`](https://classic.yarnpkg.com/lang/en/docs/install/) or `corepack` ## Quickstart ``` git clone https://github.com/PatrickAlphaC/hardhat-simple-storage-fcc cd hardhat-simple-storage-fcc yarn yarn hardhat ``` ## Typescript For the typescript edition, run: ``` git checkout typescript ``` ### Optional Gitpod If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the `clone this repo` part. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#github.com/PatrickAlphaC/hardhat-simple-storage-fcc) # Usage Deploy: ``` npx hardhat run scripts/deploy.js ``` ## Testing ``` npx hardhat test ``` ### Test Coverage ``` npx hardhat coverage ``` ## Estimate gas You can estimate how much gas things cost by running: ``` npx hardhat test ``` And you'll see and output file called `gas-report.txt` ## Local Deployment If you'd like to run your own local hardhat network, you can run: ``` npx hardhat node ``` And then **in a different terminal** ``` npx hardhat run scripts/deploy.js --network localhost ``` And you should see transactions happen in your terminal that is running `npx hardhat node` ### Important localhost note If you use metamask with a local network, everytime you shut down your node, you'll need to reset your account. Settings -> Advanced -> Reset account. Don't do this with a metamask you have real funds in. And maybe don't do this if you're a little confused by this. ## Deployment to a testnet or mainnet 1. Setup environment variables You'll want to set your `GOERLI_RPC_URL` and `PRIVATE_KEY` as environment variables. You can add them to a `.env` file, similar to what you see in `.env.example`. - `PRIVATE_KEY`: The private key of your account (like from [metamask](https://metamask.io/)). **NOTE:** FOR DEVELOPMENT, PLEASE USE A KEY THAT DOESN'T HAVE ANY REAL FUNDS ASSOCIATED WITH IT. - You can [learn how to export it here](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key). - `GOERLI_RPC_URL`: This is url of the goerli testnet node you're working with. You can get setup with one for free from [Alchemy](https://alchemy.com/?a=673c802981) 2. Get testnet ETH Head over to [faucets.chain.link](https://faucets.chain.link/) and get some tesnet ETH. You should see the ETH show up in your metamask. 3. Deploy ``` <<<<<<< HEAD npx hardhat run scripts/deploy.js --network rinkeby ======= npx hardhat run scripts/deploy.js --network goerli >>>>>>> 4a00535 (goerli update) ``` ### Verify on etherscan If you deploy to a testnet or mainnet, you can verify it if you get an [API Key](https://etherscan.io/myapikey) from Etherscan and set it as an environment variable named `ETHERSCAN_API_KEY`. You can pop it into your `.env` file as seen in the `.env.example`. <<<<<<< HEAD In it's current state, if you have your api key set, it will auto verify rinkeby contracts! ======= In it's current state, if you have your api key set, it will auto verify goerli contracts! >>>>>>> 4a00535 (goerli update) However, you can manual verify with: ``` npx hardhat verify --constructor-args arguments.js DEPLOYED_CONTRACT_ADDRESS ``` # Linting To check linting / code formatting: ``` yarn lint ``` or, to fix: ``` yarn lint:fix ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) Contract presets are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com/) as a more powerful alternative. [Content not decodable] # DODO Flashloans ## Technology Stack & Tools - Solidity (Writing Smart Contract) - Javascript (Testing) - [Hardhat](https://hardhat.org/getting-started/) (Development Framework) - [Ethers](https://docs.ethers.io/v5/) (Blockchain Interactions) - [Alchemy](https://www.alchemy.com/) (Forking Mainnet) ## Requirements For Initial Setup - Install [NodeJS](https://nodejs.org/en/), recommended version is v16.13.2 ## Setting Up ### 1. Clone/Download the Repository ### 2. Install Dependencies: `$ npm install` ### 3. Configure .env file: Create a .env file, and fill in the following values (refer to the .env.example file): - ALCHEMY_API_KEY="API_KEY" - PRIVATE_KEY="YOUR_PRIVATE_KEY" ### 4. Run tests: `npx hardhat test` By default this will fork polygon mainnet and simulate the flashloan ### 5. Run deployment script: `npx hardhat run --network polygon ./scripts/1_deploy.js` Copy the deployed contract address logged to the console. ### 6. Edit flashloan script: You'll want to paste in the address of the deployed contract on line 7 ### 7. Run flashloan script: `npx hardhat run --network polygon ./scripts/2_execute-flashloan.js` [Content not decodable] [Content not decodable] # Hardhat Smartcontract Lottery (Raffle) FCC This is a section of the Javascript Blockchain/Smart Contract FreeCodeCamp Course. *[⌨️ (13:41:02) Lesson 9: Hardhat Smart Contract Lottery](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=49262s)* [Full Repo](https://github.com/smartcontractkit/full-blockchain-solidity-course-js) - [Hardhat Smartcontract Lottery (Raffle) FCC](#hardhat-smartcontract-lottery-raffle-fcc) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Typescript](#typescript) - [Usage](#usage) - [Testing](#testing) - [Test Coverage](#test-coverage) - [Deployment to a testnet or mainnet](#deployment-to-a-testnet-or-mainnet) - [Estimate gas cost in USD](#estimate-gas-cost-in-usd) - [Verify on etherscan](#verify-on-etherscan) - [Typescript differences](#typescript-differences) - [Linting](#linting) - [Thank you!](#thank-you) This project is apart of the Hardhat FreeCodeCamp video. Checkout the full blockchain course video [here.](https://www.youtube.com/watch?v=gyMwXuJrbJQ) # Getting Started ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an ouput like: `vx.x.x` - [Yarn](https://yarnpkg.com/getting-started/install) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` and get an output like: `x.x.x` - You might need to [install it with `npm`](https://classic.yarnpkg.com/lang/en/docs/install/) or `corepack` ## Quickstart ``` git clone https://github.com/PatrickAlphaC/hardhat-smartcontract-lottery-fcc cd hardhat-smartcontract-lottery-fcc yarn ``` ## Typescript If you want to get to typescript and you cloned the javascript version, just run: ``` git checkout typescript yarn ``` # Usage Deploy: ``` yarn hardhat deploy ``` ## Testing ``` yarn hardhat test ``` ### Test Coverage ``` yarn hardhat coverage ``` # Deployment to a testnet or mainnet 1. Setup environment variabltes You'll want to set your `RINKEBY_RPC_URL` and `PRIVATE_KEY` as environment variables. You can add them to a `.env` file, similar to what you see in `.env.example`. - `PRIVATE_KEY`: The private key of your account (like from [metamask](https://metamask.io/)). **NOTE:** FOR DEVELOPMENT, PLEASE USE A KEY THAT DOESN'T HAVE ANY REAL FUNDS ASSOCIATED WITH IT. - You can [learn how to export it here](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key). - `RINKEBY_RPC_URL`: This is url of the rinkeby testnet node you're working with. You can get setup with one for free from [Alchemy](https://alchemy.com/?a=673c802981) 2. Get testnet ETH Head over to [faucets.chain.link](https://faucets.chain.link/) and get some tesnet ETH & LINK. You should see the ETH and LINK show up in your metamask. [You can read more on setting up your wallet with LINK.](https://docs.chain.link/docs/deploy-your-first-contract/#install-and-fund-your-metamask-wallet) 3. Setup a Chainlink VRF Subscription ID Head over to [vrf.chain.link](https://vrf.chain.link/) and setup a new subscription, and get a subscriptionId. You can reuse an old subscription if you already have one. [You can follow the instructions](https://docs.chain.link/docs/get-a-random-number/) if you get lost. You should leave this step with: 1. A subscription ID 2. Your subscription should be funded with LINK 3. Deploy In your `helper-hardhat-config.js` add your `subscriptionId` under the section of the chainId you're using (aka, if you're deploying to rinkeby, add your `subscriptionId` in the `subscriptionId` field under the `4` section.) Then run: ``` yarn hardhat deploy --network rinkeby ``` And copy / remember the contract address. 4. Add your contract address as a Chainlink VRF Consumer Go back to [vrf.chain.link](https://vrf.chain.link) and under your subscription add `Add consumer` and add your contract address. You should also fund the contract with a minimum of 1 LINK. 5. Register a Chainlink Keepers Upkeep [You can follow the documentation if you get lost.](https://docs.chain.link/docs/chainlink-keepers/compatible-contracts/) Go to [keepers.chain.link](https://keepers.chain.link/new) and register a new upkeep. Choose `Custom logic` as your trigger mechanism for automation. Your UI will look something like this once completed: ![Keepers](./img/keepers.png) 6. Enter your raffle! You're contract is now setup to be a tamper proof autonomous verifiably random lottery. Enter the lottery by running: ``` yarn hardhat run scripts/enter.js --network rinkeby ``` ### Estimate gas cost in USD To get a USD estimation of gas cost, you'll need a `COINMARKETCAP_API_KEY` environment variable. You can get one for free from [CoinMarketCap](https://pro.coinmarketcap.com/signup). Then, uncomment the line `coinmarketcap: COINMARKETCAP_API_KEY,` in `hardhat.config.js` to get the USD estimation. Just note, everytime you run your tests it will use an API call, so it might make sense to have using coinmarketcap disabled until you need it. You can disable it by just commenting the line back out. ## Verify on etherscan If you deploy to a testnet or mainnet, you can verify it if you get an [API Key](https://etherscan.io/myapikey) from Etherscan and set it as an environemnt variable named `ETHERSCAN_API_KEY`. You can pop it into your `.env` file as seen in the `.env.example`. In it's current state, if you have your api key set, it will auto verify kovan contracts! However, you can manual verify with: ``` yarn hardhat verify --constructor-args arguments.js DEPLOYED_CONTRACT_ADDRESS ``` ### Typescript differences 1. `.js` files are now `.ts` 2. We added a bunch of typescript and typing packages to our `package.json`. They can be installed with: 1. `yarn add @typechain/ethers-v5 @typechain/hardhat @types/chai @types/node ts-node typechain typescript` 3. The biggest one being [typechain](https://github.com/dethcrypto/TypeChain) 1. This gives your contracts static typing, meaning you'll always know exactly what functions a contract can call. 2. This gives us `factories` that are specific to the contracts they are factories of. See the tests folder for a version of how this is implemented. 4. We use `imports` instead of `require`. Confusing to you? [Watch this video](https://www.youtube.com/watch?v=mK54Cn4ceac) 5. Add `tsconfig.json` # Linting To check linting / code formatting: ``` yarn lint ``` or, to fix: ``` yarn lint:fix ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) ### Mini DeFi lending aggregator ## 📃 Instructions to run 0. **Install dependencies in project directory(working with node v12.10.)** </br>```npm i``` 1. **Install ganache-cli (globaly)** </br>```npm i -g ganache-cli``` 2. **In 1st terminal window fork mainnet with ganache-cli** </br>```ganache-cli -p 7545 -f <https://YOUR_ETH_PROVIDER>``` 3. **(in 2nd window) Run script to get DAI from UniswapV2** </br>```trufle exec script/0_get_dai.js``` 4. **Run script to check DAI APY and allocated accordingly** </br>```trufle exec script/1_deposit.js``` 5. **Run script to again check DAI APY and reallocate funds if there will be a difference** </br>```trufle exec script/2_rebalance.js``` </br> </br>Todo, add script for withdraw/end supplying </br>!Note: To reset data, restart ganache-cli # Art Generator ## Requirements For Initial Setup - Install [NodeJS](https://nodejs.org/en/), Recommended version is 14.16.0 - Generator comes with already created layers, you will need your own layers if you want to create different images ## Setting Up ### 1. Clone/Download the Repository ### 2. Install Dependencies: `$ npm install` ### 3. (Optional) Import Layers If you plan to use different layers than the one already provided, you'll need to update the *layers* folder with your custom layers. ### 4. Edit config.json Inside of the settings folder, you will see a *config.json* file. You'll want to open it and edit the following values to your liking: - **layers** (This will be a list of all your layers, *order is important!*) - **image_description** (A description of your collection) - **image_location** (IPFS link, don't worry about this until after you've uploaded the images to IPFS) - **image_count** (How many images you want to generate) - **image_details** (Adjust the width & height of the generated images) ### 5. Generate rarity.json `$ node scripts/generateRarityConfig.js`. This will generate a rarity.json file inside of settings, you can then edit the weight of specific attributes. By default all layers have a equal weight of 10. By lowering this number you'll get increase the rarity. In more detail, if you have 5 attributes each with a weight of 10, the total weight is 50. A random number is generated from 0 to the total weight, in this case 50. Let's say the random number is 28, it will cycle through each attribute subtracting the weight by the random number until the random number reaches less than or equal to 0. Once that happens, that attribute is selected. ### 5. Generate Images `$ node scripts/create.js` ### 6. Upload your image folder to IPFS After generating the images, a build folder will appear with all your images. You'll want to take the *image* folder and upload to IPFS. ### 7. Re-edit config.json After uploading to IPFS, you'll want to update the IPFS link inside of config.json with a similar format to: *ipfs://QmThdTBCR8DsnXMViDGC13EH9NughYzJrk7VjaAsRBmhX8* ### 8. Regenerate Metadata `$ node scripts/regenerateMetadata.js` # Hardhat NFT Marketplace <br/> <p align="center"> <img src="./img/hero.png" width="500" alt="Hardhat NextJS Marketplace"> </a> </p> <br/> This is a repo showing how to make an NFT Marketplace from scratch! Huge Shoutout to [Matt Durkin](https://twitter.com/mdurkin92) for his help on this repo! [Full Repo](https://github.com/smartcontractkit/full-blockchain-solidity-course-js) - [Hardhat NFT Marketplace](#hardhat-nft-marketplace) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Typescript](#typescript) - [Optional Gitpod](#optional-gitpod) - [Usage](#usage) - [Testing](#testing) - [Deployment to a testnet or mainnet](#deployment-to-a-testnet-or-mainnet) - [Thank you!](#thank-you) # Getting Started ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an ouput like: `vx.x.x` - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` and get an output like: `x.x.x` - You might need to install it with `npm` ## Quickstart ``` git clone https://github.com/PatrickAlphaC/hardhat-nextjs-nft-marketplace-fcc cd hardhat-nextjs-nft-marketplace-fcc yarn ``` ## Typescript TODO!! For the typescript edition, run: ``` git checkout typescript ``` ### Optional Gitpod If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the `clone this repo` part. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#github.com/PatrickAlphaC/hardhat-nft-marketplace-fcc) > Remember if you are using gitpod then you cannot connect your local hardhat node with metamask. To resolve this you can use vs code or testnets instead of local node. # Usage Deploy: ``` yarn hardhat deploy ``` ## Testing ``` yarn hardhat test ``` # Deployment to a testnet or mainnet 1. Setup environment variabltes You'll want to set your `KOVAN_RPC_URL` and `PRIVATE_KEY` as environment variables. You can add them to a `.env` file, similar to what you see in `.env.example`. - `PRIVATE_KEY`: The private key of your account (like from [metamask](https://metamask.io/)). **NOTE:** FOR DEVELOPMENT, PLEASE USE A KEY THAT DOESN'T HAVE ANY REAL FUNDS ASSOCIATED WITH IT. - You can [learn how to export it here](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key). - `KOVAN_RPC_URL`: This is url of the kovan testnet node you're working with. You can get setup with one for free from [Alchemy](https://alchemy.com/?a=673c802981) 2. Get testnet ETH Head over to [faucets.chain.link](https://faucets.chain.link/) and get some tesnet ETH. You should see the ETH show up in your metamask. 3. Deploy ``` yarn hardhat deploy --network kovan ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) # DAO Template <div id="top"></div> - [DAO Template](#dao-template) - [About](#about) - [How to DAO](#how-to-dao) - [No Code Tools](#no-code-tools) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Installation](#installation) - [Usage](#usage) - [On-Chain Governance Example](#on-chain-governance-example) - [Off-Chain governance Example](#off-chain-governance-example) - [Roadmap](#roadmap) - [Contributing](#contributing) - [License](#license) - [Contact](#contact) - [Acknowledgments](#acknowledgments) [You can also see the python/brownie version of this here.](https://github.com/brownie-mix/dao-mix) <!-- ABOUT THE PROJECT --> ## About ### How to DAO This repo is meant to give you all the knowledge you need to start a DAO and do governance. Since what's the point of a DAO if you can't make any decisions! There are 2 main kinds of doing governance. | Feature | On-Chain Governance | Hybrid Governance | | ---------- | ------------------- | ----------------------------- | | Gas Costs | More Expensive | Cheaper | | Components | Just the blockchain | An oracle or trusted multisig | A typical on-chain governance structure might look like: - ERC20 based voting happens on a project like [Tally](https://www.withtally.com/), but could hypothetically be done by users manually calling the vote functions. - Anyone can execute a proposal once it has passed _Examples [Compound](https://compound.finance/governance)_ On-chain governance can be much more expensive, but involves fewer parts, and the tooling is still being developed. A typical hybrid governance with an oracle might look like: - ERC20 based voting happens on a project like [Snapshot](https://snapshot.org/#/) - An oracle like [Chainlink](https://chain.link/) is used to retreive and execute the answers in a decentralized manner. (hint hint, someone should build this. ) A typical hybrid governance with a trusted multisig might looks like: - ERC20 based voting happens on a project like [Snapshot](https://snapshot.org/#/) - A trusted [gnosis multisig](https://gnosis-safe.io/) is used to exectue the results of snapshot. _Examples: [Snapsafe](https://blog.gnosis.pm/introducing-safesnap-the-first-in-a-decentralized-governance-tool-suite-for-the-gnosis-safe-ea67eb95c34f)_ Hybrid governance is much cheaper, just as secure, but the tooling is still being developed. Tools: - [Snapshot](https://snapshot.org/#/) - UI for off-chain voting / sentiment analysis - [Tally](https://www.withtally.com/) - UI for on-chain voting - [Gnosis Safe](https://gnosis-safe.io/) - Multi-sig - [Openzeppelin](https://docs.openzeppelin.com/contracts/4.x/api/governance) - DAO code tools - [Zodiac](https://github.com/gnosis/zodiac) - More DAO code tools - [Openzeppelin Defender](https://openzeppelin.com/defender/) - A tool to propose governance and other contract functions. ### No Code Tools The following have tools to help you start a DAO without having to deploy contracts yourself. - [DAO Stack](https://alchemy.daostack.io/daos/create) - [Aragon](https://www.youtube.com/watch?v=VIyG-PYJv9E) - lol, just kidding. [Here is the real link.](https://aragon.org/) - [Colony](https://colony.io/) - [DAOHaus](https://app.daohaus.club/summon) - [DAO Leaderboard](https://deepdao.io/#/deepdao/dashboard) <p align="right">(<a href="#top">back to top</a>)</p> <!-- GETTING STARTED --> # Getting Started Work with this repo in the browser (optional)<br/> [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/PatrickAlphaC/dao-template) It's recommended that you've gone through the [hardhat getting started documentation](https://hardhat.org/getting-started/) before proceeding here. ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version`and get an ouput like: `vx.x.x` - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` And get an output like: `x.x.x` - You might need to install it with npm ### Installation 1. Clone this repo: ``` git clone https://github.com/PatrickAlphaC/dao-template cd dao-template ``` 2. Install dependencies ```sh yarn ``` or ``` npm i ``` 3. Run the test suite (which also has all the functionality) ``` yarn hardhat test ``` or ``` npx hardhat test ``` If you want to deploy to a testnet: 4. Add a `.env` file with the same contents of `.env.example`, but replaced with your variables. ![WARNING](https://via.placeholder.com/15/f03c15/000000?text=+) **WARNING** ![WARNING](https://via.placeholder.com/15/f03c15/000000?text=+) > DO NOT PUSH YOUR PRIVATE_KEY TO GITHUB <!-- USAGE EXAMPLES --> ## Usage ### On-Chain Governance Example Here is the rundown of what the test suite does. 1. We will deploy an ERC20 token that we will use to govern our DAO. 2. We will deploy a Timelock contract that we will use to give a buffer between executing proposals. 1. Note: **The timelock is the contract that will handle all the money, ownerships, etc** 3. We will deploy our Governence contract 1. Note: **The Governance contract is in charge of proposals and such, but the Timelock executes!** 4. We will deploy a simple Box contract, which will be owned by our governance process! (aka, our timelock contract). 5. We will propose a new value to be added to our Box contract. 6. We will then vote on that proposal. 7. We will then queue the proposal to be executed. 8. Then, we will execute it! Additionally, you can do it all manually on your own local network like so: 1. Setup local blockchain ``` yarn hardhat node ``` 2. Propose a new value to be added to our Box contract In a second terminal (leave your blockchain running) ``` yarn hardhat run scripts/propose.ts --network localhost ``` 3. Vote on that proposal ``` yarn hardhat run scripts/vote.ts --network localhost ``` 4. Queue & Execute proposal! ``` yarn hardhat run scripts/queue-and-execute.ts --network localhost ``` You can also use the [Openzeppelin contract wizard](https://wizard.openzeppelin.com/#governor) to get other contracts to work with variations of this governance contract. ### Off-Chain governance Example > This sectoin is still being developed. Deploy your ERC20 and [make proposals in snapshot](https://docs.snapshot.org/proposals/create). <p align="right">(<a href="#top">back to top</a>)</p> <!-- ROADMAP --> ## Roadmap - [] Add Upgradeability examples with the UUPS proxy pattern - [] Add Chainlink Oracle Integration with Snapsafe example See the [open issues](https://github.com/PatrickAlphaC/dao-template/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 Hardhat - [@HardhatHQ](https://twitter.com/HardhatHQ) Patrick Collins - [@patrickalphac](https://twitter.com/patrickalphac) <p align="right">(<a href="#top">back to top</a>)</p> <!-- ACKNOWLEDGMENTS --> ## Acknowledgments * [Openzeppelin Governance Walkthrough](https://docs.openzeppelin.com/contracts/4.x/governance) * [Openzeppelin Governance Github](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/governance) * [Vitalik on DAOs](https://blog.ethereum.org/2014/05/06/daos-dacs-das-and-more-an-incomplete-terminology-guide/) * [Vitalik on On-Chain Governance](https://vitalik.ca/general/2021/08/16/voting3.html) * [Vitalik on Governance in General](https://vitalik.ca/general/2017/12/17/voting.html) <p align="right">(<a href="#top">back to top</a>)</p> You can check out the [openzeppelin javascript tests](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/e6f26b46fc8015f1b9b09bb85297464069302125/test/governance/extensions/GovernorTimelockControl.test) for a full suite of an example of what is possible. # Language Gas Comparisons The purpose of this repo is to compare the following languages for performance (gas optimization): - [Solidity](https://docs.soliditylang.org/en/v0.8.15/) - [Solidity & in-line Yul](https://docs.soliditylang.org/en/v0.8.15/yul.html?highlight=yul) - [Vyper](https://vyper.readthedocs.io/en/stable/index.html) - [Huff](https://huff.sh/) We also have some raw yul examples, but it's not the focus of this repo. # Initial Results <br/> <p align="center"> <img src="./img/simple-storage-contract-creation.png" width="500" alt="Simple Storage - Gas Creation"> <img src="./img/simple-storage-read-write.png" width="500" alt="Simple Storage - Gas Creation"> </p> <br/> | Language | Contract | Gas Cost Creation | Gas Cost Store & Read Number | |:--------------:|:-------------:|:-----------------:|------------------------------| | Huff ♘ | SimpleStorage | 63240 | 28099 | | Yul 🔡 | SimpleStorage | 66578 | No - Data | | Vyper 🐍 | SimpleStorage | 75722 | 28057 | | Sol 🐉 | SimpleStorage | 90551 | 28152 | | Sol & Yul 🐉🔡 | SimpleStorage | 93987 | 28204 | # Table Of Contents - [Language Gas Comparisons](#language-gas-comparisons) - [Initial Results](#initial-results) - [Table Of Contents](#table-of-contents) - [Working with this repo](#working-with-this-repo) - [Requirements](#requirements) - [Getting Started](#getting-started) - [Contract Creation Gas Costs](#contract-creation-gas-costs) - [Requirements](#requirements-1) - [Getting contract creation gas](#getting-contract-creation-gas) # Working with this repo ## Requirements - [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you've done it right if you can run `git --version` - [Foundry / Foundryup](https://github.com/gakonst/foundry) - This will install `forge`, `cast`, and `anvil` - You can test you've installed them right by running `forge --version` and get an output like: `forge 0.2.0 (f016135 2022-07-04T00:15:02.930499Z)` - To get the latest of each, just run `foundryup` - [Huff Compiler](https://docs.huff.sh/get-started/installing/) - You'll know you've done it right if you can run `huffc --version` and get an output like: `huffc 0.2.0` - [Vyper Compiler](https://vyper.readthedocs.io/en/stable/installing-vyper.html) - You'll know you've done it right if you can run `vyper --version` and get an output like: `0.3.4+commit.f31f0ec` - [Solidity Compiler](https://docs.soliditylang.org/en/latest/installing-solidity.html) - You'll know you've done it right if you can run `solc --verison` and get an output like: - `solc, the solidity compiler commandline interface Version: 0.8.15+commit.e14f2714.Darwin.appleclan` ## Getting Started 1. Clone the repo & install dependencies ``` git clone https://github.com/PatrickAlphaC/sc-language-comparison cd sc-language-comparison make ``` 2. Run tests ``` forge snapshot ``` You'll see the gas outputs in `.gas-snapshot`. This is a good outlook on gas costs on function calls, but not on contract creation. # Contract Creation Gas Costs To test how much gas it costs to deploy a contract, we need to compile the contracts, get their bytecode, and deploy it in a raw transaction. ## Requirements - [Python](https://www.python.org/downloads/) - You'll know you've done it right if you can run `python --verison` or `python3 --version` and get an output like: - `Python 3.9.5` - [web3py](https://web3py.readthedocs.io/en/stable/) Setup a new venv: ``` python3 -m venv venv source venv/bin/active ``` Then install ``` pip install -r requirements.txt ``` Rememebr to deactivate after done: ``` deactivate ``` ## Getting contract creation gas 1. Compile contracts To get the raw bytecode of each contract: ``` vyper src/vyper/VSimpleStorage.vy > bytecodes/vy/VSimpleStorage huffc src/huff/HSimpleStorage.huff -b > bytecodes/huff/HSimpleStorage solc --strict-assembly --optimize --optimize-runs 20000 yul/YYSimpleStorage.yul --bin | grep 60 > bytecodes/yul/YYSimpleStorage solc --optimize --optimize-runs 20000 src/yulsol/YSimpleStorage.sol --bin | grep 60 > bytecodes/sol/YSimpleStorage solc --optimize --optimize-runs 20000 src/solidity/SSimpleStorage.sol --bin | grep 60 > bytecodes/yul/SSimpleStorage ``` 2. Start local node ``` make anvil ``` 3. Run script ``` python compare_contract_creation.py ``` And you'll get an output like so: ``` 63240 gas for Language.HUFF 75722 gas for Language.VY 90551 gas for Language.SOL 93987 gas for Language.YUL 66578 gas for Language.YYL ``` # Token Sniping Bot ## Technology Stack & Tools - Solidity (Writing Smart Contract) - Javascript (React & Testing) - [Web3](https://web3js.readthedocs.io/en/v1.5.2/) (Blockchain Interaction) - [Truffle](https://www.trufflesuite.com/docs/truffle/overview) (Development Framework) - [Ganache-cli](https://github.com/trufflesuite/ganache) (For Local Blockchain) - [Alchemy](https://www.alchemy.com/) (For forking the Ethereum mainnet) ## Requirements For Initial Setup - Install [NodeJS](https://nodejs.org/en/), I recommend using node version 16.5.0 to avoid any potential dependency issues - Install [Truffle](https://www.trufflesuite.com/docs/truffle/overview), In your terminal, you can check to see if you have truffle by running `truffle --version`. To install truffle run `npm i -g truffle`. - Install [Ganache-cli](https://github.com/trufflesuite/ganache). To see if you have ganache-cli installed, in your command line type `ganache-cli --version`. To install, in your command line type `npm install ganache-cli --global` ## Setting Up ### 1. Clone/Download the Repository ### 2. Install Dependencies: `$ npm install` ### 3. Start Ganache CLI In your terminal run: ``` ganache-cli -f wss://eth-mainnet.alchemyapi.io/v2/<Your-App-Key> -m <Your-Mnemonic-Phrase> -u 0x2fEb1512183545f48f6b9C5b4EbfCaF49CfCa6F3 -p 7545 ``` Replace Your-App-Key with your Alchemy Project ID located in the settings of your project. Replace Your-Mnemonic-Phrase with your own mnemonic phrase. If you don't have a mnemonic phrase to include you can omit it: ``` ganache-cli -f wss://eth-mainnet.alchemyapi.io/v2/<Your-App-Key> -u 0x2fEb1512183545f48f6b9C5b4EbfCaF49CfCa6F3 -p 7545 ``` ### 4. Start the Bot `$ node ./bot.js` ### 5. Migrate Smart Contracts In a seperate terminal run: `$ truffle migrate --reset` ### 6. Fund Accounts `$ truffle exec ./scripts/1_fund.js` ### 6. Create Uniswap Pool `$ truffle exec ./scripts/2_create_pool.js` ### Deploying YF_LP ### 🔧 Preconfiguration 0. **Install dependencies in project directory(working with node v10.19.0)** </br>```npm i``` 1. **Install truffle globally** </br>```npm i -g truffle``` 2. **Rename .env_example to .env and fill PRIVATE_KEYS&DEV_ADDRESS (rest later)** 3. **Compile contracts** </br>```truffle compile``` </br> </br> ## 📃 Instructions to deploy on ETH 0. **Get LP Token address([instructions](https://www.reddit.com/r/CryptoCurrency/comments/jm1wah/how_to_provide_liquidity_on_uniswap_and_stake_lp/) or in Masterclass video) and add it to .env LP_TOKEN_ADDRESS** 1. **In .env fill INFURA_KEY ([instruction](https://ethereumico.io/knowledge-base/infura-api-key-guide/))** 2. **Get Test Rinkeby ETH [link](https://faucet.rinkeby.io/)** 3. **Check the latest block on Rinkeby [link](https://rinkeby.etherscan.io/)** 4. **Add to that number ~1000 blocks and put this number in .env START_BLOCK** 5. **In .env END_BLOCK add higher number than START_BLOCK (e.g. 1M higher)** 6. **Optionally edit also TOKENS_PER_BLOCK & ALLOCATION_POINT (More info in Masterclass video)** 7. **Migrate contracts to ETH** </br>```truffle migrate --reset --network rinkeby``` </br>```...and then follow log instructions``` </br> </br> ## 📃 Instructions to deploy on BSC 1. **Get Test BNB [link](https://testnet.binance.org/faucet-smart)** 2. **Create&Add liquidity pool on PancakeSwap** </br>```truffle exec scripts/create_lp.js --network bsc_testnet``` </br>```...and then follow log instructions``` 3. **Migrate Contracts to BSC** </br>```truffle migrate --reset --network bsc_testnet``` </br>```...and then follow log instructions``` # Signing Messages ### About A simple app to demonstrate signing and recovering messages on the Ethereum Blockchain. ### Usage You need to have [Metamask Wallet](https://metamask.io/). Connect to the app using your wallet. When connected, your address will show on the top navigation bar. You can follow the Metamask prompts after clicking sign etc to complete the transactions on the app ### Technology Stack and Tools * [Node Version Manager](https://heynode.com/tutorial/install-nodejs-locally-nvm) - node version manager * [Metamask Wallet](https://metamask.io/) * [Truffle](https://www.trufflesuite.com/) - development framework * [React](https://reactjs.org/) - front end framework * [Solidity](https://docs.soliditylang.org/en/v0.7.4/) - ethereum smart contract language * [Ganache](https://www.trufflesuite.com/ganache) - local blockchain development * [Web3](https://web3js.readthedocs.io/en/v1.3.0/) - library interact with ethereum nodes * [JavaScript](https://www.javascript.com/) - logic front end and testing smart contracts * [Infura](https://infura.io/) - connection to ethereum networks * [Open Zeppelin](https://infura.io/) - smart contract libraries * [Article- Ethereum Digital Signatures](https://medium.com/mycrypto/the-magic-of-digital-signatures-on-ethereum-98fe184dc9c7) - Ethereum Digital Signatures * [Article- Signing and Verifying Ethereum Signatures](https://ethvigil.com/docs/eth_sign_example_code/) - Signing and Verifying Ethereum Messages https://ethvigil.com/docs/eth_sign_example_code/ ##### Folder / Directory Structure (key folders) * Message_Signing * migrations * public * src * abis * components * contracts index.js * .env.example * package.json * README.md * truffle-config.js * yarn.lock ### Machine set up (Optional if you have not setup before or having challenges on your system) 1. Mac & Linux - Have python 2.7 installed Check if installed using command below ```sh python -V ``` If not installed download from python [Python Download](https://www.python.org/downloads/) version 2.7 related to your system - Download Ganache Graphical User Interface (GUI ) from [Truffle Framework Site](https://www.trufflesuite.com/ganache) choose related to your system - Have node-gyp installed Check if installed using command below ```sh ``` If not installed, install using command below ```sh npm i -g node-gyp ``` 2. Windows machine Ignore Step 7 in the document below (document for bootcamp setup but applies to setup ubuntu environment) - You may need to [Follow the Windows setup steps in this document](https://www.evernote.com/shard/s584/client/snv?noteGuid=960efc37-4e96-f95a-8c19-cc3b39b54836&noteKey=fd3fd7c99f629eb72a29552f16e4c9e8&sn=https%3A%2F%2Fwww.evernote.com%2Fshard%2Fs584%2Fsh%2F960efc37-4e96-f95a-8c19-cc3b39b54836%2Ffd3fd7c99f629eb72a29552f16e4c9e8&title=B00tc%2540mp%2Bwin10%2Benv.) ### Preconfiguration, Installation and Running project locally 1. You will need nvm if not laready installed; so you can use specific version node version 14 and above ```sh $ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash $ source ~/.nvm/nvm.sh ``` Restart your terminal 2. Install node v14.16.0 or versions above ```sh $ nvm install 14.16.0 $ nvm alias default 14.16.0 $ nvm use default ``` 3. Install truffle globally if not installed. Check if installed using ```sh truffle version ``` If not installed install with below ```sh $ npm install -g truffle ``` 4. Ignore if either installed already! If opting to use ganache-cli vs [Ganache GUI](https://www.trufflesuite.com/ganache), install ganache-cli globally. Note that ganache-cli rus on port 8545 and ganache-gui runs on port 7545 as placced in truffle-config.js. Check if ganache-cli installed first with ```sh ganache-cli --version ``` If not installed install with below ```sh $ npm install -g ganache-cli $ ganache-cli ``` Run ganache-cli in different terminal and keep running when compiling,testing, migrating, running app etc 6. Install yarn if not installed. Check if installed using ```sh yarn --version ``` If not installed install with below ```sh $ npm install --global yarn ``` 7. Enter project directory and install dependancies ```sh $ cd message_signing $ yarn install ``` ### Migrating Verification Contract locally 1. To compile contracts e.g you make changes to contracts ```sh $ truffle compile ``` Make sure your truffle.js or truffle-config.js file is properly configured for development environment. 2. Migrate contracts to local running instance ganache If using ganache-cli use ```sh $ truffle migrate --reset ``` ### Migrating Verification Contract Kovan Duplicate the .env.example file and rename it .env. Add the PRIVATE_KEYS as the private key of the Metamask account you will use to deploy. This is the same account you will add testnet ether to. On Metamask click Account Details-> Export Private Key to copy private key. Go to [infura.io](https://infura.io/) and create a project and copy the ID into .env as INFURA_ID 1. Migrate contracts to Ethereum Kovan testnet. You will need Kovan ETH to pay for transactions. Get Kovan ETH into a Metamask account from this [Kovan faucet click here](https://linkfaucet.protofire.io/kovan). Copy your Metamask address into site and click "Send Me 0.1 Test ETH" ```sh $ truffle migrate --reset --network kovan ``` You can verify deployment, check transactions etc on [https://kovan.etherscan.io/](https://kovan.etherscan.io/) ### Interact with app on front-end 1. Run app on localhost front-end ```sh $ yarn start ``` Enter dApp in browser at localhost:3000 2. Hash and Sign message - Enter a message into the input field and click Sign Button (Message will be hashed and Metamask prompts will allow you to sign the message and get back the signature for the signed message) 3. Verify and Recover message - For the hashed message, and signature. Click on the Verify and Recover Message. This will call the recover memsage in Verification contact allowing the address of the signer to be recovered and rendered. You can compare address is the same as the account on the NavBar. ---- MIT # NextJS Smartcontract Lottery (Raffle) FCC This is a section of the Javascript Blockchain/Smart Contract FreeCodeCamp Course. *[⌨️ (16:34:07) Lesson 10: NextJS Smart Contract Lottery (Full Stack / Front End)](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=59647s)* [Full Repo](https://github.com/smartcontractkit/full-blockchain-solidity-course-js) ![App](img/readme-app.png) [Example App here!](https://fancy-dream-3458.on.fleek.co/) [Example App on IPFS here!](ipfs://Qme4KacFx21y6pYuTC6veAU2usryXB3fNWqLkX3a2hMvDe) Built with ❤️ using: NextJS Solidity Chainlink Moralis web3uikit Ethers Hardhat IPFS - [NextJS Smartcontract Lottery (Raffle) FCC](#nextjs-smartcontract-lottery-raffle-fcc) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Typescript](#typescript) - [Optional Gitpod](#optional-gitpod) - [Formatting in VSCode](#formatting-in-vscode) - [Usage](#usage) - [Testing](#testing) - [Deploying to IPFS](#deploying-to-ipfs) - [Deploy to IPFS using Fleek](#deploy-to-ipfs-using-fleek) - [Linting](#linting) - [Thank you!](#thank-you) This project is a part of the Hardhat FreeCodeCamp video. Video coming soon... # Getting Started ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an ouput like: `vx.x.x` - [Yarn](https://yarnpkg.com/getting-started/install) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` and get an output like: `x.x.x` - You might need to [install it with `npm`](https://classic.yarnpkg.com/lang/en/docs/install/) or `corepack` ## Quickstart ``` git clone https://github.com/PatrickAlphaC/nextjs-smartcontract-lottery-fcc cd nextjs-smartcontract-lottery-fcc yarn yarn dev ``` ## Typescript If you want to get to typescript and you cloned the javascript version, just run: ``` git checkout typescript ``` ### Optional Gitpod If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the `clone this repo` part. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#github.com/PatrickAlphaC/nextjs-smartcontract-lottery-fcc) ## Formatting in VSCode To have VSCode extension prettier auto-format `.jsx` and `.tsx`, add the following to your settings.json file: ``` "[typescriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[javascriptreact]": { "editor.defaultFormatter": "esbenp.prettier-vscode" } ``` # Usage 1. Run your local blockchain with the lottery code > In a different terminal / command line ``` git clone https://github.com/PatrickAlphaC/hardhat-fund-me-fcc cd hardhat-fund-me-fcc yarn yarn hardhat node ``` > You can read more about how to use that repo from its [README.md](https://github.com/PatrickAlphaC/hardhat-fund-me-fcc/blob/main/README.md) 2. Add hardhat network to your metamask/wallet - Get the RPC_URL of your hh node (usually `http://127.0.0.1:8545/`) - Go to your wallet and add a new network. [See instructions here.](https://metamask.zendesk.com/hc/en-us/articles/360043227612-How-to-add-a-custom-network-RPC) - Network Name: Hardhat-Localhost - New RPC URL: http://127.0.0.1:8545/ - Chain ID: 31337 - Currency Symbol: ETH (or GO) - Block Explorer URL: None Ideally, you'd then [import one of the accounts](https://metamask.zendesk.com/hc/en-us/articles/360015489331-How-to-import-an-Account) from hardhat to your wallet/metamask. 3. Run this code Back in a different terminal with the code from this repo, run: ``` yarn dev ``` 4. Go to UI and have fun! Head over to your [localhost](http://localhost:3000) and play with the lottery! ## Testing I didn't write any front end tests 😢 If you'd like to create some tests for this repo, please make a PR! # Deploying to IPFS 1. Build your static code. ``` yarn build ``` 2. Export your site ``` yarn next export ``` > Note: Some features of NextJS & Moralis are not static, if you're deviating from this repo, you might run into errors. 3. Deploy to IPFS - [Download IPFS desktop](https://ipfs.io/#install) - Open your [IPFS desktop app](https://ipfs.io/) - Select `import` and choose the folder the above step just created (should be `out`) 4. Copy the CID of the folder you pinned ![IPFS](./img/readme-ipfs.png) 5. Get [IPFS companion](https://chrome.google.com/webstore/detail/ipfs-companion/nibjojkomfdiaoajekhjakgkdhaomnch?hl=en) for your browser (or use [Brave Browser](https://brave.com/)) 5. Go to `ipfs://YOUR_CID_HERE` and see your ipfs deployed site! # Deploy to IPFS using Fleek You can also have [Fleek](https://fleek.co/) auto-deploy your website if you connect your github. Connect to fleek and follow along the docs there. You'll get an IPFS hash and a "regular" URL for your site. # Linting To check linting / code formatting: ``` yarn lint ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) [Content not decodable] # DAO Template <div id="top"></div> - [DAO Template](#dao-template) - [About](#about) - [How to DAO](#how-to-dao) - [No Code Tools](#no-code-tools) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Installation](#installation) - [Optional Gitpod](#optional-gitpod) - [Usage](#usage) - [On-Chain Governance Example](#on-chain-governance-example) - [Off-Chain governance Example](#off-chain-governance-example) - [Roadmap](#roadmap) - [Contributing](#contributing) - [License](#license) - [Contact](#contact) - [Acknowledgments](#acknowledgments) [You can also see the python/brownie version of this here.](https://github.com/brownie-mix/dao-mix) <!-- ABOUT THE PROJECT --> ## About ### How to DAO This repo is meant to give you all the knowledge you need to start a DAO and do governance. Since what's the point of a DAO if you can't make any decisions! There are 2 main kinds of doing governance. | Feature | On-Chain Governance | Hybrid Governance | | ---------- | ------------------- | ----------------------------- | | Gas Costs | More Expensive | Cheaper | | Components | Just the blockchain | An oracle or trusted multisig | A typical on-chain governance structure might look like: - ERC20 based voting happens on a project like [Tally](https://www.withtally.com/), but could hypothetically be done by users manually calling the vote functions. - Anyone can execute a proposal once it has passed _Examples [Compound](https://compound.finance/governance)_ On-chain governance can be much more expensive, but involves fewer parts, and the tooling is still being developed. A typical hybrid governance with an oracle might look like: - ERC20 based voting happens on a project like [Snapshot](https://snapshot.org/#/) - An oracle like [Chainlink](https://chain.link/) is used to retreive and execute the answers in a decentralized manner. (hint hint, someone should build this. ) A typical hybrid governance with a trusted multisig might looks like: - ERC20 based voting happens on a project like [Snapshot](https://snapshot.org/#/) - A trusted [gnosis multisig](https://gnosis-safe.io/) is used to exectue the results of snapshot. _Examples: [Snapsafe](https://blog.gnosis.pm/introducing-safesnap-the-first-in-a-decentralized-governance-tool-suite-for-the-gnosis-safe-ea67eb95c34f)_ Hybrid governance is much cheaper, just as secure, but the tooling is still being developed. Tools: - [Snapshot](https://snapshot.org/#/) - UI for off-chain voting / sentiment analysis - [Tally](https://www.withtally.com/) - UI for on-chain voting - [Gnosis Safe](https://gnosis-safe.io/) - Multi-sig - [Openzeppelin](https://docs.openzeppelin.com/contracts/4.x/api/governance) - DAO code tools - [Zodiac](https://github.com/gnosis/zodiac) - More DAO code tools - [Openzeppelin Defender](https://openzeppelin.com/defender/) - A tool to propose governance and other contract functions. ### No Code Tools The following have tools to help you start a DAO without having to deploy contracts yourself. - [DAO Stack](https://alchemy.daostack.io/daos/create) - [Aragon](https://www.youtube.com/watch?v=VIyG-PYJv9E) - lol, just kidding. [Here is the real link.](https://aragon.org/) - [Colony](https://colony.io/) - [DAOHaus](https://app.daohaus.club/summon) - [DAO Leaderboard](https://deepdao.io/#/deepdao/dashboard) <p align="right">(<a href="#top">back to top</a>)</p> <!-- GETTING STARTED --> # Getting Started It's recommended that you've gone through the [hardhat getting started documentation](https://hardhat.org/getting-started/) before proceeding here. ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version`and get an ouput like: `vx.x.x` - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` And get an output like: `x.x.x` - You might need to install it with npm ### Installation 1. Clone this repo: ``` git clone https://github.com/PatrickAlphaC/dao-template cd dao-template ``` 2. Install dependencies ```sh yarn ``` or ``` npm i ``` 3. Run the test suite (which also has all the functionality) ``` yarn hardhat test ``` or ``` npx hardhat test ``` If you want to deploy to a testnet: 4. Add a `.env` file with the same contents of `.env.example`, but replaced with your variables. ![WARNING](https://via.placeholder.com/15/f03c15/000000?text=+) **WARNING** ![WARNING](https://via.placeholder.com/15/f03c15/000000?text=+) > DO NOT PUSH YOUR PRIVATE_KEY TO GITHUB ### Optional Gitpod If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the `clone this repo` part. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#github.com/PatrickAlphaC/hardhat-dao-fcc) <!-- USAGE EXAMPLES --> ## Usage ### On-Chain Governance Example Here is the rundown of what the test suite does. 1. We will deploy an ERC20 token that we will use to govern our DAO. 2. We will deploy a Timelock contract that we will use to give a buffer between executing proposals. 1. Note: **The timelock is the contract that will handle all the money, ownerships, etc** 3. We will deploy our Governence contract 1. Note: **The Governance contract is in charge of proposals and such, but the Timelock executes!** 4. We will deploy a simple Box contract, which will be owned by our governance process! (aka, our timelock contract). 5. We will propose a new value to be added to our Box contract. 6. We will then vote on that proposal. 7. We will then queue the proposal to be executed. 8. Then, we will execute it! Additionally, you can do it all manually on your own local network like so: 1. Setup local blockchain ``` yarn hardhat node ``` 2. Propose a new value to be added to our Box contract In a second terminal (leave your blockchain running) ``` yarn hardhat run scripts/propose.ts --network localhost ``` 3. Vote on that proposal ``` yarn hardhat run scripts/vote.ts --network localhost ``` 4. Queue & Execute proposal! ``` yarn hardhat run scripts/queue-and-execute.ts --network localhost ``` You can also use the [Openzeppelin contract wizard](https://wizard.openzeppelin.com/#governor) to get other contracts to work with variations of this governance contract. ### Off-Chain governance Example > This sectoin is still being developed. Deploy your ERC20 and [make proposals in snapshot](https://docs.snapshot.org/proposals/create). <p align="right">(<a href="#top">back to top</a>)</p> <!-- ROADMAP --> ## Roadmap - [] Add Upgradeability examples with the UUPS proxy pattern - [] Add Chainlink Oracle Integration with Snapsafe example See the [open issues](https://github.com/PatrickAlphaC/dao-template/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 Hardhat - [@HardhatHQ](https://twitter.com/HardhatHQ) Patrick Collins - [@patrickalphac](https://twitter.com/patrickalphac) <p align="right">(<a href="#top">back to top</a>)</p> <!-- ACKNOWLEDGMENTS --> ## Acknowledgments * [Openzeppelin Governance Walkthrough](https://docs.openzeppelin.com/contracts/4.x/governance) * [Openzeppelin Governance Github](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/governance) * [Vitalik on DAOs](https://blog.ethereum.org/2014/05/06/daos-dacs-das-and-more-an-incomplete-terminology-guide/) * [Vitalik on On-Chain Governance](https://vitalik.ca/general/2021/08/16/voting3.html) * [Vitalik on Governance in General](https://vitalik.ca/general/2017/12/17/voting.html) <p align="right">(<a href="#top">back to top</a>)</p> You can check out the [openzeppelin javascript tests](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/e6f26b46fc8015f1b9b09bb85297464069302125/test/governance/extensions/GovernorTimelockControl.test) for a full suite of an example of what is possible. [Content not decodable] # Hardhat Upgrades This is a section of the Javascript Blockchain/Smart Contract FreeCodeCamp Course. *[⌨️ (28:53:11) Lesson 16: Hardhat Upgrades](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=103991s)* [Full Repo](https://github.com/smartcontractkit/full-blockchain-solidity-course-js) - [Hardhat Upgrades](#hardhat-upgrades) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Typescript](#typescript) - [Optional Gitpod](#optional-gitpod) - [Usage](#usage) - [Testing](#testing) - [Test Coverage](#test-coverage) - [Deployment to a testnet or mainnet](#deployment-to-a-testnet-or-mainnet) - [Scripts](#scripts) - [Estimate gas](#estimate-gas) - [Estimate gas cost in USD](#estimate-gas-cost-in-usd) - [Verify on etherscan](#verify-on-etherscan) - [Linting](#linting) - [Formatting](#formatting) - [Thank you!](#thank-you) This project is apart of the Hardhat FreeCodeCamp video. Video coming soon... # Getting Started ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an ouput like: `vx.x.x` - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` and get an output like: `x.x.x` - You might need to install it with npm ## Quickstart ``` git clone https://github.com/PatrickAlphaC/hardhat-upgrades-fcc cd hardhat-upgrades-fcc yarn ``` ## Typescript For the typescript edition, run: ``` git checkout typescript ``` ### Optional Gitpod If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the `clone this repo` part. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#github.com/PatrickAlphaC/hardhat-upgrades-fcc) # Usage Deploy: ``` yarn hardhat deploy ``` ## Testing ``` yarn hardhat test ``` ### Test Coverage ``` yarn hardhat coverage ``` # Deployment to a testnet or mainnet 1. Setup environment variabltes You'll want to set your `KOVAN_RPC_URL` and `PRIVATE_KEY` as environment variables. You can add them to a `.env` file, similar to what you see in `.env.example`. - `PRIVATE_KEY`: The private key of your account (like from [metamask](https://metamask.io/)). **NOTE:** FOR DEVELOPMENT, PLEASE USE A KEY THAT DOESN'T HAVE ANY REAL FUNDS ASSOCIATED WITH IT. - You can [learn how to export it here](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key). - `KOVAN_RPC_URL`: This is url of the kovan testnet node you're working with. You can get setup with one for free from [Alchemy](https://alchemy.com/?a=673c802981) 2. Get testnet ETH Head over to [faucets.chain.link](https://faucets.chain.link/) and get some tesnet ETH. You should see the ETH show up in your metamask. 3. Deploy ``` yarn hardhat deploy --network kovan ``` ## Scripts After deploy to a testnet or local net, you can run the scripts. ``` yarn hardhat run scripts/fund.js ``` or ``` yarn hardhat run scripts/withdraw.js ``` ## Estimate gas You can estimate how much gas things cost by running: ``` yarn hardhat test ``` And you'll see and output file called `gas-report.txt` ### Estimate gas cost in USD To get a USD estimation of gas cost, you'll need a `COINMARKETCAP_API_KEY` environment variable. You can get one for free from [CoinMarketCap](https://pro.coinmarketcap.com/signup). Then, uncomment the line `coinmarketcap: COINMARKETCAP_API_KEY,` in `hardhat.config.js` to get the USD estimation. Just note, everytime you run your tests it will use an API call, so it might make sense to have using coinmarketcap disabled until you need it. You can disable it by just commenting the line back out. ## Verify on etherscan If you deploy to a testnet or mainnet, you can verify it if you get an [API Key](https://etherscan.io/myapikey) from Etherscan and set it as an environemnt variable named `ETHERSCAN_API_KEY`. You can pop it into your `.env` file as seen in the `.env.example`. In it's current state, if you have your api key set, it will auto verify kovan contracts! However, you can manual verify with: ``` yarn hardhat verify --constructor-args arguments.js DEPLOYED_CONTRACT_ADDRESS ``` # Linting To check linting / code formatting: ``` yarn lint ``` or, to fix: ``` yarn lint:fix ``` # Formatting ``` yarn format ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) ## 📃 Instructions to run 0. **Install dependencies in project directory(working with node v12.10.)** </br>```npm i``` 1. **Install ganache-cli (globaly)** </br>```npm i -g ganache-cli``` 2. **In 1st terminal window fork mainnet with ganache-cli** </br>```ganache-cli -p 7545 -f <https://YOUR_ETH_PROVIDER>``` 3. **In 2nd terminal window run tests** </br>```trufle test``` </br> </br>!Note: To reset data, restart ganache-cli after each test. # Graph NFT Marketplace FCC # Quickstart 1. Install Subgraph CLI ``` yarn global add @graphprotocol/graph-cli ``` 2. Log into [the graph UI](https://thegraph.com/studio/subgraph) and create a new Subgraph. Use Rinkeby as the network. 3. Initialize Subgraph ``` graph init --studio nft-marketplace ``` 4. Authenticate CLI ``` graph auth --studio YOUR_DEPLOY_KEY_HERE ``` 5. Update your `subgraph.yaml` - Update the `address` with your NftMarketplace Address - Update the `startBlock` with the block right before your contract was deployed 6. Build graph locally ``` graph codegen && graph build ``` - `graph codegen`: Generates code in the `generated` folder based on your `schema.graphql` - `graph build`: Generates the build that will be uploaded to the graph 7. Deploy subgraph Replace `VERSION_NUMBER_HERE` with a version number like `0.0.1`. ``` graph deploy --studio nft-marketplace -l VERSION_NUMBER_HERE ``` 8. View your UI Back in your hardhat project, mint and list an NFT with: ``` yarn hardhat run scripts/mint-and-list-item.js --network rinkeby ``` [Content not decodable] [Content not decodable] # Opensea NFT Visualizer Input any address and visualize their collection of NFTs ## Technology Stack & Dependencies - Solidity (Writing Smart Contract) - Javascript (Game interaction) - [NodeJS](https://nodejs.org/en/) To create hardhat project and install dependencis using npm ### 1. Clone/Download the Repository ### 2. Install Dependencies: ``` npm install ``` ### 3. Run app ``` npm start ``` 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 ``` # Defi-Cryptocurrency index fund Defi token index funds where you can inveset in 5 popular defi projects ## Technology Stack & Dependencies - Solidity (Writing Smart Contract) - Javascript (Testing the Smart Contracts) - [NodeJS](https://nodejs.org/en/) To create hardhat project and install dependencis using npm - [Infura](https://infura.io/) To fork the ethereum mainnet ### 1. Clone/Download the Repository ### 2. Install Dependencies: ``` $ npm install ``` ### 3. Run tests - Input infuraProjectId in hardhat config file ``` $ npx hardhat test --network hardhat ``` ### 4. Deploy to Forked Ethereum Mainnet ``` $ npx hardhat node --fork https://mainnet.infura.io/v3/<YourInfuraProjectId> ``` - Import hardhat account in MetaMask ``` $ npx hardhat run --network localhost scripts/deploy.js ``` ### 5. Run frontend React app - Input address of deployed contarct in App.js - You may need to reset your account in MetaMask from settings ``` $ npm start ``` ### 6. Index fund Token allocation uniPrice = 0,00344 eth x 50 tokens = 1.7 ether 53.543 % <br/> mkrPrice = 0,66 eth x 1 tokens = 0,66 eter 20.787 % <br/> compPrice = 0,0412 eth x 10 tokens = 0.4 ether 12.5984 % <br/> kncPrice = 0,00095 eth x 300 tokens = 0.285 ether 8.97 % <br/> snxPrice = 0.013 eth x 100 tokens = 0.13 ether 4.09448 % <br/> total price per coin : ~ 3.2 ether ### Recreating ~$42k profit arbitrage transaction: [etherscan tx link](https://etherscan.io/tx/0x01afae47b0c98731b5d20c776e58bd8ce5c2c89ed4bd3f8727fad3ebf32e9481/) ## 📃 Instructions to run 0. **Install dependencies in project directory(working with node v14.16.1)** </br>```npm i``` 1. **Install ganache-cli (globaly)** </br>```npm i -g ganache-cli``` 2. **In 1st terminal window fork mainnet on 10633644 block** </br>```ganache-cli -p 7545 -f <https://YOUR_ETH_PROVIDER>@10633644``` 3. **In 2nd terminal window migrate Arb contract** </br>```truffle migrate --reset``` 4. **Execute script** </br>```truffle exec scripts/arb.js``` </br>!Note: To reset data, restart ganache-cli after each test. </br> [Content not decodable] # Hardhat Security This is a section of the Javascript Blockchain/Smart Contract FreeCodeCamp Course. This part of the course is to help users understand basic security and some fundamentals of auditing. This repo has a few contracts with big flaws, see if you can see them, and see if the tools help you find them! *[⌨️ (31:28:32) Lesson 18: Security & Auditing ](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=113312s)* [Full Repo](https://github.com/smartcontractkit/full-blockchain-solidity-course-js) - [Hardhat Security](#hardhat-security) - [What is an Audit?](#what-is-an-audit) - [Help your auditors!](#help-your-auditors) - [Process](#process) - [Resources](#resources) - [Tools](#tools) - [Games](#games) - [Blogs](#blogs) - [Audit Examples:](#audit-examples) - [Articles](#articles) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [No Typescript Support](#no-typescript-support) - [Optional Gitpod](#optional-gitpod) - [Usage](#usage) - [Slither](#slither) - [Echidna](#echidna) - [Linting](#linting) - [Formatting](#formatting) - [Thank you!](#thank-you) This project is apart of the Hardhat FreeCodeCamp video. # What is an Audit? An audit is a security focused code review for looking for issues with your code. # Help your auditors! When writing good code, you 100% need to follow these before sending you code to an audit. [Tweet from legendary security expert Tincho](https://twitter.com/tinchoabbate/status/1400170232904400897) - Add comments - This will help your auditors understand what you're doing. - Use [natspec](https://docs.soliditylang.org/en/v0.8.11/natspec-format.html) - Document your functions. DOCUMENT YOUR FUNCTIONS. - Test - If you don't have tests, and test coverage of all your functions and lines of code, you shouldn't go to audit. If your tests don't pass, don't go to audit. - Be ready to talk to your auditors - The more communication, the better. - Be prepared to give them plenty of time. - They literally pour themselves over your code. > "At this time, there are 0 good auditors that can get you an audit in under a week. If an auditor says they can do it in that time frame, they are either doing you a favor or they are shit. " - Patrick Collins, March 4th, 2022 # Process An auditors process looks like this: 1. Run tests 2. Read specs/docs 3. Run fast tools (like slither, linters, static analysis, etc) 4. Manual Analysis 5. Run slow tools (like echidna, manticore, symbolic execution, MythX) 6. Discuss (and repeat steps as needed) 7. Write report ([Example report](https://github.com/transmissions11/solmate/tree/main/audits)) Typically, you organize reports in a chart that looks like this: ![impact image](images/impact.png) # Resources These are some of the best places to learn even MORE about security: PRs welcome to improve the list. ## Tools - [Slither](https://github.com/crytic/slither) - Static analysis from Trail of Bits. - [Echidna](https://github.com/crytic/echidna) - Fuzzing from Trail of Bits. - [Manticore](https://github.com/trailofbits/manticore) - Symbolic execution tool from Trail of Bits. - [MythX](https://mythx.io/) - Paid service for smart contract security. - [Mythrill](https://github.com/ConsenSys/mythril) - MythX free edition. - [ETH Security Toolbox](https://github.com/trailofbits/eth-security-toolbox) - Script to create docker containers configured with Trail of Bits security tools. - [ethersplay](https://github.com/crytic/ethersplay) - ETH Disassembler - [Consensys Security Tools](https://consensys.net/diligence/tools/) - A list of Consensys tools. ## Games - [Ethernaut](https://ethernaut.openzeppelin.com/) (This is a must play!) - [Damn Vulnerable Defi](https://www.damnvulnerabledefi.xyz/) (This is a must play!) ## Blogs - [rekt](https://rekt.news/) - A blog that keeps up with all the "best" hacks in the industry. - [Trail of bits blog](https://blog.trailofbits.com/) - Learn from one of the best auditors in the space. - [Openzeppelin Blog](https://blog.openzeppelin.com/) - Another blog of one of the best auditors in the space. ## Audit Examples: - [Openzeppelin](https://blog.openzeppelin.com/fei-audit-2/) - [Sigma Prime](https://tracer.finance/radar/sigma-prime-audit/) - [Trail of Bits](https://alephzero.org/blog/trail-of-bits-audit-security/) ## Articles - [Smart Contract Security Best Practices](https://consensys.github.io/smart-contract-best-practices/) - Consensys blog on security vulnerabilities. Also [check out their tools.](https://consensys.net/diligence/tools/) - [Chainlink X Certik Blog on Security](https://www.certik.com/resources/blog/technology/top-10-defi-security-best-practices) - I helped write this. 😊 - [More attacks](https://consensys.github.io/smart-contract-best-practices/attacks/denial-of-service/) # Getting Started ## Requirements - [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an ouput like: `vx.x.x` - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` and get an output like: `x.x.x` - You might need to install it with npm - [Docker](https://docs.docker.com/get-docker/) - You'll know you've installed docker right if you can run: - `docker --version` and get an ouput like `Docker version xx.xx.xx, build xxxxx` ## Quickstart ``` git clone https://github.com/PatrickAlphaC/hardhat-security-fcc cd hardhat-security-fcc yarn ``` Then, go right into [usage](#usage) ## No Typescript Support Sorry! Feel free to make a PR if you'd like to see typescript here. ### Optional Gitpod If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the `clone this repo` part. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#github.com/PatrickAlphaC/hardhat-security-fcc) # Usage ## Slither Open the docker shell: ``` yarn toolbox ``` Then, run: ``` slither /src/contracts/ --solc-remaps @openzeppelin=/src/node_modules/@openzeppelin --exclude naming-convention,external-function,low-level-calls ``` To exit: ``` exit ``` ## Echidna Open the docker shell: ``` yarn toolbox ``` Then, run this: ``` echidna-test /src/contracts/test/fuzzing/VaultFuzzTest.sol --contract VaultFuzzTest --config /src/contracts/test/fuzzing/config.yaml ``` To exit: ``` exit ``` # Linting To check linting / code formatting: ``` yarn lint ``` or, to fix: ``` yarn lint:fix ``` # Formatting ``` yarn format ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) <!-- [YouTube Video](https://www.youtube.com/watch?v=M576WGiDBdQ) --> <!-- <br/> <p align="center"> <a href="https://www.youtube.com/watch?v=M576WGiDBdQ" target="_blank"> <img src="./img/youtube_thumbnail.jpeg" width="350" alt="Solidity, Blockchain, and Smart Contract Course – Beginner to Expert Python Tutorial"> </a> </p> <br/> --> # Web3, Full Stack Solidity, Smart Contract & Blockchain - Beginner to Expert ULTIMATE Course | Javascript Edition <br/> <p align="center"> <a href="https://www.youtube.com/watch?v=gyMwXuJrbJQ" target="_blank"> <img src="./img/blockchain1.png" width="500" alt="Solidity, Blockchain, and Smart Contract Course – Beginner to Expert Javascript Tutorial"> </a> </p> <br/> Welcome to the repository for the Ultimate Web3, Full Stack Solidity, and Smart Contract - Beginner to Expert Full Course | Javascript Edition FreeCodeCamp Course! # Link to video: https://www.youtube.com/watch?v=gyMwXuJrbJQ All code references have both a javascript and a typescript edition. Recommended Testnet: Rinkeby # [Testnet Faucets](https://faucets.chain.link) Main Faucet: https://faucets.chain.link Backup Faucet: https://rinkebyfaucet.com/ > ⚠️ All code associated with this course is for demo purposes only. They have not been audited and should not be considered production ready. Please use at your own risk. # Resources For This Course ### Questions - [Github Discussions](https://github.com/smartcontractkit/full-blockchain-solidity-course-js/discussions) - Ask questions and chat about the course here! - [Stack Exchange Ethereum](https://ethereum.stackexchange.com/) - Great place for asking technical questions about Ethereum - [StackOverflow](https://stackoverflow.com/) - Great place for asking technical questions overall # Table of Contents <details> <summary>Resources</summary> <ol> <li><a href="#testnet-faucets">Testnet Faucets</a></li> <li><a href="#resources-for-this-course">Resources For This Course</a><ul> <li><a href="#questions">Questions</a></li> </ul> </li> <li><a href="#table-of-contents">Table of Contents</a></li> </ol> </details> <details> <summary> <a href="#lesson-0-the-edge-of-the-rabbit-hole">Lesson 0: The Edge of the Rabbit Hole</a></summary> <ol> <li> <a href="#welcome-to-the-course">Welcome to the course! </a> </li> <li> <a href="#best-practices">Best Practices </a> </li> </ol> </details> <details> <summary> <a href="#lesson-1-blockchain-basics"> Lesson 1: Blockchain Basics </a> </summary> <ol> <li> <a href="#what-is-a-blockchain-what-does-a-blockchain-do">What is a Blockchain? What does a blockchain do?</a> </li> <li><a href="#the-purpose-of-smart-contracts">The Purpose Of Smart Contracts</a></li> <li><a href="#other-blockchain-benefits">Other Blockchain Benefits</a></li> <li><a href="#what-have-smart-contracts-done-so-far">What have Smart Contracts done so far?</a></li> <li><a href="#making-your-first-transaction">Making Your First Transaction</a></li> <li><a href="#gas-i-introduction-to-gas">Gas I: Introduction to Gas</a></li> <li><a href="#how-do-blockchains-work">How Do Blockchains Work?</a></li> <li><a href="#signing-transactions">Signing Transactions</a></li> <li><a href="#gas-ii">Gas II</a></li> <li><a href="#high-level-blockchain-fundamentals">High-Level Blockchain Fundamentals</a></li> </ol> </details> <details> <summary><a href="#lesson-2-welcome-to-remix-simple-storage">Lesson 2: Welcome to Remix! Simple Storage</a></summary> <ol> <li><a href="#introduction">Introduction</a></li> <li><a href="#setting-up-your-first-contract">Setting Up Your First Contract</a></li> <li><a href="#basic-solidity-types">Basic Solidity: Types</a></li> <li><a href="#basic-solidity-functions">Basic Solidity: Functions</a></li> <li><a href="#basic-solidity-arrays--structs">Basic Solidity: Arrays &amp; Structs</a></li> <li><a href="#basic-solidity-compiler-errors-and-warnings">Basic Solidity: Compiler Errors and Warnings</a></li> <li><a href="#memory-storage-calldata-intro">Memory, Storage, Calldata (Intro)</a></li> <li><a href="#mappings">Mappings</a></li> <li><a href="#deploying-your-first-contract">Deploying your First Contract</a></li> <li><a href="#the-evm--a-recap-of-lesson-2">The EVM &amp; A Recap of Lesson 2</a></li> </ol> </details> <details> <summary><a href="#lesson-3-remix-storage-factory">Lesson 3: Remix Storage Factory</a></summary> <ol> <li><a href="#introduction-1">Introduction</a></li> <li><a href="#basic-solidity-importing-contracts-into-other-contracts">Basic Solidity: Importing Contracts into other Contracts</a></li> <li><a href="#basic-solidity-interacting-with-other-contracts">Basic Solidity: Interacting with other Contracts</a></li> <li><a href="#basic-solidity-inheritance--overrides">Basic Solidity: Inheritance &amp; Overrides</a></li> <li><a href="#lesson-3-recap">Lesson 3 Recap</a></li> </ol> </details> <details> <summary><a href="#lesson-4-remix-fund-me">Lesson 4: Remix Fund Me</a></summary> <ol> <li><a href="#introduction-2">Introduction</a></li> <li><a href="#sending-eth-through-a-function--reverts">Sending ETH Through a Function &amp; Reverts</a></li> <li><a href="#chainlink--oracles">Chainlink &amp; Oracles</a></li> <li><a href="#review-of-sending-eth-and-working-with-chainlink">Review of Sending ETH and working with Chainlink</a></li> <li><a href="#interfaces--price-feeds">Interfaces &amp; Price Feeds</a></li> <li><a href="#importing-from-github--npm">Importing from GitHub &amp; NPM</a></li> <li><a href="#floating-point-math-in-solidtiy">Floating Point Math in Solidity</a></li> <li><a href="#basic-solidity-arrays--structs-ii">Basic Solidity: Arrays &amp; Structs II</a></li> <li><a href="#review-of-interfacs-importing-from-github--math-in-solidity">Review of Interfacs, Importing from GitHub, &amp; Math in Solidity</a></li> <li><a href="#libraries">Libraries</a></li> <li><a href="#safemath-overflow-checking-and-the-unchecked-keywork">SafeMath, Overflow Checking, and the &quot;unchecked&quot; keywork</a></li> <li><a href="#basic-solidity-for-loop">Basic Solidity: For Loop</a></li> <li><a href="#basic-solidity-resetting-an-array">Basic Solidity: Resetting an Array</a></li> <li><a href="#sending-eth-from-a-contract">Sending ETH from a Contract</a></li> <li><a href="#basic-solidity-constructor">Basic Solidity: Constructor</a></li> <li><a href="#basic-solidity-modifiers">Basic Solidity: Modifiers</a></li> <li><a href="#testnet-demo">Testnet Demo</a></li> <li><a href="#advanced-solidity">Advanced Solidity</a><ul> <li><a href="#immutable--constant">Immutable &amp; Constant</a></li> <li><a href="#custom-errors">Custom Errors</a></li> <li><a href="#receive--fallback-functions">Receive &amp; Fallback Functions</a></li> <li><a href="#lesson-4-recap">Lesson 4 Recap</a></li> </ol> </details> <details> <summary><a href="#lesson-5-ethersjs-simple-storage">Lesson 5: Ethers.js Simple Storage</a></summary> <ol> <li><a href="#effective-debugging-strategies--getting-help">Effective Debugging Strategies &amp; Getting Help</a><ul> <li><a href="#how-to-debug-anything-video">How to Debug Anything Video</a></li> </ul> </li> <li><a href="#installation--setup">Installation &amp; Setup</a><ul> <li><a href="#mac--linux-setup">Mac &amp; Linux Setup</a></li> <li><a href="#windows-setup">Windows Setup</a></li> <li><a href="#gitpod">Gitpod</a></li> </ul> </li> <li><a href="#local-development-introduction">Local Development Introduction</a><ul> <li><a href="#optional-javascript-crash-courses">Optional Javascript Crash Courses</a></li> </ul> </li> <li><a href="#tiny-javascript-refresher">Tiny Javascript Refresher</a></li> <li><a href="#asynchronous-programming-in-javascript">Asynchronous Programming in Javascript</a></li> <li><a href="#compiling-our-solidity">Compiling our Solidity</a></li> <li><a href="#ganache--networks">Ganache &amp; Networks</a></li> <li><a href="#introduction-to-ethersjs">Introduction to Ethers.js</a><ul> <li><a href="#a-note-on-the-await-keyword">A Note on the await Keyword</a></li> </ul> </li> <li><a href="#adding-transaction-overrides">Adding Transaction Overrides</a></li> <li><a href="#transaction-receipts">Transaction Receipts</a></li> <li><a href="#sending-a-raw-transaction-in-ethersjs">Sending a &quot;raw&quot; Transaction in Ethersjs</a></li> <li><a href="#interacting-with-contracts-in-ethersjs">Interacting with Contracts in Ethersjs</a></li> <li><a href="#environment-variables">Environment Variables</a></li> <li><a href="#better-private-key-management">Better Private Key Management</a></li> <li><a href="#optional-prettier-formatting">Optional Prettier Formatting</a></li> <li><a href="#deploying-to-a-testnet-or-a-mainnet">Deploying to a Testnet or a Mainnet</a></li> <li><a href="#verifying-on-block-explorers-from-the-ui">Verifying on Block Explorers from the UI</a></li> <li><a href="#alchemy-dashboard--the-mempool">Alchemy Dashboard &amp; The Mempool</a></li> <li><a href="#lesson-5-recap">Lesson 5 Recap</a><ul> <li><a href="#typescript-ethers-simple-storage">Typescript Ethers Simple Storage</a></li> </ul> </li> </ol> </details> <details> <summary><a href="#lesson-6-hardhat-simple-storage">Lesson 6: Hardhat Simple Storage</a></summary> <ol> <li><a href="#introduction-3">Introduction</a></li> <li><a href="#hardhat-setup">Hardhat Setup</a><ul> <li><a href="#troubleshooting-hardaht-setup">Troubleshooting Hardaht Setup</a></li> </ul> </li> <li><a href="#hardhat-setup-continued">Hardhat Setup Continued</a></li> <li><a href="#deploying-simplestorage-from-hardhat">Deploying SimpleStorage from Hardhat</a></li> <li><a href="#networks-in-hardhat">Networks in Hardhat</a></li> <li><a href="#programatic-verification">Programatic Verification</a></li> <li><a href="#interacting-with-contracts-in-hardhat">Interacting with Contracts in Hardhat</a></li> <li><a href="#artifacts-troubleshooting">Artifacts Troubleshooting</a></li> <li><a href="#custom-hardhat-tasks">Custom Hardhat Tasks</a></li> <li><a href="#hardhat-localhost-node">Hardhat Localhost Node</a></li> <li><a href="#the-hardhat-console">The Hardhat Console</a></li> <li><a href="#hardhat-tests">Hardhat Tests</a></li> <li><a href="#hardhat-gas-reporter">Hardhat Gas Reporter</a></li> <li><a href="#solidity-coverage">Solidity Coverage</a></li> <li><a href="#hardhat-waffle">Hardhat Waffle</a></li> <li><a href="#lesson-6-recap">Lesson 6 Recap</a><ul> <li><a href="#typescript-hardhat-simple-storage">Typescript Hardhat Simple Storage</a></li> </ul> </li> </ol> </details> <details> <summary><a href="#lesson-7-hardhat-fund-me">Lesson 7: Hardhat Fund Me</a></summary> <ol> <li><a href="#introduction-4">Introduction</a></li> <li><a href="#hardhat-setup---fund-me">Hardhat Setup - Fund Me</a></li> <li><a href="#linting">Linting</a></li> <li><a href="#hardhat-setup---fund-me---continued">Hardhat Setup - Fund Me - Continued</a></li> <li><a href="#importing-from-npm">Importing from NPM</a></li> <li><a href="#hardhat-deploy">Hardhat Deploy</a></li> <li><a href="#mocking">Mocking</a></li> <li><a href="#utils-folder">Utils Folder</a></li> <li><a href="#testnet-demo---hardhat-fund-me">Testnet Demo - Hardhat Fund Me</a></li> <li><a href="#solidity-style-guide">Solidity Style Guide</a></li> <li><a href="#testing-fund-me">Testing Fund Me</a></li> <li><a href="#breakpoints--debugging">Breakpoints &amp; Debugging</a></li> <li><a href="#gas-iii">Gas III:</a></li> <li><a href="#consolelog--debugging">console.log &amp; Debugging</a></li> <li><a href="#testing-fund-me-ii">Testing Fund Me II</a></li> <li><a href="#storage-in-solidity">Storage in Solidity</a></li> <li><a href="#gas-optimizations-using-storage-knowledge">Gas Optimizations using Storage Knowledge</a></li> <li><a href="#solidity-chainlink-style-guide">Solidity Chainlink Style Guide</a></li> <li><a href="#storage-review">Storage Review</a></li> <li><a href="#staging-tests">Staging Tests</a></li> <li><a href="#running-scripts-on-a-local-node">Running Scripts on a Local Node</a></li> <li><a href="#adding-scripts-to-your-packagejson">Adding Scripts to your package.json</a></li> <li><a href="#pushing-to-github">Pushing to GitHub</a></li> <li><a href="#-tweet-me-add-your-repo-in">🐸🐦 Tweet Me (add your repo in)!</a></li> </ol> </details> <details> <summary><a href="#lesson-8-html--javascript-fund-me-full-stack--front-end">Lesson 8: HTML / Javascript Fund Me (Full Stack / Front End)</a></summary> <ol> <li><a href="#introduction-5">Introduction</a></li> <li><a href="#how-websites-work-with-web3-wallets">How Websites work with Web3 Wallets</a></li> <li><a href="#html-setup">HTML Setup</a></li> <li><a href="#connecting-html-to-metamask">Connecting HTML to Metamask</a></li> <li><a href="#javascript-in-its-own-file">Javascript in it&#39;s own file</a></li> <li><a href="#es6-vs-nodejs">ES6 vs Nodejs</a></li> <li><a href="#sending-a-transaction-from-a-website">Sending a transaction from a Website</a></li> <li><a href="#resetting-an-account-in-metamask">Resetting an Account in Metamask</a></li> <li><a href="#listening-for-events-and-completed-transactions">Listening for Events and Completed Transactions</a></li> <li><a href="#input-forms">Input Forms</a></li> <li><a href="#reading-from-the-blockchain">Reading from the Blockchain</a></li> <li><a href="#withdraw-function">Withdraw Function</a></li> <li><a href="#lesson-8-recap">Lesson 8 Recap</a><ul> <li><a href="#optional-links">Optional Links</a></li> </ul> </li> </ol> </details> <details> <summary><a href="#lesson-9-hardhat-smart-contract-lottery">Lesson 9: Hardhat Smart Contract Lottery</a></summary> <ol> <li><a href="#introduction-6">Introduction</a></li> <li><a href="#hardhat-setup---smart-contract-lottery">Hardhat Setup - Smart Contract Lottery</a></li> <li><a href="#rafflesol-setup">Raffle.sol Setup</a></li> <li><a href="#introduction-to-events">Introduction to Events</a></li> <li><a href="#events-in-rafflesol">Events in Raffle.sol</a></li> <li><a href="#introduction-to-chainlink-vrf">Introduction to Chainlink VRF</a><ul> <li><a href="#sub-lesson-chainlink-vrf">Sub-Lesson: Chainlink VRF</a></li> </ul> </li> <li><a href="#implementing-chainlink-vrf---introduction">Implementing Chainlink VRF - Introduction</a><ul> <li><a href="#hardhat-shorthand">Hardhat Shorthand</a></li> </ul> </li> <li><a href="#implementing-chainlink-vrf---the-request">Implementing Chainlink VRF - The Request</a></li> <li><a href="#implementing-chainlink-vrf---the-fulfill">Implementing Chainlink VRF - The FulFill</a><ul> <li><a href="#modulo">Modulo</a></li> </ul> </li> <li><a href="#introduction-to-chainlink-keepers">Introduction to Chainlink Keepers</a></li> <li><a href="#implementing-chainlink-keepers---checkupkeep">Implementing Chainlink Keepers - checkUpkeep</a><ul> <li><a href="#enums">Enums</a></li> </ul> </li> <li><a href="#implementing-chainlink-keepers---checkupkeep-continued">Implementing Chainlink Keepers - checkUpkeep continued</a></li> <li><a href="#implementing-chainlink-keepers---performupkeep">Implementing Chainlink Keepers - performUpkeep</a></li> <li><a href="#code-cleanup">Code Cleanup</a></li> <li><a href="#deploying-rafflesol">Deploying Raffle.sol</a><ul> <li><a href="#mock-chainlink-vrf-coordinator">Mock Chainlink VRF Coordinator</a></li> <li><a href="#continued">Continued</a></li> </ul> </li> <li><a href="#rafflesol-unit-tests">Raffle.sol Unit Tests</a><ul> <li><a href="#testing-events--chai-matchers">Testing Events &amp; Chai Matchers</a></li> <li><a href="#continued-i">Continued I</a></li> </ul> </li> <li><a href="#hardhat-methods--time-travel">Hardhat Methods &amp; Time Travel</a><ul> <li><a href="#continued-ii">Continued II</a></li> </ul> </li> <li><a href="#callstatic">Callstatic</a><ul> <li><a href="#continued-iii">Continued III</a></li> <li><a href="#massive-promise-test">Massive Promise Test</a></li> <li><a href="#continued-iv">Continued IV</a></li> </ul> </li> <li><a href="#rafflesol-staging-tests">Raffle.sol Staging Tests</a></li> <li><a href="#testing-on-a-testnet">Testing on a Testnet</a><ul> <li><a href="#recommended-link-amounts-for-rinkeby-staging-test">Recommended LINK amounts for Rinkeby Staging Test:</a></li> </ul> </li> <li><a href="#conclusion">Conclusion</a></li> <li><a href="#typescript---smart-contract-lottery">Typescript - Smart Contract Lottery</a></li> </ol> </details> <details> <summary><a href="#lesson-10-nextjs-smart-contract-lottery-full-stack--front-end">Lesson 10: NextJS Smart Contract Lottery (Full Stack / Front End)</a></summary> <ol> <li><a href="#introduction-7">Introduction</a><ul> <li><a href="#optional-sub-lesson-full-stack-development--other-libraries">Optional Sub-Lesson: Full Stack Development &amp; Other Libraries</a></li> </ul> </li> <li><a href="#nextjs-setup">NextJS Setup</a></li> <li><a href="#manual-header-i">Manual Header I</a><ul> <li><a href="#react-hooks">React Hooks</a></li> </ul> </li> <li><a href="#manual-header-ii">Manual Header II</a></li> <li><a href="#useeffect-hook">useEffect Hook</a></li> <li><a href="#local-storage">Local Storage</a></li> <li><a href="#isweb3enabledloading">isWeb3EnabledLoading</a></li> <li><a href="#web3uikit">web3uikit</a></li> <li><a href="#introduction-to-calling-functions-in-nextjs">Introduction to Calling Functions in Nextjs</a><ul> <li><a href="#automatic-constant-value-ui-updater">Automatic Constant Value UI Updater</a></li> <li><a href="#runcontractfunction">runContractFunction</a></li> </ul> </li> <li><a href="#usestate">useState</a></li> <li><a href="#calling-functions-in-nextjs">Calling Functions in NextJS</a></li> <li><a href="#usenotification">useNotification</a></li> <li><a href="#reading--displaying-contract-data">Reading &amp; Displaying Contract Data</a></li> <li><a href="#a-note-about-onsuccess">A Note about <code>onSuccess</code></a></li> <li><a href="#a-challenge-to-you">A Challenge to You</a></li> <li><a href="#tailwind--styling">Tailwind &amp; Styling</a></li> <li><a href="#introduction-to-hosting-your-site">Introduction to Hosting your Site</a></li> <li><a href="#ipfs">IPFS</a></li> <li><a href="#hosting-on-ipfs">Hosting on IPFS</a></li> <li><a href="#hosting-on-ipfs--filecoin-using-fleek">Hosting on IPFS &amp; Filecoin using Fleek</a></li> <li><a href="#filecoin-overview">Filecoin Overview</a></li> <li><a href="#lesson-10-recap">Lesson 10 Recap</a></li> </ol> </details> <details> <summary><a href="#lesson-11-hardhat-starter-kit">Lesson 11: Hardhat Starter Kit</a></summary> <ol> </details> <details> <summary><a href="#lesson-12-hardhat-erc20s">Lesson 12: Hardhat ERC20s</a></summary> <ol> <li><a href="#what-is-an-erc-what-is-an-eip">What is an ERC? What is an EIP?</a></li> <li><a href="#what-is-an-erc20">What is an ERC20?</a></li> <li><a href="#manually-creating-an-erc20-token">Manually Creating an ERC20 Token</a></li> <li><a href="#creating-an-erc20-token-with-openzeppelin">Creating an ERC20 Token with Openzeppelin</a></li> <li><a href="#lesson-12-recap">Lesson 12 Recap</a></li> </ul> </ol> </details> <details> <summary><a href="#lesson-13-hardhat-defi--aave">Lesson 13: Hardhat DeFi &amp; Aave</a></summary> <ol> <li><a href="#what-is-defi">What is DeFi?</a></li> <li><a href="#what-is-aave">What is Aave?</a></li> <li><a href="#programatic-borrowing--lending">Programatic Borrowing &amp; Lending</a></li> <li><a href="#weth---wrapped-eth">WETH - Wrapped ETH</a></li> <li><a href="#forking-mainnet">Forking Mainnet</a></li> <li><a href="#depositing-into-aave">Depositing into Aave</a></li> <li><a href="#borrowing-from-aave">Borrowing from Aave</a></li> <li><a href="#repaying-with-aave">Repaying with Aave</a></li> <li><a href="#visualizing-the-transactions">Visualizing the Transactions</a></li> <li><a href="#lesson-13-recap">Lesson 13 Recap</a></li> <li><a href="#happy-bow-tie-friday-with-austin-griffith">Happy Bow-Tie Friday with Austin Griffith</a><ul> <li><a href="#more-defi-learnings">More DeFi Learnings:</a></li> </ul> </li> </ul> </ol> </details> <details> <summary><a href="#lesson-14-hardhat-nfts-everything-you-need-to-know-about-nfts">Lesson 14: Hardhat NFTs (EVERYTHING you need to know about NFTs)</a></summary> <ol> <li><a href="#what-is-an-nft">What is an NFT?</a></li> <li><a href="#code-overview">Code Overview</a></li> <li><a href="#hardhat-setup-1">Hardhat Setup</a></li> <li><a href="#basic-nft">Basic NFT</a><ul> <li><a href="#write-tests">Write Tests</a></li> </ul> </li> <li><a href="#random-ipfs-nft">Random IPFS NFT</a><ul> <li><a href="#mapping-chainlink-vrf-requests">Mapping Chainlink VRF Requests</a></li> <li><a href="#creating-rare-nfts">Creating Rare NFTs</a></li> <li><a href="#setting-the-nft-image">Setting the NFT Image</a></li> <li><a href="#setting-an-nft-mint-price">Setting an NFT Mint Price</a></li> <li><a href="#deploy-script">Deploy Script</a></li> <li><a href="#uploading-token-images-with-pinata">Uploading Token Images with Pinata</a></li> <li><a href="#uploading-token-uris-metadata-with-pinata">Uploading Token URIs (metadata) with Pinata</a></li> <li><a href="#deploying">Deploying</a></li> <li><a href="#tests">Tests</a></li> </ul> </li> <li><a href="#dynamic-svg-on-chain-nft">Dynamic SVG On-Chain NFT</a><ul> <li><a href="#what-is-an-svg">What is an SVG?</a></li> <li><a href="#initial-code">Initial Code</a></li> <li><a href="#base64-encoding">Base64 Encoding</a></li> </ul> </li> <li><a href="#advanced-evm-opcodes-encoding-and-calling">Advanced: EVM Opcodes, Encoding, and Calling</a><ul> <li><a href="#abiencode--abiencodepacked">abi.encode &amp; abi.encodePacked</a></li> <li><a href="#introduction-to-encoding-function-calls-directly">Introduction to Encoding Function Calls Directly</a></li> <li><a href="#introduction-to-encoding-function-calls-recap">Introduction to Encoding Function Calls Recap</a></li> <li><a href="#encoding-function-calls-directly">Encoding Function Calls Directly</a></li> <li><a href="#creating-an-nft-tokenuri-on-chain">Creating an NFT TokenURI on-Chain</a></li> <li><a href="#making-the-nft-dynamic">Making the NFT Dynamic</a></li> <li><a href="#deploy-script-1">Deploy Script</a></li> </ul> </li> <li><a href="#deploying-the-nfts-to-a-testnet">Deploying the NFTs to a Testnet</a></li> <li><a href="#lesson-14-recap">Lesson 14 Recap</a></li> </ul> </ol> </details> <details> <summary><a href="#lesson-15-nextjs-nft-marketplace-if-you-finish-this-lesson-you-are-a-full-stack-monster">Lesson 15: NextJS NFT Marketplace (If you finish this lesson, you are a full-stack MONSTER!)</a></summary> <ol> <li><a href="#introduction-8">Introduction</a></li> <li><a href="#part-i-nft-marketplace-contracts">Part I: NFT Marketplace Contracts</a><ul> <li><a href="#hardhat-setup-2">Hardhat Setup</a></li> <li><a href="#nftmarketplacesol">NftMarketplace.sol</a></li> </ul> </li> <li><a href="#reentrancy">Reentrancy</a><ul> <li><a href="#nftmarketplacesol---continued">NftMarketplace.sol - Continued</a></li> <li><a href="#nftmarketplacesol---deploy-script">NftMarketplace.sol - Deploy Script</a></li> <li><a href="#nftmarketplacesol---tests">NftMarketplace.sol - Tests</a></li> <li><a href="#nftmarketplacesol---scripts">NftMarketplace.sol - Scripts</a></li> </ul> </li> <li><a href="#part-ii-moralis-front-end">Part II: Moralis Front End</a><ul> <li><a href="#what-is-moralis">What is Moralis?</a></li> <li><a href="#nextjs-setup-1">NextJS Setup</a></li> <li><a href="#adding-tailwind">Adding Tailwind</a></li> <li><a href="#introduction-to-indexing-in-web3">Introduction to Indexing in Web3</a></li> <li><a href="#connecting-moralis-to-our-local-hardhat-node">Connecting Moralis to our Local Hardhat Node</a></li> <li><a href="#moralis-event-sync">Moralis Event Sync</a><ul> <li><a href="#reset-local-chain">Reset Local Chain</a></li> </ul> </li> <li><a href="#moralis-cloud-functions">Moralis Cloud Functions</a><ul> <li><a href="#practice-resetting-the-local-chain">Practice Resetting the Local Chain</a></li> </ul> </li> <li><a href="#moralis-cloud-functions-ii">Moralis Cloud Functions II</a></li> <li><a href="#querying-the-moralis-database">Querying the Moralis Database</a></li> <li><a href="#rendering-the-nft-images">Rendering the NFT Images</a></li> <li><a href="#update-listing-modal">Update Listing Modal</a></li> <li><a href="#buy-nft-listing">Buy NFT Listing</a></li> <li><a href="#listing-nfts-for-sale">Listing NFTs for Sale</a></li> </ul> </li> <li><a href="#part-iii-thegraph-front-end">Part III: TheGraph Front End</a><ul> <li><a href="#introduction-9">Introduction</a></li> <li><a href="#what-is-the-graph">What is The Graph?</a></li> <li><a href="#building-a-subgraph">Building a Subgraph</a></li> <li><a href="#deploying-our-subgraph">Deploying our Subgraph</a></li> <li><a href="#reading-from-the-graph">Reading from The Graph</a></li> <li><a href="#hosting-our-dapp">Hosting our Dapp</a></li> </ul> </li> </ul> </ol> </details> <details> <summary><a href="#lesson-16-hardhat-upgrades">Lesson 16: Hardhat Upgrades</a></summary> <ol> <li><a href="#upgradeable-smart-contracts-overview">Upgradeable Smart Contracts Overview</a></li> <li><a href="#types-of-upgrades">Types of Upgrades</a></li> <li><a href="#delegatecall">Delegatecall</a></li> <li><a href="#small-proxy-example">Small Proxy Example</a></li> <li><a href="#transparent-upgradeable-smart-contract">Transparent Upgradeable Smart Contract</a></li> </ul> </ol> </details> <details> <summary><a href="#lesson-17-hardhat-daos">Lesson 17: Hardhat DAOs</a></summary> <ol> <li><a href="#introduction-10">Introduction</a></li> <li><a href="#what-is-a-dao">What is a DAO?</a></li> <li><a href="#how-to-build-a-dao">How to build a DAO</a></li> </ol> </details> <details> <summary><a href="#lesson-18-security--auditing">Lesson 18: Security &amp; Auditing</a></summary> <ol> <li><a href="#introduction-11">Introduction</a></li> <li><a href="#slither">Slither</a></li> <li><a href="#fuzzing-and-eth-security-toolbox">Fuzzing and Eth Security Toolbox</a></li> <li><a href="#closing-thoughts">Closing Thoughts</a></li> </ol> </details> <details> <summary>More Resources</summary> <ul> <li><a href="#congratulations">Congratulations</a><ul> <li><a href="#where-do-i-go-now">Where do I go now?</a><ul> <li><a href="#learning-more">Learning More</a></li> <li><a href="#community">Community</a></li> <li><a href="#hackathons">Hackathons</a></li> </ul> </li> </ul> </li> </ul> </ul> </details> # Lesson 0: The Edge of the Rabbit Hole ## Welcome to the course! *[⌨️ (00:00:00) Lesson 0: Welcome To Blockchain](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=0s)* ## Best Practices - **Follow the repository:** While going through the course be 100% certain to follow along with the github repository. If you run into in an issue check the chronological-updates in the repo. - **Be Active in the community:** Ask questions and engage with other developers going through the course in the discussions tab, be sure to go and say hello or gm! This space is different from the other industries, you don't have to be secretive; communicate, network and learn with others :) - **Learn at your own pace:** It doesn't matter if it takes you a day, a week, a month or even a year. Progress >>> Perfection - **Take Breaks:** You will exhaust your mind and recall less if you go all out and watch the entire course in one sitting. **Suggested Strategy** every 25 minutes take a 5 min break, and every 2 hours take a longer 30 min break - **Refer to Documentation:** Things are constantly being updated, so whenever Patrick opens up some documentation, open it your end and maybe even have the code sample next to you. # Lesson 1: Blockchain Basics *[⌨️ (00:09:05) Lesson 1: Blockchain Basics](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=545s)* ## What is a Blockchain? What does a blockchain do? - [Bitcoin Whitepaper](https://bitcoin.org/bitcoin.pdf) - [Satoshi Nakamoto](https://en.wikipedia.org/wiki/Satoshi_Nakamoto) - [Ethereum Whitepaper](https://ethereum.org/en/whitepaper/) - [Vitalik Buterin](https://en.wikipedia.org/wiki/Vitalik_Buterin) - [What is a Smart Contract?](https://chain.link/education/smart-contracts) - [Nick Szabo](https://en.wikipedia.org/wiki/Nick_Szabo) - [Hybrid Smart Contracts](https://blog.chain.link/hybrid-smart-contracts-explained/) - [Blockchain Oracles](https://betterprogramming.pub/what-is-a-blockchain-oracle-f5ccab8dbd72?source=friends_link&sk=d921a38466df8a9176ed8dd767d8c77d) - [Terminology](https://connect.comptia.org/content/articles/blockchain-terminology) - [Web3](https://en.wikipedia.org/wiki/Web3) - [What is a blockchain](https://www.investopedia.com/terms/b/blockchain.asp) ## The Purpose Of Smart Contracts - 🎥 [Original Video](https://www.youtube.com/watch?v=_JeRq7Gwj5Y&feature=youtu.be) - 🦬 [My ETH Denver Talk](https://www.youtube.com/watch?v=06hXCX_jj2E) - 🍔 [McDonalds Scandal](https://www.chicagotribune.com/sns-mcdonalds-story.html) - ⛓ [More on the evolution of agreements](https://www.youtube.com/watch?v=ufVyX7JDCgg) - ✍️ [What is a Smart Contract?](https://www.youtube.com/watch?v=ZE2HxTmxfrI) - 🧱 [How does a blockchain work?](https://www.youtube.com/watch?v=SSo_EIwHSd4) - 🔮 [Chainlink & Oracles](https://www.youtube.com/watch?v=tIUHQ7sDoaU) ## Other Blockchain Benefits - Decentralized - Transparency & Flexibility - Speed & Efficiency - Security & Immutability - Counterparty Risk Removal - Trust Minimized Agreements ## What have Smart Contracts done so far? - [DeFi](https://chain.link/education/defi) - [Defi Llama](https://defillama.com/) - [Why DeFi is Important](https://medium.com/the-capital/why-defi-1519cc4d4bd3) - [DAOs](https://betterprogramming.pub/what-is-a-dao-what-is-the-architecture-of-a-dao-how-to-build-a-dao-high-level-d096a97162cc) - [NFTs](https://www.youtube.com/watch?v=9yuHz6g_P50) ## Making Your First Transaction - [Metamask Download Link](https://metamask.io/) - [What is a Private Key?](https://www.coinbase.com/learn/crypto-basics/what-is-a-private-key) - [What is a Secret Phrase?](https://metamask.zendesk.com/hc/en-us/articles/360060826432-What-is-a-Secret-Recovery-Phrase-and-how-to-keep-your-crypto-wallet-secure) - [Etherscan](https://etherscan.io/) - [Rinkeby Etherscan](https://rinkeby.etherscan.io/) - [Kovan Etherscan](https://kovan.etherscan.io/) - Rinkeby Faucet (Check the [link token contracts page](https://docs.chain.link/docs/link-token-contracts/#rinkeby)) - NOTE: The Chainlink documentation always has the most up to date faucets on their [link token contracts page](https://docs.chain.link/docs/link-token-contracts/#rinkeby). If the faucet above is broken, check the chainlink documentation for the most up to date faucet. - OR, use the [Kovan ETH Faucet](https://faucets.chain.link/), just be sure to swap your metamask to kovan! ## Gas I: Introduction to Gas - [Gas and Gas Fees](https://ethereum.org/en/developers/docs/gas/) - [Wei, Gwei, and Ether Converter](https://eth-converter.com/) - [ETH Gas Station](https://ethgasstation.info/) ## How Do Blockchains Work? - [What is a hash?](https://techjury.net/blog/what-is-cryptographic-hash/) - [Blockchain Demo](https://andersbrownworth.com/blockchain/) - [Summary](https://ethereum.org/en/developers/docs/intro-to-ethereum/) ## Signing Transactions - [Public / Private Keys](https://andersbrownworth.com/blockchain/public-private-keys/keys) - [Layer 2 and Rollups](https://ethereum.org/en/developers/docs/scaling/layer-2-rollups/) - [Decentralized Blockchain Oracles](https://blog.chain.link/what-is-the-blockchain-oracle-problem/) ## Gas II - [Block Rewards](https://www.investopedia.com/terms/b/block-reward.asp) - Advanced Gas - [EIP 1559](https://www.youtube.com/watch?v=MGemhK9t44Q) - GWEI, WEI, and ETH - [ETH Converter](https://eth-converter.com/) ## Gas II Summary - [Run Your Own Ethereum Node](https://geth.ethereum.org/docs/getting-started) ## High-Level Blockchain Fundamentals - [Consensus](https://wiki.polkadot.network/docs/learn-consensus) - [Proof of Stake](https://ethereum.org/en/developers/docs/consensus-mechanisms/pos/) - [Proof of Work](https://ethereum.org/en/developers/docs/consensus-mechanisms/pow/) - [Nakamoto Consensus](https://blockonomi.com/nakamoto-consensus/) - [Ethereum 2 (the merge)](https://ethereum.org/en/eth2/) 🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊 Completed Blockchain Basics! 🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊 # Lesson 2: [Welcome to Remix! Simple Storage](https://github.com/PatrickAlphaC/simple-storage-fcc) *[⌨️ (02:01:16) Lesson 2: Welcome to Remix! Simple Storage](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=7276s)* 💻 Code: https://github.com/PatrickAlphaC/simple-storage-fcc ## Introduction - [Remix](https://remix.ethereum.org/) - [Solidity Documentation](https://docs.soliditylang.org/en/v0.8.6/index.html) ## Setting Up Your First Contract - Versioning - Take notes in your code! - [What is a software license](https://snyk.io/learn/what-is-a-software-license/) - SPDX License - Compiling - Contract Declaration ## Basic Solidity: Types - [Types & Declaring Variables](https://docs.soliditylang.org/en/v0.8.13/) - `uint256`, `int256`, `bool`, `string`, `address`, `bytes32` - [Solidity Types](https://docs.soliditylang.org/en/latest/types.html) - [Bits and Bytes](https://www.youtube.com/watch?v=Dnd28lQHquU) - Default Initializations - Comments ## Basic Solidity: Functions - Functions - Deploying a Contract - Smart Contracts have addresses just like our wallets - Calling a public state-changing Function - [Visibility](https://docs.soliditylang.org/en/v0.7.3/contracts.html#visibility-and-getters) - Gas III | An example - Scope - View & Pure Functions ## Basic Solidity: Arrays & Structs - Structs - Intro to Storage - Arrays - Dynamic & Fixed Sized - `push` array function ## Basic Solidity: Compiler Errors and Warnings - Yellow: Warnings are Ok - Red: Errors are not Ok ## Memory, Storage, Calldata (Intro) - 6 Places you can store and access data - calldata - memory - storage - code - logs - stack ## Mappings - [Mappings](https://solidity-by-example.org/mapping) ## Deploying your First Contract - A testnet or mainnet - Connecting Metamask - [Find a faucet here](https://docs.chain.link/docs/link-token-contracts/#rinkeby) - See the faucets at the top of this readme! - Interacting with Deployed Contracts ## The EVM & A Recap of Lesson 2 - The EVM # Lesson 3: Remix Storage Factory *[⌨️ (03:05:34) Lesson 3: Remix Storage Factory](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=11134s)* 💻 Code: https://github.com/PatrickAlphaC/storage-factory-fcc ## Introduction - [Factory Pattern](https://betterprogramming.pub/learn-solidity-the-factory-pattern-75d11c3e7d29) ## Basic Solidity: Importing Contracts into other Contracts - [Composibility](https://chain.link/techtalks/defi-composability) - [Solidity new keyword](https://docs.soliditylang.org/en/v0.8.14/control-structures.html?highlight=new#creating-contracts-via-new) - [Importing Code in solidity](https://solidity-by-example.org/import) ## Basic Solidity: Interacting with other Contracts - To interact, you always need: ABI + Address - [ABI](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html?highlight=abi) ## Basic Solidity: Inheritance & Overrides - [Inheritance](https://solidity-by-example.org/inheritance) - [Override & Virtual Keyword](https://docs.soliditylang.org/en/v0.8.14/contracts.html?highlight=override#function-overriding) ## Lesson 3 Recap # Lesson 4: Remix Fund Me *[⌨️ (03:31:55) Lesson 4: Remix Fund Me](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=12715s)* 💻 Code: https://github.com/PatrickAlphaC/fund-me-fcc ## Introduction ## Sending ETH Through a Function & Reverts - [Fields in a Transaction](https://ethereum.org/en/developers/docs/transactions/) - [More on v,r,s](https://ethereum.stackexchange.com/questions/15766/what-does-v-r-s-in-eth-gettransactionbyhash-mean) - [payable](https://solidity-by-example.org/payable) - [msg.value & Other global keywords](https://docs.soliditylang.org/en/v0.8.14/cheatsheet.html?highlight=cheatsheet#global-variables) - [require](https://codedamn.com/news/solidity/what-is-require-in-solidity) - [revert](https://medium.com/blockchannel/the-use-of-revert-assert-and-require-in-solidity-and-the-new-revert-opcode-in-the-evm-1a3a7990e06e) ## Chainlink & Oracles - [What is a blockchain oracle?](https://chain.link/education/blockchain-oracles) - [What is the oracle problem?](https://blog.chain.link/what-is-the-blockchain-oracle-problem/) - [Chainlink](https://chain.link/) - [Chainlink Price Feeds (Data Feeds)](https://docs.chain.link/docs/get-the-latest-price/) - [data.chain.link](https://data.chain.link/) - [Chainlink VRF](https://docs.chain.link/docs/chainlink-vrf/) - [Chainlink Keepers](https://docs.chain.link/docs/chainlink-keepers/introduction/) - [Chainlink API Calls](https://docs.chain.link/docs/request-and-receive-data/) - [Importing Tokens into your Metamask](https://consensys.net/blog/metamask/how-to-add-your-custom-tokens-in-metamask/) - [Request and Receive Chainlink Model](https://docs.chain.link/docs/architecture-request-model/) ## Review of Sending ETH and working with Chainlink ## Interfaces & Price Feeds - [Chainlink Price Feeds (Data Feeds)](https://docs.chain.link/docs/get-the-latest-price/) - [Chainlink GitHub](https://github.com/smartcontractkit/chainlink) - [Interface](https://solidity-by-example.org/interface) ## Importing from GitHub & NPM - [Chainlink NPM Package](https://www.npmjs.com/package/@chainlink/contracts) ## Floating Point Math in Solidity - [tuple](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html?highlight=tuple#handling-tuple-types) - [Floating Point Numbers in Solidity](https://stackoverflow.com/questions/58277234/does-solidity-supports-floating-point-number) - [Type Casting](https://ethereum.stackexchange.com/questions/6891/type-casting-in-solidity) - Gas Estimation Failed - Someone should make an article explaining this error ## Basic Solidity: Arrays & Structs II - [msg.sender](https://docs.soliditylang.org/en/v0.8.14/cheatsheet.html?highlight=msg.sender) ## Review of Interfaces, Importing from GitHub, & Math in Solidity ## Libraries - [Library](https://docs.soliditylang.org/en/v0.8.14/contracts.html?highlight=library#libraries) - [Solidity-by-example Library](https://solidity-by-example.org/library) ## SafeMath, Overflow Checking, and the "unchecked" keyword - [Openzeppelin Safemath](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol) - [unchecked vs. checked](https://docs.soliditylang.org/en/v0.8.0/control-structures.html#checked-or-unchecked-arithmetic) ## Basic Solidity: For Loop - [For Loop](https://solidity-by-example.org/loop) - `/* */` is another way to make comments ## Basic Solidity: Resetting an Array ## Sending ETH from a Contract - [Transfer, Send, Call](https://solidity-by-example.org/sending-ether/) - [this keyword](https://ethereum.stackexchange.com/questions/1781/what-is-the-this-keyword-in-solidity) ## Basic Solidity: Constructor - [Constructor](https://solidity-by-example.org/constructor) ## Basic Solidity: Modifiers - [Double equals](https://www.geeksforgeeks.org/solidity-operators/) - [Modifier](https://solidity-by-example.org/function-modifier) ## Testnet Demo - [Disconnecting Metamask](https://help.1inch.io/en/articles/4666771-metamask-how-to-connect-disconnect-and-switch-accounts-with-metamask-on-1inch-network) ## Advanced Solidity ### Immutable & Constant - [Immutable](https://solidity-by-example.org/immutable) - [Constant](https://solidity-by-example.org/constants) - [Current ETH Gas Prices](https://etherscan.io/gastracker) - Don't stress about gas optimizations! (yet) - Naming Conventions - [Someone make this!](https://github.com/smartcontractkit/full-blockchain-solidity-course-js/issues/13) ### Custom Errors - [Custom Errors Introduction](https://blog.soliditylang.org/2021/04/21/custom-errors/) ### Receive & Fallback Functions - [Solidity Docs Special Functions](https://docs.soliditylang.org/en/v0.8.14/contracts.html?highlight=fallback#special-functions) - [Fallback](https://solidity-by-example.org/fallback) - [Receive](https://docs.soliditylang.org/en/v0.8.14/contracts.html?highlight=fallback#receive-ether-function) ## Lesson 4 Recap 🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊 Completed Solidity Basics! 🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊 # Lesson 5: Ethers.js Simple Storage *[⌨️ (05:30:42) Lesson 5: Ethers.js Simple Storage](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=19842s)* 💻 Code: https://github.com/PatrickAlphaC/ethers-simple-storage-fcc 🧪 [Alchemy: https://alchemy.com/?a=673c802981](https://alchemy.com/?a=673c802981) ## Effective Debugging Strategies & Getting Help *[⌨️ (5:30:46) Effective Debugging Stategies & Getting Help](https://youtu.be/gyMwXuJrbJQ?t=19846)* 1. Tinker and isolate problem 1. For this course, take at LEAST 15 minutes to figure out a bug. 2. Google / Web Search the Exact problem 1. Go to this GitHub Repo / Discussions 3. Ask a question on a Forum like Stack Exchange Ethereum or Stack Overflow 1. Format your questions!! 2. Use [Markdown](https://www.markdowntutorial.com/) ### How to Debug Anything Video - [Patrick's Original Video](https://www.youtube.com/watch?v=XT8STflvwNo) ## Installation & Setup - [Visual Studio Code](https://code.visualstudio.com/) - [Crash Course](https://www.youtube.com/watch?v=WPqXP_kLzpo) - [NodeJS](https://nodejs.org/en/) - [VSCode Keybindings](https://code.visualstudio.com/docs/getstarted/keybindings) - [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - [What is a terminal?](https://code.visualstudio.com/docs/editor/integrated-terminal) ### Mac & Linux Setup ### Windows Setup - [WSL](https://docs.microsoft.com/en-us/windows/wsl/install) - When working in WSL, use Linux commands instead of Windows commands - [TroubleShooting](https://docs.microsoft.com/en-us/windows/wsl/troubleshooting) - `curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash` > ⚠️ Please use Gitpod as an absolute last resort ### Gitpod - [Gitpod](https://www.gitpod.io/) - **If using this, NEVER share a private key with real money on Gitpod** - Ideally you figure out the MacOS, Linux, or Windows install though ## Local Development Introduction - `CMD + K` or `CTRL + K` clears the terminal - `mkdir ethers-simple-storage-fcc` - `code .` to open VSCode in a new VSCode window ### Optional Javascript Crash Courses - [NodeJS Course](https://www.youtube.com/watch?v=RLtyhwFtXQA) - [Javascript Course](https://www.youtube.com/watch?v=jS4aFq5-91M) - Import your `SimpleStorage.sol` - [Solidity + Hardhat VSCode Extension](https://marketplace.visualstudio.com/items?itemName=NomicFoundation.hardhat-solidity) - Format your solidity code with: ``` "[solidity]": { "editor.defaultFormatter": "NomicFoundation.hardhat-solidity" }, "[javascript]":{ "editor.defaultFormatter": "esbenp.prettier-vscode" } ``` In your `.vscode/settings.json` file. - [Prettier Extension](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) ## Tiny Javascript Refresher - [Javascript Tips](https://www.freecodecamp.org/news/learn-javascript-free-js-courses-for-beginners/) ## Asynchronous Programming in Javascript - [Asynchronous Programming](https://www.bmc.com/blogs/asynchronous-programming/) - [async keyword](https://www.w3schools.com/JS//js_async.asp) - [Promise in Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) - [await keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) ## Compiling our Solidity - [Yarn Install](https://yarnpkg.com/getting-started/install) - [solc-js](https://github.com/ethereum/solc-js) - `yarn add [email protected]` - [yarn scripts](https://classic.yarnpkg.com/lang/en/docs/cli/run/) ## Ganache & Networks - [Ganache](https://trufflesuite.com/ganache/) - Networks in Metamask - RPC URL - [Geth](https://github.com/ethereum/go-ethereum) - [JSON RPC Spec Playground](https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/execution-apis/assembled-spec/openrpc.json&uiSchema%5BappBar%5D%5Bui:splitView%5D=false&uiSchema%5BappBar%5D%5Bui:input%5D=false&uiSchema%5BappBar%5D%5Bui:examplesDropdown%5D=false) ## Introduction to Ethers.js - [Ethers.js](https://docs.ethers.io/v5/getting-started/) - [prettier-plugin-solidity](https://github.com/prettier-solidity/prettier-plugin-solidity) ### A Note on the await Keyword ## Adding Transaction Overrides ## Transaction Receipts ## Sending a "raw" Transaction in Ethers.js ## Interacting with Contracts in Ethers.js - [EVM Decompiler](https://ethervm.io/decompile) - [BigNumber](https://docs.ethers.io/v5/api/utils/bignumber/) ## Environment Variables - [dotenv](https://www.npmjs.com/package/dotenv) - [.gitignore](https://www.atlassian.com/git/tutorials/saving-changes/gitignore) ## Better Private Key Management - [wallet.encrypt](https://docs.ethers.io/v5/api/signer/#Wallet-encrypt) - [THE .ENV PLEDGE](https://github.com/smartcontractkit/full-blockchain-solidity-course-js/discussions/5) ## Optional Prettier Formatting - [Prettier](https://prettier.io/docs/en/index.html) - [Best README Template](https://github.com/othneildrew/Best-README-Template) ## Deploying to a Testnet or a Mainnet - [Alchemy](https://alchemy.com/?a=673c802981) - [Getting your private key from Metamask](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key) - `CTRL + C` stops any terminal command ## Verifying on Block Explorers from the UI ## Alchemy Dashboard & The Mempool - [Special Guest Albert Hu](https://twitter.com/thatguyintech) - [Mempool](https://ethereum.org/en/developers/tutorials/sending-transactions-using-web3-and-alchemy/#see-your-transaction-in-the-mempool) ## Lesson 5 Recap ### Typescript Ethers Simple Storage # Lesson 6: Hardhat Simple Storage *[⌨️ (08:20:17) Lesson 6: Hardhat Simple Storage](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=30017s)* 💻 Code: https://github.com/PatrickAlphaC/hardhat-simple-storage-fcc ## Introduction *[⌨️ (08:20:19) Introduction](https://youtu.be/gyMwXuJrbJQ?t=30019)* ## Hardhat Setup *[⌨️ (08:22:47) Hardhat Setup](https://youtu.be/gyMwXuJrbJQ?t=30167)* - [Hardhat Documentation](https://hardhat.org/) - [DevDependencies vs Dependencies](https://stackoverflow.com/questions/18875674/whats-the-difference-between-dependencies-devdependencies-and-peerdependencies) - [@ Sign node modules](https://stackoverflow.com/questions/36667258/what-is-the-meaning-of-the-at-prefix-on-npm-packages) ### Troubleshooting Hardhat Setup *[⌨️ (08:29:43) Troubleshooting Hardhat Setup](https://youtu.be/gyMwXuJrbJQ?t=30583)* - [Special Guest Cami Ramos Garzon](https://twitter.com/camiinthisthang) ## Hardhat Setup Continued *[⌨️ (08:31:48) Hardhat Setup Continued](https://youtu.be/gyMwXuJrbJQ?t=30708)* ## Deploying SimpleStorage from Hardhat *[⌨️ (08:33:10) Deploying SimpleStorage from Hardhat](https://youtu.be/gyMwXuJrbJQ?t=30790)* ## Networks in Hardhat *[⌨️ (08:41:44) Networks in Hardhat](https://youtu.be/gyMwXuJrbJQ?t=31304)* - [The Hardhat Network](https://hardhat.org/hardhat-network/) - [Hardhat configuration](https://hardhat.org/config/#configuration) - [Chain ID List](https://chainlist.org/) ## Programmatic Verification *[⌨️ (08:51:16) Programmatic Verification](https://youtu.be/gyMwXuJrbJQ?t=31876)* - [Etherscan Verify Tutorial](https://docs.etherscan.io/tutorials/verifying-contracts-programmatically) - [Etherscan Docs](https://docs.etherscan.io/) - [Hardhat-Etherscan](https://hardhat.org/plugins/nomiclabs-hardhat-etherscan.html) - [Etherscan API Keys](https://info.etherscan.com/api-keys/) - [Javascript == vs ===](https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons) ## Interacting with Contracts in Hardhat *[⌨️ (09:06:37) Interacting with Contracts in Hardhat](https://youtu.be/gyMwXuJrbJQ?t=32797)* ## Artifacts Troubleshooting *[⌨️ (09:09:42) Artifacts Troubleshooting](https://youtu.be/gyMwXuJrbJQ?t=32982)* ## Custom Hardhat Tasks *[⌨️ (09:10:52) Custom Hardhat Tasks](https://youtu.be/gyMwXuJrbJQ?t=33052)* - [Hardhat Tasks](https://hardhat.org/guides/create-task.html) - [Javascript Arrow Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) ## Hardhat Localhost Node *[⌨️ (09:18:12) Hardhat Localhost Node](https://youtu.be/gyMwXuJrbJQ?t=33492)* ## The Hardhat Console *[⌨️ (09:23:11) The Hardhat Console](https://youtu.be/gyMwXuJrbJQ?t=33791)* - [Hardhat Console](https://hardhat.org/guides/hardhat-console.html) ## Hardhat Tests *[⌨️ (09:26:13) Hardhat Tests](https://youtu.be/gyMwXuJrbJQ?t=33973)* - [Hardhat Tests](https://hardhat.org/tutorial/testing-contracts.html#_5-testing-contracts) - [Mocha Style Tests](https://mochajs.org/) - [Chai](https://www.npmjs.com/package/chai) - [Waffle Tests](https://ethereum-waffle.readthedocs.io/en/latest/) ## Hardhat Gas Reporter *[⌨️ (09:38:10) Hardhat Gas Reporter](https://youtu.be/gyMwXuJrbJQ?t=34690)* - [Hardhat Gas Reporter](https://www.npmjs.com/package/hardhat-gas-reporter) - [Coinmarketcap API](https://coinmarketcap.com/api/) ## Solidity Coverage *[⌨️ (09:44:40) Solidity Coverage](https://youtu.be/gyMwXuJrbJQ?t=35080)* - [Solidity Coverage](https://github.com/sc-forks/solidity-coverage) ## Hardhat Waffle *[⌨️ (09:47:02) Hardhat Waffle](https://youtu.be/gyMwXuJrbJQ?t=35222)* - [Hardhat-Waffle](https://npm.io/package/@nomiclabs/hardhat-waffle) ## Lesson 6 Recap *[⌨️ (09:47:37) Lesson 6 Recap](https://youtu.be/gyMwXuJrbJQ?t=35257)* ### Typescript Hardhat Simple Storage *[⌨️ (09:52:15) Typescript Hardhat Simple Storage](https://youtu.be/gyMwXuJrbJQ?t=35535)* - [Typechain](https://github.com/dethcrypto/TypeChain) ``` yarn add --dev @typechain/ethers-v5 @typechain/hardhat @types/chai @types/node @types/mocha ts-node typechain typescript ``` # Lesson 7: Hardhat Fund Me *[⌨️ (10:00:48) Lesson 7: Hardhat Fund Me](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=36048s)* 💻 Code: https://github.com/PatrickAlphaC/hardhat-fund-me-fcc ## Introduction *[⌨️ (10:00:50) Introduction](https://youtu.be/gyMwXuJrbJQ?t=36050)* ## Hardhat Setup - Fund Me *[⌨️ (10:03:41) Hardhat Setup - Fund Me](https://youtu.be/gyMwXuJrbJQ?t=36221)* ## Linting *[⌨️ (10:06:20) Linting](https://youtu.be/gyMwXuJrbJQ?t=36380)* - [Eslint](https://eslint.org/) - [Solhint](https://github.com/protofire/solhint) - [Linting Code](https://www.perforce.com/blog/qac/what-lint-code-and-why-linting-important) ## Hardhat Setup - Fund Me - Continued *[⌨️ (10:07:47) Hardhat Setup - Fund Me - Continued](https://youtu.be/gyMwXuJrbJQ?t=36467)* ## Importing from NPM *[⌨️ (10:09:38) Importing from NPM](https://youtu.be/gyMwXuJrbJQ?t=36578)* - [@chainlink/contracts](https://www.npmjs.com/package/@chainlink/contracts) ## Hardhat Deploy *[⌨️ (10:10:43) Hardhat Deploy](https://youtu.be/gyMwXuJrbJQ?t=36643)* - [Hardhat Deploy](https://github.com/wighawag/hardhat-deploy) ## Mocking *[⌨️ (10:21:05) Mocking](https://youtu.be/gyMwXuJrbJQ?t=37265)* - [Mocking](https://stackoverflow.com/questions/2665812/what-is-mocking) - [Aave Github](https://github.com/aave/aave-v3-core) - [Chainlink Github](https://github.com/smartcontractkit/chainlink) - Multiple Versions of Solidity - Tags in hardhat ## Utils Folder *[⌨️ (10:52:51) Utils Folder](https://youtu.be/gyMwXuJrbJQ?t=39171)* ## Testnet Demo - Hardhat Fund Me *[⌨️ (10:55:45) Testnet Demo - Hardhat Fund Me](https://youtu.be/gyMwXuJrbJQ?t=39345)* - Hardhat Deploy Block Confirmations ## Solidity Style Guide *[⌨️ (11:00:10) Solidity Style Guide](https://youtu.be/gyMwXuJrbJQ?t=39610)* - [Style Guide](https://docs.soliditylang.org/en/v0.8.15/style-guide.html) - [NatSpec](https://docs.soliditylang.org/en/v0.8.15/natspec-format.html) ## Testing Fund Me *[⌨️ (11:08:36) Testing Fund Me](https://youtu.be/gyMwXuJrbJQ?t=40116)* - [Unit Testing](https://en.wikipedia.org/wiki/Unit_testing) - [Hardhat Deploy Fixtures](https://github.com/wighawag/hardhat-deploy#creating-fixtures) - [ethers.getContract](https://github.com/wighawag/hardhat-deploy-ethers) - [expect](https://ethereum-waffle.readthedocs.io/en/latest/matchers.html) - [ethers.utils.parseUnits](https://docs.ethers.io/v5/api/utils/display-logic/#utils-parseUnits) - [Waffle Chai Matchers](https://ethereum-waffle.readthedocs.io/en/latest/matchers.html) ## Breakpoints & Debugging *[⌨️ (11:30:39) Breakpoints & Debugging](https://youtu.be/gyMwXuJrbJQ?t=41439)* - [VSCode Breakpoints](https://code.visualstudio.com/Docs/editor/debugging) ## Gas III *[⌨️ (11:33:40) Gas III](https://youtu.be/gyMwXuJrbJQ?t=41620)* - [Transaction Response](https://docs.ethers.io/v5/api/providers/types/#providers-TransactionResponse) - [Transaction Receipt](https://docs.ethers.io/v5/api/providers/types/#providers-TransactionReceipt) ## console.log & Debugging *[⌨️ (11:36:35) console.log & Debugging](https://youtu.be/gyMwXuJrbJQ?t=41795)* - [Hardhat console.log](https://hardhat.org/hardhat-network/reference/#console-log) ## Testing Fund Me II *[⌨️ (11:37:31) Testing Fund Me II](https://youtu.be/gyMwXuJrbJQ?t=41851)* ## Storage in Solidity *[⌨️ (11:44:34) Storage in Solidity](https://youtu.be/gyMwXuJrbJQ?t=42274)* - [Storage Layout](https://docs.soliditylang.org/en/v0.8.13/internals/layout_in_storage.html) - [Purpose of the memory keyword](https://stackoverflow.com/questions/33839154/in-ethereum-solidity-what-is-the-purpose-of-the-memory-keyword) - [getStorageAt](https://docs.ethers.io/v5/api/providers/provider/#Provider-getStorageAt) ## Gas Optimizations using Storage Knowledge *[⌨️ (11:52:38) Gas Optimizations using Storage Knowledge](https://youtu.be/gyMwXuJrbJQ?t=42758)* - [Opcodes](https://ethereum.org/en/developers/docs/evm/opcodes/) - [Opcodes by Gas](https://github.com/crytic/evm-opcodes) - [Opcodes by Gas](https://evm.codes/) - Append `s_` to storage variables - Append `i_` to immutable variables - Caps lock and underscore constant variables ## Solidity Chainlink Style Guide *[⌨️ (12:05:29) Solidity Chainlink Style Guide](https://youtu.be/gyMwXuJrbJQ?t=43529)* - [Chainlink Solidity Style Guide](https://github.com/smartcontractkit/full-blockchain-solidity-course-js/issues/13) ## Storage Review *[⌨️ (12:09:59) Storage Review](https://youtu.be/gyMwXuJrbJQ?t=43799)* ## Staging Tests *[⌨️ (12:11:43) Staging Tests](https://youtu.be/gyMwXuJrbJQ?t=43903)* - [Ternary](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) ## Running Scripts on a Local Node *[⌨️ (12:17:58) Running Scripts on a Local Node](https://youtu.be/gyMwXuJrbJQ?t=44278)* ## Adding Scripts to your package.json *[⌨️ (12:22:00) Adding Scripts to your package.json](https://youtu.be/gyMwXuJrbJQ?t=44520)* ## Pushing to GitHub *[⌨️ (12:25:17) Pushing to GitHub](https://youtu.be/gyMwXuJrbJQ?t=44717)* - [Github Quickstart](https://docs.github.com/en/get-started/quickstart) - [What is Git?](https://www.git-scm.com/book/en/v2/Getting-Started-What-is-Git%3F) - [The quickstart that we follow in the video](https://docs.github.com/en/get-started/importing-your-projects-to-github/importing-source-code-to-github/adding-locally-hosted-code-to-github#adding-a-local-repository-to-github-using-git) - [Learn about git and GitHub](https://www.youtube.com/watch?v=RGOj5yH7evk) ## 🐸🐦 [Tweet Me (add your repo in)!](https://twitter.com/intent/tweet?text=I%20just%20made%20my%20first%20Smart%20Contract%20repo%20using%20@solidity_lang,%20@HardhatHQ,%20@chainlink,%20@AlchemyPlatform,%20and%20more!%0a%0aThanks%20@PatrickAlphaC!!) # Lesson 8: HTML / Javascript Fund Me (Full Stack / Front End) *[⌨️ (12:32:57) Lesson 8: HTML / Javascript Fund Me (Full Stack / Front End)](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=45177s)* 💻 Code: https://github.com/PatrickAlphaC/html-fund-me-fcc ## Introduction ## How Websites work with Web3 Wallets - [How to Connect your Smart Contracts to Metamask](https://www.youtube.com/watch?v=pdsYCkUWrgQ) - 💻 Code from Video: https://github.com/PatrickAlphaC/full-stack-web3-metamask-connectors - ✍️ Article from Video: https://betterprogramming.pub/everything-you-need-to-know-about-fullstack-web3-94c0f1b18019?sk=a2764bcbdae98bf05e1052931de77982 ## HTML Setup - Live Server: ExtensionID: ritwickdey.LiveServer ## Connecting HTML to Metamask - [Metamask Docs](https://docs.metamask.io/guide/) ## Javascript in it's own file ## ES6 vs Nodejs - [ES6 vs Nodesjs](https://stackoverflow.com/questions/31354559/using-node-js-require-vs-es6-import-export#31367852) - [Ethers docs for web browser](https://docs.ethers.io/v5/getting-started/#getting-started--importing--web-browser) - [module vs text/javascript](https://stackoverflow.com/questions/51418964/script-type-text-javascript-vs-script-type-module) ## Sending a transaction from a Website - [Web3Provider](https://docs.ethers.io/v5/api/providers/other/#Web3Provider) - [Adding a network to metamask](https://metamask.zendesk.com/hc/en-us/articles/360043227612-How-to-add-a-custom-network-RPC) ## Resetting an Account in Metamask ``` MetaMask - RPC Error: [ethjs-query] while formatting ouputs from RPC '{"value":{"code":-32603,"data":{"code":-32000,"message":"Nonce too high. Expected nonce to be 2 but got 4. Note that transactions can't be queued when automining."}}}' ``` ## Listening for Events and Completed Transactions - [provider.once](https://docs.ethers.io/v5/api/providers/provider/#Provider-once) - [Anonymous function](https://www.geeksforgeeks.org/javascript-anonymous-functions/) - [Javascript Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) ## Input Forms ## Reading from the Blockchain ## Withdraw Function ## Lesson 8 Recap ### Optional Links: - [Browserify](https://browserify.org/) - [Watchify](https://www.npmjs.com/package/watchify) # Lesson 9: Hardhat Smart Contract Lottery *[⌨️ (13:41:02) Lesson 9: Hardhat Smart Contract Lottery](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=49262s)* 💻 Code: https://github.com/PatrickAlphaC/hardhat-smartcontract-lottery-fcc ## Introduction ## Hardhat Setup - Smart Contract Lottery *[⌨️ (13:43:43) Hardhat Setup](https://youtu.be/gyMwXuJrbJQ?t=49423)* - Install dependencies: ```bash yarn add --dev @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers @nomiclabs/hardhat-etherscan @nomiclabs/hardhat-waffle chai ethereum-waffle hardhat hardhat-contract-sizer hardhat-deploy hardhat-gas-reporter prettier prettier-plugin-solidity solhint solidity-coverage dotenv ``` - Install dependencies (Typescript version): ```bash yarn add --dev @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers @nomiclabs/hardhat-etherscan @nomiclabs/hardhat-waffle chai ethereum-waffle hardhat hardhat-contract-sizer hardhat-deploy hardhat-gas-reporter prettier prettier-plugin-solidity solhint solidity-coverage dotenv @typechain/ethers-v5 @typechain/hardhat @types/chai @types/node ts-node typechain typescript ``` ## Raffle.sol Setup *[⌨️ (13:46:55) Raffle.sol Setup](https://youtu.be/gyMwXuJrbJQ?t=49615)* - [Custom Errors in Solidity](https://blog.soliditylang.org/2021/04/21/custom-errors/) ## Introduction to Events *[⌨️ (13:54:02) Introduction to Events](https://youtu.be/gyMwXuJrbJQ?t=50042)* - [Events & Logging Video](https://www.youtube.com/watch?v=KDYJC85eS5M) - [Events & Logging in Hardhat](https://github.com/PatrickAlphaC/hardhat-events-logs) ## Events in Raffle.sol *[⌨️ (14:00:47) Events in Raffle.sol](https://youtu.be/gyMwXuJrbJQ?t=50447)* ## Introduction to Chainlink VRF *[⌨️ (14:02:30) Introduction to Chainlink VRF](https://youtu.be/gyMwXuJrbJQ?t=50550)* - [Special Guest Stephen Fluin](https://twitter.com/stephenfluin) ### Sub-Lesson: Chainlink VRF > - [Chainlink VRFv2 Docs](https://docs.chain.link/docs/get-a-random-number/) > - [Chainlink VRFv2 Walkthrough](https://www.youtube.com/watch?v=rdJ5d8j1RCg) > - [Chainlink Contracts](https://github.com/smartcontractkit/chainlink/blob/develop/contracts/src/v0.8/VRFConsumerBase.sol) ## Implementing Chainlink VRF - Introduction *[⌨️ (14:09:53) Implementing Chainlink VRF](https://youtu.be/gyMwXuJrbJQ?t=50993)* ### Hardhat Shorthand - [Hardhat Shorthand](https://hardhat.org/guides/shorthand.html) ## Implementing Chainlink VRF - The Request ## Implementing Chainlink VRF - The FulFill ### Modulo - [Modulo](https://docs.soliditylang.org/en/v0.8.13/types.html?highlight=modulo#modulo) ## Introduction to Chainlink Keepers - [Chainlink Keepers Docs](https://docs.chain.link/docs/chainlink-keepers/introduction/) - [Chainlink Keepers Walkthrough](https://www.youtube.com/watch?v=-Wkw5JVQGUo) ## Implementing Chainlink Keepers - checkUpkeep ### Enums - [Enum](https://docs.soliditylang.org/en/v0.8.13/structure-of-a-contract.html?highlight=enum#enum-types) ## Implementing Chainlink Keepers - checkUpkeep continued - block.timestamp ## Implementing Chainlink Keepers - performUpkeep ## Code Cleanup ## Deploying Raffle.sol ### Mock Chainlink VRF Coordinator ### Continued - [LINK Token](https://docs.chain.link/docs/link-token-contracts/) ## Raffle.sol Unit Tests - We use `async function` in the describe blocks at the start, but we correctly take them out later. ### Testing Events & Chai Matchers - [Emit Chai Matcher](https://ethereum-waffle.readthedocs.io/en/latest/matchers.html#emitting-events) ### Continued I ## Hardhat Methods & Time Travel - [Make Hardhat do whatever you want it to](https://hardhat.org/hardhat-network/reference/) - [Special debugging hardhat methods](https://hardhat.org/hardhat-network/reference/#special-testing-debugging-methods) ### Continued II ## Callstatic - [Callstatic](https://docs.ethers.io/v5/api/contract/contract/#contract-callStatic) ### Continued III ### Massive Promise Test ### Continued IV ## Raffle.sol Staging Tests ## Testing on a Testnet ### Recommended LINK amounts for Rinkeby Staging Test: - Chainlink VRF: 2 LINK - Chainlink Keepers: 8 LINK ## Conclusion ## Typescript - Smart Contract Lottery 🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊 Completed Hardhat Basics! 🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊 # Lesson 10: NextJS Smart Contract Lottery (Full Stack / Front End) *[⌨️ (16:34:07) Lesson 10: NextJS Smart Contract Lottery (Full Stack / Front End)](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=59647s)* 💻 Code: https://github.com/PatrickAlphaC/nextjs-smartcontract-lottery-fcc ⚡️⚡️ Live Demo IPFS: ipfs://QmXwACyjcS8tL7UkYwimpqMqW9sKzSHUjE4uSZBSyQVuEH ⚡️⚡️ Live Demo Fleek: https://fancy-dream-3458.on.fleek.co/ ## Introduction We move into using [NextJS](https://nextjs.org/) for our front end. NextJS is a [React framework](https://reactjs.org/) for building websites. ### Optional Sub-Lesson: Full Stack Development & Other Libraries - [6 Ways to connect your dapp to a wallet](https://www.youtube.com/watch?v=pdsYCkUWrgQ) - [NextJS Crash Course](https://www.youtube.com/watch?v=mTz0GXj8NN0) - Other React libraries: - [Web3React](https://github.com/NoahZinsmeister/web3-react) - [wagmi](https://github.com/tmm/wagmi) - [react-moralis](https://www.npmjs.com/package/react-moralis) - [useDapp](https://github.com/TrueFiEng/useDApp) - [Web3Modal](https://github.com/Web3Modal/web3modal) - [useMetamask](https://github.com/mdtanrikulu/use-metamask) - Other Full Stack Web3 Templates - [scaffold-eth](https://github.com/scaffold-eth/scaffold-eth) - [ethereum-boilerplate](https://github.com/ethereum-boilerplate/ethereum-boilerplate) - [create-eth-app](https://github.com/paulrberg/create-eth-app) - [React being quite popular](https://insights.stackoverflow.com/survey/2021#section-most-popular-technologies-web-frameworks) - [Why use react?](https://www.freecodecamp.org/news/why-use-react-for-web-development/) ## NextJS Setup - [NextJS Documentation](https://nextjs.org/learn/basics/create-nextjs-app) - [NextJS Minimal Ethers Example For Lottery](https://github.com/PatrickAlphaC/nextjs-ethers-introduction) ``` yarn create next-app . ``` ## Manual Header I - [What is a component?](https://www.w3schools.com/react/react_components.asp) - [jsx](https://reactjs.org/docs/introducing-jsx.html) - [Moralis](https://moralis.io/) - [React Moralis](https://github.com/MoralisWeb3/react-moralis) ### React Hooks - [What is a react hook?](https://reactjs.org/docs/hooks-overview.html) ## Manual Header II ## useEffect Hook - [useEffect Hook](https://reactjs.org/docs/hooks-effect.html) - [More on useEffect](https://blog.logrocket.com/guide-to-react-useeffect-hook/) - [React Context](https://www.freecodecamp.org/news/react-context-for-beginners/) - [useEffect Firing Twice](https://stackoverflow.com/questions/60618844/react-hooks-useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-ar) ## Local Storage - [Local Storage](https://codinglead.co/javascript/what-is-localstorage) ## isWeb3EnabledLoading ## web3uikit - [web3uikit](https://github.com/web3ui/web3uikit) - [web3uikit interactive docs](https://web3ui.github.io/web3uikit/?path=/story/1-web3-blockie--custom-seed) - [web3uikit connect button](https://web3ui.github.io/web3uikit/?path=/story/1-web3-connectbutton--default) ## Introduction to Calling Functions in Nextjs - [useWeb3Contract](https://github.com/MoralisWeb3/react-moralis#useweb3contract) ### Automatic Constant Value UI Updater - [ethers.utils.FormatTypes](https://docs.ethers.io/v5/api/utils/abi/fragments/#fragments--formats) ### runContractFunction - [Moralis Provider](https://github.com/MoralisWeb3/react-moralis#wrap-your-app-in-a-moralisprovider) - [useMoralis](https://github.com/MoralisWeb3/react-moralis#usemoralis) - [parseInt](https://www.w3schools.com/JSREF/jsref_parseint.asp) ## useState - [useState Hook](https://reactjs.org/docs/hooks-state.html) ## Calling Functions in NextJS ## useNotification - Add `onError` to all your `runContractFunction` calls ## Reading & Displaying Contract Data ## A Note about `onSuccess` - `onSuccess` just checks to see if MetaMask sends the transaction, not ## A Challenge to You ## Tailwind & Styling - [Learn CSS](https://www.w3schools.com/css/) - [Tailwindcss](https://tailwindcss.com/) - [PostCSS Extension](https://marketplace.visualstudio.com/items?itemName=csstools.postcss) - [Tailwind Extension](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) - [Install Tailwind into NextJS](https://tailwindcss.com/docs/guides/nextjs) ## Introduction to Hosting your Site *[⌨️ (18:12:50) Introdunction to Hosting your Site](https://youtu.be/gyMwXuJrbJQ?t=65570)* - [Vercel](https://vercel.com/) - [Moralis](https://moralis.io/) - [Netilfy](https://www.netlify.com/) - [IPFS](https://ipfs.io/) ## IPFS *[⌨️ (18:15:14) IPFS](https://youtu.be/gyMwXuJrbJQ?t=65714)* - [What is IPFS](https://www.youtube.com/watch?v=5Uj6uR3fp-U) - [IPFS](https://ipfs.io/) ## Hosting on IPFS *[⌨️ (18:18:51) Hosting on IPFS](https://youtu.be/gyMwXuJrbJQ?t=65931)* - [IPFS Companion](https://chrome.google.com/webstore/detail/ipfs-companion/nibjojkomfdiaoajekhjakgkdhaomnch) - [Brave Browser](https://brave.com/) - `yarn build && yarn next export` ## Hosting on IPFS & Filecoin using Fleek *[⌨️ (18:25:45) Hosting on IPFS & Filecoin using Fleek](https://youtu.be/gyMwXuJrbJQ?t=66345)* - [Fleek](https://fleek.co/) ## Filecoin Overview *[⌨️ (18:31:28) Filecoin Overview](https://youtu.be/gyMwXuJrbJQ?t=66688)* - [Special Guest Ally Haire](https://twitter.com/DeveloperAlly) - [IPFS URL of Ally's Video](ipfs://bafybeiasd6oxqiefoxgtskrokomexnb4zcq3fhwlcbyplx2paw65zmq2du) ## Lesson 10 Recap # Lesson 11: Hardhat Starter Kit *[⌨️ (18:51:36) Lesson 11: Hardhat Starter Kit](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=67896s)* 💻 Code: https://github.com/smartcontractkit/hardhat-starter-kit # Lesson 12: Hardhat ERC20s *[⌨️ (18:59:24) Lesson 12: Hardhat ERC20s](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=68364s)* 💻 Code: https://github.com/PatrickAlphaC/hardhat-erc20-fcc ## What is an ERC? What is an EIP? - [What is an EIP?](https://eips.ethereum.org/) - [EIPs codebase](https://github.com/ethereum/EIPs) ## What is an ERC20? - [Video (using brownie/python)](https://youtu.be/8rpir_ZSK1g?t=39) - [EIP-20](https://eips.ethereum.org/EIPS/eip-20) - [ERC-677](https://github.com/ethereum/EIPs/issues/677) - [EIP-777](https://eips.ethereum.org/EIPS/eip-777) ## Manually Creating an ERC20 Token ## Creating an ERC20 Token with Openzeppelin - [Openzeppelin](https://openzeppelin.com/) - [Openzeppelin Contracts](https://github.com/OpenZeppelin/openzeppelin-contracts) - [Solmate (Openzeppelin alternative)](https://github.com/Rari-Capital/solmate) ## Lesson 12 Recap # Lesson 13: Hardhat DeFi & Aave *[⌨️ (19:16:13) Lesson 13: Hardhat DeFi & Aave](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=69373s)* 💻 Code: https://github.com/PatrickAlphaC/hardhat-defi-fcc ## What is DeFi? - [What is DeFi?](https://chain.link/education/defi) - [DefiLlama](https://defillama.com/) ## What is Aave? - [Aave](https://aave.com/) - [My Previous Aave Video on Shorting Assets](https://www.youtube.com/watch?v=TmNGAvI-RUA) ## Programmatic Borrowing & Lending - [DAI](https://makerdao.com/en/) - [Uniswap](https://app.uniswap.org/) ## WETH - Wrapped ETH - [WETH Token Rinkeby Etherscan](https://rinkeby.etherscan.io/token/0xc778417e063141139fce010982780140aa0cd5ab#writeContract) - [WETH Token Mainnet](https://etherscan.io/token/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2) ## Forking Mainnet - [Mainnet Forking](https://hardhat.org/hardhat-network/guides/mainnet-forking.html) ## Depositing into Aave - [Aave V2 Docs](https://docs.aave.com/developers/v/2.0/) - [Aave NPM](https://www.npmjs.com/package/@aave/protocol-v2) ## Borrowing from Aave - [Aave Borrowing FAQs](https://docs.aave.com/faq/borrowing) - [Health Factor](https://docs.aave.com/faq/borrowing#what-is-the-health-factor) - [Aave Risk Parameters](https://docs.aave.com/risk/asset-risk/risk-parameters) ## Repaying with Aave ## Visualizing the Transactions - [aTokens](https://docs.aave.com/developers/v/1.0/developing-on-aave/the-protocol/atokens) ## Lesson 13 Recap ## Happy Bow-Tie Friday with Austin Griffith - [Special Guest Austin Griffith](https://twitter.com/austingriffith)! - [Speed Run Ethereum](https://speedrunethereum.com/) ### More DeFi Learnings: - [Defi-Minimal](https://github.com/smartcontractkit/defi-minimal/tree/main/contracts) - [Defi Dad](https://www.youtube.com/channel/UCatItl6C7wJp9txFMbXbSTg) # Lesson 14: Hardhat NFTs (EVERYTHING you need to know about NFTs) *[⌨️ (20:28:51) Lesson 14: Hardhat NFTs ](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=73731s)* 💻 Code: https://github.com/PatrickAlphaC/hardhat-nft-fcc ## What is an NFT? - [Video](https://www.youtube.com/watch?v=9yuHz6g_P50) - [Optional: All on Chain SVG NFT](https://www.youtube.com/watch?v=9oERTH9Bkw0) - [EIP-721](https://eips.ethereum.org/EIPS/eip-721) ## Code Overview - [Opensea Testnet](https://testnets.opensea.io/) ## Hardhat Setup ## Basic NFT ### Write Tests - [Openzeppelin NFT](https://docs.openzeppelin.com/contracts/4.x/) ## Random IPFS NFT ### Mapping Chainlink VRF Requests ### Creating Rare NFTs ### Setting the NFT Image ### Setting an NFT Mint Price ### Deploy Script ### Uploading Token Images with Pinata - [Pinata](https://pinata.cloud) - [nft.storage](https://nft.storage) - [Pinata NPM](https://www.npmjs.com/package/@pinata/sdk) - [Pinata Docs](https://docs.pinata.cloud/) ### Uploading Token URIs (metadata) with Pinata ### Deploying ### Tests ## Dynamic SVG On-Chain NFT - [Patrick's Original Video](https://www.youtube.com/watch?v=9oERTH9Bkw0) ### What is an SVG? - [SVG Tutorial](https://www.w3schools.com/graphics/svg_intro.asp) - [On-Chain SVG Example](https://opensea.io/assets/matic/0x291ff90b9c410f56e047599bfee6b585c0c484d7/2) ### Initial Code ### Base64 Encoding - [Base64 Encoding](https://en.wikipedia.org/wiki/Base64) - [Example Encoder](https://base64.guru/converter/encode/image/svg) - [base64-sol](https://www.npmjs.com/package/base64-sol/v/1.0.1) ## Advanced: EVM Opcodes, Encoding, and Calling ### abi.encode & abi.encodePacked - [abi.encode](https://docs.soliditylang.org/en/v0.8.14/cheatsheet.html?highlight=cheatsheet#global-variables) - [abi.encodePacked](https://docs.soliditylang.org/en/v0.8.14/cheatsheet.html?highlight=cheatsheet#global-variables) Thanks to [Alex Roan](https://twitter.com/alexroan) for his help on this session! - [Example Contract Creation Transaction](https://rinkeby.etherscan.io/tx/0x924f592458b0e37ee17024f9c826b97697455cd97f6946b802bc42296e77ae43) What REALLY is the ABI? - [EVM Opcodes](https://www.evm.codes/) - [More EVM Opcodes](https://github.com/crytic/evm-opcodes) - [Solidity Cheatsheet](https://docs.soliditylang.org/en/v0.8.13/cheatsheet.html?highlight=encodewithsignature) - [abi.encode vs abi.encodePacked](https://ethereum.stackexchange.com/questions/91826/why-are-there-two-methods-encoding-arguments-abi-encode-and-abi-encodepacked) ### Introduction to Encoding Function Calls Directly ### Introduction to Encoding Function Calls Recap ### Encoding Function Calls Directly - [Function Selector](https://blog.openzeppelin.com/deconstructing-a-solidity-contract-part-iii-the-function-selector-6a9b6886ea49/) - [Function Signature](https://twitter.com/PatrickAlphaC/status/1517156225670078465) ### Creating an NFT TokenURI on-Chain ### Making the NFT Dynamic ### Deploy Script ## Deploying the NFTs to a Testnet ## Lesson 14 Recap Extra credit: - [Deconstructing Solidity](https://blog.openzeppelin.com/deconstructing-a-solidity-contract-part-ii-creation-vs-runtime-6b9d60ecb44c/) - [Knowing and controlling your Smart Contract Address](https://www.youtube.com/watch?v=56K0FdosZ8g) - [From Solidity to byte code](https://www.youtube.com/watch?v=RxL_1AfV7N4) # Lesson 15: NextJS NFT Marketplace (If you finish this lesson, you are a full-stack MONSTER!) *[⌨️ (23:37:03) Lesson 15: NextJS NFT Marketplace (Full Stack / Front End)](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=85023s)* 💻 Code: - Backend (Contracts): https://github.com/PatrickAlphaC/hardhat-nft-marketplace-fcc - Frontend (Moralis Indexer): https://github.com/PatrickAlphaC/nextjs-nft-marketplace-moralis-fcc - Frontend (TheGraph Indexer): https://github.com/PatrickAlphaC/nextjs-nft-marketplace-thegraph-fcc - The Graph: https://github.com/PatrickAlphaC/graph-nft-marketplace-fcc Special thanks to [Matt Durkin](https://twitter.com/mdurkin92) for help with this section. ## Introduction - [Opensea](https://opensea.io/) - [Artion](https://github.com/Fantom-foundation/Artion-Contracts) ## Part I: NFT Marketplace Contracts ### Hardhat Setup ### NftMarketplace.sol - [Pull Over Push](https://fravoll.github.io/solidity-patterns/pull_over_push.html) ## Reentrancy - [Reentrancy](https://solidity-by-example.org/hacks/re-entrancy) - [Rekt.news](https://rekt.news/leaderboard/) - [Openzeppelin NonReentrant](https://docs.openzeppelin.com/contracts/4.x/api/security#ReentrancyGuard) ### NftMarketplace.sol - Continued ### NftMarketplace.sol - Deploy Script ### NftMarketplace.sol - Tests ### NftMarketplace.sol - Scripts ## Part II: Moralis Front End ### What is Moralis? - [Special Guest Ivan Liljeqvist](https://twitter.com/IvanOnTech) ### NextJS Setup - [Link NextJS](https://nextjs.org/docs/api-reference/next/link) ### Adding Tailwind - [Tailwind with NextJS](https://tailwindcss.com/docs/guides/nextjs) ### Introduction to Indexing in Web3 - [TheGraph](https://thegraph.com/en/) - [Moralis](https://moralis.io/) ### Connecting Moralis to our Local Hardhat Node - [NextJS Environment Variables](https://nextjs.org/docs/basic-features/environment-variables) - [Reverse Proxy FRP](https://github.com/fatedier/frp/releases) - [Docs](https://docs.moralis.io/moralis-dapp/web3/setting-up-ganache) - [Trouble Shooting](https://docs.moralis.io/faq#frpc) - [Moralis Forum](https://forum.moralis.io/) - [Moralis Admin CLI](https://docs.moralis.io/moralis-dapp/tools/moralis-admin-cli) ### Moralis Event Sync - [Moralis Add Event Sync From Code](https://docs.moralis.io/moralis-dapp/connect-the-sdk/connect-using-node#add-new-event-sync-from-code) #### Reset Local Chain ### Moralis Cloud Functions - [Moralis Cloud Functions](https://docs.moralis.io/moralis-dapp/cloud-code/cloud-functions) - [Moralis Logging](https://docs.moralis.io/moralis-dapp/tools/moralis-admin-cli#get-logs) - [Hardhat Network Reference](https://hardhat.org/hardhat-network/reference/) - Moralis Database only confirms a transaction with a block confirmation - so we need to move blocks on our hardhat local node. - [Moralis Triggers](https://docs.moralis.io/moralis-dapp/cloud-code/triggers) #### Practice Resetting the Local Chain ### Moralis Cloud Functions II ### Querying the Moralis Database - [Moralis Queries](https://docs.moralis.io/moralis-dapp/database/queries) ### Rendering the NFT Images - [useNFTBalance](https://github.com/MoralisWeb3/react-moralis#usenftbalances) - [fetch](https://www.npmjs.com/package/node-fetch) - [next/image](https://nextjs.org/docs/api-reference/next/image#loader-configuration) ### Update Listing Modal ### Buy NFT Listing ### Listing NFTs for Sale - [web3uikit Form](https://web3uikit.com/) ## Part III: TheGraph Front End ### Introduction ### What is The Graph? - [Special Guest Nader Dabit](https://twitter.com/dabit3) ### Building a Subgraph - [Example Subgraphs](https://thegraph.com/explorer/) - [The Graph Studio](https://thegraph.com/studio/) - [GraphQL VSCode Extension](https://marketplace.visualstudio.com/items?itemName=GraphQL.vscode-graphql) - [GraphQL](https://graphql.org/) ### Deploying our Subgraph - [GraphQL Queries](https://www.tutorialspoint.com/graphql/graphql_query.htm) ### Reading from The Graph - [@apollo/client](https://www.npmjs.com/package/@apollo/client) - [gql](https://www.npmjs.com/package/gql) - [The Graph Docs](https://thegraph.com/docs/en/) ### Hosting our Dapp 🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊 Completed Front End Basics! 🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊 # Lesson 16: Hardhat Upgrades *[⌨️ (28:53:11) Lesson 16: Hardhat Upgrades](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=103991s)* 💻 Code: https://github.com/PatrickAlphaC/hardhat-upgrades-fcc ## Upgradable Smart Contracts Overview - [Optional Video](https://www.youtube.com/watch?v=bdXJmWajZRY) - [Links from Video] ## Types of Upgrades 1. Parameter 2. Social Migrate 3. Proxy 1. Proxy Gotchas 1. [Function Collisions](https://blog.openzeppelin.com/the-state-of-smart-contract-upgrades/#diamonds) 2. [Storage Collisions](https://blog.openzeppelin.com/the-state-of-smart-contract-upgrades/#diamonds) 2. [Metamorphic Upgrades](https://github.com/PatrickAlphaC/hardhat-metamorphic-upgrades-fcc) 3. [Transparent](https://blog.openzeppelin.com/the-transparent-proxy-pattern/) 4. [UUPS](https://forum.openzeppelin.com/t/uups-proxies-tutorial-solidity-javascript/7786) 5. [Diamond](https://eips.ethereum.org/EIPS/eip-2535) ## Delegatecall - [delegatecall (solidity-by-example)](https://solidity-by-example.org/delegatecall) - [Yul](https://docs.soliditylang.org/en/latest/yul.html) ## Small Proxy Example - [EIP 1967](https://eips.ethereum.org/EIPS/eip-1967) ## Transparent Upgradable Smart Contract - [Hardhat-deploy Proxies](https://github.com/wighawag/hardhat-deploy#deploying-and-upgrading-proxies) - [Openzeppelin Upgrades Plugin](https://docs.openzeppelin.com/upgrades-plugins/1.x/) - [Openzeppelin upgrades tutorial](https://forum.openzeppelin.com/t/openzeppelin-upgrades-step-by-step-tutorial-for-hardhat/3580) - [hardhat deploy upgrades examples](https://github.com/wighawag/template-ethereum-contracts/tree/examples/openzeppelin-proxies/deploy) # Lesson 17: Hardhat DAOs *[⌨️ (29:45:24) Lesson 17: Hardhat DAOs](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=107124s)* ⬆️ Up-to-date code: https://github.com/PatrickAlphaC/dao-template 💻 Code from video: https://github.com/PatrickAlphaC/hardhat-dao-fcc ## Introduction ## What is a DAO? - [What is a DAO?](https://www.youtube.com/watch?v=X_QKZzd68ro) ## How to build a DAO - [How to build a DAO](https://www.youtube.com/watch?v=AhJtmUqhAqg) - That's Patrick - [PY Code](https://github.com/brownie-mix/dao-mix) - [Python Video](https://www.youtube.com/watch?v=rD8AxZ_wBA4) - [Openzeppelin Governance](https://docs.openzeppelin.com/contracts/4.x/api/governance) - [Compound Governance](https://compound.finance/governance) - [Contract Wizard](https://docs.openzeppelin.com/contracts/4.x/wizard) - [CastVoteBySig](https://forum.openzeppelin.com/t/what-is-votecastbysig/17069/2) # Lesson 18: Security & Auditing *[⌨️ (31:28:32) Lesson 18: Security & Auditing ](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=113312s)* 💻 Code: https://github.com/PatrickAlphaC/hardhat-security-fcc ## Introduction - [Readiness Guide](https://learn.openzeppelin.com/security-audits/readiness-guide) ## Slither - [Install python](https://www.python.org/downloads/) - [Slither](https://github.com/crytic/slither#how-to-install) - [solc-select](https://github.com/crytic/solc-select) - [Fuzz testing](https://en.wikipedia.org/wiki/Fuzzing) ## Fuzzing and Eth Security Toolbox - [Echidna](https://github.com/crytic/echidna) - [Docker Install](https://docs.docker.com/get-docker/) - [Eth-Security-ToolBox](https://github.com/trailofbits/eth-security-toolbox) ## Closing Thoughts - [Best Practices](https://consensys.github.io/smart-contract-best-practices/) - [Attacks](https://consensys.github.io/smart-contract-best-practices/known_attacks/) - [Oracle Attacks](https://hackernoon.com/how-dollar100m-got-stolen-from-defi-in-2021-price-oracle-manipulation-and-flash-loan-attacks-explained-3n6q33r1) - [Re-entrancy Attacks](https://quantstamp.com/blog/what-is-a-re-entrancy-attack) - [Damn Vulnerable Defi](https://www.damnvulnerabledefi.xyz/) - [Ethernaut](https://ethernaut.openzeppelin.com/) - Some Auditors: - [OpenZeppelin](https://openzeppelin.com/) - [SigmaPrime](https://sigmaprime.io/) - [Trail of Bits](https://www.trailofbits.com/) # Congratulations 🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊 Completed The Course! 🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊🎊 ## Where do I go now? ### Learning More - [CryptoZombies](https://cryptozombies.io/) - [Patrick Collins](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) - [Dapp University](https://www.youtube.com/channel/UCY0xL8V6NzzFcwzHCgB8orQ) - [ChainShot](https://www.chainshot.com/courses) - [Cami Ramos Garzon](https://twitter.com/camiinthisthang) - [Albert Hu](https://twitter.com/thatguyintech) - [Ivan Liljeqvist](https://twitter.com/IvanOnTech) - [Ally Haire](https://twitter.com/DeveloperAlly) - [Stephen Fluin](https://twitter.com/stephenfluin) - [Eat the Blocks](https://www.youtube.com/channel/UCZM8XQjNOyG2ElPpEUtNasA) - [Austin Griffith](https://www.youtube.com/channel/UC_HI2i2peo1A-STdG22GFsA) - [Nader Dabit](https://www.youtube.com/user/boyindasouth) - [Ethereum.org](https://ethereum.org/en/) ### Community - [Twitter](https://twitter.com/PatrickAlphaC) - [Hardhat Discord](https://discord.gg/9zk7snTfWe) - [Chainlink Discord](https://discord.gg/2YHSAey) - [Ethereum Discord](https://ethereum.org/en/) - [Reddit ethdev](https://www.reddit.com/r/ethdev/) ### Hackathons - [CL Hackathon](https://chain.link/hackathon) - [ETH Global](https://ethglobal.co/) - [ETH India](https://twitter.com/ETHIndiaco) Be sure to check out project grant programs! And make today an amazing day! # Thank you Thanks to everyone who is taking, participating in, and working on this course. It's been a passion project and a data dump of everything I've learnt in the web3 space to get you up to speed quickly. Also, a big thank you to Chainlink Labs for encouraging this course to come to light-and to the many Chainlink Labs team members who helped with various assets! [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) <br/> <p align="center"> <a href="https://chain.link" target="_blank"> <img src="./box-img-lg.png" width="225" alt="Chainlink Hardhat logo"> </a> </p> <br/> [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/smartcontractkit/hardhat-starter-kit) - [Chainlink Hardhat Starter Kit](#chainlink-hardhat-starter-kit) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Typescript](#typescript) - [Usage](#usage) - [Deploying Contracts](#deploying-contracts) - [Run a Local Network](#run-a-local-network) - [Using a Testnet or Live Network (like Mainnet or Polygon)](#using-a-testnet-or-live-network-like-mainnet-or-polygon) - [Goerli Ethereum Testnet Setup](#goerli-ethereum-testnet-setup) - [Forking](#forking) - [Auto-Funding](#auto-funding) - [Test](#test) - [Interacting with Deployed Contracts](#interacting-with-deployed-contracts) - [Chainlink Price Feeds](#chainlink-price-feeds) - [Request & Receive Data](#request--receive-data) - [VRF Get a random number](#vrf-get-a-random-number) - [Keepers](#keepers) - [Verify on Etherscan](#verify-on-etherscan) - [View Contracts Size](#view-contracts-size) - [Linting](#linting) - [Code Formatting](#code-formatting) - [Estimating Gas](#estimating-gas) - [Code Coverage](#code-coverage) - [Fuzzing](#fuzzing) - [Contributing](#contributing) - [Thank You!](#thank-you) - [Resources](#resources) # Chainlink Hardhat Starter Kit Implementation of the following 4 Chainlink features using the [Hardhat](https://hardhat.org/) development environment: - [Chainlink Price Feeds](https://docs.chain.link/docs/using-chainlink-reference-contracts) - [Chainlink VRF](https://docs.chain.link/docs/chainlink-vrf) - [Chainlink Keepers](https://docs.chain.link/docs/chainlink-keepers/introduction/) - [Request & Receive data](https://docs.chain.link/docs/request-and-receive-data) # Getting Started It's recommended that you've gone through the [hardhat getting started documentation](https://hardhat.org/getting-started/) before proceeding here. ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version`and get an output like: `vx.x.x` - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` And get an output like: `x.x.x` - You might need to install it with npm > If you're familiar with `npx` and `npm` instead of `yarn`, you can use `npx` for execution and `npm` for installing dependencies. ## Quickstart 1. Clone and install dependencies After installing all the requirements, run the following: ```bash git clone https://github.com/smartcontractkit/hardhat-starter-kit/ cd hardhat-starter-kit ``` Then: ``` yarn ``` or ``` npm i ``` 2. You can now do stuff! ``` yarn hardhat test ``` or ``` npm test ``` ### Typescript To use typescript, run: ``` git checkout typescript yarn ``` # Usage If you run `yarn hardhat --help` you'll get an output of all the tasks you can run. ## Deploying Contracts ``` yarn hardhat deploy ``` This will deploy your contracts to a local network. Additionally, if on a local network, it will deploy mock Chainlink contracts for you to interact with. If you'd like to interact with your deployed contracts, skip down to [Interacting with Deployed Contracts](#interacting-with-deployed-contracts). ## Run a Local Network One of the best ways to test and interact with smart contracts is with a local network. To run a local network with all your contracts in it, run the following: ``` yarn hardhat node ``` You'll get a local blockchain, private keys, contracts deployed (from the `deploy` folder scripts), and an endpoint to potentially add to an EVM wallet. ## Using a Testnet or Live Network (like Mainnet or Polygon) In your `hardhat.config.js` you'll see section like: ``` module.exports = { defaultNetwork: "hardhat", networks: { ``` This section of the file is where you define which networks you want to interact with. You can read more about that whole file in the [hardhat documentation.](https://hardhat.org/config/) To interact with a live or test network, you'll need: 1. An rpc URL 2. A Private Key 3. ETH & LINK token (either testnet or real) Let's look at an example of setting these up using the Goerli testnet. ### Goerli Ethereum Testnet Setup First, we will need to set environment variables. We can do so by setting them in our `.env` file (create it if it's not there). You can also read more about [environment variables](https://www.twilio.com/blog/2017/01/how-to-set-environment-variables.html) from the linked twilio blog. You'll find a sample of what this file will look like in `.env.example` > IMPORTANT: MAKE SURE YOU'D DON'T EXPOSE THE KEYS YOU PUT IN THIS `.env` FILE. By that, I mean don't push them to a public repo, and please try to keep them keys you use in development not associated with any real funds. 1. Set your `GOERLI_RPC_URL` [environment variable.](https://www.twilio.com/blog/2017/01/how-to-set-environment-variables.html) You can get one for free from [Alchemy](https://www.alchemy.com/), [Infura](https://infura.io/), or [Moralis](https://moralis.io/speedy-nodes/). This is your connection to the blockchain. 2. Set your `PRIVATE_KEY` environment variable. This is your private key from your wallet, ie [MetaMask](https://metamask.io/). This is needed for deploying contracts to public networks. You can optionally set your `MNEMONIC` environment variable instead with some changes to the `hardhat.config.js`. ![WARNING](https://via.placeholder.com/15/f03c15/000000?text=+) **WARNING** ![WARNING](https://via.placeholder.com/15/f03c15/000000?text=+) When developing, it's best practice to use a Metamask that isn't associated with any real money. A good way to do this is to make a new browser profile (on Chrome, Brave, Firefox, etc) and install Metamask on that browser, and never send this wallet money. Don't commit and push any changes to .env files that may contain sensitive information, such as a private key! If this information reaches a public GitHub repository, someone can use it to check if you have any Mainnet funds in that wallet address, and steal them! `.env` example: ``` GOERLI_RPC_URL='www.infura.io/asdfadsfafdadf' PRIVATE_KEY='abcdef' ``` `bash` example ``` export GOERLI_RPC_URL='www.infura.io/asdfadsfafdadf' export PRIVATE_KEY='abcdef' ``` > You can also use a `MNEMONIC` instead of a `PRIVATE_KEY` environment variable by uncommenting the section in the `hardhat.config.js`, and commenting out the `PRIVATE_KEY` line. However this is not recommended. For other networks like mainnet and polygon, you can use different environment variables for your RPC URL and your private key. See the `hardhat.config.js` to learn more. 3. Get some Goerli Testnet ETH and LINK Head over to the [Chainlink faucets](https://faucets.chain.link/) and get some ETH and LINK. Please follow [the chainlink documentation](https://docs.chain.link/docs/acquire-link/) if unfamiliar. 4. Create VRF V2 subscription Head over to [VRF Subscription Page](https://vrf.chain.link/goerli) and create the new subscription. Save your subscription ID and put it in `.env` file as `VRF_SUBSCRIPTION_ID` 5. Running commands You should now be all setup! You can run any command and just pass the `--network goerli` now! To deploy contracts: ``` yarn hardhat deploy --network goerli ``` To run staging testnet tests ``` yarn hardhat test --network goerli ``` ## Forking If you'd like to run tests or on a network that is a [forked network](https://hardhat.org/hardhat-network/guides/mainnet-forking.html) 1. Set a `MAINNET_RPC_URL` environment variable that connects to the mainnet. 2. Choose a block number to select a state of the network you are forking and set it as `FORKING_BLOCK_NUMBER` environment variable. If ignored, it will use the latest block each time which can lead to test inconsistency. 3. Set `enabled` flag to `true`/`false` to enable/disable forking feature ``` forking: { url: MAINNET_RPC_URL, blockNumber: FORKING_BLOCK_NUMBER, enabled: false, } ``` ## Auto-Funding This Starter Kit is configured by default to attempt to auto-fund any newly deployed contract that uses Any-API, to save having to manually fund them after each deployment. The amount in LINK to send as part of this process can be modified in the [Starter Kit Config](helper-hardhat-config.js), and are configurable per network. | Parameter | Description | Default Value | | ---------- | :------------------------------------------------ | :------------ | | fundAmount | Amount of LINK to transfer when funding contracts | 0.1 LINK | If you wish to deploy the smart contracts without performing the auto-funding, add an `AUTO_FUND` environment variable, and set it to false. # Test Tests are located in the [test](./test/) directory, and are split between unit tests and staging/testnet tests. Unit tests should only be run on local environments, and staging tests should only run on live environments. To run unit tests: ```bash yarn test ``` or ``` yarn hardhat test ``` To run staging tests on Goerli network: ```bash yarn test-staging ``` or ``` yarn hardhat test --network goerli ``` ## Performance optimizations Since all tests are written in a way to be independent from each other, you can save time by running them in parallel. Make sure that `AUTO_FUND=false` inside `.env` file. There are some limitations with parallel testing, read more about them [here](https://hardhat.org/guides/parallel-tests.html) To run tests in parallel: ``` yarn test --parallel ``` or ``` yarn hardhat test --parallel ``` # Interacting with Deployed Contracts After deploying your contracts, the deployment output will give you the contract addresses as they are deployed. You can then use these contract addresses in conjunction with Hardhat tasks to perform operations on each contract. ## Chainlink Price Feeds The Price Feeds consumer contract has one task, to read the latest price of a specified price feed contract ```bash yarn hardhat read-price-feed --contract insert-contract-address-here --network network ``` ## Request & Receive Data The APIConsumer contract has two tasks, one to request external data based on a set of parameters, and one to check to see what the result of the data request is. This contract needs to be funded with link first: ```bash yarn hardhat fund-link --contract insert-contract-address-here --network network ``` Once it's funded, you can request external data by passing in a number of parameters to the request-data task. The contract parameter is mandatory, the rest are optional ```bash yarn hardhat request-data --contract insert-contract-address-here --network network ``` Once you have successfully made a request for external data, you can see the result via the read-data task ```bash yarn hardhat read-data --contract insert-contract-address-here --network network ``` ## VRF Get a random number The VRFConsumer contract has two tasks, one to request a random number, and one to read the result of the random number request. To start, go to [VRF Subscription Page](https://vrf.chain.link/goerli) and create the new subscription. Save your subscription ID and put it in `.env` file as `VRF_SUBSCRIPTION_ID`: ```bash VRF_SUBSCRIPTION_ID=subscription_id ``` Then, deploy your VRF V2 contract consumer to the network of your recent subscription using subscription id as constructor argument. ```bash yarn hardhat deploy --network network ``` Finally, you need to go to your subscription page one more time and add the address of deployed contract as a new consumer. Once that's done, you can perform a VRF request with the request-random-number task: ```bash yarn hardhat request-random-number --contract insert-contract-address-here --network network ``` Once you have successfully made a request for a random number, you can see the result via the read-random-number task: ```bash yarn hardhat read-random-number --contract insert-contract-address-here --network network ``` ## Keepers The KeepersCounter contract is a simple Chainlink Keepers enabled contract that simply maintains a counter variable that gets incremented each time the performUpkeep task is performed by a Chainlink Keeper. Once the contract is deployed, you should head to [https://keepers.chain.link/](https://keepers.chain.link/) to register it for upkeeps, then you can use the task below to view the counter variable that gets incremented by Chainlink Keepers ```bash yarn hardhat read-keepers-counter --contract insert-contract-address-here --network network ``` ## Verify on Etherscan You'll need an `ETHERSCAN_API_KEY` environment variable. You can get one from the [Etherscan API site.](https://etherscan.io/apis). If you have it set, your deploy script will try to verify them by default, but if you want to verify any manually, you can run: ``` yarn hardhat verify --network <NETWORK> <CONTRACT_ADDRESS> <CONSTRUCTOR_PARAMETERS> ``` example: ``` yarn hardhat verify --network goerli 0x9279791897f112a41FfDa267ff7DbBC46b96c296 "0x9326BFA02ADD2366b30bacB125260Af641031331" ``` # View Contracts Size ``` yarn run hardhat size-contracts ``` # Linting This will [lint](https://stackoverflow.com/questions/8503559/what-is-linting) your smart contracts. ``` yarn lint:fix ``` # Code Formatting This will format both your javascript and solidity to look nicer. ``` yarn format ``` # Estimating Gas To estimate gas, just set a `REPORT_GAS` environment variable to true, and then run: ``` yarn hardhat test ``` If you'd like to see the gas prices in USD or other currency, add a `COINMARKETCAP_API_KEY` from [Coinmarketcap](https://coinmarketcap.com/api/documentation/v1/). # Code coverage To see a measure in percent of the degree to which the smart contract source code is executed when a particular test suite is run, type ``` yarn coverage ``` # Fuzzing We are going to use Echidna as a Fuzz testing tool. You need to have [Docker](https://www.docker.com/) installed with at least 8GB virtual memory allocated (To update this parameter go to _Settings->Resources->Advanced->Memory_). To start Echidna instance run ``` yarn fuzzing ``` If you are using it for the first time, you will need to wait for Docker to download [eth-security-toolbox](https://hub.docker.com/r/trailofbits/eth-security-toolbox) image for us. To start Fuzzing run ``` echidna-test /src/contracts/test/fuzzing/KeepersCounterEchidnaTest.sol --contract KeepersCounterEchidnaTest --config /src/contracts/test/fuzzing/config.yaml ``` To exit Echidna type ```bash exit ``` # Contributing Contributions are always welcome! Open a PR or an issue! # Thank You! ## Resources - [Chainlink Documentation](https://docs.chain.link/) - [Hardhat Documentation](https://hardhat.org/getting-started/) ## Deploy Multisig Contract on Remix Multi-Signatute Wallets allow a wallet to be controlled by more than 1 owner. In order to approve transactions a thrsehold number of signatures are required. E.g 2/3 Multisig Wallet -> if there are 3 owners, at least 2 have to apprive. A popular, secure and trusted [Multi-Sig Wallet is Gnosis](https://gnosis-safe.io/) ### Deploy Multi-Sig Contract Using Remix 1. Compile and deploy contracts on JVM to check all is working well - Copy MultiSigWallet.sol Solidity Code into a file in Remix rename MultiSigWallet.sol - Select Solidity Compiler Page - On Compiler Options dropdown select 0.8.3 version - Click "Compile MultiSigWallet.sol" button - Select Deploy and Run Transactions Page - Environment dropdown select JavaScript VM - Accounts dropdwon -> pick any of the accounts in dropdown - Deploy Button - Enter the parameters for deployment for - For _OWNERS use an array of addresses e.g first 3 addresses in Account dropdown e.g => ["0x5B38Da6a701c568545dCfcB03FcB875f56beddC4","0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2","0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c"] - For _NUMCONFIRMATIONSREQUIRED number confirmations e.g is 3 owners like above you need at least => 2 - Click deploy button - Deployed Contracts - Scroll down to deployed contracts section and click on deployed contract - View buttons for all the functions you can carry out on contract e.g - Call functions => getOwners, getTransaction, getTransactionCount, isConfirmed, owners, transactions etc - Transacting functions => submiTransaction, confirmTransaction, executeTransaction, revokeTransaction 1. Deploy Token to Kovan Testnet - Select Deploy and Run Transactions Page - Environment dropdown select Injected Web3 (to allow use of Metamask) - Accounts dropdwon will have first currently selected Metamask account - Get some testnet ETH, Kovan ETH into the deploying account - Copy the address from accounts - Go to [https://linkfaucet.protofire.io/kovan](https://linkfaucet.protofire.io/kovan) paste account and request some Kovan ETH - Deploy Button - Enter the parameters for deployment for - For _OWNERS use an array of addresses e.g first 3 addresses in Account dropdown e.g => ["0x5B38Da6a701c568545dCfcB03FcB875f56beddC4","0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2","0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c"] - For _NUMCONFIRMATIONSREQUIRED number confirmations e.g is 3 owners like above you need at least => 2 - Click deploy button and confirm transaction on MetaMask - Deployed Contracts - Scroll down to deployed contracts section and click on deployed contract - View buttons for all the functions you can carry out on contract e.g - Call functions => getOwners, getTransaction, getTransactionCount, isConfirmed, owners, transactions etc - Transacting functions => submiTransaction, confirmTransaction, executeTransaction, revokeTransaction ### YF_LP on Rinkeby & BSC 0. **Visit backend README.md 1st, then come back** 1. **Install dependencies with yarn (working with: 1.22.10, to install type: npm i -g [email protected]):** </br>```yarn add``` 2. **Run dApp:** </br>```yarn start``` 3. **If you run dApp on BSC, remember to Setup BSC in your MetaMask [HowTo](https://academy.binance.com/en/articles/connecting-metamask-to-binance-smart-chain)** [Content not decodable] [Content not decodable] - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Typescript (Optional)](#typescript-optional) - [Optional Gitpod](#optional-gitpod) - [Usage](#usage) - [Deployment to a testnet or mainnet](#deployment-to-a-testnet-or-mainnet) - [Verify on etherscan](#verify-on-etherscan) - [Thank you!](#thank-you) # Getting Started ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an ouput like `vx.x.x` - [Yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` And get an output like `x.x.x` - You might need to install it with npm ## Quickstart ``` git clone https://github.com/PatrickAlphaC/hardhat-erc20-fcc cd hardhat-erc20-fcc yarn ``` ### Typescript (Optional) ``` git checkout typescript ``` ### Optional Gitpod If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the `clone this repo` part. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#github.com/PatrickAlphaC/hardhat-erc20-fcc) # Usage Deploy: ``` yarn hardhat deploy ``` # Deployment to a testnet or mainnet 1. Setup environment variabltes You'll want to set your `KOVAN_RPC_URL` and `PRIVATE_KEY` as environment variables. You can add them to a `.env` file, similar to what you see in `.env.example`. - `PRIVATE_KEY`: The private key of your account (like from [metamask](https://metamask.io/)). **NOTE:** FOR DEVELOPMENT, PLEASE USE A KEY THAT DOESN'T HAVE ANY REAL FUNDS ASSOCIATED WITH IT. - You can [learn how to export it here](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key). - `KOVAN_RPC_URL`: This is url of the kovan testnet node you're working with. You can get setup with one for free from [Alchemy](https://alchemy.com/?a=673c802981) 2. Get testnet ETH Head over to [faucets.chain.link](https://faucets.chain.link/) and get some tesnet ETH. You should see the ETH show up in your metamask. 3. Deploy ``` yarn hardhat deploy --network kovan ``` ## Verify on etherscan If you deploy to a testnet or mainnet, you can verify it if you get an [API Key](https://etherscan.io/myapikey) from Etherscan and set it as an environemnt variable named `ETHERSCAN_API_KEY`. You can pop it into your `.env` file as seen in the `.env.example`. In it's current state, if you have your api key set, it will auto verify kovan contracts! However, you can manual verify with: ``` yarn hardhat verify --constructor-args arguments DEPLOYED_CONTRACT_ADDRESS ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) This is part of the FreeCodeCamp Solidity & Javascript Blockchain Course. Video Link : https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=7276s TimeStamp : (02:01:16) ## Getting Started 1. Go to [Remix](https://remix.ethereum.org/) 2. Paste the code from `SimpleStorage.sol` into a new file in Remix 3. Hit `Compile` 4. Hit `Deploy` For a more in depth blog on working with remix, [read here](https://docs.chain.link/docs/deploy-your-first-contract/) # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) [Content not decodable] [Content not decodable] # Fractional NFTs ## Technology Stack & Tools - Solidity (Writing Smart Contract) - Javascript (React & Testing) - [Web3](https://web3js.readthedocs.io/en/v1.5.2/) (Blockchain Interaction) - [Truffle](https://www.trufflesuite.com/docs/truffle/overview) (Development Framework) - [Ganache](https://www.trufflesuite.com/ganache) (For Local Blockchain) ## Requirements For Initial Setup - Install [NodeJS](https://nodejs.org/en/), should work with any node version above 14.16.0 or below 16.5.0 - Install [Truffle](https://www.trufflesuite.com/docs/truffle/overview), In your terminal, you can check to see if you have truffle by running `truffle version`. To install truffle run `npm i -g truffle`. Ideal to have truffle version 5.4 to avoid dependency issues. - Install [Ganache](https://www.trufflesuite.com/ganache). ## Setting Up ### 1. Clone/Download the Repository ### 2. Install Dependencies: ``` $ cd fractional_nfts $ npm install ``` ### 3. Start Ganache ### 4. Migrate Smart Contracts `$ truffle migrate --reset` ### 5. Run Tests `$ truffle test` ### 6. Run Sale Script `$ truffle exec ./scripts/distribute_tokens.js` ## Flashloan LeveragedYieldFarm Make use of Flashloan from DY/DX to earn more from Compouond. ## 🔧 Project Diagram: - How it works ## 🔧 Deposit Diagram: ![Deposit Diagram](https://i.gyazo.com/77913f25dd333c7f8a9ea99813053c61.png) </br> ## 🔧 Withdraw Diagram: ![Deposit Diagram](https://i.gyazo.com/3c5736a988fe92fc7bd3c373230c2663.png) ### Technology Stack and Tools * [Node Version Manager](https://heynode.com/tutorial/install-nodejs-locally-nvm) - node version manager * [Yarn](https://yarnpkg.com/) - Alternative package manager to NPM * [Truffle](https://www.trufflesuite.com/) - development framework * [Solidity](https://docs.soliditylang.org/en/v0.7.4/) - ethereum smart contract language * [Ganache](https://www.trufflesuite.com/ganache) - local blockchain development * [Web3](https://web3js.readthedocs.io/en/v1.3.0/) - library interact with ethereum nodes * [JavaScript](https://www.javascript.com/) - logic front end and testing smart contracts * [Infura](https://infura.io/) - connection to ethereum networks * [Flashloan](https://coinmarketcap.com/alexandria/glossary/flash-loans) - Flashloans allow you to borrow lots of funds for a very small fee without need for collateral do anything else with funds as long as repayments happens in same transaction. * [Metamask Wallet](https://metamask.io/) - You need to install Metamask Wallet - [How to install Metamask](https://blog.wetrust.io/how-to-install-and-use-metamask-7210720ca047) * [ERC20](https://docs.openzeppelin.com/contracts/2.x/api/token/erc20) - ERC20 Token standards * [Compound Protocol](https://app.compound.finance/) - supply or borrow tokens and earn cTokens * Flashloan Providers * [DY/DX]() - Decentralized Exchange offering flashloans with cheap feess; that is used on this example code Alternative Flashloan Providers that can be used or to investigate * [UniswapV2 Flashswaps](https://docs.uniswap.org/protocol/V2/concepts/core-concepts/flash-swaps) - access temporary funds - Example Uniswap FlashSwap can be [found here](https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleFlashSwap.sol) * [Aave Flashloan](https://docs.aave.com/developers/guides/flash-loans) - uncollaterized loan that must be returned in same transaction * [Binance Smart Chain - Pancake Swap]() - PancakeSwap as a fork of Uniswap deployed on Binance Smart Chain has the same functionality for Flashloan using e.g ..pancakeCall vs UniswapV2Cal when considering version2 Uniswap * [Kollateral](https://www.kollateral.co/) - a liquidity aggregator * [UniLend](https://docs.unilend.finance/the-protocol/flash-loan/performing-flashloan) - UniLend Flashloans * [Augement your profits with trading bot](https://dappuniversity.teachable.com/courses/940808/lectures/24527435) - TradingBot Masterclass * Uses of Flashloans * Arbitrage - use the vast funds to make profits from price discrepencies e.g on Exchange See SimpleArb.sol * Leverage - increase exposure e.g earn more with Yield Farmin on protocols like Compound. See FlashloanLeveragedYieldFarm project ##### Folder / Directory Structure (key folders and files) * FlashloanLeveragedYieldFarm * flats * migrations * node_modules * src * abis * contracts * test * flatten.sh * truffle.js * package.json * .gitignore * README.md * yarn.lock ### Preconfiguration, Installation 1. You will need nvm if not laready installed; so you can use specific version node version 14 and above ```sh $ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash ``` Restart your terminal 2. Install node v12.0.0 or versions above e.g node v14.16.0 ```sh $ nvm install 14.16.0 $ nvm alias default 14.16.0 $ nvm use default ``` 3. Install truffle globally if not installed. Check if installed using ```sh truffle version ``` If not installed install with below ```sh $ npm install -g truffle ``` 4. Ignore if either installed already! If opting to use ganache-cli vs [Ganache GUI](https://www.trufflesuite.com/ganache), install ganache-cli globally. Note that ganache-cli rus on port 8545 and ganache-gui runs on port 7545 as placced in truffle-config.js. Check if ganache-cli installed first with ```sh ganache --version ``` If not installed install with below ```sh $ npm install -g ganache $ ganache ``` Run ganache-cli in different terminal and keep running when compiling, testing, migrating, running app, etc. ## Running the project 1. Enter project directory and install dependancies ```sh $ cd flashloan_masterclass $ npm install ``` 2. Run Ganache Fork ```sh $ ganache -p 7545 -f ``` 3. Run the test that will show example flashloan and leveraged yield farming compound and repay Open a new terminal and run ```sh $ truffle test ``` If you have problems with test e.g archived state, rpc etc, you may need to restart your ganache running fork To reset and run again, you will need to restart the terminal with ganache and rerun the fork 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. [Content not decodable] [Content not decodable] # Defi Yield Aggregator This project is a simple decentrialized app where a user can deposit DAI into our smart contract. Once funds are deposited, the contract compares the interest rate of Compound & Aave, and deposits funds to whichever has the highest interest rate. The user can rebalance his/her funds to ensure that the funds are still currently in the higher interest rate protocol, and can also withdraw at any time. ## Technology Stack & Tools - Solidity (Writing Smart Contract) - Javascript (React & Testing) - [Web3](https://web3js.readthedocs.io/en/v1.5.2/) (Blockchain Interaction) - [Truffle](https://www.trufflesuite.com/docs/truffle/overview) (Development Framework) - [Ganache-cli](https://github.com/trufflesuite/ganache) (For Local Blockchain) - [Infura.io](https://infura.io/) (For copying the Ethereum mainnet) - [MetaMask](https://metamask.io/) (Ethereum Wallet) - Openzeppelin (Solidity Math) ## Requirements - Install [NodeJS](https://nodejs.org/en/), I recommend using node version 10.16.3 to avoid any potential dependency issues - Create or log in to your [Infura.io](https://infura.io/login) account and create a new project, and save your project ID located in your project settings, you'll need this when starting the ganache-cli server. - Install [MetaMask](https://metamask.io/) in your browser. - Install [Ganache-cli](https://github.com/trufflesuite/ganache). To see if you have ganache-cli installed, in your command line type `ganache-cli --version`. To install, in your command line type `npm install ganache-cli --global` ## Setting Up ### 1. Clone the Repository: `$ git clone https://github.com/dappuniversity/yield-aggregator.git` ### 2. Install Dependencies: ``` $ cd yield-aggregator $ npm install ``` ### 3. Start Ganache-cli In a separate CMD prompt/terminal run: ``` $ ganache-cli -f https://mainnet.infura.io/v3/<Your-Project-ID> -m <Your-Mnemonic-Phrase> -u 0x9759A6Ac90977b93B58547b4A71c78317f391A28 -p 7545 ``` Replace `Your-Project-ID` with your Infura Project ID located in the settings of your project. Replace `Your-Mnemonic-Phrase` with your own mnemonic phrase. If you don't have a mnemonic phrase to include you can omit it: ``` $ ganache-cli -f https://mainnet.infura.io/v3/<Your-Project-ID> -u 0x9759A6Ac90977b93B58547b4A71c78317f391A28 -p 7545 ``` If you didn't include a mnemonic phrase, after starting the ganache server it will supply you with one, plus 10 accounts you can use, I recommend saving that mnemonic phrase to use it when you need to start (or restart) ganache, and import the 1st private key listed in MetaMask so you can interact with the frontend. ### 4. Migrate Smart Contracts `$ truffle migrate --reset` ### 5. Mint DAI `$ node ./mint-dai/dai.js` ### 6. Run Frontend Application In a separate CMD prompt/terminal run: `$ npm start` ### 6. (Optional) Test Smart Contracts `$ truffle test` ## Potential Errors ``` Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced ``` This error can happen if you update the smart contract by running a migration. To solve this error, restart your Ganache-cli, run migrations, and mint DAI to your account (Essentially repeat steps 3-5 in project setup). You may have to also reset your MetaMask transactions if you completed any previous transactions, see error below. ``` RPC Error: Error: [ethjs-query] while formatting outputs from RPC '{"value":{"code":-32603,"data":{"message":"the tx doesn't have the correct nonce... ``` You may come across this error while making a transaction, this error can happens if you previously handled any transaction with your MetaMask account and restarted your ganache-cli server. You'll have to reset your MetaMask account by going into your MetaMask settings > advanced > reset account. ``` Error: while migrating Migrations: Returned error: project ID does not have access to archive state ``` This error may come up while trying to run `$ truffle test`, to solve this issue, simply restart your ganache-cli. This will mean having to re-mint your account with DAI # Forge Standard Library • [![tests](https://github.com/brockelmore/forge-std/actions/workflows/tests.yml/badge.svg)](https://github.com/brockelmore/forge-std/actions/workflows/tests.yml) Forge Standard Library is a collection of helpful contracts for use with [`forge` and `foundry`](https://github.com/foundry-rs/foundry). It leverages `forge`'s cheatcodes to make writing tests easier and faster, while improving the UX of cheatcodes. **Learn how to use Forge Std with the [📖 Foundry Book (Forge Std Guide)](https://book.getfoundry.sh/forge/forge-std.html).** ## Install ```bash forge install foundry-rs/forge-std ``` ## Contracts ### stdError This is a helper contract for errors and reverts. In `forge`, this contract is particularly helpful for the `expectRevert` cheatcode, as it provides all compiler builtin errors. See the contract itself for all error codes. #### Example usage ```solidity import "forge-std/Test.sol"; contract TestContract is Test { ErrorsTest test; function setUp() public { test = new ErrorsTest(); } function testExpectArithmetic() public { vm.expectRevert(stdError.arithmeticError); test.arithmeticError(10); } } contract ErrorsTest { function arithmeticError(uint256 a) public { uint256 a = a - 100; } } ``` ### stdStorage This is a rather large contract due to all of the overloading to make the UX decent. Primarily, it is a wrapper around the `record` and `accesses` cheatcodes. It can *always* find and write the storage slot(s) associated with a particular variable without knowing the storage layout. The one _major_ caveat to this is while a slot can be found for packed storage variables, we can't write to that variable safely. If a user tries to write to a packed slot, the execution throws an error, unless it is uninitialized (`bytes32(0)`). This works by recording all `SLOAD`s and `SSTORE`s during a function call. If there is a single slot read or written to, it immediately returns the slot. Otherwise, behind the scenes, we iterate through and check each one (assuming the user passed in a `depth` parameter). If the variable is a struct, you can pass in a `depth` parameter which is basically the field depth. I.e.: ```solidity struct T { // depth 0 uint256 a; // depth 1 uint256 b; } ``` #### Example usage ```solidity import "forge-std/Test.sol"; contract TestContract is Test { using stdStorage for StdStorage; Storage test; function setUp() public { test = new Storage(); } function testFindExists() public { // Lets say we want to find the slot for the public // variable `exists`. We just pass in the function selector // to the `find` command uint256 slot = stdstore.target(address(test)).sig("exists()").find(); assertEq(slot, 0); } function testWriteExists() public { // Lets say we want to write to the slot for the public // variable `exists`. We just pass in the function selector // to the `checked_write` command stdstore.target(address(test)).sig("exists()").checked_write(100); assertEq(test.exists(), 100); } // It supports arbitrary storage layouts, like assembly based storage locations function testFindHidden() public { // `hidden` is a random hash of a bytes, iteration through slots would // not find it. Our mechanism does // Also, you can use the selector instead of a string uint256 slot = stdstore.target(address(test)).sig(test.hidden.selector).find(); assertEq(slot, uint256(keccak256("my.random.var"))); } // If targeting a mapping, you have to pass in the keys necessary to perform the find // i.e.: function testFindMapping() public { uint256 slot = stdstore .target(address(test)) .sig(test.map_addr.selector) .with_key(address(this)) .find(); // in the `Storage` constructor, we wrote that this address' value was 1 in the map // so when we load the slot, we expect it to be 1 assertEq(uint(vm.load(address(test), bytes32(slot))), 1); } // If the target is a struct, you can specify the field depth: function testFindStruct() public { // NOTE: see the depth parameter - 0 means 0th field, 1 means 1st field, etc. uint256 slot_for_a_field = stdstore .target(address(test)) .sig(test.basicStruct.selector) .depth(0) .find(); uint256 slot_for_b_field = stdstore .target(address(test)) .sig(test.basicStruct.selector) .depth(1) .find(); assertEq(uint(vm.load(address(test), bytes32(slot_for_a_field))), 1); assertEq(uint(vm.load(address(test), bytes32(slot_for_b_field))), 2); } } // A complex storage contract contract Storage { struct UnpackedStruct { uint256 a; uint256 b; } constructor() { map_addr[msg.sender] = 1; } uint256 public exists = 1; mapping(address => uint256) public map_addr; // mapping(address => Packed) public map_packed; mapping(address => UnpackedStruct) public map_struct; mapping(address => mapping(address => uint256)) public deep_map; mapping(address => mapping(address => UnpackedStruct)) public deep_map_struct; UnpackedStruct public basicStruct = UnpackedStruct({ a: 1, b: 2 }); function hidden() public view returns (bytes32 t) { // an extremely hidden storage slot bytes32 slot = keccak256("my.random.var"); assembly { t := sload(slot) } } } ``` ### stdCheats This is a wrapper over miscellaneous cheatcodes that need wrappers to be more dev friendly. Currently there are only functions related to `prank`. In general, users may expect ETH to be put into an address on `prank`, but this is not the case for safety reasons. Explicitly this `hoax` function should only be used for address that have expected balances as it will get overwritten. If an address already has ETH, you should just use `prank`. If you want to change that balance explicitly, just use `deal`. If you want to do both, `hoax` is also right for you. #### Example usage: ```solidity // SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "forge-std/Test.sol"; // Inherit the stdCheats contract StdCheatsTest is Test { Bar test; function setUp() public { test = new Bar(); } function testHoax() public { // we call `hoax`, which gives the target address // eth and then calls `prank` hoax(address(1337)); test.bar{value: 100}(address(1337)); // overloaded to allow you to specify how much eth to // initialize the address with hoax(address(1337), 1); test.bar{value: 1}(address(1337)); } function testStartHoax() public { // we call `startHoax`, which gives the target address // eth and then calls `startPrank` // // it is also overloaded so that you can specify an eth amount startHoax(address(1337)); test.bar{value: 100}(address(1337)); test.bar{value: 100}(address(1337)); vm.stopPrank(); test.bar(address(this)); } } contract Bar { function bar(address expectedSender) public payable { require(msg.sender == expectedSender, "!prank"); } } ``` ### Std Assertions Expand upon the assertion functions from the `DSTest` library. ### `console.log` Usage follows the same format as [Hardhat](https://hardhat.org/hardhat-network/reference/#console-log). It's recommended to use `console2.sol` as shown below, as this will show the decoded logs in Forge traces. ```solidity // import it indirectly via Test.sol import "forge-std/Test.sol"; // or directly import it import "forge-std/console2.sol"; ... console2.log(someValue); ``` If you need compatibility with Hardhat, you must use the standard `console.sol` instead. Due to a bug in `console.sol`, logs that use `uint256` or `int256` types will not be properly decoded in Forge traces. ```solidity // import it indirectly via Test.sol import "forge-std/Test.sol"; // or directly import it import "forge-std/console.sol"; ... console.log(someValue); ``` # Hardhat Fund Me This is a section of the Javascript Blockchain/Smart Contract FreeCodeCamp Course. Video Coming soon... [Full Repo](https://github.com/smartcontractkit/full-blockchain-solidity-course-js) - [Hardhat Fund Me](#hardhat-fund-me) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Typescript](#typescript) - [Useage](#useage) - [Testing](#testing) - [Test Coverage](#test-coverage) - [Deployment to a testnet or mainnet](#deployment-to-a-testnet-or-mainnet) - [Estimate gas](#estimate-gas) - [Estimate gas cost in USD](#estimate-gas-cost-in-usd) - [Verify on etherscan](#verify-on-etherscan) - [Thank you!](#thank-you) This project is apart of the Hardhat FreeCodeCamp video. Video coming soon... # Getting Started ## Requirements - [Nodejs & npm](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` - And get an ouput like: - `vx.x.x` - You'll know you've installed npm right if you can run: - `npm --version` - And get an ouput like: - `x.x.x` - Optional [yarn](https://classic.yarnpkg.com/lang/en/docs/install/) instead of `npm` ## Quickstart ``` git clone https://github.com/PatrickAlphaC/hardhat-fund-me-fcc cd hardhat-fund-me-fcc npm install ``` **Note: If you delete `package-lock.json` it won't install correctly with just `package.json`. You'll need to remove the line with `@nomiclabs/hardhat-ethers` from `package.json`, and then reinstall it with `npm install --save-dev @nomiclabs/hardhat-ethers@npm:hardhat-deploy-ethers ethers`. [Read more here](https://github.com/wighawag/hardhat-deploy-ethers#installation)** ## Typescript For the typescript edition, run: ``` git checkout typescript ``` # Useage Deploy: ``` npx hardhat deploy ``` ## Testing In this version, we run testing off a forked mainnet, so you'll need to set your `MAINNET_RPC_URL` similar to how we set all our other environment variables. ``` npx hardhat test ``` ### Test Coverage ``` npx hardhat coverage ``` # Deployment to a testnet or mainnet 1. Setup environment variabltes You'll want to set your `KOVAN_RPC_URL` and `PRIVATE_KEY` as environment variables. You can add them to a `.env` file, similar to what you see in `.env.example`. - `PRIVATE_KEY`: The private key of your account (like from [metamask](https://metamask.io/)). **NOTE:** FOR DEVELOPMENT, PLEASE USE A KEY THAT DOESN'T HAVE ANY REAL FUNDS ASSOCIATED WITH IT. - You can [learn how to export it here](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key). - `KOVAN_RPC_URL`: This is url of the kovan testnet node you're working with. You can get setup with one for free from [Alchemy](https://alchemy.com/?a=673c802981) 2. Get testnet ETH Head over to [faucets.chain.link](https://faucets.chain.link/) and get some tesnet ETH. You should see the ETH show up in your metamask. 3. Deploy ``` npx hardhat deploy --network kovan ``` ## Estimate gas You can estimate how much gas things cost by running: ``` npx hardhat test ``` And you'll see and output file called `gas-report.txt` ### Estimate gas cost in USD To get a USD estimation of gas cost, you'll need a `COINMARKETCAP_API_KEY` environment variable. You can get one for free from [CoinMarketCap](https://pro.coinmarketcap.com/signup). Then, uncomment the line `coinmarketcap: COINMARKETCAP_API_KEY,` in `hardhat.config.js` to get the USD estimation. Just note, everytime you run your tests it will use an API call, so it might make sense to have using coinmarketcap disabled until you need it. You can disable it by just commenting the line back out. ## Verify on etherscan If you deploy to a testnet or mainnet, you can verify it if you get an [API Key](https://etherscan.io/myapikey) from Etherscan and set it as an environemnt variable named `ETHERSCAN_API_KEY`. You can pop it into your `.env` file as seen in the `.env.example`. In it's current state, if you have your api key set, it will auto verify kovan contracts! However, you can manual verify with: ``` npx hardhat verify --constructor-args arguments.js DEPLOYED_CONTRACT_ADDRESS ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) # 👋🏼 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 This is part of the FreeCodeCamp Solidity & Javascript Blockchain Course. *[⌨️ (03:31:55) Lesson 4: Remix Fund Me](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=12715s)* ## Getting Started 1. Go to [Remix](https://remix.ethereum.org/) 2. Paste the code from `FundMe.sol` and `PriceConverter.sol` into new files in Remix 3. Hit `Compile` 4. Hit `Deploy` For a more in depth blog on working with remix, [read here](https://docs.chain.link/docs/deploy-your-first-contract/) # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) [Content not decodable] A few different examples on connecting your dApps to metamask / wallets. # Open Punks ## Technology Stack & Tools - Solidity (Writing Smart Contract) - Javascript (React & Testing) - [Web3](https://web3js.readthedocs.io/en/v1.5.2/) (Blockchain Interaction) - [Truffle](https://www.trufflesuite.com/docs/truffle/overview) (Development Framework) - [Ganache](https://www.trufflesuite.com/ganache) (For Local Blockchain) - [Infura.io](https://infura.io/) (For copying the Ethereum mainnet) - [MetaMask](https://metamask.io/) (Ethereum Wallet) - [Git](https://git-scm.com/)/[GitHub](https://github.com) (Commit our code) - [Fleek](https://fleek.co/) (Website Deployment) ## Requirements For Initial Setup - Install [NodeJS](https://nodejs.org/en/), Recommended version is 14.16.0 - Install [Truffle](https://www.trufflesuite.com/docs/truffle/overview), In your terminal, you can check to see if you have truffle by running `truffle --version`. To install truffle run `npm i -g truffle`. - Install [Ganache](https://www.trufflesuite.com/ganache). - Install [MetaMask](https://metamask.io/) in your browser. ## Setting Up ### 1. Clone/Download the Repository ### 2. Install Dependencies: `$ npm install ` ### 3. Setup .env File Create a .env file or rename the .env.example file, and update the values. The API & IPFS keys are technically optional for local testing, if you plan to deploy to the testnet or mainnet, you'll need to update those values. ### 4. Start Ganache ### 5. Migrate Smart Contracts `$ truffle migrate --reset` ### 6. Run Frontend Application In a separate CMD prompt/terminal run: `$ npm start` ### 7. (Optional) Test Smart Contracts `$ truffle test` ## Preparing for Contract Deployment - Create or log in to your [Infura.io](https://infura.io/login) account and create a new project, and save your project ID located in your project settings, you'll need this if deploying to Ethereum Mainnet, or Rinkeby Testnet. - If deploying to Polygon, you may need to setup the network in MetaMask. To do this, open MetaMask, in the top right click on your profile icon -> Settings -> Networks -> Add Network. - For **Polygon Mainnet** fill in the following: 1. **Network Name**: Polygon 2. **New RPC URL**: https://rpc-mainnet.maticvigil.com/ 3. **Chain ID**: 137 4. **Currency Symbol**: MATIC 5. **Block Explorer URL**: https://polygonscan.com/ - For the **Polygon Mumbai Testnet** fill in the following: 1. **Network Name**: Polygon Mumbai 2. **New RPC URL**: https://rpc-mumbai.maticvigil.com/ 3. **Chain ID**: 80001 4. **Currency Symbol**: MATIC 5. **Block Explorer URL**: https://mumbai.polygonscan.com/ ### Funding your MetaMask Wallet - If deploying to Polygon Mainnet, you will need to fund your MetaMask account with MATIC on the polygon chain, How you decide to transfer/fund is entirely upto you. Keep in mind if you have MATIC currently on the Ethereum Mainnet, you will need to bridge your MATIC over to the polygon chain. You can do this by visiting [https://wallet.polygon.technology/](https://wallet.polygon.technology/), also keep in mind you will have to have ETH in your account to cover gas fees! - If deploying to Rinkeby testnet, you may use this ETH faucet supplied by chainlink to fund your account: [https://faucets.chain.link/rinkeby](https://faucets.chain.link/rinkeby). - If deploying to Polygon Mumbai testnet, you may use this MATIC faucet: [https://faucet.polygon.technology/](https://faucet.polygon.technology/) ### 1. Setup your .env file Create a .env file in the root directory of your project, and fill in the following: - DEPLOYER_PRIVATE_KEY="YOUR_PRIVATE_KEY" - INFURA_API_KEY="PROJECT_ID" - ETHERSCAN_API_KEY="API_TOKEN" - PROJECT_NAME="YOUR_PROJECT_NAME" - PROJECT_SYMBOL="YOUR_PROJECT_SYMBOL" - MINT_COST=0 - MAX_SUPPLY=1000 - IPFS_IMAGE_METADATA_CID="IPFS_CID" - IPFS_HIDDEN_IMAGE_METADATA_CID="IPFS_CID" - NFT_MINT_DATE="Oct 27, 2021 20:00:00" ### 2. Run your migrations - For Rinkeby testnet: `truffle migrate --reset --network rinkeby` - For Polygon Mainnet: `truffle migrate --reset --network matic` ### 3. Verify your contracts - For Rinkeby testnet: `truffle run verify OpenPunks --network rinkeby` - For Polygon Mainnet: `truffle run verify OpenPunks --network matic` ## Preparing for Frontend Deployment ### 1. Create or Login to your GitHub account ### 2. Create a new repository Input the name of your project, and a description if you wish. You may also choose to make the repository public or private ### 3. Commit your code If you have downloaded this code, you may need to initialize it as a git repository, to do this back in your terminal run: `$ git init` Add files for staging: `$ git add .` This will ready your files for the commit, you may see if they have been added by running: `$ git status` Finally commit your code `$ git commit -m "Deployment Setup"` ### 4. Update & Push to Remote URL If you cloned from a repository, go ahead and update the origin link to the repository you created on GitHub by running: `$ git remote set-url origin <YOUR-GITHUB-REPO-LINK>` Otherwise run this command instead: `$ git remote add origin <YOUR-GITHUB-REPO-LINK>` Finally, push the code to the repoository: `$ git push origin master` ### 5. Create or sign in to your Fleek account Easiest option is to sign in with your GitHub account. Click on Add new site & Connect with GitHub Configure and select your repo to deploy For deploy location, select IPFS hosting On the build options and deploy tab, under the section Basic Build Settings, for framework select Create React App, then click on Deploy site. Contract presets are now deprecated in favor of [Contracts Wizard](https://wizard.openzeppelin.com/) as a more powerful alternative. [Content not decodable] [Content not decodable] # About Deploy ERC20 token to Optimistic Networks using Truffle Optimistic Box Read up on our notes on [Optimism, Layer scaling etc here](https://docs.google.com/document/d/1qJjz3rzGDKnVjs-qDdwDdGmDdtkLWmMjH4gUqrLP7Is/edit) Project uses truffle optimism box in addition to create-react-app and places build folder in src to demonstrate a full stack app / dapp deployed to Optimistic networks e.g local optimistic node, kovan optimistic network and ethereum optimistic network in addition to normal Ethereum network deployments e.g local ganache, testnets kovan etc. The project makes use of the [Truffle Optimistic Box](https://www.trufflesuite.com/boxes/optimism) To get started! First See below from original READ.me for info on Optimism Box (Ignore ##Installation section on truffle unbox) optimism box. Below is a summary of key points to compile, run, test, deploy ERC20 to networks Ethereum and Optimism Project makes some slight changes to original truffle box folder structure so as to help see Optimism side by side Ethereum networks on backend and frontend. --------------------------------KEY SUMMARY----------------------------------------------------------------------- 1. Run Install pacakges ```sh npm install ``` 2. Populate your environment variables .env see .env.example - Leave the MNEMONIC as is, it works with Optimism 3. Ensure Docker is installed and running on your computer ```sh docker-compose up ``` or if Docker Desktop is installed Start Dock 4. Compile, deploy and test Contracts Etherem networks e.g Local Ganache, Kovan Ensure ganache is running in seperate terminal ```sh ganache-cli npm run compile:evm npm run test:evm ``` - Migrate to local ganache ```sh npm run migrate:evm development ``` - Migrate to Kovan ```sh npm run migrate:evm kovan ``` 5. Configure Metamask networks for Optimistic Networks [You can also lookup with Optimism Developer documentation here](https://community.optimism.io/docs/) or reference with [Github repository](https://github.com/ethereum-optimism/optimism-tutorial) @eth-optimism/solc is the package that will allow us to compile contracts for Optimism - Optimism networks to be discuseed here are: local Optimism node, Optimistic Kovan(optimism-kovan) and Optimistic Ethereum(optimism-ethereum). Caution as testnet and mainnet networks are still in early stages at time of writing this document - Setup networks in Metamask, see images below <span><img src="./ImagesReadMe/local.png" alt="configure Optimistic Local" width="200"/><img src="./ImagesReadMe/kovan.png" alt="configure Optimistic Kovan" width="200"/> <img src="./ImagesReadMe/mainnet.png" alt="configure Optimistic Mainnet" width="200"/> 6. Compile, deploy and test Contracts Optimistic networks Key considerations e.g ETH to pay for fees - you import copy local running docker based optimistic blockchain accounts similar to when using ganache - for local blockchain ensure all transactions to blockchain use {gasPrice: 0} - for 0ptimistic Kovan network acquire Optimistic Kovan ETH by Get Kovan testnet ETH into a Metamask account e.g use faucets like https://gitter.im/kovan-testnet/faucet or https://enjin.io/software/kovan-faucet or https://linkfaucet.protofire.io/kovan Ensure Metamask is setup correctly for Optimistic Kovan Network see earlier [section or here](https://community.optimism.io/docs/developers/metamask.html#connecting-manually) [Bridge Kovan ETH to Optimistic Kovan ETH here](https://gateway.optimism.io/) - for Optimistc Mainnet at time of writing is restricted may need a whitelisting process. However briding tokens is similar to Optimistic Kovan at [gateway](https://gateway.optimism.io/) - for networks besides local, e.g Optimistic Kovan, Optimistic Mainnet care should be taken with gasLimits and gasFees - OVM and EVM may differ e.g revert messages etc e.g Optimistic Local, Optimistic Kovan, Optimistc Mainnet You will require SSH setup for Github - [visit here for info](https://docs.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh) Ensure Local Optimistic Blockchain is running in background using docker Setup once using npm run installLocalOptimism (It may take a long time) To start later on use => cd optimism/ops && docker-compose up ```sh npm run startLocalOptimism npm run compile:ovm npm run test:ovm optimistic_local ``` To stop docker for local node use => npm run stopLocalOptimism - Migrate to Optimistic Local ```sh npm run migrate:ovm optimistic_local ``` - Migrate to Optimistic Kovan ```sh npm run migrate:ovm optimistic_kovan ``` - Migrate to Optimistic Mainnet ```sh npm run migrate:ovm optimistic_mainnet ``` 6. Simple connection/interaction with front end Change the network in Metamask to interact with contract deployed on chosen network e.g Optimistic Kovan ```sh npm run start ``` Add as an Asset in Metamask the deployed token copying its address from the navbar follow [instructions here](https://metamask.zendesk.com/hc/en-us/articles/360015489031-How-to-view-see-your-tokens-custom-tokens-in-MetaMask) You can send tokens between accounts using Metamask the same way as in on Ethereum networks, care is required with gas as default 21,000 in Metamask may need changing on Optimistic Kovan and Optimistic Ethereum to higher values. Refreshs page when you change accounts or transact on front end --------MORE DETAILED INFO _ SEE ORIGINAL TRUFFLE BOX READ.ME BELOW-------------------------------------- [You will need to add Optimism network add-on in Infura](https://blog.infura.io/infura-launches-support-for-optimistic-ethereum/) # Optimism Box - [Requirements](#requirements) - [Installation](#installation) - [Setup](#setup) * [Using the .env File](#using-the-env-file) * [New Configuration File](#new-configuration-file) * [New Directory Structure for Artifacts](#new-directory-structure-for-artifacts) - [Optimistic Ethereum](#optimistic-ethereum) * [Compiling](#compiling) * [Migrating](#migrating) * [Basic Commands](#basic-commands) * [Testing](#testing) * [Communication Between Ethereum and Optimism Chains](#communication-between-ethereum-and-optimism-chains) - [Support](#support) <small><i><a href='http://ecotrust-canada.github.io/markdown-toc/'>Table of contents generated with markdown-toc</a></i></small> This Truffle Optimism Box provides you with the boilerplate structure necessary to start coding for Optimism's Ethereum Layer 2 solution. For detailed information on how Optimism works, please see the documentation [here](http://community.optimism.io/docs/developers/integration.html#). As a starting point, this box contains only the SimpleStorage Solidity contract. Including minimal code was a conscious decision as this box is meant to provide the initial building blocks needed to get to work on Optimism without pushing developers to write any particular sort of application. With this box, you will be able to compile, migrate, and test Optimistic Solidity code against a variety of Optimism test networks. Optimism's Layer 2 solution is almost fully compatible with the EVM, though it uses an "optimistic" EVM called the OVM. The main difference between the EVM and the OVM that developers will notice is that some opcodes are not available for contracts that are deployed to the OVM. You can see the complete list of differences between Optimism's fork of the `solc` compiler and the original [here](https://github.com/ethereum-optimism/solidity/compare/27d51765c0623c9f6aef7c00214e9fe705c331b1...develop-0.6). ## Requirements The Optimism Box has the following requirements: - [Node.js](https://nodejs.org/) 10.x or later - [NPM](https://docs.npmjs.com/cli/) version 5.2 or later - [docker](https://docs.docker.com/get-docker/), version 19.03.12 or later - [docker-compose](https://docs.docker.com/compose/install/), version 1.27.3 or later - Recommended Docker memory allocation of >=8 GB. - Windows, Linux or MacOS Helpful, but optional: - An [Infura](https://infura.io/) account and Project ID - A [MetaMask](https://metamask.io/) account ## Installation > Note that this installation command will only work once the box is published (in the interim you can use `truffle unbox https://github.com/truffle-box/optimism-box`). ```bash $ truffle unbox optimism ``` ## Setup ### Using the env File You will need at least one mnemonic to use with the network. The `.dotenv` npm package has been installed for you, and you will need to create a `.env` file for storing your mnemonic and any other needed private information. The `.env` file is ignored by git in this project, to help protect your private data. In general, it is good security practice to avoid committing information about your private keys to github. The `truffle-config.ovm.js` file expects a `GANACHE_MNEMONIC` and a `KOVAN_MNEMONIC` value to exist in `.env` for running commands on each of these networks, as well as a default `MNEMONIC` for the optimistic network we will run locally. If you are unfamiliar with using `.env` for managing your mnemonics and other keys, the basic steps for doing so are below: 1) Use `touch .env` in the command line to create a `.env` file at the root of your project. 2) Open the `.env` file in your preferred IDE 3) Add the following, filling in your own Infura project key and mnemonics: ``` MNEMONIC="candy maple cake sugar pudding cream honey rich smooth crumble sweet treat" INFURA_PROJECT_ID="<Your Infura Project ID>" GANACHE_MNEMONIC="<Your Ganache Mnemonic>" KOVAN_MNEMONIC="<Your Kovan Mnemonic>" ``` _Note: the value for the `MNEMONIC` above is the one you should use, as it is expected within the local optimistic ethereum network we will run in this Truffle Box._ 4) As you develop your project, you can put any other sensitive information in this file. You can access it from other files with `require('dotenv').config()` and refer to the variable you need with `process.env['<YOUR_VARIABLE>']`. ### New Configuration File A new configuration file exists in this project: `truffle-config.ovm.js`. This file contains a reference to the new file location of the `contracts_build_directory` and `contracts_directory` for Optimism contracts and lists several networks for running the Optimism Layer 2 network instance (see [below](#migrating)). Please note, the classic `truffle-config.js` configuration file is included here as well, because you will eventually want to deploy contracts to Ethereum as well. All normal truffle commands (`truffle compile`, `truffle migrate`, etc.) will use this config file and save built files to `build/ethereum-contracts`. You can save Solidity contracts that you wish to deploy to Ethereum in the `contracts/ethereum` folder. ### New Directory Structure for Artifacts When you compile or migrate, the resulting `json` files will be at `build/optimism-contracts/`. This is to distinguish them from any Ethereum contracts you build, which will live in `build/ethereum-contracts`. As we have included the appropriate `contracts_build_directory` in each configuration file, Truffle will know which set of built files to reference! ## Optimistic Ethereum ### Compiling To compile your project using the Optimistic `solc` compiler, run the following in your terminal: ``` npm run compile:ovm ``` This script lets Truffle know to use the `truffle-config.ovm.js` configuration file, which references the Optimistic `solc` compiler. When adding new contracts to compile, you may find some discrepancies and errors, so please remember to keep an eye on [differences between solc and optimistic solc](https://github.com/ethereum-optimism/solidity/compare/27d51765c0623c9f6aef7c00214e9fe705c331b1...develop-0.6)! Please note: the optimistic `solc` compiler we have included relies on the latest version of the package, and currently uses *version 0.7.6*. If you would like to use a different version of `solc`, see the available optimistic versions [here](https://www.npmjs.com/package/@eth-optimism/solc), and run: ``` npm install @eth-optimism/solc@<YourVersion> ``` You can double check that you have the version you want by looking at the `package.json` dependencies in this project. If you would like to recompile previously compiled contracts, you can manually run this command with `truffle compile --config truffle-config.ovm.js` and add the `--all` flag. ### Migrating To migrate on an Optimistic Layer 2, run: ``` npm run migrate:ovm --network=(ganache | optimistic_local | optimistic_kovan) ``` (remember to choose a network from these options!). You have several Optimistic Layer 2 networks to choose from, prepackaged in this box (note: Layer 1 networks associated with Optimism are included in the regular `truffle-config.js` file, to aid you with further development. But here we'll just go through the Layer 2 deployment options available): - `optimistic_local`: This network is the default Layer 1/Layer 2 integration provided by Optimism for testing your Optimistic Ethereum code. Documentation about this setup can be found [here](https://github.com/ethereum-optimism/optimism). * You will need to install the code for this network in this box in order to use the scripts associated with it. To install it, run `npm run installLocalOptimism`. You should only need to run this initiation command once. It will create an `optimism` directory in this project that will house the repository you need. If at any point you want to update to the latest optimism docker image, you can delete your `optimism` directory and run this command again. * If you wish to use this network, be sure to run `npm run startLocalOptimism` so that the optimism test ecosystem docker image can be served. For our purposes, you should be able to compile, migrate, and test against this network once the docker image is fully running. See [documentation and updates](https://github.com/ethereum-optimism/optimism/tree/develop/ops) about this docker container for additional information. * Please note, after running `npm run startLocalOptimism` it can take several minutes for the test ecosystem to be up and running on your local machine. The first time you run this command, it will take a bit longer for everything to be set up. Future runs will be quicker! * To stop the local docker container, use `npm run stopLocalOptimism` in a new terminal tab to ensure graceful shutdown. - `ganache`: This network uses an optimistic ganache instance for migrations. The usage is essentially identical to use of regular ganache. - `optimistic_kovan`: Optimism has deployed a testnet to the Kovan network. The RPC endpoint is https://optimism-kovan.infura.io/v3/. In order to access this node for testing, you will need to connect a wallet (we suggest [MetaMask](https://metamask.io/)). Save your seed phrase in a `.env` file as `KOVAN_MNEMONIC`. Using an `.env` file for the mnemonic is safer practice because it is listed in `.gitignore` and thus will not be committed. * Currently, we have the gasPrice for transactions on Optimistic Kovan set to zero. You should be able to use this network as configured at this time. * Eventually, you will need Kovan ETH in an Optimistic Kovan wallet to deploy contracts using this network. In order to deploy to Optimistic Kovan, you will need to acquire Optimistic Kovan ETH. As of this writing, there is not an Optimistic Kovan ETH faucet. In order to get Optimistic Kovan ETH, follow these steps: 1) Acquire ETH for your Kovan wallet on MetaMask using a Kovan faucet. 2) Add Optimistic Ethereum as a Custom RPC to your Metamask wallet, using the [steps here](https://community.optimism.io/docs/developers/metamask.html#connecting-manually), except set the RPC URL to `https://optimism-kovan.infura.io/v3/" + infuraKey` 3) Visit [this website](https://gateway.optimism.io/) to bridge your Kovan ETH to Optimistic Kovan ETH 4) Ensure that your `optimistic_kovan` network in `truffle-config.ovm.js` is connected to your Optimistic Kovan wallet. Layer 1 networks are included in the `truffle-config.js` file, but it is not necessary to deploy your base contracts to Layer 1 right now. Eventually, you will likely have a Layer 2 contract that you want to connect with a Layer 1 contract (they do not have to be identical!). One example is an ERC20 contract that is deployed on an Optimistic Ethereum network. At some point the user will wish to withdraw their funds into Ethereum. There will need to be a contract deployed on Layer 1 that can receive the message from Layer 2 to mint the appropriate tokens on Layer 1 for the user. More information on this system can be found [here](http://community.optimism.io/docs/developers/integration.html#bridging-l1-and-l2). If you would like to migrate previously migrated contracts on the same network, you can run `truffle migrate --config truffle-config.ovm.js --network=(ganache | optimistic_local | optimistic_kovan)` and add the `--reset` flag. ## Basic Commands The code here will allow you to compile, migrate, and test your code against an Optimistic Ethereum instance. The following commands can be run (more details on each can be found in the next section): To compile: ``` npm run compile:ovm ``` To migrate: ``` npm run migrate:ovm --network=(ganache | optimistic_local | optimistic_kovan) ``` To test: ``` npm run test:ovm --network=(ganache | optimistic_local | optimistic_kovan) ``` ### Testing Currently, this box supports testing via Javascript/TypeScript tests. In order to run the test currently in the boilerplate, use the following command: ``` npm run test:ovm --network=(ganache | optimistic_local | optimistic_kovan) ``` Remember that there are some differences between the EVM and the OVM, and refer to the Optimism documentation if you run into test failures. ### Communication Between Ethereum and Optimism Chains The information above should allow you to deploy to the Optimism Layer 2 chain. This is only the first step! Once you are ready to deploy your own contracts to function on Layer 1 using Layer 2, you will need to be aware of the [ways in which Layer 1 and Layer 2 interact in the Optimism ecosystem](http://community.optimism.io/docs/developers/integration.html#bridging-l1-and-l2). Keep an eye out for additional Truffle tooling and examples that elucidate this second step to full optimism integration! ## Support Support for this box is available via the Truffle community available [here](https://www.trufflesuite.com/community). # Call, Delegate Call and multi call Learn how to use call and delegatecall function and how to make multicall ## Technology Stack & Dependencies - Solidity (Writing Smart Contract) - [Remix](https://remix.ethereum.org/) Develop and deploy contracts inside the browser ### 1. Clone/Download the Repository ### 2. Copy contracts and deploy them using Remix # <img src="logo.svg" alt="OpenZeppelin" height="40px"> [![Docs](https://img.shields.io/badge/docs-%F0%9F%93%84-blue)](https://docs.openzeppelin.com/contracts) [![NPM Package](https://img.shields.io/npm/v/@openzeppelin/contracts.svg)](https://www.npmjs.org/package/@openzeppelin/contracts) [![Coverage Status](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts/graph/badge.svg)](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts) **A library for secure smart contract development.** Build on a solid foundation of community-vetted code. * Implementations of standards like [ERC20](https://docs.openzeppelin.com/contracts/erc20) and [ERC721](https://docs.openzeppelin.com/contracts/erc721). * Flexible [role-based permissioning](https://docs.openzeppelin.com/contracts/access-control) scheme. * Reusable [Solidity components](https://docs.openzeppelin.com/contracts/utilities) to build custom contracts and complex decentralized systems. :mage: **Not sure how to get started?** Check out [Contracts Wizard](https://wizard.openzeppelin.com/) — an interactive smart contract generator. :building_construction: **Want to scale your decentralized application?** Check out [OpenZeppelin Defender](https://openzeppelin.com/defender) — a secure platform for automating and monitoring your operations. ## Overview ### Installation ```console $ npm install @openzeppelin/contracts ``` OpenZeppelin Contracts features a [stable API](https://docs.openzeppelin.com/contracts/releases-stability#api-stability), which means your contracts won't break unexpectedly when upgrading to a newer minor version. An alternative to npm is to use the GitHub repository `openzeppelin/openzeppelin-contracts` to retrieve the contracts. When doing this, make sure to specify the tag for a release such as `v4.5.0`, instead of using the `master` branch. ### Usage Once installed, you can use the contracts in the library by importing them: ```solidity pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract MyCollectible is ERC721 { constructor() ERC721("MyCollectible", "MCO") { } } ``` _If you're new to smart contract development, head to [Developing Smart Contracts](https://docs.openzeppelin.com/learn/developing-smart-contracts) to learn about creating a new project and compiling your contracts._ To keep your system secure, you should **always** use the installed code as-is, and neither copy-paste it from online sources, nor modify it yourself. The library is designed so that only the contracts and functions you use are deployed, so you don't need to worry about it needlessly increasing gas costs. ## Learn More The guides in the [docs site](https://docs.openzeppelin.com/contracts) will teach about different concepts, and how to use the related contracts that OpenZeppelin Contracts provides: * [Access Control](https://docs.openzeppelin.com/contracts/access-control): decide who can perform each of the actions on your system. * [Tokens](https://docs.openzeppelin.com/contracts/tokens): create tradeable assets or collectives, and distribute them via [Crowdsales](https://docs.openzeppelin.com/contracts/crowdsales). * [Gas Station Network](https://docs.openzeppelin.com/contracts/gsn): let your users interact with your contracts without having to pay for gas themselves. * [Utilities](https://docs.openzeppelin.com/contracts/utilities): generic useful tools, including non-overflowing math, signature verification, and trustless paying systems. The [full API](https://docs.openzeppelin.com/contracts/api/token/ERC20) is also thoroughly documented, and serves as a great reference when developing your smart contract application. You can also ask for help or follow Contracts's development in the [community forum](https://forum.openzeppelin.com). Finally, you may want to take a look at the [guides on our blog](https://blog.openzeppelin.com/guides), which cover several common use cases and good practices.. The following articles provide great background reading, though please note, some of the referenced tools have changed as the tooling in the ecosystem continues to rapidly evolve. * [The Hitchhiker’s Guide to Smart Contracts in Ethereum](https://blog.openzeppelin.com/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05) will help you get an overview of the various tools available for smart contract development, and help you set up your environment. * [A Gentle Introduction to Ethereum Programming, Part 1](https://blog.openzeppelin.com/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094) provides very useful information on an introductory level, including many basic concepts from the Ethereum platform. * For a more in-depth dive, you may read the guide [Designing the Architecture for Your Ethereum Application](https://blog.openzeppelin.com/designing-the-architecture-for-your-ethereum-application-9cec086f8317), which discusses how to better structure your application and its relationship to the real world. ## Security This project is maintained by [OpenZeppelin](https://openzeppelin.com), and developed following our high standards for code quality and security. OpenZeppelin Contracts is meant to provide tested and community-audited code, but please use common sense when doing anything that deals with real money! We take no responsibility for your implementation decisions and any security problems you might experience. The core development principles and strategies that OpenZeppelin Contracts is based on include: security in depth, simple and modular code, clarity-driven naming conventions, comprehensive unit testing, pre-and-post-condition sanity checks, code consistency, and regular audits. The latest audit was done on October 2018 on version 2.0.0. We have a [**bug bounty program** on Immunefi](https://www.immunefi.com/bounty/openzeppelin). Please report any security issues you find through the Immunefi dashboard, or reach out to [email protected]. Critical bug fixes will be backported to past major releases. ## Contribute OpenZeppelin Contracts exists thanks to its contributors. There are many ways you can participate and help build high quality software. Check out the [contribution guide](CONTRIBUTING.md)! ## License OpenZeppelin Contracts is released under the [MIT License](LICENSE). [Content not decodable] # NextJS NFT Marketplace with TheGraph ## 1. Git clone the contracts repo In it's own terminal / command line, run: ``` git clone https://github.com/PatrickAlphaC/hardhat-nft-marketplace-fcc cd hardhat-nextjs-nft-marketplace-fcc yarn ``` ## 2. Deploy to rinkeby After installing dependencies, deploy your contracts to rinkeby: ``` yarn hardhat deploy --network rinkeby ``` ## 3. Deploy your subgraph ``` cd .. git clone https://github.com/PatrickAlphaC/graph-nft-marketplace-fcc cd graph-nft-marketplace-fcc yarn ``` Follow the instructions of the [README](https://github.com/PatrickAlphaC/graph-nft-marketplace-fcc/blob/main/README.md) of that repo. Then, make a `.env` file and place your temporary query URL into it as `NEXT_PUBLIC_SUBGRAPH_URL`. ## 4. Start your UI Make sure that: - In your `networkMapping.json` you have an entry for `NftMarketplace` on the rinkeby network. - You have a `NEXT_PUBLIC_SUBGRAPH_URL` in your `.env` file. ``` yarn dev ``` # Hardhat Fund Me This is a section of the Javascript Blockchain/Smart Contract FreeCodeCamp Course. *[⌨️ (10:00:48) Lesson 7: Hardhat Fund Me](https://www.youtube.com/watch?v=gyMwXuJrbJQ&t=36048s)* [Full Repo](https://github.com/smartcontractkit/full-blockchain-solidity-course-js) - [Hardhat Fund Me](#hardhat-fund-me) - [Getting Started](#getting-started) - [Requirements](#requirements) - [Quickstart](#quickstart) - [Typescript](#typescript) - [Optional Gitpod](#optional-gitpod) - [Usage](#usage) - [Testing](#testing) - [Test Coverage](#test-coverage) - [Deployment to a testnet or mainnet](#deployment-to-a-testnet-or-mainnet) - [Scripts](#scripts) - [Estimate gas](#estimate-gas) - [Estimate gas cost in USD](#estimate-gas-cost-in-usd) - [Verify on etherscan](#verify-on-etherscan) - [Linting](#linting) - [Formatting](#formatting) - [Thank you!](#thank-you) This project is apart of the Hardhat FreeCodeCamp video. # Getting Started ## Requirements - [git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) - You'll know you did it right if you can run `git --version` and you see a response like `git version x.x.x` - [Nodejs](https://nodejs.org/en/) - You'll know you've installed nodejs right if you can run: - `node --version` and get an ouput like: `vx.x.x` - [Yarn](https://yarnpkg.com/getting-started/install) instead of `npm` - You'll know you've installed yarn right if you can run: - `yarn --version` and get an output like: `x.x.x` - You might need to [install it with `npm`](https://classic.yarnpkg.com/lang/en/docs/install/) or `corepack` ## Quickstart ``` git clone https://github.com/PatrickAlphaC/hardhat-fund-me-fcc cd hardhat-fund-me-fcc yarn ``` ## Typescript For the typescript edition, run: ``` git checkout typescript ``` ### Optional Gitpod If you can't or don't want to run and install locally, you can work with this repo in Gitpod. If you do this, you can skip the `clone this repo` part. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#github.com/PatrickAlphaC/hardhat-fund-me-fcc) # Usage Deploy: ``` yarn hardhat deploy ``` ## Testing ``` yarn hardhat test ``` ### Test Coverage ``` yarn hardhat coverage ``` # Deployment to a testnet or mainnet 1. Setup environment variables You'll want to set your `KOVAN_RPC_URL` and `PRIVATE_KEY` as environment variables. You can add them to a `.env` file, similar to what you see in `.env.example`. - `PRIVATE_KEY`: The private key of your account (like from [metamask](https://metamask.io/)). **NOTE:** FOR DEVELOPMENT, PLEASE USE A KEY THAT DOESN'T HAVE ANY REAL FUNDS ASSOCIATED WITH IT. - You can [learn how to export it here](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key). - `KOVAN_RPC_URL`: This is url of the kovan testnet node you're working with. You can get setup with one for free from [Alchemy](https://alchemy.com/?a=673c802981) 2. Get testnet ETH Head over to [faucets.chain.link](https://faucets.chain.link/) and get some tesnet ETH. You should see the ETH show up in your metamask. 3. Deploy ``` yarn hardhat deploy --network kovan ``` ## Scripts After deploy to a testnet or local net, you can run the scripts. ``` yarn hardhat run scripts/fund.js ``` or ``` yarn hardhat run scripts/withdraw.js ``` ## Estimate gas You can estimate how much gas things cost by running: ``` yarn hardhat test ``` And you'll see and output file called `gas-report.txt` ### Estimate gas cost in USD To get a USD estimation of gas cost, you'll need a `COINMARKETCAP_API_KEY` environment variable. You can get one for free from [CoinMarketCap](https://pro.coinmarketcap.com/signup). Then, uncomment the line `coinmarketcap: COINMARKETCAP_API_KEY,` in `hardhat.config.js` to get the USD estimation. Just note, everytime you run your tests it will use an API call, so it might make sense to have using coinmarketcap disabled until you need it. You can disable it by just commenting the line back out. ## Verify on etherscan If you deploy to a testnet or mainnet, you can verify it if you get an [API Key](https://etherscan.io/myapikey) from Etherscan and set it as an environemnt variable named `ETHERSCAN_API_KEY`. You can pop it into your `.env` file as seen in the `.env.example`. In it's current state, if you have your api key set, it will auto verify kovan contracts! However, you can manual verify with: ``` yarn hardhat verify --constructor-args arguments.js DEPLOYED_CONTRACT_ADDRESS ``` # Linting To check linting / code formatting: ``` yarn lint ``` or, to fix: ``` yarn lint:fix ``` # Formatting ``` yarn format ``` # Thank you! If you appreciated this, feel free to follow me or donate! ETH/Polygon/Avalanche/etc Address: 0x9680201d9c93d65a3603d2088d125e955c73BD65 [![Patrick Collins Twitter](https://img.shields.io/badge/Twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/PatrickAlphaC) [![Patrick Collins YouTube](https://img.shields.io/badge/YouTube-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/channel/UCn-3f8tw_E1jZvhuHatROwA) [![Patrick Collins Linkedin](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/patrickalphac/) [![Patrick Collins Medium](https://img.shields.io/badge/Medium-000000?style=for-the-badge&logo=medium&logoColor=white)](https://medium.com/@patrick.collins_58673/) 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.
idos-network_idos-access-grants
README.md evm .env README.md artifacts contracts AccessGrants.sol AccessGrants.json hardhat.config.js package.json scripts deploy.js test AccessGrants.js near-rs README.md contract Cargo.toml build.sh deploy.sh src lib.rs integration-tests Cargo.toml empty.rs tests assert mod.rs delete_grant_by_signature.rs events mod.rs everything.rs helpers mod.rs insert_grant_by_signature.rs nep413 mod.rs package.json rust-toolchain.toml
# EVM > [!NOTE] > You can find the contract's ABI in [this compilation artifact](artifacts/contracts/AccessGrants.sol/AccessGrants.json#L5). ## Testing ``` $ yarn test ``` ## Local deployment First, start a [local Hardhat node](https://hardhat.org/hardhat-runner/docs/getting-started#connecting-a-wallet-or-dapp-to-hardhat-network) on a terminal. ``` $ npx hardhat node Started HTTP and WebSocket JSON-RPC server at http://127.0.0.1:8545/ ... ``` On another terminal, run the deployment script. ``` $ npx hardhat run --network localhost scripts/deploy.js AccessGrants deployed to 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0 ``` You can then use the [Hardhat console](https://hardhat.org/hardhat-runner/docs/guides/hardhat-console) to interact with the locally deployed contract. Make sure to use the address you deployed to. ``` $ npx hardhat console --network localhost > const accessGrants = await ethers.getContractAt("AccessGrants", "0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0"); > await accessGrants.findGrants("0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0", "0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0", "no"); Result(0) [] ... ``` # NEAR Initialized with [create-near-app](https://github.com/near/create-near-app) Requires rust ([installation instructions](https://www.rust-lang.org/tools/install)) --- ``` $ yarn test ``` # idOS access grant contracts ![EVM](https://img.shields.io/badge/EVM-gray?logo=ethereum) ![NEAR](https://img.shields.io/badge/NEAR%20VM-gray?logo=near) ![License](https://img.shields.io/badge/license-MIT-blue?&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NHB4IiBoZWlnaHQ9IjY0cHgiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjRkZGRkZGIiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCI+PGcgaWQ9IlNWR1JlcG9fYmdDYXJyaWVyIiBzdHJva2Utd2lkdGg9IjAiPjwvZz48ZyBpZD0iU1ZHUmVwb190cmFjZXJDYXJyaWVyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjwvZz48ZyBpZD0iU1ZHUmVwb19pY29uQ2FycmllciI+IDxwYXRoIGQ9Ik0xNiAxNmwzLTggMy4wMDEgOEE1LjAwMiA1LjAwMiAwIDAxMTYgMTZ6Ij48L3BhdGg+IDxwYXRoIGQ9Ik0yIDE2bDMtOCAzLjAwMSA4QTUuMDAyIDUuMDAyIDAgMDEyIDE2eiI+PC9wYXRoPiA8cGF0aCBkPSJNNyAyMWgxMCI+PC9wYXRoPiA8cGF0aCBkPSJNMTIgM3YxOCI+PC9wYXRoPiA8cGF0aCBkPSJNMyA3aDJjMiAwIDUtMSA3LTIgMiAxIDUgMiA3IDJoMiI+PC9wYXRoPiA8L2c+PC9zdmc+Cg==) When receiving a signed request for data not owned by the signer, idOS nodes use these smart contracts as the source of truth for authorizing (or denying) the request. The contract functionality is straightforward: - **a grant** is an idOS object representing a data access grant from an owner to a grantee for a given data ID (optionally with a timelock) - the contract **stores a collection of grants** - **anyone** can **list grants** - a **signer** can - **create a grant** that they own - **delete a grant** that they own (unless timelocked) ## Contracts **Implementations:** | Target VM | Language | Source | | :- | :- | :- | | EVM | Solidity | [`evm/`](./evm) | | NEAR VM | Rust | [`near-rs/`](./near-rs) | **Deployments:** | Source | Chain | Address | | :- | :- | :- | | `evm/` | Sepolia | [`0x73de8f45c0dFDf59C56a93B483246AC113a1f922`](https://sepolia.etherscan.io/address/0x73de8f45c0dFDf59C56a93B483246AC113a1f922#code) | | `evm/` | Arbitrum Sepolia | [`0x7D11563Bd4aA096CC83Fbe2cdd0557010dd58477`](https://sepolia.arbiscan.io/address/0x7D11563Bd4aA096CC83Fbe2cdd0557010dd58477#code) | | `evm/` | Arbitrum One | [`0x7D11563Bd4aA096CC83Fbe2cdd0557010dd58477`](https://arbiscan.io/address/0x7D11563Bd4aA096CC83Fbe2cdd0557010dd58477#code) | | `near-rs/` | NEAR Testnet | [`idos-dev-4.testnet`](https://explorer.testnet.near.org/accounts/idos-dev-4.testnet) | | `near-rs/` | NEAR Mainnet | [`idos-dev-4.near`](https://explorer.mainnet.near.org/accounts/idos-dev-4.near) | ### Deploy to Sepolia 1. Copy `.env` file to `.env.local` and fill it in accordingly 1. Run `npx hardhat --network sepolia run scripts/deploy.js` 1. Run `npx hardhat --network sepolia verify $RESULTING_ADDRESS` ### Deploy to local chain Use [hardhat](https://hardhat.org/) to run local node. 1. Run node in separate process `npx hardhat node` 1. Compile a contract `npx hardhat compile` 1. Deploy the contract `npx hardhat --network locahost run scripts/deploy.js` ## Interface > [!NOTE] > This interface description uses mixedCase, but each implementation follows the respective language's style guide, e.g.: > * in EVM + Solidity, we use mixedCase (`insertGrant`) > * in NEAR VM + Rust/TypeScript, we use snake_case (`insert_grant`). ### Objects <details><summary><h4><code>Grant</code></h4></summary> Represents an access grant from a data owner, to a grantee, for a given data ID, until a given time. **Variables** - `owner`: address - `grantee`: address - `dataId`: string - `lockedUntil`: 256-bit unsigned integer </details> ### Functions <details><summary><h4><code>insertGrant</code></h4></summary> Creates a new access grant. **Arguments** - required - `grantee`: address - `dataId`: string - optional - `lockedUntil`: 256-bit unsigned integer **Implements** - creates `Grant(signer, grantee, dataId, lockedUntil)` - reverts if this grant already exists </details> <details><summary><h4><code>deleteGrant</code></h4></summary> Deletes an existing access grant. **Arguments** - required - `grantee`: address - `dataId`: string - optional - `lockedUntil`: 256-bit unsigned integer **Implements** - if given `lockedUntil` - deletes `Grant(signer, grantee, dataId, lockedUntil)` - reverts if `lockedUntil` is in the future - else - deletes all `Grant(signer, grantee, dataId, *)` - reverts if any `lockedUntil` is in the future </details> <details><summary><h4><code>findGrants</code></h4></summary> Lists grants matching the provided arguments. **Arguments** - required (both or either) - `owner`: address - `grantee`: address - optional - `dataId`: string **Implements** Performs a wildcard search, matching existing grants to given arguments, which must follow one of these patterns: ``` { owner, grantee, dataId } { owner, grantee, ****** } { owner, *******, dataId } { owner, *******, ****** } { *****, grantee, dataId } { *****, grantee, ****** } ``` **Returns** A list of 0+ `Grant`s </details> <details><summary><h4><code>grantsFor</code></h4></summary> Lists grants matching the provided arguments. **Arguments** - required - `grantee`: address - `dataId`: string **Implements** Calls `grantsBy` with no `owner` argument. **Returns** A list of 0+ `Grant`s </details>
NEARFoundation_sc.smart-whitelist
Cargo.toml README.md scripts build.sh src lib.rs tests test_utils.rs
# Smart whitelist contract The purpose of this contract is to maintain a white list of accounts which have successfully passed KYC verification. The contract also includes a list of service accounts that have right to add accounts to the whitelist on the side of the backend of the Smart-whitelist KYC module. An administrator can create or delete service accounts in the contract with the help of public key which is stored in the contract during initialization. The description of the algorithm for adding an account to the white list using the components of the user interface, backend and smart contract of the KYC module below: ![Contract flow](docs/contract-flow.png) Applicant should pre-register it’s public key in the contract in order to be included in the white list by calling the method register_applicant(): ``` pub fn register_applicant(&mut self) -> Option<PublicKey>; ``` Also you can check the presence of a key in the contract using the following method: ``` pub fn get_applicant_pk(&self, applicant_account_id: AccountId) -> Option<PublicKey>; ``` Or you can remove key from the contract if it didn't pass verification: ``` pub fn remove_applicant(&mut self) -> Option<PublicKey>; ``` The backend adds the verified account to the white list after successful completion of KYC verification of client documents: ``` pub fn add_account(&mut self, account_id: AccountId) -> bool; ``` Information about the public key of the applicant is removed from the contract after adding an account to the white list. The account can be removed from the whitelist by the service account in case if it’s needed: ``` pub fn remove_account(&mut self, account_id: AccountId) -> bool; ``` You can check if account is in the white list using the following method: ``` pub fn is_whitelisted(&self, account_id: AccountId) -> bool; ```
Learn-NEAR_NCD--nftstore
README.md contracts build.sh factory Cargo.toml README.md build.sh src lib.rs token Cargo.toml README.md build.sh src lib.rs frontend .env README.md dist worker.js nftstore index.js package-lock.json package.json package.json public index.html manifest.json robots.txt src App.css App.js Tokens.js index.css index.js wrangler.toml
# Token Factory Issue your own token and without touching a line of code. Use the advanced UI features including image processing and integer rounding techniques to create and issue the most sophisticated fungible tokens. Just for 25 Ⓝ issue a brand new fungible token and own everything. Let other people know about your token. Do you really want to be on the bottom of the list of issued tokens? Go to [Token Factory](https://near-examples.github.io/token-factory/) now and make your own token today. # Meta NEAR chat Smart contract to establish WebRTC connection between 2 users. ## Building ```bash ./build.sh ``` ## Testing To test run: ```bash cargo test --package webrtc-chat -- --nocapture ``` # Fungible token Example implementation of a Fungible Token Standard (NEP#21). NOTES: - The maximum balance value is limited by U128 (2**128 - 1). - JSON calls should pass U128 as a base-10 string. E.g. "100". - The contract optimizes the inner trie structure by hashing account IDs. It will prevent some abuse of deep tries. Shouldn't be an issue, once NEAR clients implement full hashing of keys. - This contract doesn't optimize the amount of storage, since any account can create unlimited amount of allowances to other accounts. It's unclear how to address this issue unless, this contract limits the total number of different allowances possible at the same time. And even if it limits the total number, it's still possible to transfer small amounts to multiple accounts. ## Building To build run: ```bash ./build.sh ``` ## Testing To test run: ```bash cargo test --package fungible-token -- --nocapture ``` # Nft store frontend `yarn` `yarn deploy`
evgenykuzyakov_dacha
README.md config paths.js presets loadPreset.js webpack.analyze.js webpack.development.js webpack.production.js contract-rs dacha Cargo.toml README.md build.sh build_docker.sh deploy.sh rust-toolchain.toml src account.rs board.rs fungible_token_core.rs fungible_token_metadata.rs fungible_token_storage.rs internal.rs lib.rs mint.rs package.json public index.html manifest.json robots.txt src App.js Weapons.js gh-fork-ribbon.css index.css index.js webpack.config.js
# Dacha Fi Farm potatos - trade potatos Based on berryclub fork ## Building ```bash ./build.sh ``` # NEAR Place Draw with pixels. Your pixels earn you more pixels, so better artists get more pixels to draw.
npcomplete1667_Venmo-Near-Clone
README.md contract Cargo.toml README.md compile.js src lib.rs package.json src App.js Components MoneyMemo.js Transactions.js __mocks__ fileMock.js assets DeCash.svg 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
Venmo Clone on NEAR Blockchain decash_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
mason-u-borchard_rust-qbyte-clock
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/)
noemk2_zero_to_hero
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/)
marcel-krsh_NEAR_NFT-FT_Staking
FT Cargo.toml README.md build.sh ft Cargo.toml src lib.rs test-contract-defi Cargo.toml src lib.rs tests workspaces.rs NFT Cargo.toml README.md build.sh neardev dev-account.env nft Cargo.toml src lib.rs res neardev dev-account.env test-approval-receiver Cargo.toml src lib.rs test-token-receiver Cargo.toml src lib.rs tests workspaces main.rs test_approval.rs test_core.rs test_enumeration.rs utils.rs Staking Cargo.toml README.md build.sh src lib.rs tests general.rs
# Cross contract Example of using cross-contract functions, like promises, or money transfers. ## Several contracts Let's start the local Near testnet to run the contract on it. * Make sure you have [Docker](https://www.docker.com/) installed; * Clone the [nearprotocol/nearcore](https://github.com/near/nearcore); To start your local node, go to `nearcore` and run the following script: ```bash rm -rf ~/.near ./scripts/start_localnet.py ``` This will pull the docker image and start a single local node. Enter an `test_near` that you want to be associated with. Then execute the following to follow the block production logs: ```bash docker logs --follow nearcore ``` Create a new project: ```bash npx create-near-app --vanilla myproject cd myproject ``` Then in `src/config.json` modify `nodeUrl` to point to your local node: ```js case 'development': return { networkId: 'default', nodeUrl: 'http://localhost:3030', contractName: CONTRACT_NAME, walletUrl: 'https://wallet.nearprotocol.com', }; ``` Then copy the key that the node generated upon starting in your local project to use for transaction signing. ```bash mkdir ./neardev/default cp ~/.near/validator_key.json ./neardev/default/test_near.json ``` Then deploy the `cross-contract` contract: ```bash near create_account cross_contract --masterAccount=test_near --initialBalance 10000000 near deploy --accountId=cross_contract --wasmFile=../examples/cross-contract-high-level/res/cross_contract_high_level.wasm ``` ### Deploying another contract Let's deploy another contract using `cross-contract`, factory-style. ```bash near call cross_contract deploy_status_message "{\"account_id\": \"status_message\", \"amount\":1000000000000000}" --accountId=test_near ``` ### Trying money transfer First check the balance on both `status_message` and `cross_contract` accounts: ```bash near state cross_contract near state status_message ``` See that cross_contract has approximately `9,999,999` and status_message has `0.000000001` tokens. Then call a function on `cross_contract` that transfers money to `status_message`: ```bash near call cross_contract transfer_money "{\"account_id\": \"status_message\", \"amount\":1000000000000000}" --accountId=test_near ``` Then check the balances again: ```bash near state cross_contract near state status_message ``` Observe that `status_message` has `0.000000002` tokens, even though `test_near` signed the transaction and paid for all the gas that was used. ### Trying simple cross contract call Call `simple_call` function on `cross_contract` account: ```bash near call cross_contract simple_call "{\"account_id\": \"status_message\", \"message\":\"bonjour\"}" --accountId=test_near --gas 10000000000000000000 ``` Verify that this actually resulted in correct state change in `status_message` contract: ```bash near call status_message get_status "{\"account_id\":\"test_near\"}" --accountId=test_near --gas 10000000000000000000 ``` Observe: ```bash bonjour ``` ### Trying complex cross contract call Call `complex_call` function on `cross_contract` account: ```bash near call cross_contract complex_call "{\"account_id\": \"status_message\", \"message\":\"halo\"}" --accountId=test_near --gas 10000000000000000000 ``` observe `'halo'`. What did just happen? 1. `test_near` account signed a transaction that called a `complex_call` method on `cross_contract` smart contract. 2. `cross_contract` executed `complex_call` with `account_id: "status_message", message: "halo"` arguments; 1. During the execution the promise #0 was created to call `set_status` method on `status_message` with arguments `"message": "halo"`; 2. Then another promise #1 was scheduled to be executed right after promise #0. Promise #1 was to call `get_status` on `status_message` with arguments: `"message": "test_near""`; 3. Then the return value of `get_status` is programmed to be the return value of `complex_call`; 3. `status_message` executed `set_status`, then `status_message` executed `get_status` and got the `"halo"` return value which is then passed as the return value of `complex_call`. ### Trying callback with return values Call `merge_sort` function on `cross_contract` account: ```bash near call cross_contract merge_sort "{\"arr\": [2, 1, 0, 3]}" --accountId=test_near --gas 10000000000000000000 ``` observe the logs: ``` [cross_contract]: Received [2] and [1] [cross_contract]: Merged [1, 2] [cross_contract]: Received [0] and [3] [cross_contract]: Merged [0, 3] [cross_contract]: Received [1, 2] and [0, 3] [cross_contract]: Merged [0, 1, 2, 3] ``` and the output ``` '\u0004\u0000\u0000\u0000\u0000\u0001\u0002\u0003' ``` The reason why output is a binary is because we used [Borsh](http://borsh.io) binary serialization format to communicate between the contracts instead of JSON. Borsh is faster and costs less gas. In this simple example you can even read the format, here `\u0004\u0000\u0000\u0000` stands for `4u32` encoded using little-endian encoding which corresponds to the length of the array, `\u0000\u0001\u0002\u0003` are the elements of the array. Since the array has type `Vec<u8>` each element is exactly one byte. If you don't want to use it you can remove `#[serializer(borsh)]` annotation everywhere from the code and the contract will fallback to JSON. Non-fungible Token (NFT) =================== Example implementation of a [non-fungible token] contract which uses [near-contract-standards] and [simulation] tests. [non-fungible token]: https://nomicon.io/Standards/NonFungibleToken/README.html [near-contract-standards]: https://github.com/near/near-sdk-rs/tree/master/near-contract-standards [simulation]: https://github.com/near/near-sdk-rs/tree/master/near-sdk-sim NOTES: - The maximum balance value is limited by U128 (2**128 - 1). - JSON calls should pass [U128](https://docs.rs/near-sdk/latest/near_sdk/json_types/struct.U128.html) or [U64](https://docs.rs/near-sdk/latest/near_sdk/json_types/struct.U64.html) as a base-10 string. E.g. "100". - The core NFT standard does not include escrow/approval functionality, as `nft_transfer_call` provides a superior approach. Please see the approval management standard if this is the desired approach. ## Building To build run: ```bash ./build.sh ``` ## Testing To test run: ```bash cargo test --workspace --package non-fungible-token -- --nocapture ``` Fungible Token (FT) =================== Example implementation of a [Fungible Token] contract which uses [near-contract-standards] and [simulation] tests. [Fungible Token]: https://nomicon.io/Standards/Tokens/FungibleTokenCore.html [near-contract-standards]: https://github.com/near/near-sdk-rs/tree/master/near-contract-standards [simulation]: https://github.com/near/near-sdk-rs/tree/master/near-sdk-sim NOTES: - The maximum balance value is limited by U128 (2**128 - 1). - JSON calls should pass U128 as a base-10 string. E.g. "100". - This does not include escrow functionality, as `ft_transfer_call` provides a superior approach. An escrow system can, of course, be added as a separate contract. ## Building To build run: ```bash ./build.sh ``` ## Testing To test run: ```bash cargo test --package fungible-token -- --nocapture ``` ## Changelog ### `1.0.0` - Switched form using [NEP-21](https://github.com/near/NEPs/pull/21) to [NEP-141](https://github.com/near/NEPs/issues/141). ### `0.3.0` #### Breaking storage change - Switching `UnorderedMap` to `LookupMap`. It makes it cheaper and faster due to decreased storage access.
Pips-Isalnd-Metropolis_NEAR_NFT_CONTRACT
README.md nft-contract Cargo.toml build.sh src approval.rs burn.rs enumeration.rs events.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs royalty.rs target .rustc_info.json release .fingerprint Inflector-3fe6c4541cf2e4ba lib-inflector.json borsh-derive-8af633b6d9009bb6 lib-borsh-derive.json borsh-derive-internal-75466de069dd116f lib-borsh-derive-internal.json borsh-schema-derive-internal-35f61888eba9cf70 lib-borsh-schema-derive-internal.json near-sdk-macros-410a72950cf7e185 lib-near-sdk-macros.json proc-macro-crate-a3cc58630baebe9f lib-proc-macro-crate.json proc-macro2-696b863b888ffa10 build-script-build-script-build.json proc-macro2-beef33552bc9bf8f lib-proc-macro2.json proc-macro2-f20b884aa4d69a7d run-build-script-build-script-build.json quote-c1b01608bfb64c35 lib-quote.json serde-8bea865aa20e5ca3 build-script-build-script-build.json serde-9fb261c00948240e lib-serde.json serde-c1a85449c3939629 run-build-script-build-script-build.json serde-ffd1c48a5ce58c55 build-script-build-script-build.json serde_derive-77bea069ef340114 build-script-build-script-build.json serde_derive-860ba24f0a94d84e run-build-script-build-script-build.json serde_derive-d48f41e3c73d874f lib-serde_derive.json serde_json-58623f6894d74091 build-script-build-script-build.json syn-9583227545334bf4 run-build-script-build-script-build.json syn-f768651dc905b617 lib-syn.json syn-fbf1ac6733a2e21d build-script-build-script-build.json toml-b386cde4c361c662 lib-toml.json unicode-xid-aa517a3af69c4d14 lib-unicode-xid.json wee_alloc-930b09ca51478ec1 build-script-build-script-build.json rls .rustc_info.json debug .fingerprint Inflector-effef2fcf5cca855 lib-inflector.json ahash-0729d4f3763602b2 lib-ahash.json aho-corasick-e29f582473c5e358 lib-aho_corasick.json autocfg-30493ed3e6e655b6 lib-autocfg.json base64-1db3a13ab90d7d25 lib-base64.json block-buffer-2ca31169328650d0 lib-block-buffer.json block-padding-fd265843f6af725b lib-block-padding.json borsh-099c2ee13f60f212 lib-borsh.json borsh-derive-28eee6c56e91eacb lib-borsh-derive.json borsh-derive-internal-05d930e0c39e278d lib-borsh-derive-internal.json borsh-schema-derive-internal-c18ce724de59475e lib-borsh-schema-derive-internal.json bs58-02b5623ca4af73a8 lib-bs58.json byteorder-c50a62880c979536 lib-byteorder.json cfg-if-0c2d2e94f129976c lib-cfg-if.json cfg-if-e3cdf0729a772875 lib-cfg-if.json convert_case-211081cc43440598 lib-convert_case.json cpufeatures-7c3e6d262addca09 lib-cpufeatures.json derive_more-4a9a4b3384337cad lib-derive_more.json digest-f6a7e9f6b2da9c18 lib-digest.json generic-array-4bea3db498c996b8 lib-generic_array.json generic-array-90cc77329ebde3f6 build-script-build-script-build.json generic-array-b1c15cf015ec801f run-build-script-build-script-build.json hashbrown-83184040054d2b64 lib-hashbrown.json hashbrown-9e2f10abe5e5cf8e lib-hashbrown.json hex-471be06b69d7b22a lib-hex.json indexmap-22d22e9f0083f893 lib-indexmap.json indexmap-62506b12dfda0f5d run-build-script-build-script-build.json indexmap-e0a16b9ba9deb68c build-script-build-script-build.json itoa-7c7b5ffd75219d0a lib-itoa.json itoa-ff51a61e99d2cee8 lib-itoa.json keccak-92f6d4202bb49b5e lib-keccak.json lazy_static-6d32dfff5581f73f lib-lazy_static.json libc-6f9f4f691dcfdf3e lib-libc.json libc-c54e32afe4514ee3 build-script-build-script-build.json libc-f88a008b8706672e run-build-script-build-script-build.json memchr-044cc2401a04a3e7 run-build-script-build-script-build.json memchr-1398007fcf172d16 build-script-build-script-build.json memchr-8379b090eeab4b60 lib-memchr.json memory_units-4d28f5d19e975765 lib-memory_units.json near-primitives-core-0b57ce19a4316fa5 lib-near-primitives-core.json near-rpc-error-core-efc21ae736f73ede lib-near-rpc-error-core.json near-rpc-error-macro-3523aea7fec5491e lib-near-rpc-error-macro.json near-runtime-utils-65495bf1ad28430b lib-near-runtime-utils.json near-sdk-da15c98e519cea4c lib-near-sdk.json near-sdk-macros-d85812f263077133 lib-near-sdk-macros.json near-sys-41f17d081dbab9b4 lib-near-sys.json near-vm-errors-22e2b287999e133b lib-near-vm-errors.json near-vm-logic-dce3cadc0d05b5c7 lib-near-vm-logic.json nft_simple-31d935813f62c4a8 test-lib-nft_simple.json nft_simple-3d66d0dd5790bc47 lib-nft_simple.json num-bigint-34d05a9a9d8df04a run-build-script-build-script-build.json num-bigint-496b2e2479854375 build-script-build-script-build.json num-bigint-a7eca542fd48f401 lib-num-bigint.json num-integer-183453805b86e5b9 run-build-script-build-script-build.json num-integer-59df9edfd23447b9 lib-num-integer.json num-integer-b756022fd51db609 build-script-build-script-build.json num-rational-0f83a96aad2f8a84 lib-num-rational.json num-rational-37cace3b5d38ca64 run-build-script-build-script-build.json num-rational-90db0edecfad4616 build-script-build-script-build.json num-traits-b839bd80c401095e build-script-build-script-build.json num-traits-d6d59cb929e30fe3 run-build-script-build-script-build.json num-traits-e05ebd6f0a6b4d87 lib-num-traits.json opaque-debug-a3d9c7d8951acf6c lib-opaque-debug.json proc-macro-crate-d69104394253585d lib-proc-macro-crate.json proc-macro2-21448319fa72f73f build-script-build-script-build.json proc-macro2-2f79168f6e63128e run-build-script-build-script-build.json proc-macro2-a797729df313caad lib-proc-macro2.json quote-16a8fa1f4a47835e lib-quote.json regex-550024e25d177798 lib-regex.json regex-syntax-5d5a7f212ac55c65 lib-regex-syntax.json ryu-129647d32833e3e5 lib-ryu.json ryu-6cbc8df1b6e9fb5a lib-ryu.json serde-0e48a110fcaacca4 lib-serde.json serde-3a2500aff2ef06cc build-script-build-script-build.json serde-a3c799213071031b lib-serde.json serde-bcb03346c5beede5 run-build-script-build-script-build.json serde_derive-01388e1def37ea69 lib-serde_derive.json serde_derive-11c1ff9ef1cfc725 run-build-script-build-script-build.json serde_derive-9e7c0303f67350cb build-script-build-script-build.json serde_json-0b43f4cb7fc42dce run-build-script-build-script-build.json serde_json-21627719d1456825 build-script-build-script-build.json serde_json-4dbc98e66ee48b0d lib-serde_json.json serde_json-5ea6a1329c8257ae run-build-script-build-script-build.json serde_json-957d0118a3b81431 lib-serde_json.json serde_json-b14a4c28767a5de8 build-script-build-script-build.json sha2-f26359a4a93d3d52 lib-sha2.json sha3-477503ec40224d87 lib-sha3.json syn-b8fb96b3096f5b8a build-script-build-script-build.json syn-c8e69d0299c82c36 lib-syn.json syn-cda26aee082bcce8 run-build-script-build-script-build.json toml-cb585cb771089725 lib-toml.json typenum-316eef600e5f5bc9 build-script-build-script-main.json typenum-41ba153c57b1c77d lib-typenum.json typenum-7fde67f5ba16e9a8 run-build-script-build-script-main.json unicode-xid-8d3c72829a209037 lib-unicode-xid.json version_check-71502ac49be6aa12 lib-version_check.json wee_alloc-642cbf8fc5f3ad8c run-build-script-build-script-build.json wee_alloc-88a7200934ac0183 lib-wee_alloc.json wee_alloc-b6fb07c2d2c038ea build-script-build-script-build.json build generic-array-90cc77329ebde3f6 save-analysis build_script_build-90cc77329ebde3f6.json indexmap-e0a16b9ba9deb68c save-analysis build_script_build-e0a16b9ba9deb68c.json libc-c54e32afe4514ee3 save-analysis build_script_build-c54e32afe4514ee3.json memchr-1398007fcf172d16 save-analysis build_script_build-1398007fcf172d16.json num-bigint-34d05a9a9d8df04a out radix_bases.rs num-bigint-496b2e2479854375 save-analysis build_script_build-496b2e2479854375.json num-integer-b756022fd51db609 save-analysis build_script_build-b756022fd51db609.json num-rational-90db0edecfad4616 save-analysis build_script_build-90db0edecfad4616.json num-traits-b839bd80c401095e save-analysis build_script_build-b839bd80c401095e.json proc-macro2-21448319fa72f73f save-analysis build_script_build-21448319fa72f73f.json serde-3a2500aff2ef06cc save-analysis build_script_build-3a2500aff2ef06cc.json serde_derive-9e7c0303f67350cb save-analysis build_script_build-9e7c0303f67350cb.json serde_json-21627719d1456825 save-analysis build_script_build-21627719d1456825.json serde_json-b14a4c28767a5de8 save-analysis build_script_build-b14a4c28767a5de8.json syn-b8fb96b3096f5b8a save-analysis build_script_build-b8fb96b3096f5b8a.json typenum-316eef600e5f5bc9 save-analysis build_script_main-316eef600e5f5bc9.json typenum-7fde67f5ba16e9a8 out consts.rs op.rs tests.rs wee_alloc-642cbf8fc5f3ad8c out wee_alloc_static_array_backend_size_bytes.txt wee_alloc-b6fb07c2d2c038ea save-analysis build_script_build-b6fb07c2d2c038ea.json deps save-analysis libahash-0729d4f3763602b2.json libaho_corasick-e29f582473c5e358.json libautocfg-30493ed3e6e655b6.json libbase64-1db3a13ab90d7d25.json libblock_buffer-2ca31169328650d0.json libblock_padding-fd265843f6af725b.json libborsh-099c2ee13f60f212.json libbs58-02b5623ca4af73a8.json libbyteorder-c50a62880c979536.json libderive_more-4a9a4b3384337cad.json libdigest-f6a7e9f6b2da9c18.json libgeneric_array-4bea3db498c996b8.json libhashbrown-9e2f10abe5e5cf8e.json libhex-471be06b69d7b22a.json libindexmap-22d22e9f0083f893.json libinflector-effef2fcf5cca855.json libitoa-7c7b5ffd75219d0a.json libkeccak-92f6d4202bb49b5e.json liblazy_static-6d32dfff5581f73f.json libmemchr-8379b090eeab4b60.json libmemory_units-4d28f5d19e975765.json libnear_primitives_core-0b57ce19a4316fa5.json libnear_rpc_error_core-efc21ae736f73ede.json libnear_rpc_error_macro-3523aea7fec5491e.json libnear_runtime_utils-65495bf1ad28430b.json libnear_sdk-da15c98e519cea4c.json libnear_sys-41f17d081dbab9b4.json libnear_vm_errors-22e2b287999e133b.json libnear_vm_logic-dce3cadc0d05b5c7.json libnft_simple-3d66d0dd5790bc47.json libnum_bigint-a7eca542fd48f401.json libnum_integer-59df9edfd23447b9.json libnum_rational-0f83a96aad2f8a84.json libnum_traits-e05ebd6f0a6b4d87.json libopaque_debug-a3d9c7d8951acf6c.json libproc_macro2-a797729df313caad.json libproc_macro_crate-d69104394253585d.json libquote-16a8fa1f4a47835e.json libregex-550024e25d177798.json libryu-129647d32833e3e5.json libryu-6cbc8df1b6e9fb5a.json libsha2-f26359a4a93d3d52.json libsha3-477503ec40224d87.json libtoml-cb585cb771089725.json libunicode_xid-8d3c72829a209037.json libversion_check-71502ac49be6aa12.json libwee_alloc-88a7200934ac0183.json nft_simple-31d935813f62c4a8.json wasm32-unknown-unknown release .fingerprint ahash-89ff722b9fc561a9 lib-ahash.json base64-6f57e5f2ff742858 lib-base64.json borsh-c42d09e220907de8 lib-borsh.json bs58-7b1fa957726a33fc lib-bs58.json cfg-if-37ef06d10bab2744 lib-cfg-if.json hashbrown-0f38abaacccefd87 lib-hashbrown.json itoa-2b5094f20744b375 lib-itoa.json memory_units-975e76477f41cffa lib-memory_units.json near-sdk-d18f2dcb074961ab lib-near-sdk.json near-sys-9308eb8e753ce7c7 lib-near-sys.json nft_simple-322841616f66c026 lib-nft_simple.json ryu-bb19e37c74f1917e lib-ryu.json serde-bbea27b3c4e0d66f run-build-script-build-script-build.json serde-c122df60af36b475 lib-serde.json serde_json-29800dcc92161fa0 run-build-script-build-script-build.json serde_json-2be46d1b2ec5436c lib-serde_json.json wee_alloc-472ec3be1e3ba846 run-build-script-build-script-build.json wee_alloc-4ed9747105933016 lib-wee_alloc.json build wee_alloc-472ec3be1e3ba846 out wee_alloc_static_array_backend_size_bytes.txt | |","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1038,"byte_end":1133,"line_start":22,"line_end":22,"column_start":1,"column_end":96}},{"value":" | `encode` | Returns a new `String` | Always |","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1134,"byte_end":1229,"line_start":23,"line_end":23,"column_start":1,"column_end":96}},{"value":" | `encode_config` | Returns a new `String` | Always |","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1230,"byte_end":1325,"line_start":24,"line_end":24,"column_start":1,"column_end":96}},{"value":" | `encode_config_buf` | Appends to provided `String` | Only if `String` needs to grow |","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1326,"byte_end":1421,"line_start":25,"line_end":25,"column_start":1,"column_end":96}},{"value":" | `encode_config_slice` | Writes to provided `&[u8]` | Never |","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1422,"byte_end":1517,"line_start":26,"line_end":26,"column_start":1,"column_end":96}},{"value":" ","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1518,"byte_end":1521,"line_start":27,"line_end":27,"column_start":1,"column_end":4}},{"value":" All of the encoding functions that take a `Config` will pad as per the config.","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1522,"byte_end":1604,"line_start":28,"line_end":28,"column_start":1,"column_end":83}},{"value":" ","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1605,"byte_end":1608,"line_start":29,"line_end":29,"column_start":1,"column_end":4}},{"value":" # Decoding","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1609,"byte_end":1623,"line_start":30,"line_end":30,"column_start":1,"column_end":15}},{"value":" ","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1624,"byte_end":1627,"line_start":31,"line_end":31,"column_start":1,"column_end":4}},{"value":" Just as for encoding, there are different decoding functions available.","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1628,"byte_end":1703,"line_start":32,"line_end":32,"column_start":1,"column_end":76}},{"value":" ","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1704,"byte_end":1707,"line_start":33,"line_end":33,"column_start":1,"column_end":4}},{"value":" | Function | Output | Allocates |","span":{"file_name":" Users jobymacbookpro .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1708,"byte_end":1804,"line_start":34,"line_end":34,"column_start":1,"column_end":97}},{"value":" | package.json
To BUILD and Deploy contract: yarn build && near deploy --wasmFile out/main.wasm --accountId **AcountID** To itlilise contract: default setup with minimal data near call **ACCOUNTID** new_default_meta '{"owner_id": "'**Acountid**'"}' --accountId ***acountid** with full data near call **ACCOUNTID** new METADATA_AS_BELOW --accountId ***acountid** pub struct NFTContractMetadata { pub spec: String, // required, is essentially the version number pub name: String, // required name for the contract pub symbol: String, // required like the EPIC pub icon: Option<String>, //data url to represent the icon pub base_uri: Option<String>, // Centralized gateway known to have reliable access to decentralized storage assets referenced by `reference` or `media` URLs pub referance: Option<String>, // URL to a JSON file with more info pub referance_hash: Option<Base64VecU8>, // Base64-encoded sha256 hash of JSON from reference field. Required if `reference` is included. } Minting example: near call **accountid** nft_mint '{"token_id": "test-token", "metadata": {"title": "Testing Token", "description": "testing nft contract", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif"}, "receiver_id": "'**acountid**'"}' --accountId **acountid** --amount 0.1 calling view function example: near view ***acountid*** nft_tokens_for_owner '{"account_id": "'**accountid**'", "limit": 10}' balances passed in should be yoctoNEAR. Royalty percentages are bassed on 100% being 10,000 so we can have less then 1% without using decimals. Trackable evenst such as minting are tracked using a Json log who's name starts with "EVENT_JSON:" Burning example: near call nftcontractdemo.testnet burn_nft '{"token_id": "test-token"}' --accountId **AccoutnID**
pradyumna0_Voting-application-using-blockchain
.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 Components Home.js NewPoll.js PollingStation.js __mocks__ fileMock.js assets blockvotelogo.svg loadingcircles.svg 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
blockvote 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 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
L0MAkin_db-swap
.env README.md package.json postcss.config.js public index.html manifest.json robots.txt src assets svg DB black.svg DB white.svg DefaultTokenIcon.js DefaultTokenIconBlack.js DefaultUsnIcon.js Discord.js DiscordModal.svg Email.js Git.js GitHubModal.svg Medium.js MediumModal.svg SwapIconTwoArrows.js Twitter.js TwitterModal.svg bg.svg components main components Accordion.js AccordionItem.js ExchangeTable.js Footer.js Table.js USNinfo.js mainText.js secondPart.js index.js navigation Burger.js Moadal.js Modal.js NavBar.js RightNav.js pages iframe IframePage.js swap AvailableToSwap.js BlockedCountry.js ImageContainer.js Loader.js SwapAndSuccessContainer.js SwapContainerWrapper.js SwapInfoContainer.js SwapInfoItem.js SwapTokenContainer.js TextInfoSuccess.js TokenIcon.js common Container.js FormButton.js formatToken index.js helpers.js utils classNames.js isBlocedCountry.js isBlockedCountry.js views Success.js SwapPage.js config near-env index.ts hooks fetchByorSellUSN.js fungibleTokensIncludingNEAR.js usePredict.js i18n index.ts locales en.json ru.json react-app-env.d.ts redux combineReducers.js middleware index.js reducerStatus handleAsyncThunkStatus.js initialState initialErrorState.js initialStatusState.js manageStatus clearError.js clearLoading.js setError.js setLoading.js slices createParameterSelector.js multiplier index.js near index.js tokens index.js services FungibleTokens.js SpecialWallet.ts setupTests.ts styles GlobalStyle.js index.css utils bytes-and-hashes.ts nanosec.ts sleep.ts wallet.js tailwind.config.js tsconfig.json
# USN ⇄ NEAR Swap ![usn swap](public/Group%2022.png) *** This is a browser-based web wallet for working with NEAR accounts. It allows you to exchange NEAR for USN and vice versa. # Getting started *** First, set the `REACT_APP_NEAR_ENV` environment variable to the network you want to work on. This can be set in `.env` prior to build. Possible options: `testnet` or `mainnet` To build locally, run this command in the project directory: `npm install` `npm run start` or `yarn install` `yarn start` [//]: # (TODO: detailed docs)
monopoly-dao_monopoly-dapp
README.md dapp .eslintrc.json .vscode launch.json README.md components Header Header.module.css Marquee Marquee.module.css config firebase auth.ts config.ts near near-wallet.js next.config.js package-lock.json package.json pages api hello.ts public assets Article Image 1.svg Article Image 2.svg Beachfront property.svg Featured image.svg duck vector.svg fire icon.svg logo.svg notif header.svg vercel.svg styles Home.module.css Profile.module.css Signup.module.css globals.css tsconfig.json
# monopoly-dapp MonopolyDAO's frontend 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.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. ## 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.
ndxbinh1922001_js-smart-contract
.gitpod.yml README.md contract README.md babel.config.json build.sh build builder.c code.h hello_near.js methods.h deploy.sh neardev dev-account.env package-lock.json package.json src contract.ts tsconfig.json frontend App.js assets global.css logo-black.svg logo-white.svg index.html index.js near-wallet.js package-lock.json package.json start.sh ui-components.js integration-tests package-lock.json package.json src main.ava.ts package-lock.json 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>`.
NearTiger_mint
Desktop near-tiger-nft contracts tenk Cargo.toml src airdrop.rs lib.rs linkdrop.rs payout.rs raffle.rs raffle_collection.rs util.rs
PrimeLabCore_dag
.github workflows release.yml test.yml .gitpod.yml README.md cmd basic main.go terraform main.go timing main.go dag.go dag_test.go example_basic_test.go example_descandentsFlow_test.go example_idinterface_test.go marshal.go marshal_test.go storage.go storage_test.go visitor.go visitor_test.go
# dag [![run tests](https://github.com/nearprime/dag/workflows/Run%20Tests/badge.svg?branch=master)](https://github.com/nearprime/dag/actions?query=branch%3Amaster) [![PkgGoDev](https://pkg.go.dev/badge/github.com/nearprime/dag)](https://pkg.go.dev/github.com/nearprime/dag) [![Go Report Card](https://goreportcard.com/badge/github.com/nearprime/dag)](https://goreportcard.com/report/github.com/nearprime/dag) [![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/nearprime/dag) Implementation of directed acyclic graphs (DAGs). The implementation is fast and thread-safe. It prevents adding cycles or duplicates and thereby always maintains a valid DAG. The implementation caches descendants and ancestors to speed up subsequent calls. <!-- github.com/nearprime/dag: 3.770388s to add 597871 vertices and 597870 edges 1.578741s to get descendants 0.143887s to get descendants 2nd time 0.444065s to get descendants ordered 0.000008s to get children 1.301297s to transitively reduce the graph with caches poupulated 2.723708s to transitively reduce the graph without caches poupulated 0.168572s to delete an edge from the root "github.com/hashicorp/terraform/dag": 3.195338s to add 597871 vertices and 597870 edges 1.121812s to get descendants 1.803096s to get descendants 2nd time 3.056972s to transitively reduce the graph --> ## Quickstart Running: ``` go package main import ( "fmt" "github.com/nearprime/dag" ) func main() { // initialize a new graph d := NewDAG() // init three vertices v1, _ := d.AddVertex(1) v2, _ := d.AddVertex(2) v3, _ := d.AddVertex(struct{a string; b string}{a: "foo", b: "bar"}) // add the above vertices and connect them with two edges _ = d.AddEdge(v1, v2) _ = d.AddEdge(v1, v3) // describe the graph fmt.Print(d.String()) } ``` will result in something like: ``` DAG Vertices: 3 - Edges: 2 Vertices: 1 2 {foo bar} Edges: 1 -> 2 1 -> {foo bar} ```
near_treasury-dao
.github ISSUE_TEMPLATE BOUNTY.yml README.md scripts snapshot_stake.js
# Treasury DAO This is the place for all the forming documents of Treasury DAO, scripts and tools. ## Constitution TODO ## Code of Conduct TODO ## Staking snapshot Staking snapshot is the code that snapshots the amount staked and delegated by all the users. The amounts in the snapshot are used as a weight for user votes in the voting contract. On chain only merkle root of the snapshot is stored, off-chain path is computed when the vote is cast and provided to the contract. The snapshot format is `account_id,amount`, sorted by `account_id` to ensure predictability. Lockup contracts are resolved to the owner. All delegations across mulitple pools are sumed. ## Voting contract Voting contract that is used to self nominate as candidate and voting. Next set of APIs are present: - `set_snapshot(hash: CryptoHash)` -- can be only called once a quarter by `owner_id`. - `self_nominate(gov_forum_link: String)` -- can be used by individual who wants to be candidate into members. Can be called at any point. The critical piece is the link to the governance forum that will link their discussion identity and other info. This requires a small deposit to cover storage of this information. - `vote(candidate_id: AccountId, vote_amount: Balance, total_amount: Balance, proof: MerkleProof)` -- given account delegates part of their "weight" `vote_amount` to given candidate. `total_amount` and `proof` are required to validate this user in the snapshot. Next view functions are available: - `get_owner() -> AccountId` -- account that can be set `owner_id` - `get_snapshot_hash() -> CryptoHash` -- returns hash of the snapshot. Can be used to verify that snapshot is correct. - `get_user_votes(account_id: AccountId) -> [(AccountId, Balance)]` -- returns votes of the given user. The available for voting weight is balance of this user minus all already casted votes. - `get_candidate_count() -> u32` -- number of candidates. - `get_candidates(from_index: u32, limit: u32) -> [Candidate]` -- list of candidates from given interval with their votes. - `get_candidate(account_id: AccountId) -> Candidate` -- total number of votes casted for given candidate. Where `Candidate { account_id: AccountId, votes: Balance, gov_forum_link: String}`. User full balance is retrievable from the snapshot. Frontends and CLI tools must have this snapshot available to retrieve the balance and to compute merkle proof for voting. > Note, that current voting contract requires manual intervention to set snapshots of the stake due to limitations of lockup/staking contracts pair. > This problem will be addressed over time, which will allow to transition to vote without extra snapshotting. ## Voting UI User interface to submit self nomination and vote.
MehmetMHY_ln-researcher
README.md app.js assets devpost metaBuild3 README.md docs logging.md postgus-setup.md sources.txt config config.json dbConfig.sql fileFormats.json controllers cryptography.js health.js image.js test dtest.js m2test.js manager.js middlewares cli backupDB.js currentState.js database db.js postgusDB.js tests db_test_todo.js db_manager tools.js smart_contract contracts README.md babel.config.json package-lock.json package.json scripts build.sh deploy.sh manage-sc.js src contract.ts tsconfig.json nearApi.js test index.js nouns.json testNearApi.js models apiImagePayload.js imgMetaData.js scAddJob.js tests imgMetaData.test.js package.json routes health.js image.js run.sh utils logger.js request.js tests logger.test.js util.test.js util.js
<h1 align="center">Labeler NearBy - Researcher</h1> <p align="center"> <img width="200" src="./assets/repoImgs/ln-logo.png"> </p> ## ⚠️ WARNING: (12-29-2022) This project is not fully completed and still needs thorough testing before going live ## What is the Labeler NearBy project? - Labeler NearBy (ln) is a decentralized platform where machine learning researchers can outsource data labeling to labelers around the world. This is done by using ln-researcher, ln-labeler, and NEAR smart contract(s). - The ultimate goal of this project is to provide an ecosystem for machine learning researchers to have their data labeled by labelers around the world. - Labeler NearBy consists of the following projects: - ln-researcher : https://github.com/MehmetMHY/ln-researcher - ln-labeler : https://github.com/dylan-eck/ln-labeler ## Project Layout: - assets : contains assets for the repo, such as documents and images - config : contains the project config file(s) - controllers : contains all functions used by the API - middlewares : contains all middleware software - cli : contains functions for project's cli (very under developmented at the moment) - database : contains functions for talking with the project database (Postgusql) - db_manager : contains functions used by the manager - smart_contract : contains smart contract code, code that builds & deploys the smart contract, as well as functions that talk with te smart contract. - models : contains all schemas used for this projects - routes : contains the routes/endpoints for the project's API - utils : contains general functions used thoughout the project - app.js : main script for running the project's API - manager.js : main script for runnign the project's manager - .env.development : all environment variable for a development deployment - .env.production : all environment vartables for a production deployment ## About: - The reseacher can host their data though ln-researcher ([this-repo](https://github.com/MehmetMHY/ln-researcher)) and allow labelers using ln-labeler ([here](https://github.com/dylan-eck/ln-labeler)) to label the data provided by the researcher. In exchange for their work, the labeler will get rewarded with NEAR. This exchange of jobs and labels is handled my smart contracts hosted on the NEAR protocal blockchain. - Currently, there is only one smart contract used for ln-researcher, and this contract is deployed by the researcher. This smart contract's main purpose is the provide data labeling jobs to real people (by taking and sending back funds from the NEAR user), determine the best label by using a voting system (Schulze method), and make sure the labeler that provides the best label(s) gets paid. The smart contract acts as both a payment system as well as a judge of shorts that makes sure a labeler gets paided and that a researcher gets their data labeled; everyone does their job. - The Labeler NearBy project was started for the [2022 NEAR Metabuild III hackathon](https://metabuild.devpost.com/). But, if there is enough demand, the goal is to expand this project into something bigger than just a hackathon project. - Currently this project only focuses on labeling image data using squal and polyges labeling but the goal is to expend it to label many other types of data. - All smart contracts for this project will be deployed to testnet until further notice. The code base is still needs time to mature and the code needs to get audited. ## Project's Components: - Database : A Postgresql database that holds data about the image, it's labels, and any other information from the smart contract. This database is mainly used by the API and the Manager. - API : The API that the labeler can use to access the researcher's data (images). This API was designed to be secure and make it such that only the assigned labeler, using NEAR, can access/view the image. This is done by using encrpytion, RSA Keys, a NEAR smart contract, as well as the certain data stored in the database. - Manager : The manager is a component that manages both the local database (Postgresql) as well as the data stored in the smart contract. It makes sure the local database is in sync with the smart contract's data and it manages what jobs get added and/or removed from the smart contract. - Smart Contract : Read the details below for information about the smart contract for this project. - CLI : A command line interface for this project (very under developmented at the moment) ## How To Setup: - ⚠️ Please Read: This code is not finished and has a long ways to go. But this is currently how this project gets built for testing and development. 0. Ideally be on a Macbook or Linux system. This project is not designed for Windows at the moment. 1. Make sure to have the following installed: - NodeJS : https://nodejs.org/en/ - Yarn : https://classic.yarnpkg.com/lang/en/docs/install/#mac-stable - NPM : https://docs.npmjs.com/downloading-and-installing-node-js-and-npm - Docker : https://docs.docker.com/get-docker/ 2. Install the following global packages: ``` npm i near-cli -g npm install -g pino-pretty ``` 3. Log into your NEAR account (testnet): ``` near login ``` 4. Clone this rep: https://github.com/MehmetMHY/ln-researcher 5. Go to the directory for the ln-researcher you just cloned in step #2 using cd. The rest of the steps assume your at <your_path>/ln-researcher/ 6. Run yarn: ``` yarn ``` 7. Go to the project's smart contract directory: ``` cd middlewares/smart_contract/contracts ``` 8. Run Npm in the contracts directory (in the smart contract directory): ``` npm install ``` 9. Build & deploy the smart contract (in the smart contract directory): ``` # this will create & deploy a smart contract then print the name of that smart contract. SAVE THAT smart contract name for later step(s): npm run deploy ``` 10. Setup the database: - To do this, read the following documentation located in this repo: https://github.com/MehmetMHY/ln-researcher/blob/main/assets/docs/postgus-setup.md 11. After everything is setup got back to the repo's root directory and go into the config directory: ``` cd - cd config/ ``` 12. From here, check out the [config.json](https://github.com/MehmetMHY/ln-researcher/blob/main/config/config.json). Modify the values in this json for your setup and save your changes. The main key-values to look into are the following: - logfile : the path to a file that the logger will use for logging - smartContract.mainAccount : the username of the near account you added - smartContract.scAccount : the name/username of the near smart contract you created in step #9 - smartContract.maxJobsPerRound : the max number of jobs you want the smart contract to hold (be careful with this value). - smartContract.paymentPerImageNEAR : how much near your willing to pay per jon (be careful and fair with this value). - dataDirPath : directory path to your directory of images you want to label. - whatToLabel : the tags for you labels (array of strings) - labelDescriptionPath: file path to description text which should contain a descript and/or steps of how you want your labeler to label your images. - managerPauseTimeSeconds: how many seconds the manager should pause/rest before a new cycle of checking/sync data from the smart contract and the local (postgus) database. 13. Now, build the local database. To do this, run the following command: ``` yarn addDB ``` 14. Now, everything should be setting and you should be able to use thse other commands: ``` # view the logs produced by all the scripts in this project yarn logs # run the API yarn devRunAPI # run the manager yarn devRunManager ``` 15. After all of this, you can also checkout ln-labeler: https://github.com/dylan-eck/ln-labeler ## Credits: - This project uses the layout discussed on this amazing article: https://dev.to/nermineslimane/how-to-structure-your-express-and-nodejs-project-3bl - Citing code correctly: https://integrity.mit.edu/handbook/writing-code - All the links to the sources that helped me build this project: - https://github.com/MehmetMHY/ln-researcher/blob/main/assets/docs/sources.txt # Labeler NearBy - Researcher Smart Contract # Contract Interface All contract functionality, including view and change methods, is defined in `contract/src/contract.ts` # Build Process To build the smart contract, run the following command in the `contract` directory: `npm run build` # Deployment To deploy the contract, run the following command in the `contract` directory: `npm run deploy` # Contract Interaction Once the smart contract has been built and deployed, methods can be called using either of the two methods described below. ## Using the NEAR command line interface The NEAR command line interface can be installed using npm. `npm install --global near-cli` To call smart contract methods using the NEAR cli, you must first log into an existing NEAR account. This can be done by running the following command: `near login` Smart contract methods can then be called using the `view` and `call` functionalities provided by the NEAR cli. Note: args is a stringified JSON object. ### View Method `near view <contract-account-name> <method-name> <args>` ### Change Method `near call <contract-account-name> <method-name> <args> --accountId <calling-account-name>` ## Using the NEAR JavaScript API `contract/scripts/manage-sc.js` demonstrates the functionality described in this section. To call contract functions using the NEAR JavaScript API, you must first set up a connection to the NEAR network. ```javascript import NearAPI, { Near } from "near-api-js"; const { connect, KeyPair, keyStores, utils, providers } = NearAPI; const keyStore = new keyStores.UnencryptedFileSystemKeyStore( path.join(os.homedir(), ".near-credentials") ); const connection_config = { networkId: "testnet", keyStore: keyStore, nodeUrl: "https://rpc.testnet.near.org", walletUrl: "https://wallet.testnet.near.org", helperUrl: "https://helper.testnet.near.org", explorerUrl: "https://explorer.testnet.near.org", }; const near_connection = await connect(connection_config); ``` You will then need to connect to an existing NEAR account. ```javascript const account = await connect("<account-id>") ``` Contract methods can then be called using the `viewFunction()` and `functionCall()` methods of the connected account object. Note: args is a json object containing method arguments. ### View Method ```javascript const result = await account.viewFunction({ contractId: "<contract-account-name>", methodName: "<method-name>", args: {}, }); ``` ### Change Method ```javascript const response = await account.functionCall({ contractId: "<contract-account-name>", methodName: "<method-name>", args: {}, }); const result = providers.getTransactionLastResult(response); ``` # Labeler NearBy - Hackathon: [NEAR MetaBUILD III](https://metabuild.devpost.com/) - Official Submission: https://devpost.com/software/labeler-nearby - Submission Date: November 2023 - Authors: - Mehmet Yilmaz - Dylan Eck ## Description A decentralized platform where machine learning researchers can outsource data labeling to labelers around the world. <p align="center"> <a href="https://www.youtube.com/watch?v=KfaUDbWIvr8" title="Submission Video"> <img src="./thumbnail.png" width="500"> </a> </p> <p align="center"><em><strong>click the image to view the submission video (YouTube)</strong></em></p> <p><em><strong> ⚠️ Note: Due to the small size of our team, we were not able to implement everything that we wanted to. Some things described in this write up are still a work in progress and as such may not be fully present in the code submitted </strong></em></p> ## Inspiration During my (Mehmet) time as an undergraduate I was competing in a competition called AgBot. The goal of the competition was to make a robot that could fertilize Maize plants as well as kill off any weeds around a Maize plant. The Maize plant is a plant that produced corn and in the competition these Maize plants were really early in their development phase. Ultimately, me and my team for that competition did not win that competition but well helping to develop the robot, I ran into an issue. I wanted to use machine learning and computer vision to train a model that could identify maize plants such that the robot could know where a Maize plant and/or weed plant was located in the real world. So I gathered over one thousand images of maize plants during their early development stage then quickly learned that I had to label all those images such that the model could learn from the data. The issue with this was that it was going to take a lot of time to do this and as a busy undergraduate in engineering, as well as bad procrastination habits, I never got the time to label those images and eventually never got to it. But I always wondered if there could be a service that labeled machine learning data for you but at a reasonable price. A few years later, I discovered services like Scale AI and Amazon SageMaker Data Labeling that provided such a service. These companies are worth millions and/or billions by providing such a service. But my concern with these services was how they are all centralized which allows them to take a larger cut of the profit made by their service. Because of this, most likely, they provide a smaller return of the profit to the people who label that data in countries where lower pay is acceptable. So the idea of having a verison of Scale AI but decentralized was something I considered for a over two years but what stopped me from pursuing such a project was high transaction fees in popular cryptocurrencies like Ethereum and the fact that I did not really find anyone who attempted such a project. That all changed with this hackathon, where I discovered NEAR. NEAR had low transaction fees and on top of that, there was a popular project called NEAR Crowd which gets tens of thousands of transactions a day which convinced me that this project of a decentralized data labeling platform would be possible. We were really inspired by the works of Scale AI and NEAR Crowd. Our desire for this hackathon was to solve some of the problems that we saw with these two existing services. The biggest problem that we see with Scale AI is that data laborers receive very little money for their work after Scale AI takes their cut of the revenue. Near is very similar to our project, however the usage of Near Crowd is limited due to its invite only nature. ## What it does and/or was suppose to do The ultimate goal of this project is to provide an ecosystem for machine learning researchers to have their data labeled by labelers around the world. To achieve this goal, two tools are provided: - ln-researcher: A tool for hosting data (just images for now) - ln-labeler: A tool for labeling data. To see the overall layout of this project, checkout the diagram [HERE](https://raw.githubusercontent.com/MehmetMHY/ln-researcher/main/assets/repoImgs/layout.png): ![layout](https://github.com/MehmetMHY/ln-researcher/blob/main/assets/repoImgs/layout.png?raw=true) Ln-researcher (LNR) is what the researcher would use and consists of mainly four components: - Researcher’s Smart Contract : This is a smart contract (sc) deployed by the researcher. This sc hosts jobs corresponding to images the researcher wants labeled. The labeler will use this sc to determine what image they will label. When requesting jobs from the sc, labelers are required to attach NEAR to the transaction. This NEAR is immediately returned to the labeler, its inclusion merely serves to discourage the creation of fake accounts. Labelers are also required to submit an RSA public key obtained from the frontend labeling tool. This key is used to validate users when requesting images from the researcher database and ensure that images can only be viewed by assigned valid labelers. Each image is labeled multiple times. Currently the number of labels per image is set to three. Once the image has been labeled the required number of times, the labels are given to reviewers to review. Currently the labels for each image are reviewed by three reviewers. Reviewing consists of ranking each set of labels based on quality. Once all required reviews have been completed, the Schulze Method is used to determine which set of labels to use for the image. The smart contract then distributes among all reviewers and the top-ranked labeler. - Image/Data API: This is an API that allows the researcher to host their images on the internet for the labeler to access. Sense images are too large for smart contracts to store, we found it best that the researcher self hosts their images. But, this API has a layer of security such that only those who are allowed to label an image can label that image. The API has an endpoint called image/. This endpoint is a POST endpoint that requires a body containing the following: id, username, and signature. The id key-value is the id associated with the image and this value is provided as part of the job by the smart contract. The username is the NEAR username of the person assigned the job. And the signature key-value is a signature generated using the private RSA key, assigned to the user from the front end, and the user’s NEAR username as a string. When this request is made, the API checks to make sure the specified image ID exists. Then it checks to see if the username provided is the user assigned to the image. After that, it checks the local database to see if the provided signature was used in the past; if not, the signature is checked with the user’s public key, which is stored in the smart contract, and if the signature is valid, then the image starts getting encrypted. Then the image gets encrypted by a randomly generated hex key. This hex key is then encrypted with that user’s RSA public key. After this, the encrypted key and the image’s labeling description is attached as part of the response’s headers and the image, which is an encrypted string at this point, is returned as part of the response. The frontend, would then load this response, decrypt the key with the user’s assigned RSA private key. Using this decrypted key, the frontend would then decrypt the image and with that the user can view the image for labeling. All of this in turn, allows the image to be accessed only by those assigned with the task of labeling that image. We are not security expects, but this does seem like a secure way to host the images on the internet. - Local Database: This is a local database used by ln-researcher. It is used to keep track of jobs, labels, and associate images with an id. It’s also used to store other information that is useful for other components of this project; such as the API component. Its additional usage is to “backup” data that is also stored in the smart contract. The smart contract, over time, gets all its complete jobs whipped from its local storage (json). This is to save storage space in the smart contract and avoid paying high fees over time. - Manager: This component is used to manage jobs in the smart contract. It runs every couple seconds to do the following. It checks to make sure the local database is in sync with the smart contract’s database (json). It adds jobs and funds to the smart contract. Not only that, but it checks to see if any jobs are taking too long. If a job has not been completed in 1 hour, the manager makes the smart contract remove the assigner user for that job and instead re-opens the job for someone else to do. And finally, the manager tools for any completed jobs. It then saves the completed jobs, mainly the final labels, to the local database. After all this is successfully done, the manager makes the smart contract remove the complete jobs from the smart contract’s local database (json). After removing the completed jobs, the smart contract adds new jobs, if there are still images left for labeling. Ln-labeler is a web-app that labelers use to find and complete jobs. It consists of three main components: - Frontend: Provides a graphical user interface for finding jobs, labeling images, and reviewing labels created by others. The web-app provides a graphical user interface with tools for performing all labeler actions removing the need for labelers to interact directly with either the researcher smart contract or researcher database. - NEAR integration: Labelers are authenticated by signing in with their NEAR wallet. The NEAR JavaScript API is then used to interact with the researcher smart contract to request and submit jobs. The user does not directly call smart contract functions, they interact with the GUI and the associated smart contract calls are performed by the web-app. - Ln-researcher integration: After authenticating using NEAR, the web-app generates an RSA key pair for the labeler. This key pair is used to validate the user when the-web app requests images from the researcher database. It is also used to ensure that only valid labelers who have been assigned a job can view the associated image. Images are fetched automatically by the web-app after a job has been assigned by the smart contract. The received image is then loaded into either the labeling or reviewing interface depending on which kind of job was assigned. ## What does not work at the moment Due to us underestimating the complexity and difficulty of this project, we sadly ran out of time to implement everything we wanted to implement. To see what is missing you can refer to the diagram above. In the diagram, squares/features are colored either green, yellow, or red. Green means the feature was implemented. Yellow means the feature was mostly implemented but still has issues. And red means the feature was not implemented. Features we failed to implement on time or did not fully implement: - Connections between the frontend, researcher smart contract and researcher database. - Frontend reviewing workspace - Frontend job selection page - Containerization of ln-researcher using docker ## How we built it Labeler Nearby consists of three main components, the researcher data hosting server, the researcher smart contract, and the front end. Ln-researcher was building using Node.js, JavaScript, and PostgreSQL. The project used the following npm packages: ajv, axios, express.js, jest, moment, near-api-js, nodemon, pg, pino, and uuid. The smart contract used by ln-researcher and ln-labeler was built using Typescript. And used the following npm packages: near-api-js, near-cli, and near-sdk-js. The front end was put together using Next.js as the underlying framework. OpenSeadragon and Annotorious were used to provide the labeling functionality. The NEAR JavaScript API was used to handle interaction with smart contracts. The layout and styling of the rest of the front end was accomplished using plain html and css. ## Challenges we ran into The biggest challenge that we ran into was underestimating the amount of work that it would take to bring our idea to completion. We did spend a lot of time at the beginning of the hackathon brainstorming and planning what we were going to do. We pivoted a couple times early on to ideas that we at the time felt would be easier to implement. However, due to our general lack of experience in web development and blockchain technology, our assessments of the scale and difficulty of implementing our ideas were inaccurate. Another challenge was that the way that the smart contract was set up made it quite difficult and tedious to test certain functionality. This became an especially big problem later in the hackathon because we didn’t leave enough time to integrate everything. Because we didn’t have time to integrate everything we couldn’t deploy a live demo or record a proper demo video. ## Accomplishments that we're proud of Although the styling of the front end is not completely finished, we do think that it looks fairly decent in its current state. We are also proud that we were able to successfully implement the encryption and verification system used when retrieving images from the researcher. The API component for ln-researcher is something we are really proud of. ## What we learned One of the most important things we learned is that, even in hackathons as long as this one, good time management is essential when attempting to complete projects at the scale of the project that we attempted. We also learned a lot about web development and NEAR development through encountering and solving many small problems while implementing our project. ## What's next for Labeler NearBy Unfortunately, we were unable to finish our prototype implementation during the hackathon. Because of this, we were unable to deploy a live demo or create a video demonstrating the full functionality of Labeler NearBy. Moving forward, our next step would be to finish the initial prototype implementation so that we can get a feel for and demonstrate intended functionality. After that, assuming there is interest, we would go back over the prototype and clean it up, make it bullet proof, and turn it into an actual product. We feel that this concept has real potential to be beneficial, especially for those living in areas where it is difficult to find steady, gainful employment. ## Built With: annotorious, express.js, javascript, near-api-js, near-sdk-js, nextjs, node.js, openseadragon, & postgresql ## Try it out: - https://github.com/MehmetMHY/ln-researcher - https://github.com/dylan-eck/ln-labeler
iangriggs_near_delegation
lib.rs
Learn-NEAR_NCD--dice
README.md babel.config.js contract Cargo.toml README.md build.sh compile.js src lib.rs tests test_utils.rs copy-dev-account.js jest.config.js package.json src __mocks__ fileMock.js assets logo-black.svg logo-white.svg config.js global.css jest.init.js main.js main.test.js utils.js wallet login index.html tests unit Notification.spec.js SignedIn.spec.js SignedOut.spec.js
NCD-GroupA-Demo Smart Contract ================== A demo contract for NCD Pojrect Phase-1. Play with this contract ======================== the contract is deployed at testnet with the name `dev-1614240595058-5266655` you can set it to env for later use: ```shell export CONTRACTID=dev-1614240595058-5266655 ``` ## Look around ```shell # return playground info near view $CONTRACTID get_contract_info '' # return winner tip rate near view $CONTRACTID get_reward_fee_fraction '' # return win history list near view $CONTRACTID get_win_history '{"from_index": 0, "limit": 100}' # return dice count that alice has near view $CONTRACTID get_account_dice_count '{"account_id": "alice.testnet"}' ``` ## Let's play ```shell # attached 3 Near to buy 3 dices near call $CONTRACTID buy_dice '' --amount=3 --account_id=alice.testnet #check user's dice, would return 3 here near view $CONTRACTID get_account_dice_count '{"account_id": "alice.testnet"}' # roll dice 3 times, say how luck you are near call $CONTRACTID roll_dice '{"target": 1}' --account_id=alice.testnet near call $CONTRACTID roll_dice '{"target": 3}' --account_id=alice.testnet near call $CONTRACTID roll_dice '{"target": 4}' --account_id=alice.testnet ``` Build Deploy and Init ====================== Before you compile this code, you will need to install Rust with [correct target] ```shell # building it srouce ./build.sh ``` ```shell # dev-deploy or deploy it near dev-deploy res/neardice.wasm # say it was deploy at $CONTRACTID, then init it near call $CONTRACTID new \ '{"owner_id": "boss.testnet", "dice_number": 1, "rolling_fee": "1000000000000000000000000", "reward_fee_fraction": {"numerator": 5, "denominator": 100}}' \ --account_id=$CONTRACTID ``` ```shell # last step to open the playgroud is # to deposit to the jackpod the very first time near call $CONTRACTID deposit_jackpod '' --amount=50 --account_id=boss.testnet ``` 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 NCD-GroupA-Demo ================== This is a homework demo project for NCD program phase-1. Rolling Dice On NEAR ==================== Guys, let's roll dice on NEAR. ## Why dice Randomness is always a key focus on any blockchain. We wanna show you how convenient that a random number can get on NEAR blockchain. To achieve that, it is hard to believe there is a better way than to make a dice dapp. Beyond what you can see in this demo, NEAR can even generate independent randomness not per block, but per receipt! ## How to play On home page, user can see the whole status of playground without login, i.e. an NEAR account is not necessary. He would have full imformation about owner account of this contract, dice price, commission fee rate, the size of current jackpod and etc. Then, user can login with NEAR account and buy several dices. With dices bought, he can guess a number and roll dice again and again. If the dice point is equal to his guess, half of jackpod would belong to him. Otherwise the amount he paid for the dice would belong to the jackpod. During playing, the latest 20 win records would appear and be auto refreshed on screen too. About Contract ==================== It's need to be mentioned that it is a pure dapp project, which means there is no centralized backend nor data server, all persistent information is stored and mananged on NEAR chain by a contract. ## Contract Structure ```rust /// This structure describe a winning event #[derive(BorshDeserialize, BorshSerialize)] pub struct WinnerInfo { pub user: AccountId, // winner accountId pub amount: Balance, // how much he got as win reward pub height: BlockHeight, // the block hight this event happened pub ts: u64, // the timestamp this event happened } /// main structure of this contract #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct NearDice { pub owner_id: AccountId, // owner can adjust params of this playground pub dice_number: u8, // how many dices one rolling event uses pub rolling_fee: Balance, // how much a dice costs when user buys it pub jack_pod: Balance, // as name shows and half of it would belong to the winner pub owner_pod: Balance, // winner would share a tip to the playground, this is where those tips go pub reward_fee_fraction: RewardFeeFraction, // a fraction defines tip rate // an always grow vector records all win event, // as a demo, we ignore the management of its size, // but in real project, it must be taken care of, // maybe has a maximum length and remove the oldest item when exceeds. pub win_history: Vector<WinnerInfo>, // records dice user bought by his payment amount. // This map has a mechanism to shrink, // when a user's balance is reduce to zero, the entry would be removed. pub accounts: LookupMap<AccountId, Balance>, } ``` ## Contract Interface ```rust /// winner's tip rate pub struct RewardFeeFraction { pub numerator: u32, pub denominator: u32, } /// a human readable version for win event struct, used in return value to caller pub struct HumanReadableWinnerInfo { pub user: AccountId, // winner accountId pub amount: U128, // the reward he got pub height: U64, // block height the event happens pub ts: U64, // timestamp the event happens } /// status of this playground, as return value of get_contract_info pub struct HumanReadableContractInfo { pub owner: AccountId, // who runs this playground, if you feel bad, just sue him :) pub jack_pod: U128, // you know what it means pub owner_pod: U128, // winner's tip goes to here, owner can withdraw pub dice_number: u8, // how many dice we use in one rolling event pub rolling_fee: U128, // how much a dice costs when user wanna buy it } /// every roll_dice event would return this info pub struct HumanReadableDiceResult { pub user: AccountId, // who rolls pub user_guess: u8, // the number he guess pub dice_point: u8, // the number dice shows pub reward_amount: U128, // reward he got pub jackpod_left: U128, // jackpod after this event pub height: U64, // the block height when he rolls pub ts: U64, // the timestamp when he rolls } //****************/ //***** INIT *****/ //****************/ /// initialization of this contract #[init] pub fn new( owner_id: AccountId, dice_number: u8, rolling_fee: U128, reward_fee_fraction: RewardFeeFraction, ) -> Self; //***************************/ //***** OWNER FUNCTIONS *****/ //***************************/ /// deposit to jackpod, used for initalizing the very first jackpod, /// otherwise, the jackpod is initialized as 0. #[payable] pub fn deposit_jackpod(&mut self); /// withdraw ownerpod to owner's account pub fn withdraw_ownerpod(&mut self, amount: U128); /// Updates current reward fee fraction to the new given fraction. pub fn update_reward_fee_fraction(&mut self, reward_fee_fraction: RewardFeeFraction); /// Updates current dice number used in one rolling event. pub fn update_dice_number(&mut self, dice_number: u8); /// Updates current dice price. pub fn update_rolling_fee(&mut self, rolling_fee: U128); //**************************/ //***** USER FUNCTIONS *****/ //**************************/ /// user deposit near to buy dice. /// he can buy multiple dices, /// any leftover amount would refund /// eg: rolling_fee is 1 Near, he can buy_dice with 4.4 Near and got 4 dices and 0.4 Near refund. #[payable] pub fn buy_dice(&mut self); /// user roll dice once, then his available dice count would reduce by one. pub fn roll_dice(&mut self, target: u8) -> HumanReadableDiceResult; //**************************/ //***** VIEW FUNCTIONS *****/ //**************************/ /// get a list of winn events in LIFO order /// best practise is set from_index to 0, and limit to 20, /// that means to get latest 20 win events information with latest first order. pub fn get_win_history(&self, from_index: u64, limit: u64) -> Vec<HumanReadableWinnerInfo>; /// get current playground status pub fn get_contract_info(&self) -> HumanReadableContractInfo; /// get current winner tip rate pub fn get_reward_fee_fraction(&self) -> RewardFeeFraction; /// get account's available dice count pub fn get_account_dice_count(&self, account_id: String) -> u8; ``` 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/main.js` is a great place to start exploring. 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 `NCD-GroupA-Demo.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `NCD-GroupA-Demo.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 NCD-GroupA-Demo.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 || 'NCD-GroupA-Demo.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. [Vue]: https://vuejs.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
hack-a-chain-software_peter-bot-smart-contract
Cargo.toml LICENSE.md src lib.rs TEST
noemk2_storange_rs
Cargo.toml README.md build.sh src lib.rs
Hola mundo en near con Rust ================== Introducción a holamundo en near (Rust) ================== un holamundo en near protocol, este contrato te perminte: 1. print "Hello world" 2. print "Hello " + $USER 👨‍💻 Instalación en local =========== Para correr este proyecto en local debes seguir los siguientes pasos: Paso 1: Pre - Requisitos ------------------------------ 1. Asegúrese de tener todos los [prequisitos para compilar en rust] (Install Rustup , Add wasm target to your toolchain) 3. Crear un test near account [NEAR test account] 4. Instalar el NEAR CLI globally: [near-cli] es una interfaz de linea de comando (CLI) para interacturar con NEAR blockchain yarn install --global near-cli Step 2: Configura tu NEAR CLI ------------------------------- Configura tu near-cli para autorizar su cuenta de prueba creada recientemente: near login Step 3: Clonar Repositorio ------------------------------- Este comando nos permite clonar el repositorio de nuestro proyecto ```bash git clone https://github.com/noemk2/holamundo_rs.git ``` Una vez que hayas descargado el repositorio, asegurate de ejecutar los comandos dentro del repositorio descargado. Puedes hacerlo con ```bash cd holamundo_rs/ ``` Step 4: Realiza el BUILD para implementación de desarrollo de contrato inteligente ------------------------------------------------------------------------------------ Instalar dependencias ```bash cargo check ``` Cree el código de contrato inteligente e implemente el servidor de desarrollo local: ```bash sh build.sh ``` Cree la variable local $CONTRACT_NAME (permite guardar tu contrato temporal en una variable facil de recordar) ```bash source ./neardev/dev-account.env ``` ¡Felicitaciones, ahora tendrá un entorno de desarrollo local ejecutándose en NEAR TestNet! ✏️ Comando view : request estatico ----------------------------------------------- Permite imprimir "Hello world" Para Linux: ```bash near view $CONTRACT_NAME hello_world --account-id <username>.testnet ``` ✏️ Comando call : request dinamico -------------------------------------------- Permite imprimir "Hello " + <username> .testnet Para Linux : ```bash near call $CONTRACT_NAME hello --account-id <username>.testnet ``` 🤖 Test ================== Las pruebas son parte del desarrollo, luego, para ejecutar las pruebas en el contrato inteligente , debe ejecutar el siguiente comando: ```bash cargo test -- --nocapture ``` ============================================== [create-near-app]: https://github.com/near/create-near-app [prequisitos para compilar en rust]: https://github.com/near/near-sdk-rs#pre-requisites [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [NEAR test account]: https://docs.near.org/docs/develop/basics/create-account#creating-a-testnet-account
NEAR-Hispano_blockjobs
README.md accounts.sh clear.sh contract Cargo.toml README.md build.sh flags.sh ft Cargo.toml src lib.rs marketplace Cargo.toml src event.rs external.rs internal.rs lib.rs user.rs mediator Cargo.toml src events.rs lib.rs sales Cargo.toml src lib.rs deploy.sh frontend README.md build asset-manifest.json index.html manifest.json robots.txt static css 2.f4c56af9.chunk.css main.468d277d.chunk.css js 2.f67d7cea.chunk.js.LICENSE.txt main.a444b1d1.chunk.js runtime-main.94da8630.js media JobsCoinIcon.e2079029.svg create_a_service.5524ba39.svg freelancer.3e2b538f.svg get_hired.5524ba39.svg iphone-12.67aa6f9e.svg logo-black.47b91dd0.svg roadmap.f9acc1f5.svg usd-coin-usdc-logo.f08e02b1.svg config-overrides.js package.json public index.html manifest.json robots.txt src App.js assets DrawKit Vector Illustration Pack Online Shopping-04.svg JobsCoinIcon.svg Smile.svg categoriesData.json countriesData.json create_a_service.svg freelancer.svg get_hired.svg grupo_iphone.svg idiomsData.json iphone-12.svg jobs_test.svg logo-black.svg logo-white.svg main.css no-results.svg roadmap.svg tailwind.css tokensData.json usd-coin-usdc-logo.svg babel.config.js categoriesData.json components BlockTokenDialog.js BuyJobsCoinDialog.js Chat.js CreateDisputeDialog.js CreateServiceDialog.js DepositTokenDialog.js DialogUserCreator.js DisputeCard.js DisputesFilter.js Footer.js MarkdowViewer.js NavBar.js ServicesCard.js ServicesFilter.js SkeletonLoaderDispute.js SkeletonLoaderProfile.js SkeletonLoaderService.js Spinner.js TokenIcons.js UserProfile.js VotingDialog.js config.js contractsAccounts.json countriesData.json firebase.js idiomsData.json index.js logo.svg state.js tokensData.json utils.js views AboutUs.js ConnectionError.js DashBoard.js Dispute.js Disputes.js Docs.js Help.js Home.js MyChats.js MyDisputes.js MyServices.js Mytokens.js NotFoundPage.js Profile.js Service.js Services.js tailwind.config.js onlydeploy.sh sim README.md __tests__ main.ava.ts package.json tsconfig.json update.sh
BlockJobs ========= BlockJobs es un proyecto del programa DIR de NEAR hispano, con la finalidad de crear un marketplace de servicios profesionales. Pagina web ========= http://testnet.blockjobs.site/ Prerequisitos ============= 1. Instalar [Node.js] ≥ 12 2. Instalar el compilador de rust y wasm target: ``` bash $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh $ rustup target add wasm32-unknown-unknown ``` 3. Instalar el cliente de NEAR: `npm i -g near-cli` 4. Logearse con tu cuenta de testnet: `near login` Explorar el codigo ================== 1. El backend esta en la carpeta /contract 2. El frontend esta en la carpeta /src 3. Los tests se encuentra en la carpeta /sim Solo Compilar ============= ``` bash $ cd contract $ chmod +x ./build $ ./build.sh ``` Compilar y Deploy ================= ``` bash $ chmod +x ./deploy $ ./deploy.sh ``` Ejecutar las funciones ================= En cada contrato hay un fichero llamado Notes que contiene cada funcion en comandos para near-cli comando Test ==== ``` bash $ cd contract $ ./build.sh $ cd .. $ cd sim $ npm install $ npm run test -- --verbose --timeout=10m ``` Autores ======= [Sebastian Gonzalez]\ [Dario Sanchez] Frontend ======== Para correr el servidor de desarrollo de react ``` bash $ cd frontend $ npm run start ``` Para compilar tailwind ``` bash $ npm run build:css ``` Para wachear tailwind ``` bash $ npm run watch:css ``` Es posible que taiwind de errores, por que para solucionarlo elimina node_module y vuelve a instalar los paquetes. Tambien es posible que pueda haber fugas de memoria por cerrarlo incorrectamente el servidor de desarrollo y te coma toda la ram. 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. [Sebastian Gonzalez]: https://github.com/Stolkerve [Dario Sanchez]: https://github.com/SanchezDario/ [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 # 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: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm 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. ### `npm run 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. ### `npm run 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) ### `npm run 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) These tests use [near-workspaces-ava](https://github.com/near/workspaces-js/tree/main/packages/ava): delightful, deterministic local testing for NEAR smart contracts. You will need to install [NodeJS](https://nodejs.dev/). Then you can use the `scripts` defined in [package.json](./package.json): npm run test If you want to run `near-workspaces-ava` or `ava` directly, you can use [npx](https://nodejs.dev/learn/the-npx-nodejs-package-runner): npx near-workspaces-ava --help npx ava --help To run only one test file: npm run test "**/main*" # matches test files starting with "main" npm run test "**/whatever/**/*" # matches test files in the "whatever" directory To run only one test: npm run test -- -m "root sets*" # matches tests with titles starting with "root sets" yarn test -m "root sets*" # same thing using yarn instead of npm, see https://yarnpkg.com/ BlockJobs 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
Josephdara_learn-web3
.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-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-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 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 ``` # 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`? # This is a solved version. Original version available at learn.figment.io 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
near_runner-jest
.github workflows lint.yml test.yml .vscode extensions.json settings.json README.md __tests__ 01.basic-transactions.spec.ts bootstrap-starter near-runner README.md __tests__ main.spec.ts package.json tsconfig.json test.bat test.sh dist index.d.ts index.js jest.config.js package.json scripts bootstrap.js cli.js jest.js setup.js src index.ts tsconfig.jest.json tsconfig.json
These tests use [near-runner-jest](https://github.com/near/runner-jest): delightful, deterministic local testing for NEAR smart contracts. You will need to install [NodeJS](https://nodejs.dev/). Then you can use the `scripts` defined in [package.json](./package.json): npm run test If you want to run `near-runner-jest` or `jest` directly, you can use [npx](https://nodejs.dev/learn/the-npx-nodejs-package-runner): npx near-runner-jest --help npx jest --help near-runner + Jest ================== A thin wrapper around [near-runner] to make it easier to use with [Jest] and [TypeScript]. If you don't want Jest, use near-runner directly. Write tests once, run them both on [NEAR TestNet](https://docs.near.org/docs/concepts/networks) and a controlled [NEAR Sandbox](https://github.com/near/sandbox) local environment. [near-runner]: https://github.com/near/runner-js [Jest]: https://jestjs.io/ [TypeScript]: https://www.typescriptlang.org/ Quick Start =========== `near-runner-jest --bootstrap` is a one-time command to quickly initialize a project with near-runner-jest. You will need [NodeJS] installed. Then: npx near-runner-jest --bootstrap It will: * Add a `near-runner` directory to the folder where you ran the command. This directory contains all the configuration needed to get you started with near-runner-jest, and a `__tests__` subfolder with a well-commented example test file. * Create `test.sh` and `test.bat` scripts in the folder where you ran the command. These can be used to quickly run the tests in `near-runner`. Feel free to integrate test-running into your project in a way that makes more sense for you, and then remove these scripts. * Install `near-runner-jest` as a dependency using `npm install --save-dev` (most of the output you see when running the command comes from this step). [NodeJS]: https://nodejs.dev/ Manual Install ============== 1. Install. ```bash npm install --save-dev near-runner-jest # npm yarn add --dev near-runner-jest # yarn ``` 2. Configure. You can use the `near-runner-jest` script to run `jest` using a [custom configuration file](./jest.config.js). You can add this to your `test` script in your `package.json`: "test": "near-runner-jest" Now you can run tests with `npm run test` or `yarn test`. If you want to write tests with TypeScript (recommended), you can add a `tsconfig.json` to your project root with the following contents: {"extends": "near-runner-jest/tsconfig.jest.json"} If you already have TypeScript set up and you don't want to extend the config from `near-runner-jest`, feel free to just copy the settings you want from [tsconfig.jest.json](./tsconfig.jest.json). 2. Initialize. Make a `__tests__` folder, make your first test file. Call your first test file `main.spec.ts` if you're not sure what else to call it. (near-runner-jest uses [Jest's default test matcher](https://jestjs.io/docs/configuration#testmatch-arraystring), which will find any `*.ts` or `*.js` files in the `__tests__` directory and any files project-wide with a `*.(spec|test).(ts|js)` suffix. "Project-wide" here means "the directory in which you run `near-runner-jest`.") In `main.spec.ts`, set up a `runner` with NEAR accounts, contracts, and state that will be used in all of your tests. ```ts import path from 'path'; import {Runner} from 'near-runner-jest'; const runner = Runner.create(async ({root}) => { const alice = await root.createAccount('alice'); const contract = await root.createAndDeploy( 'contract-account-name', path.join(__dirname, '..', 'path', 'to', 'compiled.wasm'), ); // make other contract calls that you want as a starting point for all tests return {alice, contract}; }); describe('my contract', () => { // tests go here }); ``` `describe` is [from Jest](https://jestjs.io/docs/setup-teardown) and is optional. 4. Write tests. ```ts describe('my contract', () => { runner.test('does something', async ({alice, contract}) => { 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} ); expect(result).toBe('whatever'); }); runner.test('does something else', async ({alice, contract}) => { const result = await contract.view( 'some_view_function', {account_id: alice} ); expect(result).toBe('some default'); }); }); ``` `runner.test` is added to `near-runner` by `near-runner-jest`, and is shorthand for: ```ts test.concurrent('does something', async () => { await runner.run(async ({…}) => { // tests go here }); }); ``` Where `test.concurrent` comes [from Jest](https://jestjs.io/docs/api#testconcurrentname-fn-timeout) and `runner.run` comes [from near-runner](https://github.com/near/runner-js#how-it-works). See the [`__tests__`](https://github.com/near/runner-js/tree/main/__tests__) directory in near-runner-js for more examples. Remember that you can replace the nested `test.concurrent`…`await runner.run` sequences with `runner.test`.
near-ndc_i-am-human-backend
index.js package.json router is_admin.js supabase.js utils supabase.js
Khixinhxan_near_workshop
Cargo.toml README.md rect::tests::test_rect_complex stdout README_RU.md README_Windows.md build.sh build_for_real.sh call.sh deploy.sh draw_art.sh src art.rs circle.rs hardcore.rs invert.rs lib.rs rect.rs target .rustc_info.json debug .fingerprint Inflector-73fd077a71c32cd7 lib-inflector.json autocfg-1679e9e291bab035 lib-autocfg.json base64-f13f66aa208d38f1 lib-base64.json berry-bot-0cc9bf6849f7005d test-lib-berry-bot.json block-buffer-587d0e668737e2df lib-block-buffer.json block-padding-f297cbb59e15b3e4 lib-block-padding.json borsh-35cd9670ed16f419 lib-borsh.json borsh-derive-52bd868371682e18 lib-borsh-derive.json borsh-derive-internal-b4f2eba43d0dca35 lib-borsh-derive-internal.json borsh-schema-derive-internal-77e02cb5041ecded lib-borsh-schema-derive-internal.json bs58-29ac46e94d237acf lib-bs58.json byte-tools-41e8edb836590524 lib-byte-tools.json byteorder-1186e4aaf308fecb lib-byteorder.json byteorder-1aa023c1d2a06f72 build-script-build-script-build.json byteorder-6fcf22b0532250b1 run-build-script-build-script-build.json cfg-if-2d7a958a85ec486c lib-cfg-if.json digest-efe1697374692f15 lib-digest.json fake-simd-88ab6649bdc4a694 lib-fake-simd.json generic-array-879b661bfcf2a880 lib-generic_array.json indexmap-24d37044fa10b251 run-build-script-build-script-build.json indexmap-2a755f81fdc19917 lib-indexmap.json indexmap-ece3badb25234955 build-script-build-script-build.json itoa-c30223ac332b1702 lib-itoa.json keccak-8e64845737f9159e lib-keccak.json libc-4db2009a4e1a709b build-script-build-script-build.json libc-6a5cca59b4427e5a lib-libc.json libc-ef689fdf7c2bae78 run-build-script-build-script-build.json memory_units-ce291cb1f2242b2e lib-memory_units.json near-rpc-error-core-04f3b7e823d73e81 lib-near-rpc-error-core.json near-rpc-error-macro-6059dbb5a3f0f64a lib-near-rpc-error-macro.json near-runtime-fees-04a35118259974cc lib-near-runtime-fees.json near-sdk-7fa271cfddb336db lib-near-sdk.json near-sdk-core-c965b62e97873f1c lib-near-sdk-core.json near-sdk-macros-f23b53fc54afdf42 lib-near-sdk-macros.json near-vm-errors-ff269e27ead8c22e lib-near-vm-errors.json near-vm-logic-be3f536466ab26a4 lib-near-vm-logic.json num-bigint-3066acc269f2deb7 run-build-script-build-script-build.json num-bigint-4e477da9cef7af34 lib-num-bigint.json num-bigint-5221afa2ff78907b build-script-build-script-build.json num-integer-a84216a0c057c2d7 lib-num-integer.json num-integer-c04b092b3925843c run-build-script-build-script-build.json num-integer-fa97f02122e92647 build-script-build-script-build.json num-rational-0a8acb95f2851c3f build-script-build-script-build.json num-rational-0d712a1db9d1a708 run-build-script-build-script-build.json num-rational-60b89029a9713f24 lib-num-rational.json num-traits-63c3d2437479199c run-build-script-build-script-build.json num-traits-65d5f80ceb4ff933 build-script-build-script-build.json num-traits-c82c6431d7ae00ae lib-num-traits.json opaque-debug-44d36b022a267616 lib-opaque-debug.json proc-macro2-67dbb9c4f06e2f5b lib-proc-macro2.json proc-macro2-cadb7804aef11580 build-script-build-script-build.json proc-macro2-e843741dc0ed8fe5 run-build-script-build-script-build.json quote-8f7b8502ec016a5f lib-quote.json ryu-d212310295c22a6a build-script-build-script-build.json ryu-fd1b6a184764685c lib-ryu.json ryu-fddd7b21ddd3319a run-build-script-build-script-build.json serde-6996f5e10cbbe749 run-build-script-build-script-build.json serde-7860ccfa4ef5be65 build-script-build-script-build.json serde-deff2b0c8b76ae72 lib-serde.json serde_derive-dfbd142ccf0714f1 lib-serde_derive.json serde_json-259d4fac4176f6da lib-serde_json.json sha2-1787928b7efda4dc lib-sha2.json sha3-6a36c0fccb00427d lib-sha3.json syn-1bd6d96e7a46cbad run-build-script-build-script-build.json syn-b0ab1d2c27fefb9c lib-syn.json syn-ebec5e50ba1f788a build-script-build-script-build.json typenum-4a9c03631bf3eeff run-build-script-build-script-main.json typenum-6ea7522ba45d176a build-script-build-script-main.json typenum-f4e9caabfbfb13a1 lib-typenum.json unicode-xid-d457d5c173c08da5 lib-unicode-xid.json wee_alloc-4481e6cc904a3f17 lib-wee_alloc.json wee_alloc-4870af1613a1ab68 build-script-build-script-build.json wee_alloc-cf563775af167769 run-build-script-build-script-build.json build typenum-4a9c03631bf3eeff out consts.rs op.rs wee_alloc-cf563775af167769 out wee_alloc_static_array_backend_size_bytes.txt release .fingerprint Inflector-04a25fb8c6ce9e45 lib-inflector.json autocfg-954a826acd05cade lib-autocfg.json borsh-derive-7b21f729a09592a2 lib-borsh-derive.json borsh-derive-internal-ba8e72fb900c4b8a lib-borsh-derive-internal.json borsh-schema-derive-internal-b6a7d24e5575f943 lib-borsh-schema-derive-internal.json byteorder-a6928a05be507e60 build-script-build-script-build.json indexmap-bde7d80d105bfa8d build-script-build-script-build.json indexmap-e02ccb1ebeeeb165 run-build-script-build-script-build.json indexmap-ef75e4c8ef26183b lib-indexmap.json itoa-5503a7e419ebdcc4 lib-itoa.json near-rpc-error-core-abc2e38fcf6135b3 lib-near-rpc-error-core.json near-rpc-error-macro-9d2c3704cb9a93c0 lib-near-rpc-error-macro.json near-sdk-core-89bfb0b3e2233424 lib-near-sdk-core.json near-sdk-macros-952380f2aed3f9cd lib-near-sdk-macros.json num-bigint-44165bb63b2bc333 build-script-build-script-build.json num-integer-c2119593105edc4c build-script-build-script-build.json num-rational-5fe0837102a5eac4 build-script-build-script-build.json num-traits-c412154b217e8d42 build-script-build-script-build.json proc-macro2-5f8b01acf7459337 run-build-script-build-script-build.json proc-macro2-68ca1d6be064d252 lib-proc-macro2.json proc-macro2-e0580975e1e330ed build-script-build-script-build.json quote-c3ef17c6fb8d2487 lib-quote.json ryu-50a5eb9fc2d65992 run-build-script-build-script-build.json ryu-5ff3e6ea5dcf5e44 lib-ryu.json ryu-e608d9b01e72ff1d build-script-build-script-build.json serde-24b5fdba7d743b0c lib-serde.json serde-38c3888fd898c390 build-script-build-script-build.json serde-9b8a95a52a69557c run-build-script-build-script-build.json serde_derive-168fda38aeeed9e4 lib-serde_derive.json serde_json-1c1a63add142fa1c lib-serde_json.json syn-a10a76989fac13ce build-script-build-script-build.json syn-d7c68f8e2fe484c8 lib-syn.json syn-e68ad53126325c2c run-build-script-build-script-build.json typenum-91ef9a69bf461c8b build-script-build-script-main.json unicode-xid-67444cc0becf91cc lib-unicode-xid.json wee_alloc-12b838f4f26288d4 build-script-build-script-build.json wasm32-unknown-unknown release .fingerprint base64-acd7c80288744a36 lib-base64.json berry-bot-95f1dca723327e3e lib-berry-bot.json block-buffer-6a799f8b1a5ab486 lib-block-buffer.json block-padding-da99d7c361ad16e2 lib-block-padding.json borsh-dbb1d50594372ca6 lib-borsh.json bs58-568f94e18687cda5 lib-bs58.json byte-tools-acefa29d0625aba2 lib-byte-tools.json byteorder-053b23b67dfafe8f run-build-script-build-script-build.json byteorder-1badf2adb64bb098 lib-byteorder.json cfg-if-c584dedd36299098 lib-cfg-if.json digest-9ac80aa81882ca27 lib-digest.json fake-simd-6221478413a2cba4 lib-fake-simd.json generic-array-817cb308601c1091 lib-generic_array.json indexmap-69a15b2097676677 run-build-script-build-script-build.json indexmap-bf1601e153a24cb9 lib-indexmap.json itoa-f19bf30b106e9b40 lib-itoa.json keccak-0086333c30480325 lib-keccak.json memory_units-27e0e587b68d7c45 lib-memory_units.json near-runtime-fees-18a75178e9e46d7c lib-near-runtime-fees.json near-sdk-dc9a0b1b10a8aa8d lib-near-sdk.json near-vm-errors-e8692cf939aeb940 lib-near-vm-errors.json near-vm-logic-236eae948a163b5c lib-near-vm-logic.json num-bigint-74e941225119dd3e run-build-script-build-script-build.json num-bigint-d45df50dfbb2f623 lib-num-bigint.json num-integer-3a7e02ba1528b3e8 run-build-script-build-script-build.json num-integer-4d1b0f1b4ed37f57 lib-num-integer.json num-rational-83e7350f43756970 lib-num-rational.json num-rational-97a7091ccaa9e3f3 run-build-script-build-script-build.json num-traits-634f4cbb2d12d7d3 run-build-script-build-script-build.json num-traits-9fab5c6442ec7b34 lib-num-traits.json opaque-debug-eaee80d8abde5adb lib-opaque-debug.json ryu-536c1567c54065ad lib-ryu.json ryu-657734b1bec3a27a run-build-script-build-script-build.json serde-05020a58fe2b931f lib-serde.json serde-80e82fd36825a156 run-build-script-build-script-build.json serde_json-6fc90033f55778fc lib-serde_json.json sha2-47e644caa8eae04e lib-sha2.json sha3-2edb6d86e0d6ea33 lib-sha3.json typenum-5cc8489bd46891c9 lib-typenum.json typenum-ea2a545269b43c9c run-build-script-build-script-main.json wee_alloc-00e716713f840121 run-build-script-build-script-build.json wee_alloc-a092d5dfc34124a6 lib-wee_alloc.json build typenum-ea2a545269b43c9c out consts.rs op.rs wee_alloc-00e716713f840121 out wee_alloc_static_array_backend_size_bytes.txt test.sh win build.bat build_for_real.bat call.bat deploy.bat draw_art.bat test.bat
Fix and update by Dang Nguyen 97 # Berry Club Bot Workshop This is a workshop to cover basics of NEAR Protocol smart-contracts written in Rust. ## Support * Telegram: [https://t.me/neardev](https://t.me/neardev) * Discord [https://near.chat](https://near.chat) * Docs: [https://docs.near.org/](https://docs.near.org/) ## Preparation ### Install required tools NOTE: This process is for Unix-like system, e.g. Linux or Mac OS. Windows installation process is different and covered in [`README_Windows.md`](./README_Windows.md). #### Install [Rustup](https://rustup.rs/): ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source ~/.cargo/env ``` #### Add wasm target to your toolchain: ```bash rustup target add wasm32-unknown-unknown ``` #### Install `near-cli` See [`near-cli` installation docs](https://docs.near.org/docs/development/near-cli#installation) #### Install `git` See [installation guide](https://github.com/git-guides/install-git) from github. ### Prepare workshop repo and verify tools installation #### Clone the workshop repository ```bash git clone https://github.com/evgenykuzyakov/workshop cd workshop ``` It should clone the repository to a local folder `workshop`. #### Compile the contract ```bash ./build.sh ``` If you have successfully installed Rust and `wasm32` target, then `./build.sh` should compile the contract into `res/berry_bot.wasm`. ``` Compiling autocfg v1.0.0 Compiling proc-macro2 v1.0.9 Compiling unicode-xid v0.2.0 ... Compiling near-vm-logic v2.0.0 Compiling near-sdk v2.0.0 Compiling berry-bot v0.1.0 (workshop) Finished release [optimized] target(s) in 43.13s ``` #### You can check that the contract is present in `res/berry_bot.wasm` ```bash test res/berry_bot.wasm && echo "OK" || echo "BAD :(" ``` I hope you see `OK` ### Setup NEAR account #### Register a new account on testnet. You can create a new account using [NEAR Testnet Wallet](https://wallet.testnet.near.org/) It'll create a new account for you on the NEAR Testnet. The full account ID will be something like `alice.testnet` As a `Security Method` for this workshop I'd recommend to use either `Recovery Phrase` or `Email Recovery`. #### Authorize your account with `near-cli` To allow using your account with `near-cli` you need to login from the terminal. ```bash near login ``` This should open a new browser tab in the NEAR Testnet web-wallet and ask you give `full access` to your account. It's fine to do, since we're talking about Testnet account. You'll need access from command line and `near-cli` for this workshop. Once you authorized it in the browser, the command line should automatically succeed. You should see something like this in the console: ``` Logged in as [ alice.testnet ] with public key [ ed25519:HP3oxy... ] successfully ``` #### Store your account ID into local variable To help with this workshop let's store your account ID into `ACCOUNT_ID` variable in bash. Replace `<YOUR_ACCOUNT_ID>` with your actual account ID that you created in the wallet, e.g. `alice.testnet`. ```bash export ACCOUNT_ID=<YOUR_ACCOUNT_ID> ``` #### Verification Let's verify that you've successfully created the account and added it to `near-cli`. Run the following: ```bash near call --accountId=$ACCOUNT_ID workshop.testnet hello ``` If it succeeded then you've successfully completed your account setup. You should see something like this: ``` Scheduling a call: workshop.testnet.hello() Receipt: 5rKUqv4t9JVQryvyfrgrFr8R48iV4sFX7nD56KUv6Vhb Log [workshop.testnet]: Hello, test-12331.testnet! Transaction Id 8D2L4AdhbZ3CqWXMpRURsyqUTNJaBJDcFQsN4W8vU4y7 To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/8D2L4AdhbZ3CqWXMpRURsyqUTNJaBJDcFQsN4W8vU4y7 'Hello, test-12331.testnet!' ``` **Congrats!** ## Part 1 - Fix my code Guess what, I made a bunch of errors in the implementation and you need to fix them. Good thing, that I've added unit tests before I broke the code. Run unit tests ```bash ./test.sh ``` You'll see a failed test. E.g. ``` running 1 test test rect::tests::test_rect_complex ... FAILED failures: ---- rect::tests::test_rect_complex stdout ---- 00 .................................................. 01 .................................................. 02 .................................................. 03 .....XXXX......................................... 04 .....XXXX......................................... 05 .....XXXX......................................... 06 .....XXXX......................................... 07 .................................................. 08 .................................................. 09 .................................................. 10 .................................................. 11 .................................................. 12 .................................................. 13 .................................................. 14 .................................................. 15 .................................................. 16 .................................................. 17 .................................................. 18 .................................................. 19 .................................................. 20 .................................................. 21 .................................................. 22 .................................................. 23 .................................................. 24 .................................................. 25 .................................................. 26 .................................................. 27 .................................................. 28 .................................................. 29 .................................................. 30 .................................................. 31 .................................................. 32 .................................................. 33 .................................................. 34 .................................................. 35 .................................................. 36 .................................................. 37 .................................................. 38 .................................................. 39 .................................................. 40 .................................................. 41 .................................................. 42 .................................................. 43 .................................................. 44 .................................................. 45 .................................................. 46 .................................................. 47 .................................................. 48 .................................................. 49 .................................................. thread 'rect::tests::test_rect_complex' panicked at 'assertion failed: `(left == right)` left: `".....XXXX......"`, right: `"..............."`: Line 3', src/rect.rs:90:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` It means the test `test_rect_complex` has failed and the assert at file `src/rect.rs` line `90` failed. Open the file and try to figure out what went wrong. Once you figured out what is wrong, try rerunning tests. Repeat the process of fixing the implementation (not tests) to resolve all bugs. Once all unit tests are fixed, you're ready to move to the part 2. ## Part 2 - Let's draw In this part you'll need to implement a new method that will draw something complex. To do this, you can use rectangle and circle primitives and later merge them into one image. Run ```bash ./draw_art.sh ``` You should see a preview of the art. Right now it renders a target with three circles. ``` 00 .................................................. 01 .................................................. 02 .................................................. 03 .................................................. 04 .................................................. 05 .................XXXXXXX.......................... 06 ..............XXX.......XXX....................... 07 ............XX.............XX..................... 08 ...........X.................X.................... 09 ..........X...................X................... 10 .........X.......XXXXXXX.......X.................. 11 ........X......XXX.....XXX......X................. 12 .......X......X...........X......X................ 13 .......X.....X.............X.....X................ 14 ......X.....X...............X.....X............... 15 ......X....X......XXXXX......X....X............... 16 ......X....X.....XX...XX.....X....X............... 17 .....X....XX....X.......X....XX....X.............. 18 .....X....X....XX.......XX....X....X.............. 19 .....X....X....X.........X....X....X.............. 20 .....X....X....X.........X....X....X.............. 21 .....X....X....X.........X....X....X.............. 22 .....X....X....XX.......XX....X....X.............. 23 .....X....XX....X.......X....XX....X.............. 24 ......X....X.....XX...XX.....X....X............... 25 ......X....X......XXXXX......X....X............... 26 ......X.....X...............X.....X............... 27 .......X.....X.............X.....X................ 28 .......X......X...........X......X................ 29 ........X......XXX.....XXX......X................. 30 .........X.......XXXXXXX.......X.................. 31 ..........X...................X................... 32 ...........X.................X.................... 33 ............XX.............XX..................... 34 ..............XXX.......XXX....................... 35 .................XXXXXXX.......................... 36 .................................................. 37 .................................................. 38 .................................................. 39 .................................................. 40 .................................................. 41 .................................................. 42 .................................................. 43 .................................................. 44 .................................................. 45 .................................................. 46 .................................................. 47 .................................................. 48 .................................................. 49 .................................................. test art::tests::draw_art ... ok ``` Now, open file `src/art.rs` and modify the implementation of method `internal_render_art` at line `26`. You can draw whatever you want and debug it using `./draw_art.sh`. But note, that too many pixels might lead to performance issues. Once you are satisfied with your art preview, it's time to try it for real. ## Part 3 - Deploy to testnet ### Recompile the contract You've modified the code to fix tests and implemented your art, so we need to rebuild. ```bash ./build.sh ``` Every time you modify code of your contract you may want to recompile the contract. The resulting binary is be located at `res/berry_bot.wasm` ### Deploying the contract Accounts in NEAR Protocol can also contain one contract. The contract has full access to the account it belongs. But a new transaction can only be initiated by signing this transaction with an access key (this stops Skynet and singularity). A transaction may call a method on the contract by name and pass arguments. To deploy a contract, we need to issue a transaction. I wrote a convenient script to deploy the contract to your account stored in `$ACCOUNT_ID`. (All it does is `near deploy $ACCOUNT_ID res/berry_bot.wasm`) ```bash ./deploy.sh ``` You should see something like this: ``` Starting deployment. Account id: test-12331.testnet, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: res/berry_bot.wasm Transaction Id 7jxk9ANig8wJ1BqFennJN4pSuVaMn9n3HjaeKfDYfsDY To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/7jxk9ANig8wJ1BqFennJN4pSuVaMn9n3HjaeKfDYfsDY Done deploying to test-12331.testnet ``` NOTE: You can re-deploy your contract multiple times, so long as you have access key on the account. Every time you've modified the code and want to change the contract on-chain you need to recompile and redeploy. ### Call the contract To call `<METHOD_NAME>` on your contract with arguments `<ARGS>` issue the following command: ```bash near call $ACCOUNT_ID --accountId=$ACCOUNT_ID --gas=300000000000000 <METHOD_NAME> <ARGS> ``` * `<METHOD_NAME>` is a public method name that you want to call from the contract * `<ARGS>` are JSON encoded arguments to the method, e.g. `'{"left": 10, "top": 20, "width": 10, "height": 5, "color": 16711680}'` Since bash needs to keep JSON in one string, we recommend to wrap args with `'` when passing it, e.g. `'{}'` For example to draw you art, you need to call the following: ```bash near call $ACCOUNT_ID --accountId=$ACCOUNT_ID --gas=300000000000000 render_art '{}' ``` If everything works well, then you should see your art rendered in logs, e.g.: ``` Scheduling a call: test-12331.testnet.render_art({}) Receipts: B3odJ16wnajwsrUbw2PVZyY2QDCbwFJsTAXvsWTaGGZV, 7FMyKSgszNgGhCBYv7Sg7jVS2b2LzTJ4w8e9T1fTEDWV Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................XXXXXXX.......................... Log [test-12331.testnet]: ..............XXX.......XXX....................... Log [test-12331.testnet]: ............XX.............XX..................... Log [test-12331.testnet]: ...........X.................X.................... Log [test-12331.testnet]: ..........X...................X................... Log [test-12331.testnet]: .........X.......XXXXXXX.......X.................. Log [test-12331.testnet]: ........X......XXX.....XXX......X................. Log [test-12331.testnet]: .......X......X...........X......X................ Log [test-12331.testnet]: .......X.....X.............X.....X................ Log [test-12331.testnet]: ......X.....X...............X.....X............... Log [test-12331.testnet]: ......X....X......XXXXX......X....X............... Log [test-12331.testnet]: ......X....X.....XX...XX.....X....X............... Log [test-12331.testnet]: .....X....XX....X.......X....XX....X.............. Log [test-12331.testnet]: .....X....X....XX.......XX....X....X.............. Log [test-12331.testnet]: .....X....X....X.........X....X....X.............. Log [test-12331.testnet]: .....X....X....X.........X....X....X.............. Log [test-12331.testnet]: .....X....X....X.........X....X....X.............. Log [test-12331.testnet]: .....X....X....XX.......XX....X....X.............. Log [test-12331.testnet]: .....X....XX....X.......X....XX....X.............. Log [test-12331.testnet]: ......X....X.....XX...XX.....X....X............... Log [test-12331.testnet]: ......X....X......XXXXX......X....X............... Log [test-12331.testnet]: ......X.....X...............X.....X............... Log [test-12331.testnet]: .......X.....X.............X.....X................ Log [test-12331.testnet]: .......X......X...........X......X................ Log [test-12331.testnet]: ........X......XXX.....XXX......X................. Log [test-12331.testnet]: .........X.......XXXXXXX.......X.................. Log [test-12331.testnet]: ..........X...................X................... Log [test-12331.testnet]: ...........X.................X.................... Log [test-12331.testnet]: ............XX.............XX..................... Log [test-12331.testnet]: ..............XXX.......XXX....................... Log [test-12331.testnet]: .................XXXXXXX.......................... Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Log [test-12331.testnet]: .................................................. Transaction Id ZWv4Ac2Qqvs8cA1CT1AHE6ovNXUGT7SCuLiDQFmSqv3 To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/ZWv4Ac2Qqvs8cA1CT1AHE6ovNXUGT7SCuLiDQFmSqv3 '' ``` You can also click the explorer link to see this on chain, e.g [Target](https://explorer.testnet.near.org/transactions/ZWv4Ac2Qqvs8cA1CT1AHE6ovNXUGT7SCuLiDQFmSqv3) There is a helper script that let you call methods on your contract easier `./call.sh`. ```bash ./call.sh <METHOD_NAME> <ARGS> ``` An example of a command to render a red rectangle ```bash ./call.sh render_rect '{"left": 10, "top": 20, "width": 10, "height": 5, "color": 16711680}' ``` Or to render your art ```bash ./call.sh render_art '{}' ``` ## Part 4 - Test in Prod If you were able to see your art in the explorer, you've already made the history on Testnet. It's now persistent on chain. The next step is to use it with the real app. ### Build for real Your current contract doesn't actually issue cross-contract calls to berry club, so you need to re-compile it with a compilation feature. ```bash ./build_for_real.sh ``` Now redeploy your contract ```bash ./deploy.sh ``` Game on. ### Buy some 🥑 The first thing we'll need is to buy some avocados to draw in the berry club. Your contract has a helper method `buy_avocado` to do this. ```bash ./call.sh buy_avocado '{}' ``` You should see a log message like this: ``` Log [test-12331.testnet]: Purchased 15001.500 Avocado tokens for 50.000 NEAR ``` `50 NEAR` is enough to get you `15000` 🥑 and this is enough to draw `15000` pixels. ### Open Berry Club on the Testnet [test.berryclub.io](https://test.berryclub.io) You should see a board. It might be messy, because everyone shares the same board. You can login with your testnet account using web-wallet. This will display your name and your avocado balance. Keep this tab open. ### Let's render your art ```bash ./call.sh render_art '{}' ``` You should see it rendered on the board in the browser. You should also see your account ID in the list on the right. If you hover over your account ID in the list, it will highlight your pixels. ### Iterate Now try drawing other primitives by using `./call.sh` Remember, if you modify the code, then you need to recompile and redeploy the contract. Enjoy!
AncaWebDev_NearResources
README.md contract Cargo.toml build.bat build.sh src lib.rs models.rs utils.rs target .rustc_info.json debug .fingerprint Inflector-c436f7f0ac4cac71 lib-inflector.json ahash-3ca249c075ff40fa build-script-build-script-build.json ahash-6be43b08f7829411 lib-ahash.json ahash-9f755501bff2d7f3 lib-ahash.json ahash-de49f4b5450b1065 run-build-script-build-script-build.json aho-corasick-bd486f8f47a9c700 lib-aho_corasick.json arrayref-bac72455fb2a8394 lib-arrayref.json arrayvec-aed08be5fb00987a lib-arrayvec.json arrayvec-c00d75366f0ad0e1 lib-arrayvec.json autocfg-8f6f992da8b6439e lib-autocfg.json base64-63fa1d9b157223de lib-base64.json base64-d0d7040c192b07cf lib-base64.json bitvec-993288ca2ec0bb75 lib-bitvec.json blake2-c7606a87b3288b57 lib-blake2.json block-buffer-352012584a3dc04a lib-block-buffer.json block-padding-eda545815dc84a62 lib-block-padding.json borsh-1cd4d2fde8946ed0 lib-borsh.json borsh-b4c3900b53fda9a8 lib-borsh.json borsh-derive-59b17e8e637c9d51 lib-borsh-derive.json borsh-derive-a6be663c719512bd lib-borsh-derive.json borsh-derive-internal-2cacbbf9adb92e80 lib-borsh-derive-internal.json borsh-derive-internal-db40e6714cd98f97 lib-borsh-derive-internal.json borsh-schema-derive-internal-063fb86386f8af09 lib-borsh-schema-derive-internal.json borsh-schema-derive-internal-9be2590f2069d5bf lib-borsh-schema-derive-internal.json bs58-1801d0e23fc90040 lib-bs58.json byte-slice-cast-b67ebdc846990284 lib-byte-slice-cast.json byteorder-05f1bf91f5cd7369 lib-byteorder.json byteorder-6f81471ce5763f88 lib-byteorder.json bytesize-722c024f2b32b9df lib-bytesize.json c2-chacha-6d70368dd3c64b15 lib-c2-chacha.json cc-54e8cca63c475679 lib-cc.json cfg-if-2079fcd564b2b5d6 lib-cfg-if.json cfg-if-7e74d31581507915 lib-cfg-if.json chrono-e504f39f1c31df28 lib-chrono.json cipher-0024bd5dba7948c1 lib-cipher.json convert_case-6aefe2f3d987d223 lib-convert_case.json cpufeatures-6becbfb968b15950 lib-cpufeatures.json crunchy-128eaf845b31747e run-build-script-build-script-build.json crunchy-991842f243804516 lib-crunchy.json crunchy-aa8111c089e459a8 build-script-build-script-build.json crypto-mac-92fb8a13f34f5e0f lib-crypto-mac.json curve25519-dalek-66bec20eb87557c1 lib-curve25519-dalek.json derive_more-9b93f7e4005d31c1 lib-derive_more.json digest-f97ea15c3fa55aad lib-digest.json easy-ext-d9786f713d8ee29f lib-easy-ext.json ed25519-daf065800a8df291 lib-ed25519.json ed25519-dalek-07a4c05d062c34be lib-ed25519-dalek.json fixed-hash-728527e3035f9345 lib-fixed-hash.json form_urlencoded-5ecc48fff589f16c lib-form_urlencoded.json funty-16f254d755ac153a lib-funty.json generic-array-13d383fe19cd14c1 build-script-build-script-build.json generic-array-402d805d9e6f4512 run-build-script-build-script-build.json generic-array-c416dfb4c61cd3c9 lib-generic_array.json getrandom-332c1073ae61e48b lib-getrandom.json getrandom-73e7aa3655b4dfdc lib-getrandom.json getrandom-b7be7020457d64bc build-script-build-script-build.json getrandom-daff043dae6ed538 run-build-script-build-script-build.json hashbrown-3ac20ce16539a84d lib-hashbrown.json hashbrown-4529697c30aea89c lib-hashbrown.json hashbrown-cc0873b95a3962ff lib-hashbrown.json hex-f285e0a400276b11 lib-hex.json idna-dd35388b806392d7 lib-idna.json impl-codec-b188cb3c22bfb033 lib-impl-codec.json impl-trait-for-tuples-9bb4dd833514c2f2 lib-impl-trait-for-tuples.json indexmap-0a9ef522bbba19a4 run-build-script-build-script-build.json indexmap-2acd3fc8fa5d7820 build-script-build-script-build.json indexmap-718a207fbea377ad lib-indexmap.json itoa-de9eca8b84305685 lib-itoa.json keccak-1e0e12c090d36ea1 lib-keccak.json lazy_static-13a7b4f24d55cf9a lib-lazy_static.json libc-133bddfc2fcfb775 run-build-script-build-script-build.json libc-308b1cec4310fc7d run-build-script-build-script-build.json libc-5f1d2576916917e2 build-script-build-script-build.json libc-6d47f7d50ef71faf lib-libc.json libc-89f1ac18432c8e14 build-script-build-script-build.json libc-d85ff30af4a50914 lib-libc.json matches-7b1c271b0103ce23 lib-matches.json memchr-7874de389e22e218 lib-memchr.json memchr-a201cd490254d922 run-build-script-build-script-build.json memchr-c3ebe4d322f0e647 build-script-build-script-build.json memory_units-50d579d213a1cb67 lib-memory_units.json near-account-id-36f5e54992c52bb6 lib-near-account-id.json near-crypto-254b016d74e80b2c lib-near-crypto.json near-primitives-core-b0d102c4e9109375 lib-near-primitives-core.json near-primitives-core-dbcb177a8afcb623 lib-near-primitives-core.json near-primitives-ec1a5ff3358860ad lib-near-primitives.json near-resources-1139701f9270573c test-lib-near-resources.json near-resources-256eaac194143526 test-lib-near-resources.json near-resources-e4fd25eda884c5b1 lib-near-resources.json near-rpc-error-core-20fdab0f8200424a lib-near-rpc-error-core.json near-rpc-error-core-b1789b765e8f8fdc lib-near-rpc-error-core.json near-rpc-error-macro-07156fe8ceec9ffc lib-near-rpc-error-macro.json near-rpc-error-macro-9873f213df43b86d lib-near-rpc-error-macro.json near-runtime-utils-c15489b065628b8d lib-near-runtime-utils.json near-sdk-28bc2a91916f2eee lib-near-sdk.json near-sdk-core-882d9f6522bedd5a lib-near-sdk-core.json near-sdk-f6b30c06b6a10e8f lib-near-sdk.json near-sdk-macros-62abbae54bcb2ede lib-near-sdk-macros.json near-sdk-macros-646e50d42de9fe76 lib-near-sdk-macros.json near-sys-1dfb61d87473dd8d lib-near-sys.json near-vm-errors-4749c7cc5d0843bf lib-near-vm-errors.json near-vm-errors-5b4241047371c44b lib-near-vm-errors.json near-vm-logic-12ce9f2aba5edd3f lib-near-vm-logic.json near-vm-logic-a970efbe24a1642e lib-near-vm-logic.json num-bigint-3b7cab2399247391 build-script-build-script-build.json num-bigint-5cd94574fdd45f3e run-build-script-build-script-build.json num-bigint-cf0b048035cd209f lib-num-bigint.json num-integer-0c25348a4954a4b0 lib-num-integer.json num-integer-3b2247b31c3aecf8 run-build-script-build-script-build.json num-integer-a0e3105dffcc3dde build-script-build-script-build.json num-rational-12d836b2f69fc833 build-script-build-script-build.json num-rational-a64359aede749935 lib-num-rational.json num-rational-bf38c5e3bd865d02 run-build-script-build-script-build.json num-rational-ce5de319246e7131 lib-num-rational.json num-traits-36835eb20362574d lib-num-traits.json num-traits-d05bcce64698e647 run-build-script-build-script-build.json num-traits-f77ca2ceffbad669 build-script-build-script-build.json once_cell-85cf7fbbf4776163 lib-once_cell.json opaque-debug-0d82ef37e467c2b8 lib-opaque-debug.json parity-scale-codec-6b2090533f234764 lib-parity-scale-codec.json parity-scale-codec-derive-32cbefb358fc95ff lib-parity-scale-codec-derive.json parity-secp256k1-1cf79e98fc6cdb9d run-build-script-build-script-build.json parity-secp256k1-4a748e93ef961eed lib-secp256k1.json parity-secp256k1-ddc11fe31c308a48 build-script-build-script-build.json percent-encoding-fe8b6cd01de646cc lib-percent-encoding.json ppv-lite86-af0aa57e4bfe14bb lib-ppv-lite86.json primitive-types-76f5e27985d31624 lib-primitive-types.json proc-macro-crate-8c2eb796cd64e4d0 lib-proc-macro-crate.json proc-macro-crate-e5596aebbb3381ef lib-proc-macro-crate.json proc-macro2-7291bf7eee435204 build-script-build-script-build.json proc-macro2-7e35b434889e2fbc run-build-script-build-script-build.json proc-macro2-ee2418dbec756101 lib-proc-macro2.json quote-101ed4dd61507e34 lib-quote.json radium-20b02729ff45726e lib-radium.json radium-ea868e7aa8a315c8 run-build-script-build-script-build.json radium-f6bd0065d634b1f8 build-script-build-script-build.json rand-23194a10b285f06d lib-rand.json rand-f1de898d31bf3c69 lib-rand.json rand_chacha-944b3dd22b93da7f lib-rand_chacha.json rand_chacha-ba74cf216790845e lib-rand_chacha.json rand_core-6d6a10f57adb54c6 lib-rand_core.json rand_core-f9e3a48f016aa976 lib-rand_core.json reed-solomon-erasure-53055abcae501862 build-script-build-script-build.json reed-solomon-erasure-9f58b8423a893cc3 run-build-script-build-script-build.json reed-solomon-erasure-edd3d237b3f2d8c0 lib-reed-solomon-erasure.json regex-316ffd98bb8735ce lib-regex.json regex-syntax-55c532d7f6596a1e lib-regex-syntax.json ripemd160-8b841d77fa29e30f lib-ripemd160.json rustc-hex-8dd753eddefe3572 lib-rustc-hex.json ryu-52b84e8d03c8c45c lib-ryu.json serde-1eb1a1571907f472 build-script-build-script-build.json serde-4c138022e7f259ab run-build-script-build-script-build.json serde-58a76426637c9167 lib-serde.json serde-7108713fe6650c46 build-script-build-script-build.json serde-a406e9db853edbf0 run-build-script-build-script-build.json serde-f6af7a65bdf3555c lib-serde.json serde_derive-7b10c2427f78aa4a lib-serde_derive.json serde_derive-ab1eb1b837683c79 build-script-build-script-build.json serde_derive-e1992cd1fbde908b run-build-script-build-script-build.json serde_json-0b60a0e76a8594e6 build-script-build-script-build.json serde_json-46094e36ffbc04ce lib-serde_json.json serde_json-6cbd52e45114545e lib-serde_json.json serde_json-7d745c79c9d82faf build-script-build-script-build.json serde_json-7ff21dce083ba23c run-build-script-build-script-build.json serde_json-b765cbc60ad8c976 lib-serde_json.json serde_json-c658efe6e37764e9 run-build-script-build-script-build.json sha2-df83a03bc5293aab lib-sha2.json sha3-290ffbaf6b841cf2 lib-sha3.json signature-0b9d711cc39d1c05 lib-signature.json smallvec-6e607e4b44ac7647 lib-smallvec.json smart-default-31fda560a576462f lib-smart-default.json static_assertions-d1b409b175079532 lib-static_assertions.json subtle-bdda6ecc8dd6d12c lib-subtle.json syn-5047e226435ddef0 lib-syn.json syn-a2e6dc1d550d999e run-build-script-build-script-build.json syn-c998c8ac30099f7a build-script-build-script-build.json synstructure-0d8c64402f7dd7db lib-synstructure.json tap-0cb5338fc51936a1 lib-tap.json thiserror-5707fa37add7066f lib-thiserror.json thiserror-impl-8af9c3ea398e68fc lib-thiserror-impl.json time-b88d1d11aeace232 lib-time.json tinyvec-f21def35c025b370 lib-tinyvec.json tinyvec_macros-f65dc17d4e146bd9 lib-tinyvec_macros.json toml-a2ea202978671b0d lib-toml.json typenum-a1dd6198bef276d8 lib-typenum.json typenum-f3cdf2a7bd3a3e52 build-script-build-script-main.json typenum-f652251080214f38 run-build-script-build-script-main.json uint-52ddf425ffdf10cf lib-uint.json unicode-bidi-a065f09fe93ce46a lib-unicode_bidi.json unicode-normalization-478c9e4665a195d4 lib-unicode-normalization.json unicode-xid-bd66b29b8868e1cc lib-unicode-xid.json url-b590792a3d932085 lib-url.json validator-d1299c2de954cdca lib-validator.json validator_types-b464e1ba6241b6ac lib-validator_types.json version_check-9aa0558631c3a6ad lib-version_check.json wee_alloc-9efbf0ae52da930b lib-wee_alloc.json wee_alloc-b724ac321ae537f6 build-script-build-script-build.json wee_alloc-cd594dea98d095c0 lib-wee_alloc.json wee_alloc-e2cb34bd00ad2611 run-build-script-build-script-build.json wyz-b6a709967d1bae44 lib-wyz.json zeroize-f35b8b96c2718c4a lib-zeroize.json zeroize_derive-5a619af3a9e33c17 lib-zeroize_derive.json build crunchy-128eaf845b31747e out lib.rs num-bigint-5cd94574fdd45f3e out radix_bases.rs parity-secp256k1-1cf79e98fc6cdb9d out flag_check.c reed-solomon-erasure-9f58b8423a893cc3 out table.rs typenum-f652251080214f38 out consts.rs op.rs tests.rs wee_alloc-e2cb34bd00ad2611 out wee_alloc_static_array_backend_size_bytes.txt release .fingerprint Inflector-2da74efad54ec4e9 lib-inflector.json ahash-5fcbd5fdedca49df build-script-build-script-build.json borsh-derive-2aa6b1482b0b1534 lib-borsh-derive.json borsh-derive-internal-d52d872e0a5fc539 lib-borsh-derive-internal.json borsh-schema-derive-internal-d3f099e7975db469 lib-borsh-schema-derive-internal.json near-sdk-macros-bd3b9186e0538760 lib-near-sdk-macros.json proc-macro-crate-cb0a193ba729e3c6 lib-proc-macro-crate.json proc-macro2-28923fa4b5e13c4b run-build-script-build-script-build.json proc-macro2-5c9c89fd4377e7fd lib-proc-macro2.json proc-macro2-de2c5fc02e908ae5 build-script-build-script-build.json quote-25735ae2025c91ea lib-quote.json serde-5eacec62b311cc33 build-script-build-script-build.json serde-9440da4838c8f6fc build-script-build-script-build.json serde-e3de13a1331c6c82 run-build-script-build-script-build.json serde-f59f1e4557062dac lib-serde.json serde_derive-0eb300c6ec37afed build-script-build-script-build.json serde_derive-6abf712a738e42af run-build-script-build-script-build.json serde_derive-9a3673da4a2139c5 lib-serde_derive.json serde_json-879752c2217c3dd6 build-script-build-script-build.json syn-1d236f2ec0494c3d build-script-build-script-build.json syn-6746bc1fd932cafb run-build-script-build-script-build.json syn-862d3911e2c5e9f3 lib-syn.json toml-610310de92c757a4 lib-toml.json unicode-xid-52b256690085ed1a lib-unicode-xid.json version_check-be548d5c336a88df lib-version_check.json wee_alloc-0c0fa5accfc438b3 build-script-build-script-build.json rls .rustc_info.json debug .fingerprint Inflector-c436f7f0ac4cac71 lib-inflector.json ahash-18920e1d19dd3093 lib-ahash.json ahash-1967cc04c22c18c6 lib-ahash.json ahash-3ca249c075ff40fa build-script-build-script-build.json ahash-de49f4b5450b1065 run-build-script-build-script-build.json aho-corasick-de0e276c9032f05b lib-aho_corasick.json arrayref-9ff70625afc675df lib-arrayref.json arrayvec-9a93676e7e74dde2 lib-arrayvec.json arrayvec-a7a36f29ecf7f74b lib-arrayvec.json autocfg-8f6f992da8b6439e lib-autocfg.json base64-71c90ac137df990d lib-base64.json base64-8d0aa40c04140afe lib-base64.json bitvec-1571b6f5d6ba9c93 lib-bitvec.json blake2-09a8b30941c39c8a lib-blake2.json block-buffer-b2b9846559caac65 lib-block-buffer.json block-padding-279c2d138032bc65 lib-block-padding.json borsh-10eef4b48e9a15f9 lib-borsh.json borsh-90aadc368f81c945 lib-borsh.json borsh-cf49aca460a954fb lib-borsh.json borsh-derive-59b17e8e637c9d51 lib-borsh-derive.json borsh-derive-5af25631576e605c lib-borsh-derive.json borsh-derive-a6be663c719512bd lib-borsh-derive.json borsh-derive-internal-2cacbbf9adb92e80 lib-borsh-derive-internal.json borsh-derive-internal-7ff710be071072b9 lib-borsh-derive-internal.json borsh-derive-internal-db40e6714cd98f97 lib-borsh-derive-internal.json borsh-schema-derive-internal-063fb86386f8af09 lib-borsh-schema-derive-internal.json borsh-schema-derive-internal-50afbf7d08dc052f lib-borsh-schema-derive-internal.json borsh-schema-derive-internal-9be2590f2069d5bf lib-borsh-schema-derive-internal.json bs58-69a66f084a652b72 lib-bs58.json byte-slice-cast-5a4569b40012ab92 lib-byte-slice-cast.json byteorder-0dac5eb881eb88e7 lib-byteorder.json byteorder-181adc8e678d3532 lib-byteorder.json bytesize-e0e2337cde54a216 lib-bytesize.json c2-chacha-0e2ef6f672b72eaf lib-c2-chacha.json cc-54e8cca63c475679 lib-cc.json cfg-if-2079fcd564b2b5d6 lib-cfg-if.json cfg-if-3cd7bda968e519ae lib-cfg-if.json cfg-if-d11314982639f912 lib-cfg-if.json chrono-93733ac8aff4dcff lib-chrono.json chrono-b15d07057a0d5c16 lib-chrono.json cipher-5165aee59a4be128 lib-cipher.json contract-6ec69513edb34a48 lib-contract.json contract-b03efea5e0a8dba9 test-lib-contract.json convert_case-6aefe2f3d987d223 lib-convert_case.json cpufeatures-1cdaf062eab5ab43 lib-cpufeatures.json crunchy-128eaf845b31747e run-build-script-build-script-build.json crunchy-948e5ff4fb38e92d lib-crunchy.json crunchy-aa8111c089e459a8 build-script-build-script-build.json crypto-mac-33dc99cab307d393 lib-crypto-mac.json curve25519-dalek-8d500b99b91c6031 lib-curve25519-dalek.json curve25519-dalek-c79c01ae4276c612 lib-curve25519-dalek.json derive_more-9b93f7e4005d31c1 lib-derive_more.json derive_more-e703a12be656558e lib-derive_more.json digest-51931e9e5760974c lib-digest.json easy-ext-d9786f713d8ee29f lib-easy-ext.json ed25519-70e35c468b1ac491 lib-ed25519.json ed25519-dalek-01d59517143d16ac lib-ed25519-dalek.json ed25519-dalek-c6b29ba17b03c140 lib-ed25519-dalek.json fixed-hash-9efa222caf5a0a7a lib-fixed-hash.json form_urlencoded-92467b68507122ad lib-form_urlencoded.json funty-d88be5f152c6a109 lib-funty.json generic-array-13d383fe19cd14c1 build-script-build-script-build.json generic-array-402d805d9e6f4512 run-build-script-build-script-build.json generic-array-61990963c9533961 lib-generic_array.json getrandom-6136961547f8066b lib-getrandom.json getrandom-b7be7020457d64bc build-script-build-script-build.json getrandom-ba81026d6998daa1 lib-getrandom.json getrandom-daff043dae6ed538 run-build-script-build-script-build.json hashbrown-3ac20ce16539a84d lib-hashbrown.json hashbrown-4348655c29ade1fb lib-hashbrown.json hashbrown-62d2794599d0b3a5 lib-hashbrown.json hex-b14a6cc6710b1be9 lib-hex.json idna-e8d97b6a5092afde lib-idna.json impl-codec-2cb02bf79cf36d0d lib-impl-codec.json impl-codec-707665338f38da35 lib-impl-codec.json impl-trait-for-tuples-9bb4dd833514c2f2 lib-impl-trait-for-tuples.json impl-trait-for-tuples-a2aa96203679c6f5 lib-impl-trait-for-tuples.json indexmap-0a9ef522bbba19a4 run-build-script-build-script-build.json indexmap-2acd3fc8fa5d7820 build-script-build-script-build.json indexmap-718a207fbea377ad lib-indexmap.json itoa-19f0d96e674cd7c4 lib-itoa.json itoa-de9eca8b84305685 lib-itoa.json keccak-9486c3b3fabd92f5 lib-keccak.json lazy_static-c4fa5978e157842d lib-lazy_static.json libc-133bddfc2fcfb775 run-build-script-build-script-build.json libc-308b1cec4310fc7d run-build-script-build-script-build.json libc-5f1d2576916917e2 build-script-build-script-build.json libc-89f1ac18432c8e14 build-script-build-script-build.json libc-96bcd27a6ec484c0 lib-libc.json libc-aa16f682bbb86764 lib-libc.json matches-b4b116d12983a8bb lib-matches.json memchr-5c7636a459fee649 lib-memchr.json memchr-a201cd490254d922 run-build-script-build-script-build.json memchr-c3ebe4d322f0e647 build-script-build-script-build.json memory_units-7cdfc6b494713aeb lib-memory_units.json near-account-id-91f0ca14bfb9e33d lib-near-account-id.json near-account-id-cf24eb20f62824a8 lib-near-account-id.json near-crypto-1c40c0a1d3eadefd lib-near-crypto.json near-crypto-7a7bbabab003fe26 lib-near-crypto.json near-primitives-152e783a67c75a47 lib-near-primitives.json near-primitives-570cf5922f853b23 lib-near-primitives.json near-primitives-core-00c54351e793fd6c lib-near-primitives-core.json near-primitives-core-8ab3ce3acd9e9ed4 lib-near-primitives-core.json near-primitives-core-d6e62e97efa996ca lib-near-primitives-core.json near-resources-21f4f885e5aa5124 test-lib-near-resources.json near-resources-53bbdb2e1177c656 test-lib-near-resources.json near-resources-60e8cd093a646d79 test-lib-near-resources.json near-resources-dca10be12a369b59 lib-near-resources.json near-resources-eaf19b6c06357429 lib-near-resources.json near-resources-f9ff8c40d4c5e925 lib-near-resources.json near-rpc-error-core-20fdab0f8200424a lib-near-rpc-error-core.json near-rpc-error-core-56c0321cced74777 lib-near-rpc-error-core.json near-rpc-error-core-b1789b765e8f8fdc lib-near-rpc-error-core.json near-rpc-error-macro-07156fe8ceec9ffc lib-near-rpc-error-macro.json near-rpc-error-macro-35f129335fc43710 lib-near-rpc-error-macro.json near-rpc-error-macro-9873f213df43b86d lib-near-rpc-error-macro.json near-runtime-utils-565ee7954b02df12 lib-near-runtime-utils.json near-sdk-056d5426c632f130 lib-near-sdk.json near-sdk-2f9b9ef734de63a9 lib-near-sdk.json near-sdk-3d3a9e705ea29501 lib-near-sdk.json near-sdk-core-882d9f6522bedd5a lib-near-sdk-core.json near-sdk-macros-62abbae54bcb2ede lib-near-sdk-macros.json near-sdk-macros-646e50d42de9fe76 lib-near-sdk-macros.json near-sdk-macros-af244d1593211def lib-near-sdk-macros.json near-sys-f94c1dc338f814fe lib-near-sys.json near-vm-errors-8efd424335786987 lib-near-vm-errors.json near-vm-errors-9cab23522b12b88f lib-near-vm-errors.json near-vm-errors-ea50ca2ec771bef1 lib-near-vm-errors.json near-vm-logic-39b1db595586fe9f lib-near-vm-logic.json near-vm-logic-4df66e7cfecd4c11 lib-near-vm-logic.json near-vm-logic-effd2aa06d718ae7 lib-near-vm-logic.json num-bigint-3b7cab2399247391 build-script-build-script-build.json num-bigint-5cd94574fdd45f3e run-build-script-build-script-build.json num-bigint-64f5b33455e0ceb9 lib-num-bigint.json num-integer-3b2247b31c3aecf8 run-build-script-build-script-build.json num-integer-723477fb82d49b8d lib-num-integer.json num-integer-a0e3105dffcc3dde build-script-build-script-build.json num-rational-12084f6b0cdfee80 lib-num-rational.json num-rational-12d836b2f69fc833 build-script-build-script-build.json num-rational-4f7dc50422428536 lib-num-rational.json num-rational-8da92991a3968f0b lib-num-rational.json num-rational-bf38c5e3bd865d02 run-build-script-build-script-build.json num-traits-155401f7582e1709 lib-num-traits.json num-traits-d05bcce64698e647 run-build-script-build-script-build.json num-traits-f77ca2ceffbad669 build-script-build-script-build.json once_cell-ee4f0202d721af68 lib-once_cell.json opaque-debug-9f33558de634ada2 lib-opaque-debug.json parity-scale-codec-76a448241c818ed1 lib-parity-scale-codec.json parity-scale-codec-8d829f3566e98e8f lib-parity-scale-codec.json parity-scale-codec-derive-32cbefb358fc95ff lib-parity-scale-codec-derive.json parity-scale-codec-derive-4348465b6378b495 lib-parity-scale-codec-derive.json parity-secp256k1-1cf79e98fc6cdb9d run-build-script-build-script-build.json parity-secp256k1-23fd51b20697957a lib-secp256k1.json parity-secp256k1-ddc11fe31c308a48 build-script-build-script-build.json percent-encoding-8abb535346780936 lib-percent-encoding.json ppv-lite86-7e89c859113ac408 lib-ppv-lite86.json primitive-types-6e98be12dc3ba0ea lib-primitive-types.json primitive-types-bd700f2e7674e38a lib-primitive-types.json proc-macro-crate-8947a3ee5b53b5d2 lib-proc-macro-crate.json proc-macro-crate-8c2eb796cd64e4d0 lib-proc-macro-crate.json proc-macro-crate-d66d5eb94f9a32fd lib-proc-macro-crate.json proc-macro-crate-e5596aebbb3381ef lib-proc-macro-crate.json proc-macro2-7291bf7eee435204 build-script-build-script-build.json proc-macro2-7e35b434889e2fbc run-build-script-build-script-build.json proc-macro2-ee2418dbec756101 lib-proc-macro2.json quote-101ed4dd61507e34 lib-quote.json radium-9c50abd1de38fffd lib-radium.json radium-ea868e7aa8a315c8 run-build-script-build-script-build.json radium-f6bd0065d634b1f8 build-script-build-script-build.json rand-127c761edf7710b0 lib-rand.json rand-4bec1bd680d4323d lib-rand.json rand_chacha-a7be93b5e47cbddf lib-rand_chacha.json rand_chacha-c68d0378503a9b14 lib-rand_chacha.json rand_core-9240ddf06410616c lib-rand_core.json rand_core-aa4d1c983ce2b3d5 lib-rand_core.json reed-solomon-erasure-53055abcae501862 build-script-build-script-build.json reed-solomon-erasure-9f58b8423a893cc3 run-build-script-build-script-build.json reed-solomon-erasure-da2a8762ec0e7556 lib-reed-solomon-erasure.json regex-a1c716d4ba625285 lib-regex.json regex-syntax-ef07e97d687779e1 lib-regex-syntax.json ripemd160-8b607ba2ab84db43 lib-ripemd160.json rustc-hex-66f2f8ed693e64da lib-rustc-hex.json ryu-52b84e8d03c8c45c lib-ryu.json ryu-7e3518dd7719de0a lib-ryu.json serde-17d35c349eb22ea1 run-build-script-build-script-build.json serde-1eb1a1571907f472 build-script-build-script-build.json serde-20b5b752e301274a lib-serde.json serde-4c138022e7f259ab run-build-script-build-script-build.json serde-5fdca74b85cda1ac build-script-build-script-build.json serde-6c04745bc3df23b9 lib-serde.json serde-7108713fe6650c46 build-script-build-script-build.json serde-989c70e05e4538fa build-script-build-script-build.json serde-a406e9db853edbf0 run-build-script-build-script-build.json serde-aac014efeb55a21e lib-serde.json serde-ddc1f6be8aa40e33 lib-serde.json serde-f6af7a65bdf3555c lib-serde.json serde-f89479eb21bbbd02 run-build-script-build-script-build.json serde_derive-7a793a86acae7821 build-script-build-script-build.json serde_derive-7b10c2427f78aa4a lib-serde_derive.json serde_derive-a3d3bc16e2bdb5f6 run-build-script-build-script-build.json serde_derive-ab1eb1b837683c79 build-script-build-script-build.json serde_derive-dcd661941d0f172d lib-serde_derive.json serde_derive-e1992cd1fbde908b run-build-script-build-script-build.json serde_json-0670ee89b39f2cba lib-serde_json.json serde_json-0b60a0e76a8594e6 build-script-build-script-build.json serde_json-4c5bbf314a999863 lib-serde_json.json serde_json-5001548da1054dfa lib-serde_json.json serde_json-7d745c79c9d82faf build-script-build-script-build.json serde_json-7ff21dce083ba23c run-build-script-build-script-build.json serde_json-b765cbc60ad8c976 lib-serde_json.json serde_json-b8000eb66f0f55c7 lib-serde_json.json serde_json-c658efe6e37764e9 run-build-script-build-script-build.json sha2-bf632ea53973549a lib-sha2.json sha3-8142806e64ea8035 lib-sha3.json signature-7cbbc05230c5ea31 lib-signature.json smallvec-609dbab9de444c56 lib-smallvec.json smart-default-2056d5a3370653ce lib-smart-default.json smart-default-31fda560a576462f lib-smart-default.json static_assertions-dd54fb0273d93db0 lib-static_assertions.json subtle-61882c839f9dbc45 lib-subtle.json syn-1637a4db13f5302c lib-syn.json syn-5047e226435ddef0 lib-syn.json syn-a2e6dc1d550d999e run-build-script-build-script-build.json syn-b685f69720067a20 run-build-script-build-script-build.json syn-c998c8ac30099f7a build-script-build-script-build.json syn-f3ac0df9819c00c1 build-script-build-script-build.json synstructure-0d8c64402f7dd7db lib-synstructure.json synstructure-2a60a8456be80738 lib-synstructure.json tap-b7448b916338aab6 lib-tap.json thiserror-0ab607933531a99e lib-thiserror.json thiserror-5707fa37add7066f lib-thiserror.json thiserror-e921418121266970 lib-thiserror.json thiserror-f9c4c230e6ed0076 lib-thiserror.json thiserror-impl-23daa48bb442ce60 lib-thiserror-impl.json thiserror-impl-8af9c3ea398e68fc lib-thiserror-impl.json time-ef2890efc0db348b lib-time.json tinyvec-44c9bb1071122b81 lib-tinyvec.json tinyvec_macros-0ae3feeb268d9e8d lib-tinyvec_macros.json toml-47093ddb94ccf7b7 lib-toml.json toml-a2ea202978671b0d lib-toml.json typenum-eba9811536b7659f lib-typenum.json typenum-f3cdf2a7bd3a3e52 build-script-build-script-main.json typenum-f652251080214f38 run-build-script-build-script-main.json uint-d6ab972fc8d1db86 lib-uint.json unicode-bidi-0ee8739504c6a136 lib-unicode_bidi.json unicode-normalization-2662e62d1adb082c lib-unicode-normalization.json unicode-xid-bd66b29b8868e1cc lib-unicode-xid.json url-c2013a46c86f7f93 lib-url.json validator-3acdb41a8cb45610 lib-validator.json validator-e4941d73a18a3745 lib-validator.json validator_types-89545ba088367af8 lib-validator_types.json version_check-9aa0558631c3a6ad lib-version_check.json wee_alloc-2d9978e9906ae984 lib-wee_alloc.json wee_alloc-aeb965ea9678533f lib-wee_alloc.json wee_alloc-b724ac321ae537f6 build-script-build-script-build.json wee_alloc-e2cb34bd00ad2611 run-build-script-build-script-build.json wyz-b35a16f4edc725c4 lib-wyz.json zeroize-037b382f976e71b1 lib-zeroize.json zeroize-456b1255ebf2182d lib-zeroize.json zeroize_derive-519fdca77dda202e lib-zeroize_derive.json zeroize_derive-5a619af3a9e33c17 lib-zeroize_derive.json build ahash-3ca249c075ff40fa save-analysis build_script_build-3ca249c075ff40fa.json crunchy-128eaf845b31747e out lib.rs crunchy-aa8111c089e459a8 save-analysis build_script_build-aa8111c089e459a8.json generic-array-13d383fe19cd14c1 save-analysis build_script_build-13d383fe19cd14c1.json getrandom-b7be7020457d64bc save-analysis build_script_build-b7be7020457d64bc.json indexmap-2acd3fc8fa5d7820 save-analysis build_script_build-2acd3fc8fa5d7820.json libc-5f1d2576916917e2 save-analysis build_script_build-5f1d2576916917e2.json libc-89f1ac18432c8e14 save-analysis build_script_build-89f1ac18432c8e14.json memchr-c3ebe4d322f0e647 save-analysis build_script_build-c3ebe4d322f0e647.json num-bigint-3b7cab2399247391 save-analysis build_script_build-3b7cab2399247391.json num-bigint-5cd94574fdd45f3e out radix_bases.rs num-integer-a0e3105dffcc3dde save-analysis build_script_build-a0e3105dffcc3dde.json num-rational-12d836b2f69fc833 save-analysis build_script_build-12d836b2f69fc833.json num-traits-f77ca2ceffbad669 save-analysis build_script_build-f77ca2ceffbad669.json parity-secp256k1-1cf79e98fc6cdb9d out flag_check.c parity-secp256k1-ddc11fe31c308a48 save-analysis build_script_build-ddc11fe31c308a48.json proc-macro2-7291bf7eee435204 save-analysis build_script_build-7291bf7eee435204.json radium-f6bd0065d634b1f8 save-analysis build_script_build-f6bd0065d634b1f8.json reed-solomon-erasure-53055abcae501862 save-analysis build_script_build-53055abcae501862.json reed-solomon-erasure-9f58b8423a893cc3 out table.rs serde-1eb1a1571907f472 save-analysis build_script_build-1eb1a1571907f472.json serde-5fdca74b85cda1ac save-analysis build_script_build-5fdca74b85cda1ac.json serde-7108713fe6650c46 save-analysis build_script_build-7108713fe6650c46.json serde-989c70e05e4538fa save-analysis build_script_build-989c70e05e4538fa.json serde_derive-7a793a86acae7821 save-analysis build_script_build-7a793a86acae7821.json serde_derive-ab1eb1b837683c79 save-analysis build_script_build-ab1eb1b837683c79.json serde_json-0b60a0e76a8594e6 save-analysis build_script_build-0b60a0e76a8594e6.json serde_json-7d745c79c9d82faf save-analysis build_script_build-7d745c79c9d82faf.json syn-c998c8ac30099f7a save-analysis build_script_build-c998c8ac30099f7a.json syn-f3ac0df9819c00c1 save-analysis build_script_build-f3ac0df9819c00c1.json typenum-f3cdf2a7bd3a3e52 save-analysis build_script_main-f3cdf2a7bd3a3e52.json typenum-f652251080214f38 out consts.rs op.rs tests.rs wee_alloc-b724ac321ae537f6 save-analysis build_script_build-b724ac321ae537f6.json wee_alloc-e2cb34bd00ad2611 out wee_alloc_static_array_backend_size_bytes.txt deps save-analysis contract-b03efea5e0a8dba9.json libahash-1967cc04c22c18c6.json libaho_corasick-de0e276c9032f05b.json libarrayref-9ff70625afc675df.json libarrayvec-a7a36f29ecf7f74b.json libautocfg-8f6f992da8b6439e.json libbase64-71c90ac137df990d.json libbase64-8d0aa40c04140afe.json libblake2-09a8b30941c39c8a.json libblock_buffer-b2b9846559caac65.json libblock_padding-279c2d138032bc65.json libborsh-10eef4b48e9a15f9.json libbs58-69a66f084a652b72.json libbyte_slice_cast-5a4569b40012ab92.json libbyteorder-0dac5eb881eb88e7.json libbytesize-e0e2337cde54a216.json libcurve25519_dalek-8d500b99b91c6031.json libderive_more-9b93f7e4005d31c1.json libdigest-51931e9e5760974c.json libeasy_ext-d9786f713d8ee29f.json libed25519-70e35c468b1ac491.json libed25519_dalek-01d59517143d16ac.json libfixed_hash-9efa222caf5a0a7a.json libform_urlencoded-92467b68507122ad.json libfunty-d88be5f152c6a109.json libgeneric_array-61990963c9533961.json libgetrandom-6136961547f8066b.json libgetrandom-ba81026d6998daa1.json libhashbrown-62d2794599d0b3a5.json libhex-b14a6cc6710b1be9.json libimpl_codec-2cb02bf79cf36d0d.json libimpl_trait_for_tuples-9bb4dd833514c2f2.json libindexmap-718a207fbea377ad.json libinflector-c436f7f0ac4cac71.json libitoa-de9eca8b84305685.json libkeccak-9486c3b3fabd92f5.json liblazy_static-c4fa5978e157842d.json libmatches-b4b116d12983a8bb.json libmemchr-5c7636a459fee649.json libmemory_units-7cdfc6b494713aeb.json libnear_account_id-91f0ca14bfb9e33d.json libnear_crypto-7a7bbabab003fe26.json libnear_resources-f9ff8c40d4c5e925.json libnear_rpc_error_core-b1789b765e8f8fdc.json libnear_rpc_error_macro-9873f213df43b86d.json libnear_runtime_utils-565ee7954b02df12.json libnear_sdk-2f9b9ef734de63a9.json libnear_sys-f94c1dc338f814fe.json libnear_vm_errors-9cab23522b12b88f.json libnear_vm_logic-39b1db595586fe9f.json libnum_bigint-64f5b33455e0ceb9.json libnum_integer-723477fb82d49b8d.json libnum_rational-12084f6b0cdfee80.json libonce_cell-ee4f0202d721af68.json libopaque_debug-9f33558de634ada2.json libparity_scale_codec-76a448241c818ed1.json libpercent_encoding-8abb535346780936.json libppv_lite86-7e89c859113ac408.json libprimitive_types-6e98be12dc3ba0ea.json libproc_macro2-ee2418dbec756101.json libproc_macro_crate-8c2eb796cd64e4d0.json libquote-101ed4dd61507e34.json libradium-9c50abd1de38fffd.json librand-127c761edf7710b0.json librand-4bec1bd680d4323d.json libreed_solomon_erasure-da2a8762ec0e7556.json libregex-a1c716d4ba625285.json libripemd160-8b607ba2ab84db43.json librustc_hex-66f2f8ed693e64da.json libryu-52b84e8d03c8c45c.json libsecp256k1-23fd51b20697957a.json libsha2-bf632ea53973549a.json libsha3-8142806e64ea8035.json libsignature-7cbbc05230c5ea31.json libsmallvec-609dbab9de444c56.json libsmart_default-31fda560a576462f.json libstatic_assertions-dd54fb0273d93db0.json libsubtle-61882c839f9dbc45.json libsynstructure-0d8c64402f7dd7db.json libtap-b7448b916338aab6.json libthiserror-5707fa37add7066f.json libthiserror-e921418121266970.json libtime-ef2890efc0db348b.json libtinyvec-44c9bb1071122b81.json libtoml-a2ea202978671b0d.json libuint-d6ab972fc8d1db86.json libunicode_bidi-0ee8739504c6a136.json libunicode_xid-bd66b29b8868e1cc.json liburl-c2013a46c86f7f93.json libvalidator-e4941d73a18a3745.json libversion_check-9aa0558631c3a6ad.json libwee_alloc-aeb965ea9678533f.json libwyz-b35a16f4edc725c4.json libzeroize-037b382f976e71b1.json near_resources-21f4f885e5aa5124.json wasm32-unknown-unknown release .fingerprint ahash-781ca4364ca59a30 lib-ahash.json ahash-f9a8712053e0cb95 run-build-script-build-script-build.json base64-6dd7fa554e4b25ad lib-base64.json borsh-90807a1fefb607e5 lib-borsh.json bs58-02cb14529ea3e405 lib-bs58.json cfg-if-7e4eee7be11dc5c3 lib-cfg-if.json hashbrown-adcc6e1b254d5ad6 lib-hashbrown.json hex-b39bd06acc2b1c4a lib-hex.json itoa-9623879f867ebd76 lib-itoa.json memory_units-105ffb4b05d80382 lib-memory_units.json near-resources-e4fd25eda884c5b1 lib-near-resources.json near-sdk-f25023d6246fa79e lib-near-sdk.json near-sys-e0f5f5862ee08099 lib-near-sys.json once_cell-0916c82eedbc1b7e lib-once_cell.json ryu-448478bdb37e47b0 lib-ryu.json serde-2c149a35770f6a8b run-build-script-build-script-build.json serde-f59916132a86de73 lib-serde.json serde_json-caf805421bcc5165 lib-serde_json.json serde_json-f5c07e32125ec6dd run-build-script-build-script-build.json wee_alloc-959d0e0879cb87ab lib-wee_alloc.json wee_alloc-eee7ea5cef997a34 run-build-script-build-script-build.json build wee_alloc-eee7ea5cef997a34 out wee_alloc_static_array_backend_size_bytes.txt test.sh | |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1038,"byte_end":1133,"line_start":22,"line_end":22,"column_start":1,"column_end":96}},{"value":" | `encode` | Returns a new `String` | Always |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1134,"byte_end":1229,"line_start":23,"line_end":23,"column_start":1,"column_end":96}},{"value":" | `encode_config` | Returns a new `String` | Always |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1230,"byte_end":1325,"line_start":24,"line_end":24,"column_start":1,"column_end":96}},{"value":" | `encode_config_buf` | Appends to provided `String` | Only if `String` needs to grow |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1326,"byte_end":1421,"line_start":25,"line_end":25,"column_start":1,"column_end":96}},{"value":" | `encode_config_slice` | Writes to provided `&[u8]` | Never |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1422,"byte_end":1517,"line_start":26,"line_end":26,"column_start":1,"column_end":96}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1518,"byte_end":1521,"line_start":27,"line_end":27,"column_start":1,"column_end":4}},{"value":" All of the encoding functions that take a `Config` will pad as per the config.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1522,"byte_end":1604,"line_start":28,"line_end":28,"column_start":1,"column_end":83}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1605,"byte_end":1608,"line_start":29,"line_end":29,"column_start":1,"column_end":4}},{"value":" # Decoding","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1609,"byte_end":1623,"line_start":30,"line_end":30,"column_start":1,"column_end":15}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1624,"byte_end":1627,"line_start":31,"line_end":31,"column_start":1,"column_end":4}},{"value":" Just as for encoding, there are different decoding functions available.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1628,"byte_end":1703,"line_start":32,"line_end":32,"column_start":1,"column_end":76}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1704,"byte_end":1707,"line_start":33,"line_end":33,"column_start":1,"column_end":4}},{"value":" | Function | Output | Allocates |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1708,"byte_end":1804,"line_start":34,"line_end":34,"column_start":1,"column_end":97}},{"value":" | base64-0.11.0 src lib.rs","byte_start":1038,"byte_end":1133,"line_start":22,"line_end":22,"column_start":1,"column_end":96}},{"value":" | `encode` | Returns a new `String` | Always |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1134,"byte_end":1229,"line_start":23,"line_end":23,"column_start":1,"column_end":96}},{"value":" | `encode_config` | Returns a new `String` | Always |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1230,"byte_end":1325,"line_start":24,"line_end":24,"column_start":1,"column_end":96}},{"value":" | `encode_config_buf` | Appends to provided `String` | Only if `String` needs to grow |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1326,"byte_end":1421,"line_start":25,"line_end":25,"column_start":1,"column_end":96}},{"value":" | `encode_config_slice` | Writes to provided `&[u8]` | Never |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1422,"byte_end":1517,"line_start":26,"line_end":26,"column_start":1,"column_end":96}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1518,"byte_end":1521,"line_start":27,"line_end":27,"column_start":1,"column_end":4}},{"value":" All of the encoding functions that take a `Config` will pad as per the config.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1522,"byte_end":1604,"line_start":28,"line_end":28,"column_start":1,"column_end":83}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1605,"byte_end":1608,"line_start":29,"line_end":29,"column_start":1,"column_end":4}},{"value":" # Decoding","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1609,"byte_end":1623,"line_start":30,"line_end":30,"column_start":1,"column_end":15}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1624,"byte_end":1627,"line_start":31,"line_end":31,"column_start":1,"column_end":4}},{"value":" Just as for encoding, there are different decoding functions available.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1628,"byte_end":1703,"line_start":32,"line_end":32,"column_start":1,"column_end":76}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1704,"byte_end":1707,"line_start":33,"line_end":33,"column_start":1,"column_end":4}},{"value":" | Function | Output | Allocates |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 base64-0.11.0 src lib.rs","byte_start":1708,"byte_end":1804,"line_start":34,"line_end":34,"column_start":1,"column_end":97}},{"value":" | toml-0.5.9 src datetime.rs","byte_start":53465,"byte_end":53527,"line_start":29,"line_end":29,"column_start":1,"column_end":63}},{"value":" | `Some(_)` | `Some(_)` | `Some(_)` | [Offset Date-Time] |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":53528,"byte_end":53590,"line_start":30,"line_end":30,"column_start":1,"column_end":63}},{"value":" | `Some(_)` | `Some(_)` | `None` | [Local Date-Time] |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":53591,"byte_end":53653,"line_start":31,"line_end":31,"column_start":1,"column_end":63}},{"value":" | `Some(_)` | `None` | `None` | [Local Date] |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":53654,"byte_end":53716,"line_start":32,"line_end":32,"column_start":1,"column_end":63}},{"value":" | `None` | `Some(_)` | `None` | [Local Time] |","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":53717,"byte_end":53779,"line_start":33,"line_end":33,"column_start":1,"column_end":63}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":53780,"byte_end":53783,"line_start":34,"line_end":34,"column_start":1,"column_end":4}},{"value":" **1. Offset Date-Time**: If all the optional values are used, `Datetime`","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":53784,"byte_end":53860,"line_start":35,"line_end":35,"column_start":1,"column_end":77}},{"value":" corresponds to an [Offset Date-Time]. From the TOML v1.0.0 spec:","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":53861,"byte_end":53929,"line_start":36,"line_end":36,"column_start":1,"column_end":69}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":53930,"byte_end":53933,"line_start":37,"line_end":37,"column_start":1,"column_end":4}},{"value":" > To unambiguously represent a specific instant in time, you may use an","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":53934,"byte_end":54009,"line_start":38,"line_end":38,"column_start":1,"column_end":76}},{"value":" > RFC 3339 formatted date-time with offset.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54010,"byte_end":54057,"line_start":39,"line_end":39,"column_start":1,"column_end":48}},{"value":" >","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54058,"byte_end":54063,"line_start":40,"line_end":40,"column_start":1,"column_end":6}},{"value":" > ```toml","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54064,"byte_end":54077,"line_start":41,"line_end":41,"column_start":1,"column_end":14}},{"value":" > odt1 = 1979-05-27T07:32:00Z","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54078,"byte_end":54111,"line_start":42,"line_end":42,"column_start":1,"column_end":34}},{"value":" > odt2 = 1979-05-27T00:32:00-07:00","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54112,"byte_end":54150,"line_start":43,"line_end":43,"column_start":1,"column_end":39}},{"value":" > odt3 = 1979-05-27T00:32:00.999999-07:00","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54151,"byte_end":54196,"line_start":44,"line_end":44,"column_start":1,"column_end":46}},{"value":" > ```","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54197,"byte_end":54206,"line_start":45,"line_end":45,"column_start":1,"column_end":10}},{"value":" >","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54207,"byte_end":54212,"line_start":46,"line_end":46,"column_start":1,"column_end":6}},{"value":" > For the sake of readability, you may replace the T delimiter between date","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54213,"byte_end":54292,"line_start":47,"line_end":47,"column_start":1,"column_end":80}},{"value":" > and time with a space character (as permitted by RFC 3339 section 5.6).","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54293,"byte_end":54370,"line_start":48,"line_end":48,"column_start":1,"column_end":78}},{"value":" >","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54371,"byte_end":54376,"line_start":49,"line_end":49,"column_start":1,"column_end":6}},{"value":" > ```toml","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54377,"byte_end":54390,"line_start":50,"line_end":50,"column_start":1,"column_end":14}},{"value":" > odt4 = 1979-05-27 07:32:00Z","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54391,"byte_end":54424,"line_start":51,"line_end":51,"column_start":1,"column_end":34}},{"value":" > ```","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54425,"byte_end":54434,"line_start":52,"line_end":52,"column_start":1,"column_end":10}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54435,"byte_end":54438,"line_start":53,"line_end":53,"column_start":1,"column_end":4}},{"value":" **2. Local Date-Time**: If `date` and `time` are given but `offset` is","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54439,"byte_end":54513,"line_start":54,"line_end":54,"column_start":1,"column_end":75}},{"value":" `None`, `Datetime` corresponds to a [Local Date-Time]. From the spec:","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54514,"byte_end":54587,"line_start":55,"line_end":55,"column_start":1,"column_end":74}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54588,"byte_end":54591,"line_start":56,"line_end":56,"column_start":1,"column_end":4}},{"value":" > If you omit the offset from an RFC 3339 formatted date-time, it will","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54592,"byte_end":54666,"line_start":57,"line_end":57,"column_start":1,"column_end":75}},{"value":" > represent the given date-time without any relation to an offset or","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54667,"byte_end":54739,"line_start":58,"line_end":58,"column_start":1,"column_end":73}},{"value":" > timezone. It cannot be converted to an instant in time without additional","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54740,"byte_end":54819,"line_start":59,"line_end":59,"column_start":1,"column_end":80}},{"value":" > information. Conversion to an instant, if required, is implementation-","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54820,"byte_end":54896,"line_start":60,"line_end":60,"column_start":1,"column_end":77}},{"value":" > specific.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54897,"byte_end":54912,"line_start":61,"line_end":61,"column_start":1,"column_end":16}},{"value":" >","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54913,"byte_end":54918,"line_start":62,"line_end":62,"column_start":1,"column_end":6}},{"value":" > ```toml","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54919,"byte_end":54932,"line_start":63,"line_end":63,"column_start":1,"column_end":14}},{"value":" > ldt1 = 1979-05-27T07:32:00","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54933,"byte_end":54965,"line_start":64,"line_end":64,"column_start":1,"column_end":33}},{"value":" > ldt2 = 1979-05-27T00:32:00.999999","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":54966,"byte_end":55005,"line_start":65,"line_end":65,"column_start":1,"column_end":40}},{"value":" > ```","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55006,"byte_end":55015,"line_start":66,"line_end":66,"column_start":1,"column_end":10}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55016,"byte_end":55019,"line_start":67,"line_end":67,"column_start":1,"column_end":4}},{"value":" **3. Local Date**: If only `date` is given, `Datetime` corresponds to a","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55020,"byte_end":55095,"line_start":68,"line_end":68,"column_start":1,"column_end":76}},{"value":" [Local Date]; see the docs for [`Date`].","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55096,"byte_end":55140,"line_start":69,"line_end":69,"column_start":1,"column_end":45}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55141,"byte_end":55144,"line_start":70,"line_end":70,"column_start":1,"column_end":4}},{"value":" **4. Local Time**: If only `time` is given, `Datetime` corresponds to a","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55145,"byte_end":55220,"line_start":71,"line_end":71,"column_start":1,"column_end":76}},{"value":" [Local Time]; see the docs for [`Time`].","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55221,"byte_end":55265,"line_start":72,"line_end":72,"column_start":1,"column_end":45}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55266,"byte_end":55269,"line_start":73,"line_end":73,"column_start":1,"column_end":4}},{"value":" [TOML v1.0.0 spec]: https: toml.io en v1.0.0","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55270,"byte_end":55319,"line_start":74,"line_end":74,"column_start":1,"column_end":50}},{"value":" [Offset Date-Time]: https: toml.io en v1.0.0#offset-date-time","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55320,"byte_end":55386,"line_start":75,"line_end":75,"column_start":1,"column_end":67}},{"value":" [Local Date-Time]: https: toml.io en v1.0.0#local-date-time","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55387,"byte_end":55451,"line_start":76,"line_end":76,"column_start":1,"column_end":65}},{"value":" [Local Date]: https: toml.io en v1.0.0#local-date","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55452,"byte_end":55506,"line_start":77,"line_end":77,"column_start":1,"column_end":55}},{"value":" [Local Time]: https: toml.io en v1.0.0#local-time","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55507,"byte_end":55561,"line_start":78,"line_end":78,"column_start":1,"column_end":55}}]},{"kind":"Field","id":{"krate":0,"index":1779},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55718,"byte_end":55722,"line_start":83,"line_end":83,"column_start":9,"column_end":13},"name":"date","qualname":"::datetime::Datetime::date","value":"std::option::Option<datetime::Date>","parent":{"krate":0,"index":1778},"children":[],"decl_id":null,"docs":" Optional date.\n Required for: *Offset Date-Time*, *Local Date-Time*, *Local Date*.\n","sig":null,"attributes":[{"value":" Optional date.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55616,"byte_end":55634,"line_start":81,"line_end":81,"column_start":5,"column_end":23}},{"value":" Required for: *Offset Date-Time*, *Local Date-Time*, *Local Date*.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55639,"byte_end":55709,"line_start":82,"line_end":82,"column_start":5,"column_end":75}}]},{"kind":"Field","id":{"krate":0,"index":1780},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55845,"byte_end":55849,"line_start":87,"line_end":87,"column_start":9,"column_end":13},"name":"time","qualname":"::datetime::Datetime::time","value":"std::option::Option<datetime::Time>","parent":{"krate":0,"index":1778},"children":[],"decl_id":null,"docs":" Optional time.\n Required for: *Offset Date-Time*, *Local Date-Time*, *Local Time*.\n","sig":null,"attributes":[{"value":" Optional time.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55743,"byte_end":55761,"line_start":85,"line_end":85,"column_start":5,"column_end":23}},{"value":" Required for: *Offset Date-Time*, *Local Date-Time*, *Local Time*.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55766,"byte_end":55836,"line_start":86,"line_end":86,"column_start":5,"column_end":75}}]},{"kind":"Field","id":{"krate":0,"index":1781},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55941,"byte_end":55947,"line_start":91,"line_end":91,"column_start":9,"column_end":15},"name":"offset","qualname":"::datetime::Datetime::offset","value":"std::option::Option<datetime::Offset>","parent":{"krate":0,"index":1778},"children":[],"decl_id":null,"docs":" Optional offset.\n Required for: *Offset Date-Time*.\n","sig":null,"attributes":[{"value":" Optional offset.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55870,"byte_end":55890,"line_start":89,"line_end":89,"column_start":5,"column_end":25}},{"value":" Required for: *Offset Date-Time*.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55895,"byte_end":55932,"line_start":90,"line_end":90,"column_start":5,"column_end":42}}]},{"kind":"Struct","id":{"krate":0,"index":1788},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56081,"byte_end":56099,"line_start":96,"line_end":96,"column_start":12,"column_end":30},"name":"DatetimeParseError","qualname":"::datetime::DatetimeParseError","value":"DatetimeParseError { }","parent":null,"children":[{"krate":0,"index":1789}],"decl_id":null,"docs":" Error returned from parsing a `Datetime` in the `FromStr` implementation.\n","sig":null,"attributes":[{"value":" Error returned from parsing a `Datetime` in the `FromStr` implementation.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":55968,"byte_end":56045,"line_start":94,"line_end":94,"column_start":1,"column_end":78}}]},{"kind":"Struct","id":{"krate":0,"index":1794},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57025,"byte_end":57029,"line_start":124,"line_end":124,"column_start":12,"column_end":16},"name":"Date","qualname":"::datetime::Date","value":"Date { year, month, day }","parent":null,"children":[{"krate":0,"index":1795},{"krate":0,"index":1796},{"krate":0,"index":1797}],"decl_id":null,"docs":" A parsed TOML date value","sig":null,"attributes":[{"value":" A parsed TOML date value","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56554,"byte_end":56582,"line_start":109,"line_end":109,"column_start":1,"column_end":29}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56583,"byte_end":56586,"line_start":110,"line_end":110,"column_start":1,"column_end":4}},{"value":" May be part of a [`Datetime`]. Alone, `Date` corresponds to a [Local Date].","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56587,"byte_end":56666,"line_start":111,"line_end":111,"column_start":1,"column_end":80}},{"value":" From the TOML v1.0.0 spec:","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56667,"byte_end":56697,"line_start":112,"line_end":112,"column_start":1,"column_end":31}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56698,"byte_end":56701,"line_start":113,"line_end":113,"column_start":1,"column_end":4}},{"value":" > If you include only the date portion of an RFC 3339 formatted date-time,","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56702,"byte_end":56780,"line_start":114,"line_end":114,"column_start":1,"column_end":79}},{"value":" > it will represent that entire day without any relation to an offset or","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56781,"byte_end":56857,"line_start":115,"line_end":115,"column_start":1,"column_end":77}},{"value":" > timezone.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56858,"byte_end":56873,"line_start":116,"line_end":116,"column_start":1,"column_end":16}},{"value":" >","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56874,"byte_end":56879,"line_start":117,"line_end":117,"column_start":1,"column_end":6}},{"value":" > ```toml","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56880,"byte_end":56893,"line_start":118,"line_end":118,"column_start":1,"column_end":14}},{"value":" > ld1 = 1979-05-27","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56894,"byte_end":56916,"line_start":119,"line_end":119,"column_start":1,"column_end":23}},{"value":" > ```","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56917,"byte_end":56926,"line_start":120,"line_end":120,"column_start":1,"column_end":10}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56927,"byte_end":56930,"line_start":121,"line_end":121,"column_start":1,"column_end":4}},{"value":" [Local Date]: https: toml.io en v1.0.0#local-date","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":56931,"byte_end":56985,"line_start":122,"line_end":122,"column_start":1,"column_end":55}}]},{"kind":"Field","id":{"krate":0,"index":1795},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57066,"byte_end":57070,"line_start":126,"line_end":126,"column_start":9,"column_end":13},"name":"year","qualname":"::datetime::Date::year","value":"u16","parent":{"krate":0,"index":1794},"children":[],"decl_id":null,"docs":" Year: four digits\n","sig":null,"attributes":[{"value":" Year: four digits","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57036,"byte_end":57057,"line_start":125,"line_end":125,"column_start":5,"column_end":26}}]},{"kind":"Field","id":{"krate":0,"index":1796},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57108,"byte_end":57113,"line_start":128,"line_end":128,"column_start":9,"column_end":14},"name":"month","qualname":"::datetime::Date::month","value":"u8","parent":{"krate":0,"index":1794},"children":[],"decl_id":null,"docs":" Month: 1 to 12\n","sig":null,"attributes":[{"value":" Month: 1 to 12","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57081,"byte_end":57099,"line_start":127,"line_end":127,"column_start":5,"column_end":23}}]},{"kind":"Field","id":{"krate":0,"index":1797},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57184,"byte_end":57187,"line_start":130,"line_end":130,"column_start":9,"column_end":12},"name":"day","qualname":"::datetime::Date::day","value":"u8","parent":{"krate":0,"index":1794},"children":[],"decl_id":null,"docs":" Day: 1 to {28, 29, 30, 31} (based on month year)\n","sig":null,"attributes":[{"value":" Day: 1 to {28, 29, 30, 31} (based on month year)","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57123,"byte_end":57175,"line_start":129,"line_end":129,"column_start":5,"column_end":57}}]},{"kind":"Struct","id":{"krate":0,"index":1804},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57980,"byte_end":57984,"line_start":154,"line_end":154,"column_start":12,"column_end":16},"name":"Time","qualname":"::datetime::Time","value":"Time { hour, minute, second, nanosecond }","parent":null,"children":[{"krate":0,"index":1805},{"krate":0,"index":1806},{"krate":0,"index":1807},{"krate":0,"index":1808}],"decl_id":null,"docs":" A parsed TOML time value","sig":null,"attributes":[{"value":" A parsed TOML time value","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57196,"byte_end":57224,"line_start":133,"line_end":133,"column_start":1,"column_end":29}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57225,"byte_end":57228,"line_start":134,"line_end":134,"column_start":1,"column_end":4}},{"value":" May be part of a [`Datetime`]. Alone, `Time` corresponds to a [Local Time].","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57229,"byte_end":57308,"line_start":135,"line_end":135,"column_start":1,"column_end":80}},{"value":" From the TOML v1.0.0 spec:","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57309,"byte_end":57339,"line_start":136,"line_end":136,"column_start":1,"column_end":31}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57340,"byte_end":57343,"line_start":137,"line_end":137,"column_start":1,"column_end":4}},{"value":" > If you include only the time portion of an RFC 3339 formatted date-time,","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57344,"byte_end":57422,"line_start":138,"line_end":138,"column_start":1,"column_end":79}},{"value":" > it will represent that time of day without any relation to a specific","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57423,"byte_end":57498,"line_start":139,"line_end":139,"column_start":1,"column_end":76}},{"value":" > day or any offset or timezone.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57499,"byte_end":57535,"line_start":140,"line_end":140,"column_start":1,"column_end":37}},{"value":" >","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57536,"byte_end":57541,"line_start":141,"line_end":141,"column_start":1,"column_end":6}},{"value":" > ```toml","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57542,"byte_end":57555,"line_start":142,"line_end":142,"column_start":1,"column_end":14}},{"value":" > lt1 = 07:32:00","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57556,"byte_end":57576,"line_start":143,"line_end":143,"column_start":1,"column_end":21}},{"value":" > lt2 = 00:32:00.999999","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57577,"byte_end":57604,"line_start":144,"line_end":144,"column_start":1,"column_end":28}},{"value":" > ```","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57605,"byte_end":57614,"line_start":145,"line_end":145,"column_start":1,"column_end":10}},{"value":" >","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57615,"byte_end":57620,"line_start":146,"line_end":146,"column_start":1,"column_end":6}},{"value":" > Millisecond precision is required. Further precision of fractional","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57621,"byte_end":57693,"line_start":147,"line_end":147,"column_start":1,"column_end":73}},{"value":" > seconds is implementation-specific. If the value contains greater","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57694,"byte_end":57765,"line_start":148,"line_end":148,"column_start":1,"column_end":72}},{"value":" > precision than the implementation can support, the additional precision","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57766,"byte_end":57843,"line_start":149,"line_end":149,"column_start":1,"column_end":78}},{"value":" > must be truncated, not rounded.","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57844,"byte_end":57881,"line_start":150,"line_end":150,"column_start":1,"column_end":38}},{"value":" ","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57882,"byte_end":57885,"line_start":151,"line_end":151,"column_start":1,"column_end":4}},{"value":" [Local Time]: https: toml.io en v1.0.0#local-time","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57886,"byte_end":57940,"line_start":152,"line_end":152,"column_start":1,"column_end":55}}]},{"kind":"Field","id":{"krate":0,"index":1805},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":58017,"byte_end":58021,"line_start":156,"line_end":156,"column_start":9,"column_end":13},"name":"hour","qualname":"::datetime::Time::hour","value":"u8","parent":{"krate":0,"index":1804},"children":[],"decl_id":null,"docs":" Hour: 0 to 23\n","sig":null,"attributes":[{"value":" Hour: 0 to 23","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":57991,"byte_end":58008,"line_start":155,"line_end":155,"column_start":5,"column_end":22}}]},{"kind":"Field","id":{"krate":0,"index":1806},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":58059,"byte_end":58065,"line_start":158,"line_end":158,"column_start":9,"column_end":15},"name":"minute","qualname":"::datetime::Time::minute","value":"u8","parent":{"krate":0,"index":1804},"children":[],"decl_id":null,"docs":" Minute: 0 to 59\n","sig":null,"attributes":[{"value":" Minute: 0 to 59","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":58031,"byte_end":58050,"line_start":157,"line_end":157,"column_start":5,"column_end":24}}]},{"kind":"Field","id":{"krate":0,"index":1807},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":58142,"byte_end":58148,"line_start":160,"line_end":160,"column_start":9,"column_end":15},"name":"second","qualname":"::datetime::Time::second","value":"u8","parent":{"krate":0,"index":1804},"children":[],"decl_id":null,"docs":" Second: 0 to {58, 59, 60} (based on leap second rules)\n","sig":null,"attributes":[{"value":" Second: 0 to {58, 59, 60} (based on leap second rules)","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":58075,"byte_end":58133,"line_start":159,"line_end":159,"column_start":5,"column_end":63}}]},{"kind":"Field","id":{"krate":0,"index":1808},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":58199,"byte_end":58209,"line_start":162,"line_end":162,"column_start":9,"column_end":19},"name":"nanosecond","qualname":"::datetime::Time::nanosecond","value":"u32","parent":{"krate":0,"index":1804},"children":[],"decl_id":null,"docs":" Nanosecond: 0 to 999_999_999\n","sig":null,"attributes":[{"value":" Nanosecond: 0 to 999_999_999","span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":58158,"byte_end":58190,"line_start":161,"line_end":161,"column_start":5,"column_end":37}}]},{"kind":"TupleVariant","id":{"krate":0,"index":1816},"span":{"file_name":" Users ancatoma .cargo registry src github.com-1ecc6299db9ec823 toml-0.5.9 src datetime.rs","byte_start":58609,"byte_end":58610,"line_start":174,"line_end":174,"column_start":5,"column_end":6},"name":"Z","qualname":"::datetime::Offset::Z","value":"Offset::Z","parent":{"krate":0,"index":1815},"children":[],"decl_id":null,"docs":" > A suffix which, when applied to a time, denotes a UTC offset of 00:00;\n > often spoken \"Zulu\" from the ICAO phonetic alphabet representation of\n > the letter \"Z\". package.json src App.js components AddResources.js ListResources.js config.js global.css index.html index.js utils.js
# NearResources To run the project locally: yarn yarn start
LNThanhNhan_LNThanhNhan-homework_near_app_day2
Cargo.toml README.md build.sh src lib.rs order.rs
# UIT Payment Smart contract Application Design: [Ecommerce Payment user flow](https://drive.google.com/file/d/1ilBGG7hfkx7r6KzQy_6cEiHJqQlcSf6w/view?usp=sharing) Prerequires - NodeJS - Near CLI - Rust/Rustup and Wasm Actions 1. Create new account in testnet ``` export CONTRACT_ID=uit-payment-contract.vbidev.testnet export ACCOUNT_ID=vbidev.testnet near create $CONTRACT_ID --masterAccount $ACCOUNT_ID --initialBalance 5 ``` 2. Build contract ``` cargo test & build.sh ``` 3. Deploy and init contract ``` near deploy --wasmFile out/contract.wasm --accountId $CONTRACT_ID--initFunction new '{"owner_id": "$ACCOUNT_ID"}' ``` 4. Pay order ``` near call $CONTRACT_ID pay_order '{"order_id": "order_1", "order_amount": "1000000000000000000000000"}' --accountId $ACCOUNT_ID --deposit 1 ``` 5. Get order ``` near view $CONTRACT_ID get_order '{"order_id": "order_1"}' ``` Ex response: ``` { order_id: 'order_1', payer_id: 'vbidev.testnet', amount: 1e+24, received_amount: 2e+24, is_completed: true, is_refund: false, created_at: 1661439327890786600 } ```
Lagotrixa_NCD_project
.github dependabot.yml workflows tests.yml .gitpod.yml .theia settings.json .travis.yml README-Gitpod.md README.md comands.txt contract Cargo.toml src lib.rs package.json src App.js config.js index.html index.js
NCD project (Near Wallet) ================================= [![Open in Gitpod!](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/Lagotrixa/NCD_project/) <!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page --> ## Description The basis of the project is the repositories [Guest book in AS](https://github.com/near-examples/guest-book), [Simple counter in Rust](https://github.com/near-examples/rust-counter), [Lottery](https://github.com/ryantanwk/lottery). Used information from sources [Near SDK docs](https://www.near-sdk.io/contract-interface/payable-methods), [Examples near](https://examples.near.org/). Contract in `contract/src/lib.rs` provides methods get/send Near. Only those users who know the passphrase (key) can receive Near tokens. Any participants can send Near to a smart contract. ![Screenshot](Screenshot.png) ## To Run Open in the Gitpod link above or clone the repository. ``` git clone https://github.com/Lagotrixa/NCD_project ``` ## 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 = 'YOUR_ACCOUNT_NAME_HERE'; /* TODO: fill this in! */ … ``` Start the example! ``` yarn start ``` ## To Test ``` cd contract cargo test -- --nocapture ``` ## 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 ## To Build the Documentation ``` cd contract cargo doc --no-deps --open ```
mkilc_fungible-token
Cargo.toml src lib.rs
near_near-one-project-tracking
.github ISSUE_TEMPLATE BOUNTY.yml near_one_project_tracking.md README.md
# NEAR One project tracking This repository will be used to track overall work items that NEAR One will work on. The issues created here will be listed on [this board](https://github.com/orgs/near/projects/124/views/1).
marcel-krsh_Near-NFT_Marketplace
.gitpod.yml README.md babel.config.js contract Cargo.toml README.md compile.js src lib.rs target .rustc_info.json debug .fingerprint Inflector-f35c64bdcc83a85c lib-inflector.json autocfg-5eed84e18ea4d38d lib-autocfg.json borsh-derive-761b64255590aa8b lib-borsh-derive.json borsh-derive-internal-a0b35acc7193a1d0 lib-borsh-derive-internal.json borsh-schema-derive-internal-9f37d535db6c4ee3 lib-borsh-schema-derive-internal.json byteorder-4e4f329b09aeb3fd build-script-build-script-build.json convert_case-04564bf453e861d8 lib-convert_case.json derive_more-566efde9e14e316d lib-derive_more.json generic-array-bec72fe46df5bb50 build-script-build-script-build.json hashbrown-42f79a9088e90730 lib-hashbrown.json hashbrown-500377f64ca2c366 run-build-script-build-script-build.json hashbrown-59f80045d7236bc4 build-script-build-script-build.json indexmap-1f3eccbb1f1b3fcd build-script-build-script-build.json indexmap-5fbed610fb2dc724 run-build-script-build-script-build.json indexmap-dc7cadd029b47868 lib-indexmap.json itoa-63cf47e13d3db781 lib-itoa.json memchr-67a2ff728556da01 build-script-build-script-build.json near-rpc-error-core-2a45664b5ee46cf1 lib-near-rpc-error-core.json near-rpc-error-macro-adaa389a95c4c64d lib-near-rpc-error-macro.json near-sdk-core-046688a20778ab0c lib-near-sdk-core.json near-sdk-macros-bf97191d7917f968 lib-near-sdk-macros.json num-bigint-52ecb3e36d449c07 build-script-build-script-build.json num-integer-71fdd49567fe1141 build-script-build-script-build.json num-rational-caea7e28069930f5 build-script-build-script-build.json num-traits-b7d192d6afcd3dde build-script-build-script-build.json proc-macro-crate-3bf1cd013445ff64 lib-proc-macro-crate.json proc-macro2-2367cc8cea2612ce run-build-script-build-script-build.json proc-macro2-395b943ebbf040f9 lib-proc-macro2.json proc-macro2-b648b70837f1c6f4 build-script-build-script-build.json quote-54f9d5620c49c274 lib-quote.json ryu-52f1bb91b4882a97 build-script-build-script-build.json ryu-ce84462a99e7adbd run-build-script-build-script-build.json ryu-f8178accb5946406 lib-ryu.json serde-36a08739de5d3f86 lib-serde.json serde-473481d18b5ff63a build-script-build-script-build.json serde-835d15f265575fe4 run-build-script-build-script-build.json serde_derive-1e873dceb097610e lib-serde_derive.json serde_derive-2086cae8fa2c1432 build-script-build-script-build.json serde_derive-bfa500c2eadb07be run-build-script-build-script-build.json serde_json-2c194e4afdebdac8 run-build-script-build-script-build.json serde_json-4317fae4e2dcf266 lib-serde_json.json serde_json-a63a4500f066a2d2 build-script-build-script-build.json syn-56a5bf88b05722f8 run-build-script-build-script-build.json syn-7c765a4c08ca1842 build-script-build-script-build.json syn-c9ee3dc821cbeb4b lib-syn.json toml-bd2b444908e77606 lib-toml.json typenum-1c3be606d652c4ef build-script-build-script-main.json unicode-xid-bee6a97a0e141568 lib-unicode-xid.json version_check-255985b2dd15b66b lib-version_check.json wee_alloc-e93d2ce325a73164 build-script-build-script-build.json release .fingerprint Inflector-b1f6533151e7be62 lib-inflector.json autocfg-735fbe8c5dbf71b9 lib-autocfg.json borsh-derive-7d59e150cdb518c0 lib-borsh-derive.json borsh-derive-internal-2d78bb3d30492957 lib-borsh-derive-internal.json borsh-schema-derive-internal-85e7e315ba312ee7 lib-borsh-schema-derive-internal.json byteorder-81302f6bfc5eb31f build-script-build-script-build.json convert_case-d9acb4e6c727fc39 lib-convert_case.json derive_more-8d1bb25cd5020356 lib-derive_more.json generic-array-d6c13f53da57eaab build-script-build-script-build.json hashbrown-07494e18ba19bf78 run-build-script-build-script-build.json hashbrown-83b09df10dd1e41a build-script-build-script-build.json hashbrown-d7a8c4c4bbc55cd6 lib-hashbrown.json indexmap-777ecb07eb7c653b build-script-build-script-build.json indexmap-c1b64f93eeed18e9 lib-indexmap.json indexmap-fdbd2f59d739307d run-build-script-build-script-build.json itoa-bb11e9a682f4a0a3 lib-itoa.json memchr-59f60882f3a6fdc4 build-script-build-script-build.json near-rpc-error-core-87cd92434b55bc20 lib-near-rpc-error-core.json near-rpc-error-macro-988344ce9064fcf8 lib-near-rpc-error-macro.json near-sdk-core-2289a4a8c4b53ccd lib-near-sdk-core.json near-sdk-macros-c0403bcb04e8a0ea lib-near-sdk-macros.json num-bigint-74134c594c8b09e4 build-script-build-script-build.json num-integer-982480eb0675b6e4 build-script-build-script-build.json num-rational-ee02237c4a087c84 build-script-build-script-build.json num-traits-9155197deb68bde0 build-script-build-script-build.json proc-macro-crate-e11d07896b88a341 lib-proc-macro-crate.json proc-macro2-4a41766285ae3b71 lib-proc-macro2.json proc-macro2-9508761ff3b2ceb3 run-build-script-build-script-build.json proc-macro2-dff7675cc3d539cf build-script-build-script-build.json quote-af2ffbfaeb05cf39 lib-quote.json ryu-03d8d14e187b80dd build-script-build-script-build.json ryu-8aabbea4a072ce32 run-build-script-build-script-build.json ryu-b58a78f25485d0d7 lib-ryu.json serde-43577858555c1f0e lib-serde.json serde-d041d925dd72a9a7 build-script-build-script-build.json serde-f0856918557b9658 run-build-script-build-script-build.json serde_derive-2fda46d22992ac7e run-build-script-build-script-build.json serde_derive-34c1264feee50417 lib-serde_derive.json serde_derive-ec64f90e16c9291e build-script-build-script-build.json serde_json-314108b27f235f7e build-script-build-script-build.json serde_json-d24cdaf20879683a lib-serde_json.json serde_json-d2ee8bb4d740eab8 run-build-script-build-script-build.json syn-54daadb1bc6d3c9c lib-syn.json syn-5eff70ac5a70f6e0 run-build-script-build-script-build.json syn-e12e1ce835e719c1 build-script-build-script-build.json toml-832b9f05674868c2 lib-toml.json typenum-979d1ff71f05660b build-script-build-script-main.json unicode-xid-2b21b505d13ab61a lib-unicode-xid.json version_check-e88a35665327f85d lib-version_check.json wee_alloc-7ac7d6f4e423032d build-script-build-script-build.json rls .rustc_info.json debug .fingerprint Inflector-f35c64bdcc83a85c lib-inflector.json ahash-428cc931c0061897 lib-ahash.json aho-corasick-62bc7b16d1ecc60a lib-aho_corasick.json autocfg-5eed84e18ea4d38d lib-autocfg.json base64-9831c71dbdcf3467 lib-base64.json block-buffer-2ee406e183b1e995 lib-block-buffer.json block-buffer-fc89891d9a73cbc9 lib-block-buffer.json block-padding-9e3229b1b1de667d lib-block-padding.json borsh-271d126b0b7fda82 lib-borsh.json borsh-derive-761b64255590aa8b lib-borsh-derive.json borsh-derive-internal-a0b35acc7193a1d0 lib-borsh-derive-internal.json borsh-schema-derive-internal-9f37d535db6c4ee3 lib-borsh-schema-derive-internal.json bs58-4db8f3d1f4404b7b lib-bs58.json byte-tools-c334b989feef0d17 lib-byte-tools.json byteorder-0f87af00ba794053 run-build-script-build-script-build.json byteorder-4e4f329b09aeb3fd build-script-build-script-build.json byteorder-cd21f5e36b15e5b7 lib-byteorder.json cfg-if-209477e418b9c94a lib-cfg-if.json cfg-if-66978c2a0b8c4bd7 lib-cfg-if.json convert_case-04564bf453e861d8 lib-convert_case.json cpuid-bool-e4a37930b5b7b75f lib-cpuid-bool.json derive_more-566efde9e14e316d lib-derive_more.json digest-526039a6cce2ddf8 lib-digest.json digest-f5c1d7ce22b1cf76 lib-digest.json generic-array-1c9b39dcaa2d5910 lib-generic_array.json generic-array-58f32267f8fc2ff9 lib-generic_array.json generic-array-bec72fe46df5bb50 build-script-build-script-build.json generic-array-c76236cef8e4bf47 run-build-script-build-script-build.json greeter-4d4824e8c3b8153b test-lib-greeter.json greeter-85cd84318bdc7a0a lib-greeter.json hashbrown-42f79a9088e90730 lib-hashbrown.json hashbrown-500377f64ca2c366 run-build-script-build-script-build.json hashbrown-59ae038a00c92530 lib-hashbrown.json hashbrown-59f80045d7236bc4 build-script-build-script-build.json hashbrown-bbe47eb036f4b0fa lib-hashbrown.json hex-7dc44f68c82eaecd lib-hex.json indexmap-1f3eccbb1f1b3fcd build-script-build-script-build.json indexmap-5fbed610fb2dc724 run-build-script-build-script-build.json indexmap-7822859b71d5e519 lib-indexmap.json indexmap-dc7cadd029b47868 lib-indexmap.json itoa-63cf47e13d3db781 lib-itoa.json itoa-68148c820965b3d9 lib-itoa.json keccak-5e37937124ecf844 lib-keccak.json lazy_static-15431e18af437aa6 lib-lazy_static.json libc-50d344a18a59b8a9 build-script-build-script-build.json libc-58df33a1e8a3f158 lib-libc.json libc-ece3c94859a4132c run-build-script-build-script-build.json memchr-5477fe007a150197 run-build-script-build-script-build.json memchr-67a2ff728556da01 build-script-build-script-build.json memchr-dddf087657da3543 lib-memchr.json memory_units-8bfe333c6f7b7962 lib-memory_units.json near-primitives-core-aefef53ea44cb2e1 lib-near-primitives-core.json near-rpc-error-core-2a45664b5ee46cf1 lib-near-rpc-error-core.json near-rpc-error-macro-adaa389a95c4c64d lib-near-rpc-error-macro.json near-runtime-utils-61602078ba4e9a0a lib-near-runtime-utils.json near-sdk-c401a38a518c16b0 lib-near-sdk.json near-sdk-core-046688a20778ab0c lib-near-sdk-core.json near-sdk-macros-bf97191d7917f968 lib-near-sdk-macros.json near-vm-errors-9fb33973aef5574e lib-near-vm-errors.json near-vm-logic-957746ed6c004c24 lib-near-vm-logic.json num-bigint-430aefc3b702cc48 lib-num-bigint.json num-bigint-52ecb3e36d449c07 build-script-build-script-build.json num-bigint-addec1ef51041742 run-build-script-build-script-build.json num-integer-1e1d4dff9ced5d24 run-build-script-build-script-build.json num-integer-1fcfeadbb61834c6 lib-num-integer.json num-integer-71fdd49567fe1141 build-script-build-script-build.json num-rational-18586ac14bbeb9d6 lib-num-rational.json num-rational-9ac90676bb3804c4 run-build-script-build-script-build.json num-rational-caea7e28069930f5 build-script-build-script-build.json num-traits-23253bfc4e2a669c run-build-script-build-script-build.json num-traits-95043c39ba4deedf lib-num-traits.json num-traits-b7d192d6afcd3dde build-script-build-script-build.json opaque-debug-99c15dd0db4417c8 lib-opaque-debug.json opaque-debug-b5faa4e85b1fe92f lib-opaque-debug.json proc-macro-crate-3bf1cd013445ff64 lib-proc-macro-crate.json proc-macro2-2367cc8cea2612ce run-build-script-build-script-build.json proc-macro2-395b943ebbf040f9 lib-proc-macro2.json proc-macro2-b648b70837f1c6f4 build-script-build-script-build.json quote-54f9d5620c49c274 lib-quote.json regex-3b35b35321346d38 lib-regex.json regex-syntax-ab3c9461f350dbfd lib-regex-syntax.json ryu-52f1bb91b4882a97 build-script-build-script-build.json ryu-68207a75b1fa756c lib-ryu.json ryu-ce84462a99e7adbd run-build-script-build-script-build.json ryu-f8178accb5946406 lib-ryu.json serde-36a08739de5d3f86 lib-serde.json serde-473481d18b5ff63a build-script-build-script-build.json serde-835d15f265575fe4 run-build-script-build-script-build.json serde-c283e464a596c364 lib-serde.json serde_derive-1e873dceb097610e lib-serde_derive.json serde_derive-2086cae8fa2c1432 build-script-build-script-build.json serde_derive-bfa500c2eadb07be run-build-script-build-script-build.json serde_json-2c194e4afdebdac8 run-build-script-build-script-build.json serde_json-3c3a184038918792 lib-serde_json.json serde_json-4317fae4e2dcf266 lib-serde_json.json serde_json-a63a4500f066a2d2 build-script-build-script-build.json sha2-00a7517df25156fb lib-sha2.json sha3-7876d5d8d21e0bb7 lib-sha3.json syn-56a5bf88b05722f8 run-build-script-build-script-build.json syn-7c765a4c08ca1842 build-script-build-script-build.json syn-c9ee3dc821cbeb4b lib-syn.json toml-bd2b444908e77606 lib-toml.json typenum-1c3be606d652c4ef build-script-build-script-main.json typenum-702ddccd7905b4a9 run-build-script-build-script-main.json typenum-eaa7a1ac2e092c74 lib-typenum.json unicode-xid-bee6a97a0e141568 lib-unicode-xid.json version_check-255985b2dd15b66b lib-version_check.json wee_alloc-0d447978bf917136 run-build-script-build-script-build.json wee_alloc-2328ee1404412d3a lib-wee_alloc.json wee_alloc-e93d2ce325a73164 build-script-build-script-build.json build byteorder-4e4f329b09aeb3fd save-analysis build_script_build-4e4f329b09aeb3fd.json generic-array-bec72fe46df5bb50 save-analysis build_script_build-bec72fe46df5bb50.json hashbrown-59f80045d7236bc4 save-analysis build_script_build-59f80045d7236bc4.json indexmap-1f3eccbb1f1b3fcd save-analysis build_script_build-1f3eccbb1f1b3fcd.json libc-50d344a18a59b8a9 save-analysis build_script_build-50d344a18a59b8a9.json memchr-67a2ff728556da01 save-analysis build_script_build-67a2ff728556da01.json num-bigint-52ecb3e36d449c07 save-analysis build_script_build-52ecb3e36d449c07.json num-bigint-addec1ef51041742 out radix_bases.rs num-integer-71fdd49567fe1141 save-analysis build_script_build-71fdd49567fe1141.json num-rational-caea7e28069930f5 save-analysis build_script_build-caea7e28069930f5.json num-traits-b7d192d6afcd3dde save-analysis build_script_build-b7d192d6afcd3dde.json proc-macro2-b648b70837f1c6f4 save-analysis build_script_build-b648b70837f1c6f4.json ryu-52f1bb91b4882a97 save-analysis build_script_build-52f1bb91b4882a97.json serde-473481d18b5ff63a save-analysis build_script_build-473481d18b5ff63a.json serde_derive-2086cae8fa2c1432 save-analysis build_script_build-2086cae8fa2c1432.json serde_json-a63a4500f066a2d2 save-analysis build_script_build-a63a4500f066a2d2.json syn-7c765a4c08ca1842 save-analysis build_script_build-7c765a4c08ca1842.json typenum-1c3be606d652c4ef save-analysis build_script_main-1c3be606d652c4ef.json typenum-702ddccd7905b4a9 out consts.rs op.rs tests.rs wee_alloc-0d447978bf917136 out wee_alloc_static_array_backend_size_bytes.txt wee_alloc-e93d2ce325a73164 save-analysis build_script_build-e93d2ce325a73164.json deps save-analysis greeter-4d4824e8c3b8153b.json libahash-428cc931c0061897.json libaho_corasick-62bc7b16d1ecc60a.json libautocfg-5eed84e18ea4d38d.json libbase64-9831c71dbdcf3467.json libblock_buffer-2ee406e183b1e995.json libblock_padding-9e3229b1b1de667d.json libborsh-271d126b0b7fda82.json libbs58-4db8f3d1f4404b7b.json libbyte_tools-c334b989feef0d17.json libbyteorder-cd21f5e36b15e5b7.json libderive_more-566efde9e14e316d.json libgeneric_array-1c9b39dcaa2d5910.json libgeneric_array-58f32267f8fc2ff9.json libgreeter-85cd84318bdc7a0a.json libhashbrown-42f79a9088e90730.json libhashbrown-59ae038a00c92530.json libhex-7dc44f68c82eaecd.json libindexmap-7822859b71d5e519.json libindexmap-dc7cadd029b47868.json libinflector-f35c64bdcc83a85c.json libitoa-68148c820965b3d9.json libkeccak-5e37937124ecf844.json liblazy_static-15431e18af437aa6.json libmemchr-dddf087657da3543.json libmemory_units-8bfe333c6f7b7962.json libnear_primitives_core-aefef53ea44cb2e1.json libnear_rpc_error_core-2a45664b5ee46cf1.json libnear_rpc_error_macro-adaa389a95c4c64d.json libnear_runtime_utils-61602078ba4e9a0a.json libnear_sdk-c401a38a518c16b0.json libnear_vm_errors-9fb33973aef5574e.json libnear_vm_logic-957746ed6c004c24.json libnum_bigint-430aefc3b702cc48.json libnum_integer-1fcfeadbb61834c6.json libnum_rational-18586ac14bbeb9d6.json libnum_traits-95043c39ba4deedf.json libopaque_debug-b5faa4e85b1fe92f.json libproc_macro2-395b943ebbf040f9.json libproc_macro_crate-3bf1cd013445ff64.json libquote-54f9d5620c49c274.json libregex-3b35b35321346d38.json libryu-68207a75b1fa756c.json libsha2-00a7517df25156fb.json libsha3-7876d5d8d21e0bb7.json libtoml-bd2b444908e77606.json libunicode_xid-bee6a97a0e141568.json libversion_check-255985b2dd15b66b.json libwee_alloc-2328ee1404412d3a.json wasm32-unknown-unknown debug .fingerprint ahash-eb636ec8915dddf7 lib-ahash.json aho-corasick-a71edad06bb68cab lib-aho_corasick.json base64-0ae58e1dbffe7e84 lib-base64.json block-buffer-20af8d642b837847 lib-block-buffer.json block-buffer-85b17d9b8595e159 lib-block-buffer.json block-padding-095fc83b1607738a lib-block-padding.json borsh-bf7950abe3f09d4c lib-borsh.json bs58-286532934081eba1 lib-bs58.json byte-tools-b7ac364c6d558430 lib-byte-tools.json byteorder-0cd1ed356486674f lib-byteorder.json byteorder-f5dc4b4e48bded04 run-build-script-build-script-build.json cfg-if-4d8a2758c80889c0 lib-cfg-if.json cfg-if-a77a3c4e042d055d lib-cfg-if.json digest-72529d28ecf61488 lib-digest.json digest-d4124ab6c18e79e5 lib-digest.json generic-array-0ecce5cce49dcea1 run-build-script-build-script-build.json generic-array-a51a241793992f40 lib-generic_array.json generic-array-f88c74110034607c lib-generic_array.json greeter-98ace302c5fafa12 lib-greeter.json hashbrown-88c4fd68d369e204 lib-hashbrown.json hashbrown-c79eeed063cebff2 lib-hashbrown.json hashbrown-d08c50da5660759f run-build-script-build-script-build.json hex-ed3e76e456925cba lib-hex.json indexmap-5c193501167d8447 run-build-script-build-script-build.json indexmap-b28a5ce6ad124174 lib-indexmap.json itoa-8131ef3e89947368 lib-itoa.json keccak-fec8796739ce5fde lib-keccak.json lazy_static-4d5361ccf5b352f5 lib-lazy_static.json memchr-25b196f1bd4b2ecc lib-memchr.json memchr-d7d50b3eb5e79daf run-build-script-build-script-build.json memory_units-27c0630f88317c76 lib-memory_units.json near-primitives-core-1dbb5cc6733d750e lib-near-primitives-core.json near-runtime-utils-2fc656fcfaaacd29 lib-near-runtime-utils.json near-sdk-ee3ca4da10262bbf lib-near-sdk.json near-vm-errors-979533521df46ffd lib-near-vm-errors.json near-vm-logic-4713d4cfd3563cc5 lib-near-vm-logic.json num-bigint-a7776bc10849fa10 lib-num-bigint.json num-bigint-cf5799adc943a33e run-build-script-build-script-build.json num-integer-1354f87f88c7c4b3 lib-num-integer.json num-integer-c1d009c0dcda2b1a run-build-script-build-script-build.json num-rational-8a750fca4189c112 run-build-script-build-script-build.json num-rational-9191d276205b351e lib-num-rational.json num-traits-2fa84436ba59c6a5 lib-num-traits.json num-traits-b827cec4781ff7ef run-build-script-build-script-build.json opaque-debug-9a055071732a2e05 lib-opaque-debug.json opaque-debug-ce59ec0a8ef85c91 lib-opaque-debug.json regex-180ae6db84ef7c43 lib-regex.json regex-syntax-64d72df1a7a24eed lib-regex-syntax.json ryu-cee8a9e3ef551249 run-build-script-build-script-build.json ryu-f5f5279d17e4558f lib-ryu.json serde-454350dad00c836f lib-serde.json serde-9c4e68c7bafb97ab run-build-script-build-script-build.json serde_json-89e9633a411c631e lib-serde_json.json serde_json-99a433b6f05242fb run-build-script-build-script-build.json sha2-f58f5f9043003f37 lib-sha2.json sha3-e89a3e3ea208ff02 lib-sha3.json typenum-5bdf061afe46b05e run-build-script-build-script-main.json typenum-5eb09d9567c7402c lib-typenum.json wee_alloc-87427b00e2478ff4 run-build-script-build-script-build.json wee_alloc-adb071298af20a95 lib-wee_alloc.json build num-bigint-cf5799adc943a33e out radix_bases.rs typenum-5bdf061afe46b05e out consts.rs op.rs tests.rs wee_alloc-87427b00e2478ff4 out wee_alloc_static_array_backend_size_bytes.txt release .fingerprint ahash-5733d2af5ab642f9 lib-ahash.json aho-corasick-358cd9fc49fc208f lib-aho_corasick.json base64-0ed85d98192b35cb lib-base64.json block-buffer-1e4e2337592206e5 lib-block-buffer.json block-buffer-c54763f257b15dd1 lib-block-buffer.json block-padding-c555c563296295f4 lib-block-padding.json borsh-beb3e822996c2cb4 lib-borsh.json bs58-41d69aa5ea2113ca lib-bs58.json byte-tools-fb87ed39c08375ce lib-byte-tools.json byteorder-0c3b7b13740da921 lib-byteorder.json byteorder-405f574730de3eef run-build-script-build-script-build.json cfg-if-b071a0b2275e82e2 lib-cfg-if.json cfg-if-d5346bc0bf7330e8 lib-cfg-if.json digest-0d4237bf4d9c1a6a lib-digest.json digest-adac54607d80ee38 lib-digest.json generic-array-217ce918508d02cd run-build-script-build-script-build.json generic-array-e67b0eb4308d514e lib-generic_array.json generic-array-f16946a2302dd633 lib-generic_array.json greeter-98ace302c5fafa12 lib-greeter.json hashbrown-2ec52ed5ef7e8301 run-build-script-build-script-build.json hashbrown-8c8841b45faaaabd lib-hashbrown.json hashbrown-ae7cd6c71d752e9a lib-hashbrown.json hex-7df3a25827098668 lib-hex.json indexmap-499bc4cee6a96e5a lib-indexmap.json indexmap-cb04952586968012 run-build-script-build-script-build.json itoa-809e1c13e2b226d3 lib-itoa.json keccak-8f1f086e7e9699d2 lib-keccak.json lazy_static-972e121ee292811f lib-lazy_static.json memchr-137fa0863f905d2c run-build-script-build-script-build.json memchr-e48956fbf149470d lib-memchr.json memory_units-6d9926a0d4bb6989 lib-memory_units.json near-primitives-core-c1d94f159e4a2fcc lib-near-primitives-core.json near-runtime-utils-a3cb73bd60125da8 lib-near-runtime-utils.json near-sdk-425250cb7ccbf675 lib-near-sdk.json near-vm-errors-8abc13bf4c874e4c lib-near-vm-errors.json near-vm-logic-27a1fbe8540f5631 lib-near-vm-logic.json num-bigint-5f3184d31ccdc4aa lib-num-bigint.json num-bigint-edd88df40ad0adeb run-build-script-build-script-build.json num-integer-3caf5a2e1cd3ffa6 run-build-script-build-script-build.json num-integer-80774b99740e0f81 lib-num-integer.json num-rational-461cc94cc1251d94 run-build-script-build-script-build.json num-rational-9439f578daeff963 lib-num-rational.json num-traits-542afd3e0b9f4731 run-build-script-build-script-build.json num-traits-d764c2a26c748628 lib-num-traits.json opaque-debug-e7c6e45d0f6dbcbc lib-opaque-debug.json opaque-debug-fbd12b4a5adf74d4 lib-opaque-debug.json regex-c45e85a87d9d3aa2 lib-regex.json regex-syntax-4308c62ce412d750 lib-regex-syntax.json ryu-17d9881e571cdd4b lib-ryu.json ryu-6c0eafb381d8ef83 run-build-script-build-script-build.json serde-8cfb315b6ee116ce lib-serde.json serde-a8f4a3c392c64d21 run-build-script-build-script-build.json serde_json-c74861dd6cf40b64 run-build-script-build-script-build.json serde_json-dd836d1a69b1c32b lib-serde_json.json sha2-e06d4e2ca3f7096b lib-sha2.json sha3-7e8ddc190e555192 lib-sha3.json typenum-4acd3ba97586d824 lib-typenum.json typenum-55ff30b9565f0355 run-build-script-build-script-main.json wee_alloc-2b2eac064dc92512 run-build-script-build-script-build.json wee_alloc-c61199675b501834 lib-wee_alloc.json build num-bigint-edd88df40ad0adeb out radix_bases.rs typenum-55ff30b9565f0355 out consts.rs op.rs tests.rs wee_alloc-2b2eac064dc92512 out wee_alloc_static_array_backend_size_bytes.txt | |","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1038,"byte_end":1133,"line_start":22,"line_end":22,"column_start":1,"column_end":96}},{"value":" | `encode` | Returns a new `String` | Always |","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1134,"byte_end":1229,"line_start":23,"line_end":23,"column_start":1,"column_end":96}},{"value":" | `encode_config` | Returns a new `String` | Always |","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1230,"byte_end":1325,"line_start":24,"line_end":24,"column_start":1,"column_end":96}},{"value":" | `encode_config_buf` | Appends to provided `String` | Only if `String` needs to grow |","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1326,"byte_end":1421,"line_start":25,"line_end":25,"column_start":1,"column_end":96}},{"value":" | `encode_config_slice` | Writes to provided `&[u8]` | Never |","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1422,"byte_end":1517,"line_start":26,"line_end":26,"column_start":1,"column_end":96}},{"value":" ","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1518,"byte_end":1521,"line_start":27,"line_end":27,"column_start":1,"column_end":4}},{"value":" All of the encoding functions that take a `Config` will pad as per the config.","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1522,"byte_end":1604,"line_start":28,"line_end":28,"column_start":1,"column_end":83}},{"value":" ","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1605,"byte_end":1608,"line_start":29,"line_end":29,"column_start":1,"column_end":4}},{"value":" # Decoding","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1609,"byte_end":1623,"line_start":30,"line_end":30,"column_start":1,"column_end":15}},{"value":" ","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1624,"byte_end":1627,"line_start":31,"line_end":31,"column_start":1,"column_end":4}},{"value":" Just as for encoding, there are different decoding functions available.","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1628,"byte_end":1703,"line_start":32,"line_end":32,"column_start":1,"column_end":76}},{"value":" ","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1704,"byte_end":1707,"line_start":33,"line_end":33,"column_start":1,"column_end":4}},{"value":" | Function | Output | Allocates |","span":{"file_name":" workspace .cargo registry src github.com-1ecc6299db9ec823 base64-0.13.0 src lib.rs","byte_start":1708,"byte_end":1804,"line_start":34,"line_end":34,"column_start":1,"column_end":97}},{"value":" | gitpod.yml neardev shared-test-staging test.near.json shared-test test.near.json package.json src App.js Components Home.js Mintnft.js exmaple.js mynft.js __mocks__ fileMock.js assets logo-black.svg logo-white.svg config.js global.css http-common.js index.html index.js jest.init.js main.test.js services FileUploadService.js utils.js wallet login index.html supas.sh
pumpblock 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 pumpblock ================== This [React] app was initialized with [create-near-app] `rustup target add wasm32-unknown-unknown` `npm install -g near-cli near-api-js` `create wallet on ` [near wallet](https://wallet.testnet.near.org/) `npm install nft.storage` ### `create account on` [nft.storage](https://nft.storage) `and copy API ID to store it in your storage` `add the api key to Mintnft.js file in src/component` `yarn build` `yarn start` `After Starting we have to initiliaze the contract, Use console to track the progress` `after loging in, we can start minting the NFTS` Quick Start =========== `yarn install` 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 `pumpblock.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `pumpblock.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 pumpblock.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 || 'pumpblock.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
holyaustin_decentralized-library
README.md components footer index.js layout index.js navbar.js config.js data applieddata.js catebooksdata.js catevideodata.js formaldata.js humanitiesdata.js myindex.js naturaldata.js physicaldata.js physicalviddata.js recent.json socialdata.js uploaddata.js uploadvideodata.js hardhat.config.js next.config.js package.json pages _app.js about.js catebooks.js catvideos.js community.js create-item-ebook.js create-item-video.js csbooks.js csvideos.js earn.js index.js listbooks.js liveclass.js mint.js physical.js physicalvid.js reading.js upload.js watching.js postcss.config.js public index.html script.js style.css vercel.svg routes stat.js scripts deploy.js server.js src app.ts ceramic.ts components footer index.js header index.js nav.js home posts.js layout index.js idx.ts skydb.ts wallet.ts styles Home.module.css globals.css tailwind.config.js
Decentralized Library A Decentralized digital Library that uses Web3 to log user in to read books and earn. ======= The need to implement more web2 solutions into web3 have necesitated this idea. Decentralized library is a no-censorship library where users go to read testbooks and watch video books using the wallet. The following benefit awaits users of this project 1. Hundreds of Academic E-Books: The Library has more books that you could imagine. E-books repository are decentralized (IPFS Storage). 2. Lot of Video-Books: The full video books are here for you. if you cannot read the ebook format, you can read you favorite textbooks by watching them (IPFS Storage). 3. No Political Censorship: No fear from government of your country not allowing certain books. You can read or watch them here. 4. Learn and Earn: The very First decentralized Library where you LEARN and EARN. 5. Live Class Streaming: Lecturers / Teachers can use this platform to shedule live teaching and learning. just contact us 6. No Loss of Books: Prevent the accidental or intentional loss of information from human consciousness Local setup To run this project locally, follow these steps. Clone the project locally, change into the directory, and install the dependencies: git clone https://github.com/holyaustin/decentralized-library.git cd decentralized-library # install using NPM or Yarn npm install # or yarn Start the local Hardhat node npx hardhat node With the network running, deploy the contracts to the local network in a separate terminal window npx hardhat run scripts/deploy.js --network localhost Start the app npm run dev
Narwallets_lau-near-utils
Readme.md package.json src config.ts constants.ts contract.ts errors.ts index.ts init.ts interactiveConsole.ts logger.ts near-connection.ts near.ts start.ts util.js tsconfig.json
gagdiez_pool_party
README.md
This Is Not the Repo You Are Looking For ======================================= The development of Pool Party has been moved to [here](https://github.com/poolpartynear/pool_party). This repo will be removed soon.
eteu-technologies_nearkit
.github workflows lint.yml README.md cmd nearkit command_change.go command_deploy.go command_genesis.go command_genkey.go command_view.go common.go main.go internal account account.go types.go vendorsha.sh
# NEARKit [![CI](https://github.com/eteu-technologies/nearkit/actions/workflows/lint.yml/badge.svg)](https://github.com/eteu-technologies/nearkit/actions/workflows/lint.yml) [![built with nix](https://builtwithnix.org/badge.svg)](https://builtwithnix.org) CLI to interact with NEAR blockchain ## Running ### Using Nix We're using Nix flakes! `nix run github:eteu-technologies/nearkit -- --help` ### Build & run Clone and do `go build ./cmd/nearkit`. You'll get binary named `nearkit` what you can install somewhere. <!-- NOTE: Broken as of 2021-07-25: go/src/github.com/eteu-technologies/near-api-go/pkg/types/balance.go:9:2: code in directory /Users/mark/go/src/github.com/eteu-technologies/golang-uint128 expects import "lukechampine.com/uint128" ### Using Go CLI ``` GO111MODULE=off go get github.com/eteu-technologies/nearkit/cmd/nearkit GO111MODULE=off go run github.com/eteu-technologies/nearkit/cmd/nearkit ``` --> ## License MIT
Musti2735_NEAR-Poject-FootballPlayer
README.md as-pect.config.js asconfig.json package.json scripts 1.dev-deploy.sh 2.getContract.sh 3.cleanup.sh src as_types.d.ts simple asconfig.json assembly index.ts model.ts tsconfig.json utils.ts
Footbal Player ============== The project is about choosing a random football player from a football team entered by the user. Firstly, users select a team and deposit minumum 2 near. When call the contract, the user is given a random player from the selected team. ## Get Started ============== Install yarn (package manager) from terminal like this: install -g yarn INSTALL `NEAR CLI` first like this: `npm i -g near-cli` npm i -g near-cli clone this repo to a local folder: git clone https://github.com/Musti2735/NEAR-Poject-FootballPlayer Then install dependencies and node modules using yarn package manager : yarn run yarn build:release run near dev-deploy ./build/release/simple.wasm export CONTRACT=dev-####-#### or RUN ./scripts/1.dev-deploy.sh ## Usage ============== There are 3 teams on the project. Manchester United, Paris Saint Germen and Liverpool. There are 3 football palyers in each teams.(Teams and players could be more) Select a team. There are ony 3 teams you can chose.('PSG', 'MANU', 'LIVERPOOL') You must write one of this teams on the value of 'team' parameter. Add your testnet account. Make sure to attach 2 NEAR. If near amount is less 2 near, assert code runs. It must be like that : "near call $CONTRACT getPlayer '{"team":"####"}' --accountId ####.testnet --amount #" For example : "near call $CONTRACT getPlayer '{"team":"PSG"}' --accountId mycodebag.testnet --amount 2" or RUN ./scripts/2.getContract.sh Finally, selected player adds the storage. You can see your selected random player on terminal and storage using from https://github.com/near-examples/near-account-utils repostories.
k3rn3lpanicc_near-payment-contract
Cargo.toml README.md deploy deploy.bat paymentdeployer.json keys k3rn3lpanic.json src lib.rs
# near-payment-contract Payment Contract for NEAR
nitrocinema_risiko-v2
back Cargo.toml neardev dev-account.env package-lock.json package.json src contract mod.rs risiko.rs info.rs lib.rs main.rs models battle.rs mod.rs team.rs responses add_battle_response.rs delete_battle_response.rs join_battle_response.rs mod.rs front .eslintrc.json README.md config near.ts next-env.d.ts next.config.js package-lock.json package.json pages api hello.ts public vercel.svg tsconfig.json
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.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. ## 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.
Learn-NEAR_NCD--PostComm
Readme.md postcomm as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts example.spec.ts index.ts tsconfig.json package.json
pagoda-gallery-repos_js-repo
.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
# 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>`. <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>`. <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)._
NEARBuilders_bos-blocks
.github workflows continuous-integration.yml release-mainnet.yml release-testnet.yml README.md aliases.mainnet.json aliases.testnet.json bos.config.json data.json package.json playwright-tests README.md storage-states admin-connected.json wallet-connected.json wallet-not-connected.json testUtils.js tests bosloaderenvironment.spec.js util constants.js playwright.config.js tree.json
# Quickstart ## Getting started 1. Install packages ```cmd npm install ``` 2. Start dev environment ```cmd npm run dev ``` This will start a gateway at [127.0.0.1:8080](http://127.0.0.1:8080) which will render your local widgets. The entry point for this app is [every.near/widget/app](http://127.0.0.1:8080/devs.near/widget/Library) # Testing Guide This project uses [playwright](https://playwright.dev/) for end-to-end testing. Please become familiar with this documentation. ## Writing tests Tests should be written for each change or addition to the codebase. If a new feature is introduced, tests should be written to validate its functionality. If a bug is fixed, tests should be written to prevent regression. Writing tests not only safeguards against future breaks by other developers but also accelerates development by minimizing manual coding and browser interactions. When writing tests, remember to: - Test user-visible behavior - Make tests as isolated as possible - Avoid testing third-party dependencies > **[LEARN BEST PRACTICES](https://playwright.dev/docs/best-practices)** See the [cookbook](#cookbook) for help in covering scenerios. It is possible to [generate tests](https://playwright.dev/docs/codegen) via the [VS Code Extension](https://marketplace.visualstudio.com/items?itemName=ms-playwright.playwright). ## Running tests To run the tests, you may do so through the command line: ```cmd npm run test ``` Or through VS Code **(recommended)**, see [Getting started - VS Code](https://playwright.dev/docs/getting-started-vscode). ## Recording video You may automatically record video with your tests by setting ``` use: { video: "on" } ``` in the [playwright.config.js](../playwright.config.js). After running tests, you will find the output as a `.webm` in `./test-results`. Then, [convert to MP4](https://video.online-convert.com/convert/webm-to-mp4) and share. It is encouraged to include video in pull requests in order to demonstrate functionality and prove thorough testing. ## Cookbook ### Capturing the VM Confirmation Popup Currently, none of the tests post actual transactions to the smart contracts. Still you should try writing your tests so that they do the actual function call, but just skip the final step of sending the transaction. You can do this by capturing the transaction confirmation popup provided by the NEAR social VM. ```javascript // click button that triggers transaction await page.getByRole("button", { name: "Donate" }).nth(1).click(); const transactionObj = JSON.parse(await page.locator("div.modal-body code").innerText()); // do something with transactionObj expect(transactionObj).toMatchObject({ amount: 100, message: "", projectId: DEFAULT_PROJECT_ID, }); ``` See the test called "project with no active pot should donate direct with correct amount" in donate.spec.js for a full example.
NearDate-PastAndFuture_NearDate-PastAndFuture-FE
.eslintrc.json assets readme.md next-env.d.ts next.config.js package.json pages api hello.ts postcss.config.js public google619add6080a4a785.html near-protocol.svg vercel.svg styles Home.module.css globals.css tailwind.config.js tsconfig.json types convert_from,.ts index.d.ts utils config.ts file.ts format.ts ipfs.ts near.ts
Joystick-team_joystick-demo
.eslintrc.json .github workflows main.yml preview.yml test.yml .vscode settings.json README.md | dist assets index-6fbbda55.css index-b015545a.css index.html index.html package.json src Action-Creators Authenication Profile.Auth.js Profile.Update.js Signin.Auth.js Signup.Auth.js FetchAllPosts.AC.js FetchGames.AC.js Mutuals FetchFollowing.AC.js FetchFollwers.AC.js Notifications.AC.js Search.AC.js profileForm.AC.js updateProfile.AC.js Actions Authentication Profile.Action.js Profile.Update.Action.js Signin.Action.js Sigup.Action.js Games.Action.js Mutuals Followers.Action.js Following.Actions.js Notifications.Action.js Posts.Action.js Search.Action.js profileForm.Action.js updateProfileAction.js App.css LiverperrClient.js Reducers AuthReducer Profile.Update.Reducer.js profile.Reducer.js signin.Reducer.js signup.Reducer.js Games.Reducer.js MutualReducers Followers.Reducer.js Following.Reducing.js Notifications.Reducer.js Posts.Reducer.js Search.Reducer.js profileForm.reducer.js updateProfile.reducer.js Store gamesdata.js librarygamesdata.js storefiles.js walletStorage.js assets svg JOYSTICK-svg.svg error-img.svg component Chats Friendrequest FriendrequestData.js chatsdata.js Games games.css Profile UpdateProfile.css config config.json hooks useFetch.js usePost.js index.css near-wallet.js pages Home home.css Livestream StreamModal modal.css Settings Account.data.js Update.form.css navs.css settings.css setupProxy.js store.js vite.config.js
### Brief Description The Freetyl application/platform (formerly Joystick) is a gamefi platform that is built to be a collection of different genres of games ranging from 2D to vectors games. The platform houses 1. A marketplace- a small inbuilt store for gamers/users to sell and trade in-game assets and NFTs 2. A social network for gamers and content creators to communicate with one another 3. A live stream application to stream contents ### Table of Milestone | Milestones | Links/Deliverables | | ---------------- | ---------------- | | Complete Social Media and Streaming app development | [Freetyl](https://testnet.freetyl.io/) | | Hire Rust developers and GameFi experts | [Letter of Employment](https://drive.google.com/file/d/1TenttiMvYZGlaL7Yd5onWZ8kWW2yX2py/view?usp=share_link) [Github Account Link](https://github.com/scapula07) | |Build Joystick Token Smart Contract on NEAR | [JSK Token Testnet](https://explorer.testnet.near.org/transactions/AJ4zY5Q9UfXTbsJAsc2NpPuWN5L1QU6H4WBMqTLh3aUT) | |Joystick Game Teasers & Trailers |[Link](https://drive.google.com/file/d/1d3dIbvK7BfcldGYGoI8i8k03YsyqNmdg/view?usp=sharing) | |Complete technical testing |Text | ```
mehtaphysical_art-work-app
.vscode settings.json asconfig.json assembly as_types.d.ts index.ts tsconfig.json fe-app README.md package.json public index.html manifest.json robots.txt src index.js services art.js package.json
# 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: ### `yarn start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) 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)
hermessecund_near-sosmed-contracts
README.md main-contract Cargo.toml build.sh deploy.sh src lib.rs post.rs user.rs
# Decentralized Social Media - Contract Repo This repo serves written smart contract code for decentralized social media app. **Client repo could be visited through this [link](https://github.com/laitsky/decentralized-social-media)** The smart contract was written using Rust and NEAR SDK. Finished functions on the smart contract: - Create account - Check if an user exists - Get an account details - Edit account - Check if user is followed by another user - Follow/unfollow user - Get user following list and count - Get user follower list and count - Create new post - Like a post - Give comment on a post - Retrieve post comment details - Retrieve post likes details - Get poster address based on post ID - Retrieve all available posts - Retrieve single post detail - Get specific user posts
FucktheKingcode_Uranus
.gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src lib.rs target .rustc_info.json release .fingerprint Inflector-e6c94e9a894426cc lib-inflector.json ahash-be7d3dcadc11df0f build-script-build-script-build.json borsh-derive-33001e212de08eef lib-borsh-derive.json borsh-derive-internal-015e30a79e0ff5aa lib-borsh-derive-internal.json borsh-schema-derive-internal-8db1d31d2cd3c965 lib-borsh-schema-derive-internal.json crunchy-86ab52436e71cfbe build-script-build-script-build.json near-sdk-macros-64b9527309daf330 lib-near-sdk-macros.json proc-macro-crate-609f527ee49bf0da lib-proc-macro-crate.json proc-macro2-2af6e608c487cf29 lib-proc-macro2.json proc-macro2-6942a756ff2fa902 build-script-build-script-build.json proc-macro2-a971207d3747d958 run-build-script-build-script-build.json quote-e340e0d1efec2237 lib-quote.json schemars-98d9b5767950cecd build-script-build-script-build.json schemars_derive-757991f73d634616 lib-schemars_derive.json semver-617c56d76ac1397c build-script-build-script-build.json serde-4a82e612bb5e924e run-build-script-build-script-build.json serde-5f9781b7a8715acf lib-serde.json serde-86fe527015a871f7 build-script-build-script-build.json serde-e953858f48fda48f build-script-build-script-build.json serde_derive-70bc60812e2686a3 lib-serde_derive.json serde_derive_internals-7df0758ca55b7ccf lib-serde_derive_internals.json serde_json-8d54e293787ed74c build-script-build-script-build.json syn-110d42369912b06e lib-syn.json syn-52595f17440013b6 run-build-script-build-script-build.json syn-93d2f34fdd6f7aaf lib-syn.json syn-dee6a7e28f7dcfa7 build-script-build-script-build.json toml-fbc7d316475ba83c lib-toml.json unicode-ident-a2435905867009fc lib-unicode-ident.json version_check-c2908a003991f88b lib-version_check.json wee_alloc-aa531acaf38f55ef build-script-build-script-build.json wasm32-unknown-unknown release .fingerprint ahash-8120dd8f398c456e lib-ahash.json ahash-badad04baac78cee run-build-script-build-script-build.json base64-5f88084a906491af lib-base64.json borsh-a896ba70103e63c0 lib-borsh.json bs58-fdcd9e4386053a8a lib-bs58.json byteorder-6ee1062ac42e19fd lib-byteorder.json cfg-if-ed6319254f2ac6c9 lib-cfg-if.json crunchy-48bfaffbfe599ad8 run-build-script-build-script-build.json crunchy-dc25377e27ce5ed5 lib-crunchy.json dyn-clone-1f893cf1bb88f239 lib-dyn-clone.json hashbrown-20b8244bf32cf285 lib-hashbrown.json hello_near-00ca379cccdf6430 lib-hello_near.json hex-5848bfa5e5d6fb7b lib-hex.json itoa-61bbcca3c98f0b46 lib-itoa.json memory_units-30fbdd35bce85c99 lib-memory_units.json near-abi-b75c5f9bba69e0f8 lib-near-abi.json near-sdk-1651074d25b9ae82 lib-near-sdk.json near-sys-2df7bc89594ec1d0 lib-near-sys.json once_cell-a84088dd32f6a49d lib-once_cell.json ryu-467680a73147b083 lib-ryu.json schemars-b0af12db8e031f91 run-build-script-build-script-build.json schemars-fd3e42f1f0fda77b lib-schemars.json semver-2f8830f9c44d3001 lib-semver.json semver-908f87917051027a run-build-script-build-script-build.json serde-095a25a4a43e82f6 run-build-script-build-script-build.json serde-60521d9cbe1f0866 lib-serde.json serde_json-a94d8b512be2f256 lib-serde_json.json serde_json-dc9ac22e2bf19aa9 run-build-script-build-script-build.json static_assertions-7fb90f37b417cd40 lib-static_assertions.json uint-ceb2d198cf8b5dc8 lib-uint.json wee_alloc-8768961fc67f6cab lib-wee_alloc.json wee_alloc-f825098e48d8671d run-build-script-build-script-build.json build crunchy-48bfaffbfe599ad8 out lib.rs wee_alloc-f825098e48d8671d out wee_alloc_static_array_backend_size_bytes.txt frontend App.js assets global.css logo-black.svg logo-white.svg dist fetch.5aa4d3e3.js 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-toolchain.toml
# 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
mpeterdev_console-boilerplate-template-rs-2
.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
# 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>`. <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)._
NEARFoundation_NEAR-NDC-Trust-Instrument-OS
README.md
# NEAR NDC Trust Instrument OS This is a template trust instrument for a Guernsey Non-Charitable Purpose Trust, based on the trust instrument used by the NEAR Digital Collective (NDC) to launch the NEAR Community Purpose Trust. ## Disclaimer For information purposes only. Use at own risk, with appropriate legal advice and subject to the disclaimer contained in the template.
Learn-NEAR-Club_todo
README.md as-pect.config.js asconfig.json command.md neardev dev-account.env node_modules .package-lock.json @as-pect assembly README.md assembly index.ts internal Actual.ts Expectation.ts Expected.ts Reflect.ts ReflectedValueType.ts Test.ts assert.ts call.ts comparison toIncludeComparison.ts toIncludeEqualComparison.ts log.ts noOp.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 umd 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 README.md assembly __tests__ as-pect.d.ts i128.spec.as.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 package.json asbuild README.md dist cli.d.ts cli.js index.d.ts index.js main.d.ts main.js index.js node_modules cliui CHANGELOG.md LICENSE.txt README.md index.js package.json wrap-ansi index.js package.json readme.md y18n CHANGELOG.md README.md index.js package.json 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.json assemblyscript-json .eslintrc.js .travis.yml README.md as-pect.config.js assembly JSON.ts __tests__ as-pect.d.ts json-parse.spec.ts roundtrip.spec.ts to-string.spec.ts usage.spec.ts decoder.ts encoder.ts index.ts tsconfig.json util index.ts docs README.md classes decoderstate.md json.arr.md json.bool.md json.float.md json.integer.md json.null.md json.num.md json.obj.md json.str.md json.value.md jsondecoder.md jsonencoder.md jsonhandler.md throwingjsonhandler.md modules json.md 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 bin rtplot.js 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 console.ts crypto.ts dataview.ts date.ts diagnostics.ts error.ts function.ts index.d.ts iterator.ts map.ts math.ts memory.ts number.ts object.ts polyfills.ts process.ts reference.ts regexp.ts rt.ts rt README.md common.ts index-incremental.ts index-minimal.ts index-stub.ts index.d.ts itcms.ts rtrace.ts stub.ts tcms.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 uri.ts util casemap.ts error.ts hash.ts math.ts memory.ts number.ts sort.ts string.ts uri.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 .github FUNDING.yml 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 build lib index.js string-utils.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 escalade dist index.js index.d.ts package.json readme.md sync index.d.ts index.js 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 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 hasurl README.md index.js package.json inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json 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 max-heap.spec.ts model.ts near.spec.ts persistent-set.spec.ts promise.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 json.lib.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 maxHeap.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 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 require-directory .travis.yml index.js package.json require-main-filename CHANGELOG.md LICENSE.txt README.md index.js package.json 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 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 cjs decorator.js index.js mixin-tracking.js mixins.js proxy.js settings.js types.js util.js esm index.js index.min.js types decorator.d.ts index.d.ts mixin-tracking.d.ts mixins.d.ts proxy.d.ts settings.d.ts types.d.ts util.d.ts package.json universal-url README.md browser.js index.js package.json visitor-as .github workflows test.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 build lib cjs.js index.js platform-shims node.js package.json yallist README.md iterator.js package.json yallist.js yargs-parser CHANGELOG.md LICENSE.txt README.md browser.js build lib index.js string-utils.js tokenize-arg-string.js yargs-parser-types.js yargs-parser.js package.json yargs CHANGELOG.md README.md build lib argsert.js command.js completion-templates.js completion.js middleware.js parse-command.js typings common-types.js yargs-parser-types.js usage.js utils apply-extends.js is-promise.js levenshtein.js obj-filter.js process-argv.js set-blocking.js which-module.js validation.js yargs-factory.js yerror.js helpers index.js package.json 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 | package-lock.json package.json scripts build.sh full.sh view_call.sh src as-pect.d.ts as_types.d.ts sample __tests__ README.md index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
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> 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**(low: `number`, high: `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 // 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 }); } ``` # 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 ``` Shims used when bundling asc for browser usage. # 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 # 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. [Describe]: greeting [Success]: ✔ should respond to sayHi() [Success]: ✔ should respond to greetingUser() [Success]: ✔ should respond to addToMyList() [Success]: ✔ should respond to getNumTasks() [Success]: ✔ should respond to showMyTasks() [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]: 5 pass, 0 fail, 5 total [Time]: 16.649ms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Result]: ✔ PASS [Files]: 1 total [Groups]: 2 count, 2 pass [Tests]: 5 pass, 0 fail, 5 total [Time]: 14260.268ms $ cargo test -- --nocapture # 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. # 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). # [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} } ``` # cliui ![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) easily create complex multi-column command-line-interfaces. ## Example ```js const ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 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()) ``` ## Deno/ESM Support As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and [ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): ```typescript import cliui from "https://deno.land/x/cliui/deno.ts"; const ui = cliui({}) ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div({ text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }) 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`. # 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/ # 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. # 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) 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 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 ``` [![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 ``` # 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) ``` # 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.) # 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. # 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) # 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. # 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. # 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 Rtrace A tiny utility to sanitize the AssemblyScript runtime. Records allocations 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 const 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; } }); const { module, instance } = await WebAssembly.instantiate(..., rtrace.install({ ...imports... }) ); instance.exports._start(); ... if (rtrace.active) { let leakCount = rtr.check(); if (leakCount) { // handle error } } ``` Note that references in globals which are not cleared before collection is performed 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. <p align="center"> <img width="250" src="https://raw.githubusercontent.com/yargs/yargs/master/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> ![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) [![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: ``` mocha [spec..] Run tests with Mocha Commands mocha inspect [spec..] Run tests with Mocha [default] mocha init <path> create a client-side Mocha setup at <path> Rules & Behavior --allow-uncaught Allow uncaught errors to propagate [boolean] --async-only, -A Require all tests to use a callback (async) or return a Promise [boolean] ``` * 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 yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') const argv = yargs(hideBin(process.argv)).argv 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 const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') yargs(hideBin(process.argv)) .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. ## Supported Platforms ### TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ### Deno As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): ```typescript import yargs from 'https://deno.land/x/yargs/deno.ts' import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' yargs(Deno.args) .command('download <files...>', 'download a list of files', (yargs: any) => { return yargs.positional('files', { describe: 'a list of files to do something with' }) }, (argv: Arguments) => { console.info(argv) }) .strictCommands() .demandCommand(1) .argv ``` ### ESM As of `v16`,`yargs` supports ESM imports: ```js import yargs from 'yargs' import { hideBin } from 'yargs/helpers' yargs(hideBin(process.argv)) .command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => { console.info(argv) }) .demandCommand(1) .argv ``` ### Usage in Browser See examples of using yargs in the browser in [docs](/docs/browser.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) * [Bundling yargs](/docs/bundling.md) * [Contributing](/contributing.md) ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). [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 # 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 # 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 # 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. # 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. # 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) ``` [![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_ # 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. # 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,4.1,4.2?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) <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> [![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). # 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 The AssemblyScript Runtime ========================== The runtime provides the functionality necessary to dynamically allocate and deallocate memory of objects, arrays and buffers, as well as collect garbage that is no longer used. The current implementation is either a Two-Color Mark & Sweep (TCMS) garbage collector that must be called manually when the execution stack is unwound or an Incremental Tri-Color Mark & Sweep (ITCMS) garbage collector that is fully automated with a shadow stack, implemented on top of a Two-Level Segregate Fit (TLSF) memory manager. It's not designed to be the fastest of its kind, but intentionally focuses on simplicity and ease of integration until we can replace it with the real deal, i.e. Wasm GC. Interface --------- ### Garbage collector / `--exportRuntime` * **__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`. * **__pin**(ptr: `usize`): `usize`<br /> Pins the object pointed to by `ptr` externally so it and its directly reachable members and indirectly reachable objects do not become garbage collected. * **__unpin**(ptr: `usize`): `void`<br /> Unpins the object pointed to by `ptr` externally so it can become garbage collected. * **__collect**(): `void`<br /> Performs a full garbage collection. ### Internals * **__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**(ptr: `usize`, size: `usize`): `usize`<br /> Dynamically changes the size of a chunk of memory, possibly moving it to a new address. * **__free**(ptr: `usize`): `void`<br /> Frees a dynamically allocated chunk of memory by its address. * **__renew**(ptr: `usize`, size: `usize`): `usize`<br /> Like `__realloc`, but for `__new`ed GC objects. * **__link**(parentPtr: `usize`, childPtr: `usize`, expectMultiple: `bool`): `void`<br /> Introduces a link from a parent object to a child object, i.e. upon `parent.field = child`. * **__visit**(ptr: `usize`, cookie: `u32`): `void`<br /> Concrete visitor implementation called during traversal. Cookie can be used to indicate one of multiple operations. * **__visit_globals**(cookie: `u32`): `void`<br /> Calls `__visit` on each global that is of a managed type. * **__visit_members**(ptr: `usize`, cookie: `u32`): `void`<br /> Calls `__visit` on each member of the object pointed to by `ptr`. * **__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 type is managed, an array or similar, and what the relevant alignments when creating an instance externally are etc. * **__instanceof**(ptr: `usize`, classId: `u32`): `bool`<br /> Tests if the object pointed to by `ptr` is an instance of the specified class id. ITCMS / `--runtime incremental` ----- The Incremental Tri-Color Mark & Sweep garbage collector maintains a separate shadow stack of managed values in the background to achieve full automation. Maintaining another stack introduces some overhead compared to the simpler Two-Color Mark & Sweep garbage collector, but makes it independent of whether the execution stack is unwound or not when it is invoked, so the garbage collector can run interleaved with the program. There are several constants one can experiment with to tweak ITCMS's automation: * `--use ASC_GC_GRANULARITY=1024`<br /> How often to interrupt. The default of 1024 means "interrupt each 1024 bytes allocated". * `--use ASC_GC_STEPFACTOR=200`<br /> How long to interrupt. The default of 200% means "run at double the speed of allocations". * `--use ASC_GC_IDLEFACTOR=200`<br /> How long to idle. The default of 200% means "wait for memory to double before kicking in again". * `--use ASC_GC_MARKCOST=1`<br /> How costly it is to mark one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. * `--use ASC_GC_SWEEPCOST=10`<br /> How costly it is to sweep one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. TCMS / `--runtime minimal` ---- If automation and low pause times aren't strictly necessary, using the Two-Color Mark & Sweep garbage collector instead by invoking collection manually at appropriate times when the execution stack is unwound may be more performant as it simpler and has less overhead. The execution stack is typically unwound when invoking the collector externally, at a place that is not indirectly called from Wasm. STUB / `--runtime stub` ---- The stub is a maximally minimal runtime substitute, consisting of a simple and fast bump allocator with no means of freeing up memory again, except when freeing the respective most recently allocated object on top of the bump. Useful where memory is not a concern, and/or where it is sufficient to destroy the whole module including any potential garbage after execution. See also: [Garbage collection](https://www.assemblyscript.org/garbage-collection.html) 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. # 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. assemblyscript-json # assemblyscript-json ## Table of contents ### Namespaces - [JSON](modules/json.md) ### Classes - [DecoderState](classes/decoderstate.md) - [JSONDecoder](classes/jsondecoder.md) - [JSONEncoder](classes/jsonencoder.md) - [JSONHandler](classes/jsonhandler.md) - [ThrowingJSONHandler](classes/throwingjsonhandler.md) 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`. # 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)) ``` # 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 # 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. ![a fun cartoon logo made of glob characters](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) ## 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) # 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`. # <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() ``` # 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 ``` ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## 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. # 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 # 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() } } ``` # listtodo # 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 # 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 # 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. # 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. # 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). # 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. # 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 # assemblyscript-json ![npm version](https://img.shields.io/npm/v/assemblyscript-json) ![npm downloads per month](https://img.shields.io/npm/dm/assemblyscript-json) JSON encoder / decoder for AssemblyScript. Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing infra for AssemblyScript. ## Installation `assemblyscript-json` is available as a [npm package](https://www.npmjs.com/package/assemblyscript-json). You can install `assemblyscript-json` in your AssemblyScript project by running: `npm install --save assemblyscript-json` ## Usage ### Parsing JSON ```typescript import { JSON } from "assemblyscript-json"; // Parse an object using the JSON object let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}')); // We can then use the .getX functions to read from the object if you know it's type // This will return the appropriate JSON.X value if the key exists, or null if the key does not exist let worldOrNull: JSON.Str | null = jsonObj.getString("hello"); // This will return a JSON.Str or null if (worldOrNull != null) { // use .valueOf() to turn the high level JSON.Str type into a string let world: string = worldOrNull.valueOf(); } let numOrNull: JSON.Num | null = jsonObj.getNum("value"); if (numOrNull != null) { // use .valueOf() to turn the high level JSON.Num type into a f64 let value: f64 = numOrNull.valueOf(); } // If you don't know the value type, get the parent JSON.Value let valueOrNull: JSON.Value | null = jsonObj.getValue("hello"); if (valueOrNull != null) { let value: JSON.Value = changetype<JSON.Value>(valueOrNull); // Next we could figure out what type we are if(value.isString) { // value.isString would be true, so we can cast to a string let stringValue: string = changetype<JSON.Str>(value).toString(); // Do something with string value } } ``` ### Encoding JSON ```typescript import { JSONEncoder } from "assemblyscript-json"; // 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(); assert(jsonString, '"obj": {"int": 10, "str": ""}'); // True! ``` ### Custom JSON Deserializers ```typescript import { JSONDecoder, JSONHandler } from "assemblyscript-json"; // 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: i64): void { // Handle field } setFloat(name: string, value: f64): 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()); // Create a byte buffer of our JSON. NOTE: Deserializers work on UTF8 string buffers. let jsonString = '{"hello": "world"}'; let jsonBuffer = Uint8Array.wrap(String.UTF8.encode(jsonString)); // Parse JSON decoder.deserialize(jsonBuffer); // This will send events to MyJSONEventsHandler ``` Feel free to look through the [tests](https://github.com/nearprotocol/assemblyscript-json/tree/master/assembly/__tests__) for more usage examples. ## Reference Documentation Reference API Documentation can be found in the [docs directory](./docs). ## License [MIT](./LICENSE) # 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'. # 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). Like `chown -R`. Takes the same arguments as `fs.chown()` # 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) 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 <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 # 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 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) 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 }); }); ... ``` # 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. # 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. 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)); ``` # yargs-parser ![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) 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 const argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```console $ node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js const argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```console { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js const parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## Deno Example As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): ```typescript import parser from "https://deno.land/x/yargs_parser/deno.ts"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` ## ESM Example As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): **Node.js:** ```js import parser from 'yargs-parser' const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` **Browsers:** ```html <!doctype html> <body> <script type="module"> import parser from "https://unpkg.com/[email protected]/browser.js"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) </script> </body> ``` ## API ### 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? ```console $ node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```console $ node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```console $ node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```console $ node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```console $ node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```console $ 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? ```console $ node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```console $ node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### parse positional numbers * default: `true` * key: `parse-positional-numbers` Should positional keys that look like numbers be treated as such. ```console $ node example.js 99.3 { _: [99.3] } ``` _if disabled:_ ```console $ node example.js 99.3 { _: ['99.3'] } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```console $ node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```console $ 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: ```console $ node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```console $ 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: ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```console $ 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. ```console $ node example --arr 1 2 { _[], arr: [1, 2] } ``` _if disabled:_ ```console $ 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. ```console $ node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```console $ node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```console $ node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```console $ 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:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```console $ 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:_ ```console $ node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```console $ 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:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```console $ 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:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```console $ 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_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## 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 # 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. # y18n [![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 const __ = require('y18n')().__; console.log(__('my awesome string %s', 'foo')); ``` output: `my awesome string foo` _using tagged template literals_ ```js const __ = require('y18n')().__; const str = 'foo'; console.log(__`my awesome string ${str}`); ``` output: `my awesome string foo` _pluralization support:_ ```js const __n = require('y18n')().__n; console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); ``` output: `2 fishes foo` ## Deno Example As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): ```typescript import y18n from "https://deno.land/x/y18n/deno.ts"; const __ = y18n({ locale: 'pirate', directory: './test/locales' }).__ console.info(__`Hi, ${'Ben'} ${'Coe'}!`) ``` You will need to run with `--allow-read` to load alternative locales. ## 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`. ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## License ISC [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 ![](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)
near_near-state-indexer
.buildkite pipeline.yml .fossa.yml .github ISSUE_TEMPLATE BOUNTY.yml CHANGELOG.md CONTRIBUTING.md Cargo.toml README.md TROBLESHOOTING.md rust-toolchain.toml rustfmt.toml src configs.rs main.rs retriable.rs
# NEAR State Indexer NEAR State Indexer is built on top of [NEAR Indexer microframework](https://github.com/near/nearcore/tree/master/chain/indexer) to watch the network and store all the state changes in the Redis database. It can be consumed by https://github.com/vgrichina/fast-near to run NEAR RPC service. ## Self-hosting Before you proceed, make sure you have the following software installed: * [rustup](https://rustup.rs/) or Rust version that is mentioned in `rust-toolchain` file in the root of [nearcore](https://github.com/nearprotocol/nearcore) project. Clone this repository and open the project folder ```bash $ git clone [email protected]:near/near-indexer-for-explorer.git $ cd near-indexer-for-explorer ``` You need to provide database credentials in `.env` file like below (replace Redis connection string as needed): ```bash $ echo "REDIS_URL=redis://127.0.0.1/" > .env ``` To connect the specific chain you need to have necessary configs, you can generate it as follows: ```bash $ cargo run --release -- --home-dir ~/.near/testnet init --chain-id testnet --download-config ``` The above code will download the official genesis config and generate necessary configs. You can replace `testnet` in the command above to different network ID (`betanet`, `mainnet`). **NB!** According to changes in `nearcore` config generation we don't fill all the necessary fields in the config file. While this issue is open https://github.com/nearprotocol/nearcore/issues/3156 you need to download config you want and replace the generated one manually. - [testnet config.json](https://s3-us-west-1.amazonaws.com/build.nearprotocol.com/nearcore-deploy/testnet/config.json) - [betanet config.json](https://s3-us-west-1.amazonaws.com/build.nearprotocol.com/nearcore-deploy/betanet/config.json) - [mainnet config.json](https://s3-us-west-1.amazonaws.com/build.nearprotocol.com/nearcore-deploy/mainnet/config.json) Configs for the specified network are in the `--home-dir` provided folder. We need to ensure that NEAR State Indexer follows all the necessary shards, so `"tracked_shards"` parameters in `~/.near/testnet/config.json` needs to be configured properly. For example, with a single shared network, you just add the shard #0 to the list: ``` ... "tracked_shards": [0], ... ``` ## Running NEAR State Indexer: Command to run NEAR State Indexer have to contain sync mode. You can choose NEAR State Indexer sync mode by setting what to stream: - `sync-from-latest` - start indexing blocks from the latest finalized block - `sync-from-interruption --delta <number_of_blocks>` - start indexing blocks from the block NEAR Indexer was interrupted last time but earlier for `<number_of_blocks>` if provided - `sync-from-block --height <block_height>` - start indexing blocks from the specific block height Optionally you can tell Indexer to store data from genesis (Accounts and Access Keys) by adding key `--store-genesis` to the `run` command. NEAR State Indexer works in strict mode by default, but you can disable it for specific amount of blocks. The strict mode means that every piece of data will be retried to store to database in case of error. Errors may occur when the parent piece of data is still processed but the child piece is already trying to be stored. So Indexer keeps retrying to store the data until success. However if you're running Indexer not from the genesis it is possible that you really miss some of parent data and it'll be impossible to store child one, so you can disable strict mode for 1000 blocks to ensure you've passed the strong relation data area and you're running Indexer where it is impossible to loose any piece of data. To disable strict mode you need to provide: ``` --non-strict-mode ``` Sometimes you may want to index block while sync process is happening, by default an indexer node is waiting for full sync to complete but you can enable indexing while the node is syncing by passing `--stream-while-syncing` By default NEAR State Indexer processes only a single block at a time. You can adjust this with the `--concurrency` argument (when the blocks are mostly empty, it is fine to go with as many as 100 blocks of concurrency). So final command to run NEAR State Indexer can look like: ```bash $ cargo run --release -- --home-dir ~/.near/testnet run --store-genesis --stream-while-syncing --non-strict-mode --stop-after-number-of-blocks 1000 --concurrency 1 sync-from-latest ``` After the network is synced, you should see logs of every block height currently received by NEAR State Indexer. ## Syncing Whenever you run NEAR State Indexer for any network except localnet you'll need to sync with the network. This is required because it's a natural behavior of `nearcore` node and NEAR State Indexer is a wrapper for the regular `nearcore` node. In order to work and index the data your node must be synced with the network. This process can take a while, so we suggest to download a fresh backup of the `data` folder and put it in you `--home-dir` of your choice (by default it is `~/.near`) Running your NEAR State Indexer node on top of a backup data will reduce the time of syncing process because your node will download only missing data and it will take reasonable time. All the backups can be downloaded from the public S3 bucket which contains latest daily snapshots: * [Recent 5-epoch Mainnet data folder](https://near-protocol-public.s3.ca-central-1.amazonaws.com/backups/mainnet/rpc/data.tar) * [Recent 5-epoch Testnet data folder](https://near-protocol-public.s3.ca-central-1.amazonaws.com/backups/testnet/rpc/data.tar) ## Running NEAR State Indexer as archival node It's not necessary but in order to index everything in the network it is better to do it from the genesis. `nearcore` node is running in non-archival mode by default. That means that the node keeps data only for [5 last epochs](https://docs.near.org/docs/concepts/epoch). In order to index data from the genesis we need to turn the node in archival mode. To do it we need to update `config.json` located in `--home-dir` or your choice (by default it is `~/.near`). Find next keys in the config and update them as following: ```json { ... "archive": true, "tracked_shards": [0], ... } ``` The syncing process in archival mode can take a lot of time, so it's better to download a backup provided by NEAR and put it in your `data` folder. After that your node will need to sync only missing data and it should take reasonable time. All the backups can be downloaded from the public S3 bucket which contains latest daily snapshots: * [Archival Mainnet data folder](https://near-protocol-public.s3.ca-central-1.amazonaws.com/backups/mainnet/archive/data.tar) * [Archival Testnet data folder](https://near-protocol-public.s3.ca-central-1.amazonaws.com/backups/testnet/archive/data.tar) See https://docs.near.org/docs/roles/integrator/exchange-integration#running-an-archival-node for reference ## Local debugging If you want to play with the code locally, it's better not to copy existing mainnet/testnet (it requires LOTS of memory), but to have your own small example. Go through steps [above](https://github.com/near/near-indexer-for-explorer#self-hosting) until (by not including) `init` command. Then use `init` command with different arguments, ```bash $ cargo run --release -- --home-dir ~/.near/localnet init --chain-id localnet ``` Edit `~/.near/localnet/config.json` by adding tracking shards and archiving option (see [example above](https://github.com/near/near-indexer-for-explorer#running-near-indexer-for-explorer-as-archival-node)). ```bash $ cargo run -- --home-dir ~/.near/localnet run --store-genesis sync-from-latest ``` Congrats, the blocks are being produced right now! There should be some lines in the DB. Now, we need to generate some activity to add new examples. ```bash $ npm i -g near-cli $ NEAR_ENV=local near create-account awesome.test.near --initialBalance 30 --masterAccount test.near --keyPath=~/.near/localnet/validator_key.json $ NEAR_ENV=local near send test.near awesome.test.near 5 ``` All available commands are [here](https://github.com/near/near-cli#near-cli-command-line-interface). You can stop and re-run the example at any time. Blocks will continue producing from the last state. ## Troubleshooting When operating normally, you should see "INFO indexer_for_explorer: Block height ..." messages in the logs. ### The node is fully synced and running, but no indexer messages and no transactions in the database (not indexing) Make sure the blocks you want to save exist on the node. Check them via [JSON RPC](https://docs.near.org/docs/api/rpc#block-details): ``` curl http://127.0.0.1:3030/ -X POST --header 'Content-type: application/json' --data '{"jsonrpc": "2.0", "id": "dontcare", "method": "block", "params": {"block_id": 9820214}}' ``` NOTE: Block #9820214 is the first block after genesis block (#9820210) on Mainnet. If it returns an error that the block does not exist or missing, it means that your node does not have the necessary data. Your options here are to start from the blocks that are recorded on the node or start an archival node (see above) and make sure you have the full network history (either use a backup or let the node sync from scratch (it is quite slow, so backup is recommended))
NEAR-Hispano_magic-chess
.gitpod.yml README.md babel.config.js contract Cargo.toml README.md compile.js src lib.rs 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
magic-chess 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 magic-chess ================== 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: `npm install` 3. Run the local development server: `npm run dev` (see `package.json` for a full list of `scripts` you can run with `npm`) 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 `npm run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run 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 `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 `magic-chess.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `magic-chess.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 magic-chess.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 || 'magic-chess.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: npm run 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
esaminu_console-donation-template-23q89
.github scripts runfe.sh workflows deploy-to-console.yml readme.yml tests.yml .gitpod.yml README.md contract README.md build.sh deploy.sh package-lock.json package.json src contract.ts model.ts utils.ts tsconfig.json integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json
# 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-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) [![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fnear-examples%2Fdonation-js%2Fbadge&style=flat&label=Tests)](https://actions-badge.atrox.dev/near-examples/donation-js/goto) 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-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 ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome). # Donation Contract The smart contract exposes methods to handle donating $NEAR to a `beneficiary`. ```ts @call donate() { // Get who is calling the method and how much $NEAR they attached let donor = near.predecessorAccountId(); let donationAmount: bigint = near.attachedDeposit() as bigint; let donatedSoFar = this.donations.get(donor) === null? BigInt(0) : BigInt(this.donations.get(donor) as string) let toTransfer = donationAmount; // This is the user's first donation, lets register it, which increases storage if(donatedSoFar == BigInt(0)) { assert(donationAmount > STORAGE_COST, `Attach at least ${STORAGE_COST} yoctoNEAR`); // Subtract the storage cost to the amount to transfer toTransfer -= STORAGE_COST } // Persist in storage the amount donated so far donatedSoFar += donationAmount this.donations.set(donor, donatedSoFar.toString()) // Send the money to the beneficiary const promise = near.promiseBatchCreate(this.beneficiary) near.promiseBatchActionTransfer(promise, toTransfer) // Return the total amount donated so far return donatedSoFar.toString() } ``` <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 ``` 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> init '{"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>`.
khoa-nvk_paydii-near
.github workflows tests.yml .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh src call_terminal.txt lib.rs paydii.rs target .rustc_info.json debug .fingerprint Inflector-06fc89ebb1419705 lib-inflector.json ahash-8dc18f8d33529380 run-build-script-build-script-build.json ahash-ba1278f2114c5ee8 lib-ahash.json ahash-fd96d6157b5fc5dc build-script-build-script-build.json arrayref-181babb8235e4940 lib-arrayref.json arrayvec-02bf59924e01da96 lib-arrayvec.json arrayvec-30831b0edd109f69 lib-arrayvec.json autocfg-a8094e5db7aeb3b9 lib-autocfg.json base64-061765eebc6ab889 lib-base64.json base64-8526695c07182036 lib-base64.json bitvec-70796b31f33abdb8 lib-bitvec.json blake2-44a0114917d7d8b7 lib-blake2.json block-buffer-16f4c6e7e1e10e80 lib-block-buffer.json block-buffer-33368cdc1dcbd462 lib-block-buffer.json borsh-769f4109db0a8bba lib-borsh.json borsh-derive-57673fa18435d456 lib-borsh-derive.json borsh-derive-internal-9bea6bf01b0a63de lib-borsh-derive-internal.json borsh-schema-derive-internal-226fea01cdfe892b lib-borsh-schema-derive-internal.json bs58-c1fc162ef573dba3 lib-bs58.json byte-slice-cast-b9ccdfbd8c4334b1 lib-byte-slice-cast.json byteorder-51817991a0132537 lib-byteorder.json bytesize-d363966817cf34f9 lib-bytesize.json c2-chacha-c2dc3ad2c7ffcfaf lib-c2-chacha.json cc-f95177fd45f972e5 lib-cc.json cfg-if-439c63f29a387258 lib-cfg-if.json cfg-if-602366ad92ff528c lib-cfg-if.json cfg-if-6c91d993d710cd83 lib-cfg-if.json chrono-ba42a4002b47fa43 lib-chrono.json cipher-9d88564d80205adb lib-cipher.json contract-db323a6727c4c688 lib-contract.json contract-db3b4c7446856082 test-lib-contract.json convert_case-229873f6b459944d lib-convert_case.json core-foundation-sys-1ffc03650d1b79be run-build-script-build-script-build.json core-foundation-sys-5c78e5f6fa101158 lib-core-foundation-sys.json core-foundation-sys-60a7c801cee78c38 build-script-build-script-build.json cpufeatures-0462cffc1a80e3a3 lib-cpufeatures.json crunchy-155a116eb952279b run-build-script-build-script-build.json crunchy-a20148c49ee472f5 lib-crunchy.json crunchy-d670c53c9a8d060c build-script-build-script-build.json crypto-common-d10d02a949ad5619 lib-crypto-common.json crypto-mac-1998602761c926a9 lib-crypto-mac.json curve25519-dalek-7fba5396d1e8af1c lib-curve25519-dalek.json derive_more-3c6a356b5661d8f2 lib-derive_more.json digest-22d671fa2891af77 lib-digest.json digest-94675d9c29be0adf lib-digest.json easy-ext-bce5aab97e6f2ac8 lib-easy-ext.json ed25519-43ba35faa225b702 lib-ed25519.json ed25519-dalek-ce7f7d74aa709da0 lib-ed25519-dalek.json fixed-hash-4392543644803172 lib-fixed-hash.json funty-9e453fa8899cc179 lib-funty.json generic-array-16d95d073cbde43b lib-generic_array.json generic-array-1aed5e8dd5017722 build-script-build-script-build.json generic-array-277ca85636969e11 run-build-script-build-script-build.json getrandom-0d40cf8b822001c8 lib-getrandom.json getrandom-3e32493ca521f551 build-script-build-script-build.json getrandom-76ac8b41823da965 lib-getrandom.json getrandom-8ecbe5de1d40f9fa run-build-script-build-script-build.json hashbrown-570a74799f2e452f lib-hashbrown.json heck-993562c5147ab636 lib-heck.json hex-00bc11ce0455e8b8 lib-hex.json iana-time-zone-69e1f107d89017f4 lib-iana-time-zone.json impl-codec-4937650c44456375 lib-impl-codec.json impl-trait-for-tuples-dc11bcf415534235 lib-impl-trait-for-tuples.json itoa-2cd7adad9a7f4e5c lib-itoa.json keccak-7369d951e85cc9d9 lib-keccak.json libc-24c81b13eea3363d build-script-build-script-build.json libc-2922a8e233526779 run-build-script-build-script-build.json libc-9e24396dc990764d lib-libc.json memory_units-ed9cb6b41fa1ea61 lib-memory_units.json near-account-id-7faaecc7e8d9d9ad lib-near-account-id.json near-crypto-89908037200d1790 lib-near-crypto.json near-primitives-72606b35045013fc lib-near-primitives.json near-primitives-core-b2a5a4a06bb2e766 lib-near-primitives-core.json near-rpc-error-core-9f84da5612bdbd0e lib-near-rpc-error-core.json near-rpc-error-macro-32654c0dbfc4ffb7 lib-near-rpc-error-macro.json near-sdk-c52616fd763b7485 lib-near-sdk.json near-sdk-macros-45e1864f9df7f8b0 lib-near-sdk-macros.json near-sys-bb0696488776a567 lib-near-sys.json near-vm-errors-1eb0dbfad538d39e lib-near-vm-errors.json near-vm-logic-a04361da049ba585 lib-near-vm-logic.json num-bigint-3e0da93e75ba3544 build-script-build-script-build.json num-bigint-b280e2e279e9a747 run-build-script-build-script-build.json num-bigint-f6a58184f0c6bf2e lib-num-bigint.json num-integer-1ba4ac498a86e685 build-script-build-script-build.json num-integer-81c4b3c8cee43ab8 lib-num-integer.json num-integer-f7e4ea9fde79b0fe run-build-script-build-script-build.json num-rational-6554d6d9d2d23464 lib-num-rational.json num-rational-c9518ad0aa42347d build-script-build-script-build.json num-rational-e290183ace118e9d run-build-script-build-script-build.json num-traits-42a34840034df151 lib-num-traits.json num-traits-9591c74318da00b6 run-build-script-build-script-build.json num-traits-fe0ac8b63094c67a build-script-build-script-build.json once_cell-ab411aabbff9ff36 lib-once_cell.json once_cell-bd0271d32e68b3cf lib-once_cell.json opaque-debug-272fb658f6a0c4de lib-opaque-debug.json parity-scale-codec-a40221c3813c889c lib-parity-scale-codec.json parity-scale-codec-derive-4e90ad322b26de0f lib-parity-scale-codec-derive.json parity-secp256k1-4255957560901a67 lib-secp256k1.json parity-secp256k1-6535b23c50837cb7 run-build-script-build-script-build.json parity-secp256k1-94179fc9db5f8748 build-script-build-script-build.json ppv-lite86-f69aa681226c18a8 lib-ppv-lite86.json primitive-types-cbed334a3067493a lib-primitive-types.json proc-macro-crate-df09ed97c75a7f7f lib-proc-macro-crate.json proc-macro-crate-f92fa9c632905335 lib-proc-macro-crate.json proc-macro2-06f08a5758960733 run-build-script-build-script-build.json proc-macro2-a50ff96e8f31346f lib-proc-macro2.json proc-macro2-abd246e359dfaa49 build-script-build-script-build.json quote-299eba77ed777314 build-script-build-script-build.json quote-2f58e63c4e07c81c run-build-script-build-script-build.json quote-cd86d5b79bf17173 lib-quote.json radium-285babd7592a1739 lib-radium.json radium-bf4da1eb51e54ebe build-script-build-script-build.json radium-c160ca25a27bbf49 run-build-script-build-script-build.json rand-1518c11509443982 lib-rand.json rand-9587ebeb603a3638 lib-rand.json rand_chacha-033c7524fdc4834e lib-rand_chacha.json rand_chacha-0b4aaf9aae59cc8c lib-rand_chacha.json rand_core-2c3cf157ae573a5f lib-rand_core.json rand_core-679cdcbd76ae1e25 lib-rand_core.json reed-solomon-erasure-657cb3aff7beb678 run-build-script-build-script-build.json reed-solomon-erasure-75d9238f65c579c5 lib-reed-solomon-erasure.json reed-solomon-erasure-92de65706c8efad4 build-script-build-script-build.json ripemd-da835ce7b8954ba7 lib-ripemd.json rustc-hex-9fddc5950e49f74d lib-rustc-hex.json rustversion-18cc0397dad8cff0 lib-rustversion.json rustversion-329b000a5bfb234e run-build-script-build-script-build.json rustversion-e75079b13b8a16e7 build-script-build-script-build.json ryu-3e99fe5c8f731b59 lib-ryu.json serde-0b0d47eda4454cda lib-serde.json serde-292100e725633765 run-build-script-build-script-build.json serde-41661ce31079bfff lib-serde.json serde-6e0c6407772d2e7d build-script-build-script-build.json serde-920a94ef3b487b86 build-script-build-script-build.json serde-f59e6c5d5f5559d5 run-build-script-build-script-build.json serde_derive-6ee01169d2e9e3b4 build-script-build-script-build.json serde_derive-7f2fee8db05d6b10 run-build-script-build-script-build.json serde_derive-9e695925b53b2967 lib-serde_derive.json serde_json-3d9ac1691ad91eb5 build-script-build-script-build.json serde_json-6e305550073c2a50 run-build-script-build-script-build.json serde_json-94b9347b26c844e1 lib-serde_json.json sha2-cdd1fcf6ce61f456 lib-sha2.json sha2-f6bcbdfd878bd8db lib-sha2.json sha3-49f852c097d8f3fe lib-sha3.json signature-78f0936edcf92ab7 lib-signature.json smallvec-b6ca0c9743d36605 lib-smallvec.json smart-default-4ceeb5f63995984e lib-smart-default.json static_assertions-845195a0fdd673bc lib-static_assertions.json strum-5092e2b242b52e4f lib-strum.json strum_macros-407b3a38f09e544c lib-strum_macros.json subtle-984835ecea000cd2 lib-subtle.json syn-0991fbf3739fc96a build-script-build-script-build.json syn-601814be7e3d5c55 lib-syn.json syn-883cbba3fc2ad9c2 run-build-script-build-script-build.json synstructure-50d7b83421e38dcf lib-synstructure.json tap-89260bad62957cf1 lib-tap.json thiserror-398a2b72adf06e32 lib-thiserror.json thiserror-5178875f4a7e2491 build-script-build-script-build.json thiserror-c319dec0f8794d5d lib-thiserror.json thiserror-e2059553dc9db80a run-build-script-build-script-build.json thiserror-impl-9ac12cce0715dc56 lib-thiserror-impl.json time-53bd58cc1f564220 lib-time.json toml-be3a24b05579a7f9 lib-toml.json typenum-32adf123d86ba338 lib-typenum.json typenum-425fe4beccbcb525 build-script-build-script-main.json typenum-bbbd944f7adb252c run-build-script-build-script-main.json uint-3dc4c9b6a840131f lib-uint.json unicode-ident-9cf561d1409be7dc lib-unicode-ident.json unicode-xid-ca7e29387ab80b4c lib-unicode-xid.json version_check-7e248a17d8100e28 lib-version_check.json wee_alloc-1a48381bce917f06 run-build-script-build-script-build.json wee_alloc-5a08008144897148 build-script-build-script-build.json wee_alloc-b7a72e9a9e4c0230 lib-wee_alloc.json wyz-f376f6c5698896fc lib-wyz.json zeroize-2d5689c9bc8d1310 lib-zeroize.json zeroize_derive-d825ef8359663816 lib-zeroize_derive.json release .fingerprint Inflector-11bb8be44207b82a lib-inflector.json ahash-0e2c93042a8936eb build-script-build-script-build.json borsh-derive-1ff3bf5d6d5d38be lib-borsh-derive.json borsh-derive-internal-e70d0ad15812eb83 lib-borsh-derive-internal.json borsh-schema-derive-internal-584de4380a845d34 lib-borsh-schema-derive-internal.json crunchy-0b3fbbe4b831ef5f build-script-build-script-build.json near-sdk-macros-6c5defc0018c611a lib-near-sdk-macros.json proc-macro-crate-66115aaf39d99dd2 lib-proc-macro-crate.json proc-macro2-45f13a2f88ee4e02 build-script-build-script-build.json proc-macro2-4a51efd8a62e608e run-build-script-build-script-build.json proc-macro2-e3f459528f80ff0f lib-proc-macro2.json quote-1bee81fce3a80b6a run-build-script-build-script-build.json quote-713c1bca9ff74065 lib-quote.json quote-8258a4d87978ea3f build-script-build-script-build.json serde-19e5559cbc492dc6 run-build-script-build-script-build.json serde-5bd49da48003353a lib-serde.json serde-6a093e07a7cbb5cc build-script-build-script-build.json serde-84d62abc1a482519 build-script-build-script-build.json serde_derive-06a268d76b103602 lib-serde_derive.json serde_derive-34387754c396b5f3 run-build-script-build-script-build.json serde_derive-9d6188b09ea308c4 build-script-build-script-build.json serde_json-a533d2af1a82d39f build-script-build-script-build.json syn-2658df990b68dcfd lib-syn.json syn-8793969c248f2149 run-build-script-build-script-build.json syn-b88026d6fca304af build-script-build-script-build.json toml-9c0c6e5581596f62 lib-toml.json unicode-ident-7c76976581abd101 lib-unicode-ident.json version_check-6202324f23387d26 lib-version_check.json wee_alloc-af15dbe76c8ab2d8 build-script-build-script-build.json wasm32-unknown-unknown release .fingerprint ahash-4612410d2080660f run-build-script-build-script-build.json ahash-9556ea2a69343b60 lib-ahash.json base64-748d6b20d0185db9 lib-base64.json borsh-f5d85939345e096f lib-borsh.json bs58-656922a39e2b8a03 lib-bs58.json byteorder-2df056e5bf1e5640 lib-byteorder.json cfg-if-667ab62a5098c2f5 lib-cfg-if.json contract-90b1a6f00cb41a14 lib-contract.json crunchy-6f21289d737e0a0c run-build-script-build-script-build.json crunchy-bd4deb88266812af lib-crunchy.json hashbrown-03c49058a54beaed lib-hashbrown.json hex-8ca4036d7b2fb587 lib-hex.json itoa-fb75f04dd13a8b53 lib-itoa.json memory_units-ab0adde73769008c lib-memory_units.json near-sdk-13a0ce69ee9a04b9 lib-near-sdk.json near-sys-1b4e7d702b05fd71 lib-near-sys.json once_cell-d05582c22043ea6d lib-once_cell.json ryu-e2144070b3c7b2eb lib-ryu.json serde-5a04c5d79f92cd19 run-build-script-build-script-build.json serde-e9346c76db878f1b lib-serde.json serde_json-504c89bdde4b33ee lib-serde_json.json serde_json-abc18c60a73ae9ea run-build-script-build-script-build.json static_assertions-d877579027f55fd5 lib-static_assertions.json uint-77377a1c441725fd lib-uint.json wee_alloc-41dfa4c73d5ac61a lib-wee_alloc.json wee_alloc-9768216a9d615b12 run-build-script-build-script-build.json frontend assets global.css logo-black.svg logo-white.svg index.html index.js near-interface.js near-wallet.js package.json start.sh integration-tests package.json src main.ava.ts package.json
# 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>`. # 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) [![](https://img.shields.io/badge/Testing-passing-green)](https://docs.near.org/develop/integrate/frontend) 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).
lhjokg_rust-near
MyContract Cargo.toml src lib.rs README.md okx-dex Cargo.toml src action.rs errors.rs lib.rs
# rust-near
nearvndev_vbi-certificate-nft-contract
Cargo.toml README.md nft Cargo.toml src lib.rs res README.md scripts build.bat build.sh flags.sh test-approval-receiver Cargo.toml src lib.rs test-token-receiver Cargo.toml src lib.rs
# Folder that contains wasm files Non-fungible Token (NFT) =================== This repository includes an example implementation of a [non-fungible token] contract which uses [near-contract-standards] and [simulation] tests. [non-fungible token]: https://nomicon.io/Standards/NonFungibleToken/README.html [near-contract-standards]: https://github.com/near/near-sdk-rs/tree/master/near-contract-standards [simulation]: https://github.com/near/near-sdk-rs/tree/master/near-sdk-sim Prerequisites ============= * Make sure Rust is installed per the prerequisites in [`near-sdk-rs`](https://github.com/near/near-sdk-rs). * Make sure [near-cli](https://github.com/near/near-cli) is installed. Explore this contract ===================== The source for this contract is in `nft/src/lib.rs`. It provides methods to manage access to tokens, transfer tokens, check access, and get token owner. Note, some further exploration inside the rust macros is needed to see how the `NonFungibleToken` contract is implemented. Building this contract ====================== Run the following, and we'll build our rust project up via cargo. This will generate our WASM binaries into our `res/` directory. This is the smart contract we'll be deploying onto the NEAR blockchain later. ```bash ./scripts/build.sh ``` Testing this contract ===================== We have some tests that you can run. For example, the following will run our simple tests to verify that our contract code is working. *Unit Tests* ```bash cd nft cargo test -- --nocapture ``` *Integration Tests* *Rust* ```bash cd integration-tests/rs cargo run --example integration-tests ``` *TypeScript* ```bash cd integration-tests/ts yarn && yarn test ``` The more complex simulation tests aren't run with this command, but we can find them in `tests/sim`. Using this contract =================== ### Quickest deploy You can build and deploy this smart contract to a development account. [Dev Accounts](https://docs.near.org/docs/concepts/account#dev-accounts) are auto-generated accounts to assist in developing and testing smart contracts. Please see the [Standard deploy](#standard-deploy) section for creating a more personalized account to deploy to. ```bash near dev-deploy --wasmFile res/non_fungible_token.wasm ``` Behind the scenes, this is creating an account and deploying a contract to it. On the console, notice a message like: >Done deploying to dev-1234567890123 In this instance, the account is `dev-1234567890123`. A file has been created containing a key pair to the account, located at `neardev/dev-account`. To make the next few steps easier, we're going to set an environment variable containing this development account id and use that when copy/pasting commands. Run this command to set the environment variable: ```bash source neardev/dev-account.env ``` You can tell if the environment variable is set correctly if your command line prints the account name after this command: ```bash echo $CONTRACT_NAME ``` The next command will initialize the contract using the `new` method: ```bash near call $CONTRACT_NAME new_default_meta '{"owner_id": "'$CONTRACT_NAME'"}' --accountId $CONTRACT_NAME ``` To view the NFT metadata: ```bash near view $CONTRACT_NAME nft_metadata ``` ### Standard deploy This smart contract will get deployed to your NEAR account. For this example, please create a new NEAR account. Because NEAR allows the ability to upgrade contracts on the same account, initialization functions must be cleared. If you'd like to run this example on a NEAR account that has had prior contracts deployed, please use the `near-cli` command `near delete`, and then recreate it in Wallet. To create (or recreate) an account, please follow the directions in [Test Wallet](https://wallet.testnet.near.org) or ([NEAR Wallet](https://wallet.near.org/) if we're using `mainnet`). In the project root, log in to your newly created account with `near-cli` by following the instructions after this command. near login To make this tutorial easier to copy/paste, we're going to set an environment variable for our account id. In the below command, replace `MY_ACCOUNT_NAME` with the account name we just logged in with, including the `.testnet` (or `.near` for `mainnet`): ID=MY_ACCOUNT_NAME We can tell if the environment variable is set correctly if our command line prints the account name after this command: echo $ID Now we can deploy the compiled contract in this example to your account: near deploy --wasmFile res/non_fungible_token.wasm --accountId $ID NFT contract should be initialized before usage. More info about the metadata at [nomicon.io](https://nomicon.io/Standards/NonFungibleToken/Metadata.html). But for now, we'll initialize with the default metadata. near call $ID new_default_meta '{"owner_id": "'$ID'"}' --accountId $ID We'll be able to view our metadata right after: near view $ID nft_metadata Then, let's mint our first token. This will create a NFT based on Olympus Mons where only one copy exists: near call $ID nft_mint '{"receiver_id": "'$ID'", "token_metadata": { "title": "VBI GFS Near Developer Advanced Course Certificate", "media": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Olympus_Mons_alt.jpg/1024px-Olympus_Mons_alt.jpg", "copies": 1}}' --accountId $ID --deposit 0.1 And you can mint NFT with IPFS upload with INFURA [`ipfs-upload-client`](https://github.com/INFURA/ipfs-upload-client) ipfs-upload-client --id $INFURA_PROJECT_ID --secret $INFURA_PROJECT_SECRET /path/file/image.jpg | xargs -I{} near call $ID nft_mint '{"receiver_id": "'$ID'", "token_metadata": {"title":"VBI GFS Near Developer Advanced Course Certificate", "media": "https://ipfs.infura.io{}", "copies": 1}}' --accountId $ID --deposit 0.01 Transferring our NFT ==================== Let's set up an account to transfer our freshly minted token to. This account will be a sub-account of the NEAR account we logged in with originally via `near login`. near create-account alice.$ID --masterAccount $ID --initialBalance 10 Checking Alice's account for tokens: near view $ID nft_tokens_for_owner '{"account_id": "'alice.$ID'"}' Then we'll transfer over the NFT into Alice's account. Exactly 1 yoctoNEAR of deposit should be attached: near call $ID nft_transfer '{"token_id": "0", "receiver_id": "alice.'$ID'", "memo": "transfer ownership"}' --accountId $ID --depositYocto 1 Checking Alice's account again shows us that she has the Olympus Mons token. Notes ===== * The maximum balance value is limited by U128 (2**128 - 1). * JSON calls should pass U128 as a base-10 string. E.g. "100". * This does not include escrow functionality, as ft_transfer_call provides a superior approach. An escrow system can, of course, be added as a separate contract or additional functionality within this contract. AssemblyScript ============== Currently, AssemblyScript is not supported for this example. An old version can be found in the [NEP4 example](https://github.com/near-examples/NFT/releases/tag/nep4-example), but this is not recommended as it is out of date and does not follow the standards the NEAR SDK has set currently.
Juice-Hackathon_unvested-v0
.prettierrc.js .solcover.js .solhint.json .vscode launch.json settings.json LICENSE.txt README.md abi CDelegateInterface.json CDelegationStorage.json CDelegatorInterface.json CErc20.json CErc20Interface.json CErc20Storage.json CToken.json CTokenInterface.json CTokenStorage.json ChainlinkPriceOracle.json CompLike.json Comptroller.json ComptrollerErrorReporter.json ComptrollerG1.json ComptrollerInterface.json ComptrollerV1Storage.json ComptrollerV2Storage.json ComptrollerV3Storage.json ComptrollerV4Storage.json ComptrollerV5Storage.json ComptrollerV6Storage.json ComptrollerV7Storage.json EIP20Interface.json EIP20NonStandardInterface.json ERC20.json IChainlinkAggregatorV3.json IERC20.json IVesting.json IVestingCollateralWrapper.json IVestingContractWrapper.json InterestRateModel.json LINKMockToken.json PriceOracle.json SimplePriceOracle.json StandardTokenMock.json TokenErrorReporter.json USDCMockToken.json Unitroller.json UnitrollerAdminStorage.json Vesting.json VestingCollateralWrapper.json VestingContractWrapper.json VestingDemoCreator.json VestingUserTwo.json WhitePaperInterestRateModel.json YearnMockToken.json archive baseProtocol.ts deploy Comptroller.js InterestRateModel.js SimplePriceOracle.js USDC.js Vesting.js VestingDemoCreator.js jUSDC.js deployments kovan CErc20.json ChainlinkPriceOracle.json Comptroller.json LINKMockToken.json SimplePriceOracle.json USDCMockToken.json Vesting.json VestingDemoCreator.json VestingUserTwo.json WhitePaperInterestRateModel.json solcInputs f2f1ca7f59ca0117723b533f70db86be.json docs DEPLOYMENT.md DEVELOPMENT.md exports arbitrum-testnet.json aurora-testnet.json harmony-testnet.json kovan.json metis-testnet.json hardhat.config.ts notes.md package.json scripts borrowVestingOne.ts createNewVesting.ts demo changeOraclePriceForLiquidation.ts liquidateLiquidBorrowerOne.ts liquidateUnvestedBorrowerTwo.ts liquidatorUnvestedClaimTokens.ts liquidateLiquidTokens.ts liquidateUnvestedTokens.ts registerVestingContract.ts solhint.json test lender.ts utilities index.ts time.ts tsconfig.dist.json tsconfig.json utils common unitsUtils.ts constants.ts contracts compound.ts deploys dependencies.ts deployExternal.ts index.ts fixtures compoundFixture.ts types.ts
# Juice Protocol Lending protocol that enables isolated borrowing USDC against tokens locked in vesting contracts. Therefore, unlocking the ability to use future earnings as collateral - a form of undercollateralized lending. A Net Present Value is applied to borrow capacity where future tokens are discounted using a formula. Liquidators may seize unvested tokens that stream to the liquidator over time at a steep discount. Built using Compound Protocol as a starting point, Vesting contracts use a standard template many DAOs use, and oracles use Chainlink. Deployed to Kovan, Arbitrum Rinkeby, Harmony testnet, Aurora testnet. ETHDenver Bounty Winners: #### Harmony: Unique Usage for NFTs - 1st Prize #### Metis - 2nd Place #### Chainlink - Runner Up #### Arbitrum: Best DeFi App - 1st Prize #### Magic: A Magical User Experience - Winner # Contract Addresses ## Kovan - jUSDC: 0x063f8C3a224abEd8e821B57e7152BCa0e633D432 - USDC: 0xCec9b9aA30b51D2cdaE6586b7016FceC901aDC25 - LINK: 0x5f105f831dcD69C7af3fA7919dA2e89cd291239C - ChainlinkPriceOracle: 0xc6CC421A38c724448219eDb68e9E59Ac389dC7D6 - VestingDemoCreator: 0x840A47872E07f83B8cb2bAB63e66BB984dfbFe37 - LendingController: 0xE85177c2E8c9C397fB971A13046317803C063cD7 - InterestRateModel: 0x13584Ac0Befd9E37DCcA8B4D9aE143C2500A8e0e ## Arbitrum Rinkeby - jUSDC: 0xb91A8f3710879EfC365D16734a9D7e78DdB86128 - USDC: 0x08202D3B5E0dc6fa060E33Ed25F2C84582bc64E3 - LINK: 0x3FE2319074E3A1103A26d8321d827aabbf1015C4 - ChainlinkPriceOracle: 0x57D8387279c8B030Ff3eB3E588626C901Af4893D - LendingController: 0x3b2A3077ecF80AAfA126dB18f641a148ad3848e8 - InterestRateModel: 0x068eC2df4FBDA4A6428c3F029F659e521EA9c8B8 ## Harmony Testnet - jUSDC: 0x125c0d97938c3e2EF7d236BaFCE8d4c927374137 - USDC: 0x8050676c6ca7ecC8Fef4e383DF7bF804BeF915D6 - LINK: 0x6715713831724679e0fEd5B63Fa4CDe8f73D2d76 - ChainlinkPriceOracle: 0x400aF5d37438c0beB9Ae69b05919599b1E2fb556 - LendingController: 0x19D46C4D663344646A29001aC39714c27Fbf0A17 - InterestRateModel: 0xeBAe4bB9bD4774E143543Ad3c8A2c5e847308b83 ## Aurora NEAR Testnet - jUSDC: 0x125c0d97938c3e2EF7d236BaFCE8d4c927374137 - USDC: 0x8050676c6ca7ecC8Fef4e383DF7bF804BeF915D6 - LINK: 0x6715713831724679e0fEd5B63Fa4CDe8f73D2d76 - PriceOracle: 0x400aF5d37438c0beB9Ae69b05919599b1E2fb556 - LendingController: 0x19D46C4D663344646A29001aC39714c27Fbf0A17 - InterestRateModel: 0xeBAe4bB9bD4774E143543Ad3c8A2c5e847308b83 ## METIS Testnet - jUSDC: 0x05b2880220D0f8C4d255856259A439A5F5D5fad6 - USDC: 0x8050676c6ca7ecC8Fef4e383DF7bF804BeF915D6 - LINK: 0xD9C60E01F98232a9f48d2fD0bEe8271b90bA738d - PriceOracle: 0x400aF5d37438c0beB9Ae69b05919599b1E2fb556 - LendingController: 0x19D46C4D663344646A29001aC39714c27Fbf0A17 - InterestRateModel: 0xeBAe4bB9bD4774E143543Ad3c8A2c5e847308b83
kinnevo_SharingShard-JC2
Cargo.toml README.md src lib.rs
# SharingShard source $HOME/.cargo/env rustup target add wasm32-unknown-unknown cargo build --target wasm32-unknown-unknown --release near deploy --wasmFile target/wasm32-unknown-unknown/release/near_sharingshard.wasm --accountId ss2022_jc.testnet *** ** Deploying contract ** *** Use near-cli to deploy the smart contract to NEAR test network: near deploy --wasmFile target/wasm32-unknown-unknown/release/SharingShard.wasm --accountId ss2022_jc.testnet *** ** Initializing ** *** Initializing contract: `near call <YOUR_ACCOUNT_HERE> new --accountId <YOUR_ACCOUNT_HERE>` *** ** Setters ** *** Add new user: `near call <CONTRACT OWNER WALLET> new_user --args '{"wallet": "<USER WALLET>", "n": "<USER NAME>", "disc": "<USER DIRCORD>", "mail": "<USER EMAIL>", "interst": <CODE NUMBER FOR USER ITERESTS>}' --accountId <CALLER WALLET>` Add new experience: `near call <CONTRACT OWNER WALLET> add_experience --args '{"wallet": "<USER WALLET>", "experience_name": "<NAME>", "description": "<EXPERIENCE DESCRIPTION>", "url": "<VIDEO URL>", "reward": <MOMENT REWARD>, "expire_date": <EXPIRATION DATE>, "topic": <CODE NUMBER FOR TOPIC OF VIDEO>}' --accountId <CALLER WALLET>` Add moment to experience: `near call <CONTRACT OWNER WALLET> add_moment --args '{"wallet": "<USER WALLET>", "experience_number": "<CODE NUMBER FOR THE EXPERIENCE>", "time": <TIME ON THE VIDEO>, "comment": "<MOMENT COMMENT>"}' --accountId <CALLER WALLET>` ************* ** Getters ** ************* Get experience title: `near call <CONTRACT OWNER WALLET> get_title --args '{"video_n": <EXPERIENCE NUMBER>}' --accountId <CALLER WALLET>` Get experience description: `near call <CONTRACT OWNER WALLET> get_description --args '{"video_n": <EXPERIENCE NUMBER>}' --accountId <CALLER WALLET>` Get video url: `near call <CONTRACT OWNER WALLET> get_url --args '{"video_n": <EXPERIENCE NUMBER>}' --accountId <CALLER WALLET>` Get experience topic: `near call <CONTRACT OWNER WALLET> get_topic --args '{"video_n": <EXPERIENCE NUMBER>}' --accountId <CALLER WALLET>` Get experience reward: `near call <CONTRACT OWNER WALLET> get_reward --args '{"video_n": <EXPERIENCE NUMBER>}' --accountId <CALLER WALLET>` Get experience expiration date: `near call <CONTRACT OWNER WALLET> get_expiration_date --args '{"video_n": <EXPERIENCE NUMBER>}' --accountId <CALLER WALLET>` Get moment coment: `near call <CONTRACT OWNER WALLET> get_moment_coment --args '{"video_n": <EXPERIENCE NUMBER>}' --accountId <CALLER WALLET>` Get moment time: `near call <CONTRACT OWNER WALLET> get_moment_time --args '{"video_n": <EXPERIENCE NUMBER>}' --accountId <CALLER WALLET>` Get points of view for a moment: `near call <CONTRACT OWNER WALLET> get_pov_of_vid --args '{"video_n": <EXPERIENCE NUMBER>}' --accountId <CALLER WALLET>` Get experiences by topic : `near call <CONTRACT OWNER WALLET> get_exp_by_topic --args '{"topic": <CODE NUMBER OF TOPIC>}' --accountId <CALLER WALLET>` Get user's name: `near call <CONTRACT OWNER WALLET> get_user_name --args '{"wallet": <USER WALLET>}' --accountId <CALLER WALLET>` Get user's discord: `near call <CONTRACT OWNER WALLET> get_user_discord --args '{"wallet": <USER WALLET>}' --accountId <CALLER WALLET>` Get user's email: `near call <CONTRACT OWNER WALLET> get_user_email --args '{"wallet": <USER WALLET>}' --accountId <CALLER WALLET>` Get user's interests: `near call <CONTRACT OWNER WALLET> get_user_interests --args '{"wallet": <USER WALLET>}' --accountId <CALLER WALLET>` Get user's experiences: `near call <CONTRACT OWNER WALLET> get_user_exp --args '{"wallet": <USER WALLET>}' --accountId <CALLER WALLET>` Get experiences the user left a point of view: `near call <CONTRACT OWNER WALLET> get_user_exp_pov --args '{"wallet": <USER WALLET>}' --accountId <CALLER WALLET>` Get user's date of last comment: `near call <CONTRACT OWNER WALLET> get_user_date --args '{"wallet": <USER WALLET>}' --accountId <CALLER WALLET>` Get total of experiences in the contract: `near call <CONTRACT OWNER WALLET> get_number_of_experiences --accountId <CALLER WALLET>`
gencoglutugrul_near-protocol-nft-dapp
.eslintrc.js .gitpod.yml README.md babel.config.js contract Cargo.toml README.md compile.js src lib.rs package.json src App.js __mocks__ fileMock.js assets logo-black.svg logo-white.svg components Collectibles.js Mint.js SignIn.js config.js global.css index.html index.js jest.init.js main.test.js utils.js wallet login index.html
love-is-love-nft-dapp 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 love-is-love-nft-dapp ================== 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 `love-is-love-nft-dapp.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `love-is-love-nft-dapp.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 love-is-love-nft-dapp.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 || 'love-is-love-nft-dapp.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
lytves_near-multisender-test
.gitpod.yml README.md babel.config.js contract Cargo.toml README.md compile.js src lib.rs package-lock.json package.json src App.js __mocks__ fileMock.js assets logo-black.svg logo-white.svg nearc27c19c0.svg config.js global.css index.html index.js jest.init.js main.test.js utils.js wallet login index.html
near-multisender-test ================== This [React] app was initialized with [create-near-app] **Near DApp** on **Rust and React**: NEAR Multi-Sender-App on NodeJS through React's **create-near-app** module Project was created according to the Zavodil's video tutorial [Программируем dApp за полчаса на Rust и React: NEAR MultiSender на NodeJS через create-near-app](https://www.youtube.com/watch?v=SJhJ1sKjCBI) - good way to start to learn programming on NEAR. Check it out the DEMO-version: https://lytves.github.io/near-multisender-test/ ![](img.png) Run Developing Version =========== ``` npm run dev ``` Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `npm install` 3. Run the local development server: `npm run dev` (see `package.json` for a full list of `scripts` you can run with `npm`) 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 `npm run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run 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 `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-multisender-test.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-multisender-test.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-multisender-test.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-multisender-test.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: npm run 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-multisender-test 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
gagdiez_reentrancy_attack
README.md exploitable_contract 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 model.ts tsconfig.json compile.js package.json package.json src assets js blockchain.js config.js index.js index.html reentrancy_attack 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 model.ts tsconfig.json compile.js package.json package.json src assets css main.css js blockchain.js config.js index.js index.html
pool_party 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 pool_party 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 # Exploitable Contract To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies **in /contract**: `cd contract && yarn install` 3. Install dependencies **in /**: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) # Reentrancy Attacks ![img](example.png) This repository shows how to perform a reentrancy attack on a smart contract, as well as how to protect a contract from such attack. The repo is composed by two components: 1. A simple contract which allows to deposit and withdraw NEARs. 2. A contract that can perform a reentrancy attack in any (unprotected) contract. ## The Exploitable Contract The Exploitable Contract (EC) is a contract that implements 3 methods: - Deposit: Method that allows to deposit money - Withdraw: Method that allows to withdraw the deposited money - Withdraw Reentrancy: An exploitable version of the method "withdraw". ## Reentrancy Attack Contract The Reentrancy Attack Contract (RAC) implements a single method. Given a contract address (TARGET), a function (fc), its arguments (args), and a number N, our contract will call Target.fc(args) N times in a row to try to exploit it. I have built a user friendly UI to interact with the contract. # Performing a Reentrancy Attack in the Explitable Contract ## Starting the contracts Enter in the folders and run ```bash npm install npm start ``` This will open two browser tabs: One to interact with the Exploitable Contract (EC), and the other to interact with the Reentrancy Attrack Contract (RAC). ## Reentrancy Attack Copy the EC address into the "Target" field of the RAC. Call first the function "deposit" with 0.01N attached to deposit them in the EC. Then, call "withdraw" with the parameters {"amount": "10000000000000000"} 3 times, it should fail. Try again but calling "withdraw\_reentrance" this time. Congratulations, you just performed a reentrancy attack. # Reentrancy Attack Contract To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies **in /contract**: `cd contract && yarn install` 3. Install dependencies **in /**: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`)
mlibre_Tutorials
.github workflows npm.yml .vscode settings.json Contents Health.md Lovely Tools.md ai generative ai.md langchain.md lobe-chat.md prompt.md readme.md blockchain Bitcoin btc.svg readme.md Cryptography readme.md Ethereum CLI.md Quorum readme.md assets eth.svg readme.md Hyperledger Getting Start.md readme.md LBRY readme.md NEAR CLI.md SDK.md readme.md simple-exchange MLB1-contract Cargo.toml README.md build.bat build.sh ft Cargo.toml src lib.rs rustfmt.toml test-contract-defi Cargo.toml src lib.rs tests sim main.rs no_macros.rs utils.rs with_macros.rs exchange-contract Cargo.toml src lib.rs readme.md web-ui babel.config.js package.json src App.js assets logo-black.svg logo-white.svg config.js global.css index.html index.js utils.js wallet login index.html Polygon PoS Bridge .eslintrc.js erc-1155-pos-brdige.js erc-20-pos-brdige.js erc-721-pos-brdige.js erc1155-pos-bridge.md erc20-pos-bridge.md erc721-pos-bridge.md package.json Smart Contracts .eslintrc.js bin Voter_abi.json main.js package.json readme.md readme.md readme.md docusaurus.md linux access.md automation.md disk-file.md log-monitoring.md multimedia.md other.md processes.md readme.md shell-scripting.md systemd.md text.md tools.md network basic.md dns.md other.md readme.md ssh.md vpn.md raspberry pi.md readme.md vscode.md docs 404.html Health index.html Lovely Tools index.html ai generative ai index.html index.html langchain index.html lobe-chat index.html prompt index.html assets css styles.f97fa848.css js 00386a24.dc9b2acb.js 0267278e.b3620519.js 05bd16ad.34fa1e5b.js 06c16bc1.2ee1aa9a.js 06def0a1.7278a8b5.js 0814b3ee.baefd90d.js 089ea00c.ec32d2ed.js 0d3f1f56.76f326e9.js 0d726ec9.1a73199b.js 11cdba9e.92543471.js 12c9fd0c.5756c226.js 12d34978.f67d2fbf.js 144286ec.4bd49ecc.js 14802848.6bdad7e2.js 16e94c2c.6d5c89c1.js 17896441.4486dbd3.js 182cc002.38f061ad.js 1b6a7de4.d38a9c60.js 1be4aa9f.e9baf098.js 1be78505.914d05d6.js 1f6c1e16.cc488c01.js 20ac2874.f8c500e3.js 217e7ab6.c40fd1d4.js 2572.40e853bf.js 26445734.b364d30b.js 28d9a6fb.41fab222.js 2b9b2b35.b2ce0b08.js 2c31e1fc.a17cf360.js 2d53f62c.40b6676a.js 2f46f4f6.fdc2225e.js 3328306b.8c4ea2b2.js 3720c009.25aff8eb.js 3a026971.d87f055f.js 3b33162a.de5789ec.js 3b3f9a17.2f6d3d7a.js 3c604bc8.d70a0a0d.js 3c7a1985.e2763ab9.js 439794d8.e69d3cd9.js 442b48ab.098d5081.js 44579dd5.84eab808.js 4611.77298230.js 4611.77298230.js.LICENSE.txt 4972.eae2a020.js 4c027927.458208ec.js 4f2b7581.28ab9649.js 4fae5413.cca50e5e.js 4fbaae46.9968eba8.js 52bb9c04.ce0b01ea.js 52e2a80b.11b3d258.js 53d607c0.ea6fb117.js 53f55093.73fda190.js 5447f8a1.c4bbb299.js 54510f97.58200f6f.js 549b1afd.4e541fc6.js 55960ee5.ab8df0d7.js 55d4b6a5.d43316e9.js 5618cd27.41942bab.js 5684.6c114feb.js 587bab49.d89d3f1a.js 5a97b260.ddccc8ab.js 5cd2cf3b.93fefbbe.js 5dee6bcf.e9ac0bd8.js 5eb7d76c.513964a7.js 600268cd.9fa3a9af.js 606da10e.97fb9b30.js 6731f580.0666951e.js 69d14787.86d53be9.js 6a3dfb58.e42899e7.js 6eac3654.1de59877.js 6fb182c9.5dc7674f.js 72c8d2e5.23d02825.js 73573f06.35703694.js 73dd2e7d.2cd46610.js 83f4e8b1.2ed19318.js 8467b7f5.e63714f6.js 8503b981.5155703f.js 866b8020.8de69c31.js 89b22097.4f607f1d.js 8d678e06.b21af63f.js 8f172175.e3897a35.js 8f2cd53c.239cc140.js 90371975.3121b66e.js 914beddb.79e03eb7.js 935512d6.eb975b05.js 935f2afb.51e7e5a3.js 94693fb1.d22608f8.js 96518a57.33df2d71.js 990145a0.110d3d9a.js 9ae8dec8.f6d028d6.js 9c5129ac.abb0499a.js 9ce8b3a5.788b4267.js 9d3a9e09.62cfbebb.js 9ea2d7c6.57b25d72.js 9fa3b5e9.a2307fdb.js a049fff7.891194c2.js a4ffaf38.c88505bf.js aa10d896.121a5d9f.js ad65d7aa.d1c6d769.js ad95a979.49fddc3c.js b49cb379.5b8c202d.js b731a8e8.f3e35356.js be697916.20cca151.js c4a8a0c6.155b1406.js c6461e50.475da86b.js cd5e1f2e.31549fbc.js ce00cef5.ad8d6f81.js ce09d5eb.6bbd23f3.js cf6f78a3.4301d528.js d73a239c.83b48252.js dc43b967.254ed92a.js dc48c437.39f4ac62.js df203c0f.9d93ac9c.js df684998.e50f1ec2.js e004505d.955905b1.js e3960513.9c906a5b.js e49b4f37.d17f6226.js e7c96db3.9f376a9f.js e8795368.5879001c.js eb9e3663.91b3fa55.js edcfdff1.3e0839eb.js ef4e2d6b.d0e69faf.js f116b37b.f49f5bef.js f4b21e4b.d170b1c3.js f7359c4a.c99bf356.js fab5a811.79a78897.js fc661e0a.4af9d01e.js fcf30ac0.ad40e181.js ff64dfed.f3c86078.js main.69116ce9.js main.69116ce9.js.LICENSE.txt runtime~main.7c845cc5.js blockchain Bitcoin index.html Cryptography index.html Ethereum CLI index.html Quorum index.html index.html Hyperledger Getting Start index.html index.html LBRY index.html NEAR CLI index.html SDK index.html index.html simple-exchange MLB1-contract index.html index.html Polygon PoS Bridge erc1155-pos-bridge index.html erc20-pos-bridge index.html erc721-pos-bridge index.html Smart Contracts index.html index.html index.html docusaurus index.html img logo.svg index.html linux access index.html automation index.html disk-file index.html index.html log-monitoring index.html multimedia index.html other index.html processes index.html shell-scripting index.html systemd index.html text index.html tools index.html network basic index.html dns index.html index.html other index.html ssh index.html raspberry pi index.html search-doc-1715577786063.json search-doc.json sitemap.xml tags access-control index.html ai index.html automatic index.html automation index.html backup index.html bash index.html basic index.html blockchain index.html cat index.html cheat index.html dd index.html dex index.html disk index.html dns index.html docusaurus index.html editor index.html fix index.html game index.html graphic index.html grep index.html gui index.html health index.html index.html ipv-6 index.html journalctl index.html langchain index.html less index.html linux index.html ln index.html log index.html manjaro index.html mlibre index.html monitor index.html monitoring index.html mount index.html near index.html network index.html open-vpn index.html permissions index.html port-forwarding index.html process index.html prompt index.html raspberry-pi index.html repair index.html restore index.html ring-buffer index.html rsync index.html script index.html service index.html sheet index.html shell index.html shutdown index.html socks index.html split index.html ssh index.html startup index.html swap index.html syslog index.html systemd index.html text index.html tools index.html tutorial index.html vpn index.html vscode index.html vulkan index.html windows-11 index.html wisdom-hub index.html xdg index.html zsh index.html vscode index.html docusaurus babel.config.js docs Health.md Lovely Tools.md ai generative ai.md langchain.md lobe-chat.md prompt.md readme.md blockchain Bitcoin btc.svg readme.md Cryptography readme.md Ethereum CLI.md Quorum readme.md assets eth.svg readme.md Hyperledger Getting Start.md readme.md LBRY readme.md NEAR CLI.md SDK.md readme.md simple-exchange MLB1-contract Cargo.toml README.md build.bat build.sh ft Cargo.toml src lib.rs rustfmt.toml test-contract-defi Cargo.toml src lib.rs tests sim main.rs no_macros.rs utils.rs with_macros.rs exchange-contract Cargo.toml src lib.rs readme.md web-ui babel.config.js package.json src App.js assets logo-black.svg logo-white.svg config.js global.css index.html index.js utils.js wallet login index.html Polygon PoS Bridge .eslintrc.js erc-1155-pos-brdige.js erc-20-pos-brdige.js erc-721-pos-brdige.js erc1155-pos-bridge.md erc20-pos-bridge.md erc721-pos-bridge.md package.json Smart Contracts .eslintrc.js bin Voter_abi.json main.js package.json readme.md readme.md readme.md docusaurus.md linux access.md automation.md disk-file.md log-monitoring.md multimedia.md other.md processes.md readme.md shell-scripting.md systemd.md text.md tools.md network basic.md dns.md other.md readme.md ssh.md vpn.md raspberry pi.md readme.md vscode.md docusaurus.config.js package-lock.json package.json sidebars.js src css custom.css static img logo.svg readme.md
Fungible Token (FT) =================== Example implementation of a [Fungible Token] contract which uses [near-contract-standards] and [simulation] tests. This is a contract-only example. [Fungible Token]: https://nomicon.io/Standards/FungibleToken/Core.html [near-contract-standards]: https://github.com/near/near-sdk-rs/tree/master/near-contract-standards [simulation]: https://github.com/near/near-sdk-rs/tree/master/near-sdk-sim Prerequisites ============= If you're using Gitpod, you can skip this step. 1. Make sure Rust is installed per the prerequisites in [`near-sdk-rs`](https://github.com/near/near-sdk-rs#pre-requisites) 2. Ensure `near-cli` is installed by running `near --version`. If not installed, install with: `npm install -g near-cli` ## Building To build run: ```bash ./build.sh ``` Using this contract =================== ### Quickest deploy You can build and deploy this smart contract to a development account. [Dev Accounts](https://docs.near.org/docs/concepts/account#dev-accounts) are auto-generated accounts to assist in developing and testing smart contracts. Please see the [Standard deploy](#standard-deploy) section for creating a more personalized account to deploy to. ```bash near dev-deploy --wasmFile res/fungible_token.wasm --helperUrl https://near-contract-helper.onrender.com ``` Behind the scenes, this is creating an account and deploying a contract to it. On the console, notice a message like: >Done deploying to dev-1234567890123 In this instance, the account is `dev-1234567890123`. A file has been created containing a key pair to the account, located at `neardev/dev-account`. To make the next few steps easier, we're going to set an environment variable containing this development account id and use that when copy/pasting commands. Run this command to the environment variable: ```bash source neardev/dev-account.env ``` You can tell if the environment variable is set correctly if your command line prints the account name after this command: ```bash echo $CONTRACT_NAME ``` The next command will initialize the contract using the `new` method: ```bash near call $CONTRACT_NAME new '{"owner_id": "'$CONTRACT_NAME'", "total_supply": "1000000000000000", "metadata": { "spec": "ft-1.0.0", "name": "Example Token Name", "symbol": "EXLT", "decimals": 8 }}' --accountId $CONTRACT_NAME ``` To get the fungible token metadata: ```bash near view $CONTRACT_NAME ft_metadata ``` ### Standard deploy This smart contract will get deployed to your NEAR account. For this example, please create a new NEAR account. Because NEAR allows the ability to upgrade contracts on the same account, initialization functions must be cleared. If you'd like to run this example on a NEAR account that has had prior contracts deployed, please use the `near-cli` command `near delete`, and then recreate it in Wallet. To create (or recreate) an account, please follow the directions on [NEAR Wallet](https://wallet.near.org/). Switch to `mainnet`. You can skip this step to use `testnet` as a default network. export NEAR_ENV=mainnet In the project root, log in to your newly created account with `near-cli` by following the instructions after this command: near login To make this tutorial easier to copy/paste, we're going to set an environment variable for your account id. In the below command, replace `MY_ACCOUNT_NAME` with the account name you just logged in with, including the `.near`: ID=MY_ACCOUNT_NAME You can tell if the environment variable is set correctly if your command line prints the account name after this command: echo $ID Now we can deploy the compiled contract in this example to your account: near deploy --wasmFile res/fungible_token.wasm --accountId $ID FT contract should be initialized before usage. You can read more about metadata at ['nomicon.io'](https://nomicon.io/Standards/FungibleToken/Metadata.html#reference-level-explanation). Modify the parameters and create a token: near call $ID new '{"owner_id": "'$ID'", "total_supply": "1000000000000000", "metadata": { "spec": "ft-1.0.0", "name": "Example Token Name", "symbol": "EXLT", "decimals": 8 }}' --accountId $ID Get metadata: near view $ID ft_metadata Transfer Example --------------- Let's set up an account to transfer some tokens to. These account will be a sub-account of the NEAR account you logged in with. near create-account bob.$ID --masterAccount $ID --initialBalance 1 Add storage deposit for Bob's account: near call $ID storage_deposit '' --accountId bob.$ID --amount 0.00125 Check balance of Bob's account, it should be `0` for now: near view $ID ft_balance_of '{"account_id": "'bob.$ID'"}' Transfer tokens to Bob from the contract that minted these fungible tokens, exactly 1 yoctoNEAR of deposit should be attached: near call $ID ft_transfer '{"receiver_id": "'bob.$ID'", "amount": "19"}' --accountId $ID --amount 0.000000000000000000000001 Check the balance of Bob again with the command from before and it will now return `19`. ## Testing As with many Rust libraries and contracts, there are tests in the main fungible token implementation at `ft/src/lib.rs`. Additionally, this project has [simulation] tests in `tests/sim`. Simulation tests allow testing cross-contract calls, which is crucial to ensuring that the `ft_transfer_call` function works properly. These simulation tests are the reason this project has the file structure it does. Note that the root project has a `Cargo.toml` which sets it up as a workspace. `ft` and `test-contract-defi` are both small & focused contract projects, the latter only existing for simulation tests. The root project imports `near-sdk-sim` and tests interaction between these contracts. You can run all these tests with one command: ```bash cargo test ``` If you want to run only simulation tests, you can use `cargo test simulate`, since all the simulation tests include "simulate" in their names. ## Notes - The maximum balance value is limited by U128 (`2**128 - 1`). - JSON calls should pass U128 as a base-10 string. E.g. "100". - This does not include escrow functionality, as `ft_transfer_call` provides a superior approach. An escrow system can, of course, be added as a separate contract or additional functionality within this contract. ## No AssemblyScript? [near-contract-standards] is currently Rust-only. We strongly suggest using this library to create your own Fungible Token contract to ensure it works as expected. Someday NEAR core or community contributors may provide a similar library for AssemblyScript, at which point this example will be updated to include both a Rust and AssemblyScript version. ## Contributing When making changes to the files in `ft` or `test-contract-defi`, remember to use `./build.sh` to compile all contracts and copy the output to the `res` folder. If you forget this, **the simulation tests will not use the latest versions**. Note that if the `rust-toolchain` file in this repository changes, please make sure to update the `.gitpod.Dockerfile` to explicitly specify using that as default as well. Fungible Token (FT) =================== Example implementation of a [Fungible Token] contract which uses [near-contract-standards] and [simulation] tests. This is a contract-only example. [Fungible Token]: https://nomicon.io/Standards/FungibleToken/Core.html [near-contract-standards]: https://github.com/near/near-sdk-rs/tree/master/near-contract-standards [simulation]: https://github.com/near/near-sdk-rs/tree/master/near-sdk-sim Prerequisites ============= If you're using Gitpod, you can skip this step. 1. Make sure Rust is installed per the prerequisites in [`near-sdk-rs`](https://github.com/near/near-sdk-rs#pre-requisites) 2. Ensure `near-cli` is installed by running `near --version`. If not installed, install with: `npm install -g near-cli` ## Building To build run: ```bash ./build.sh ``` Using this contract =================== ### Quickest deploy You can build and deploy this smart contract to a development account. [Dev Accounts](https://docs.near.org/docs/concepts/account#dev-accounts) are auto-generated accounts to assist in developing and testing smart contracts. Please see the [Standard deploy](#standard-deploy) section for creating a more personalized account to deploy to. ```bash near dev-deploy --wasmFile res/fungible_token.wasm --helperUrl https://near-contract-helper.onrender.com ``` Behind the scenes, this is creating an account and deploying a contract to it. On the console, notice a message like: >Done deploying to dev-1234567890123 In this instance, the account is `dev-1234567890123`. A file has been created containing a key pair to the account, located at `neardev/dev-account`. To make the next few steps easier, we're going to set an environment variable containing this development account id and use that when copy/pasting commands. Run this command to the environment variable: ```bash source neardev/dev-account.env ``` You can tell if the environment variable is set correctly if your command line prints the account name after this command: ```bash echo $CONTRACT_NAME ``` The next command will initialize the contract using the `new` method: ```bash near call $CONTRACT_NAME new '{"owner_id": "'$CONTRACT_NAME'", "total_supply": "1000000000000000", "metadata": { "spec": "ft-1.0.0", "name": "Example Token Name", "symbol": "EXLT", "decimals": 8 }}' --accountId $CONTRACT_NAME ``` To get the fungible token metadata: ```bash near view $CONTRACT_NAME ft_metadata ``` ### Standard deploy This smart contract will get deployed to your NEAR account. For this example, please create a new NEAR account. Because NEAR allows the ability to upgrade contracts on the same account, initialization functions must be cleared. If you'd like to run this example on a NEAR account that has had prior contracts deployed, please use the `near-cli` command `near delete`, and then recreate it in Wallet. To create (or recreate) an account, please follow the directions on [NEAR Wallet](https://wallet.near.org/). Switch to `mainnet`. You can skip this step to use `testnet` as a default network. export NEAR_ENV=mainnet In the project root, log in to your newly created account with `near-cli` by following the instructions after this command: near login To make this tutorial easier to copy/paste, we're going to set an environment variable for your account id. In the below command, replace `MY_ACCOUNT_NAME` with the account name you just logged in with, including the `.near`: ID=MY_ACCOUNT_NAME You can tell if the environment variable is set correctly if your command line prints the account name after this command: echo $ID Now we can deploy the compiled contract in this example to your account: near deploy --wasmFile res/fungible_token.wasm --accountId $ID FT contract should be initialized before usage. You can read more about metadata at ['nomicon.io'](https://nomicon.io/Standards/FungibleToken/Metadata.html#reference-level-explanation). Modify the parameters and create a token: near call $ID new '{"owner_id": "'$ID'", "total_supply": "1000000000000000", "metadata": { "spec": "ft-1.0.0", "name": "Example Token Name", "symbol": "EXLT", "decimals": 8 }}' --accountId $ID Get metadata: near view $ID ft_metadata Transfer Example --------------- Let's set up an account to transfer some tokens to. These account will be a sub-account of the NEAR account you logged in with. near create-account bob.$ID --masterAccount $ID --initialBalance 1 Add storage deposit for Bob's account: near call $ID storage_deposit '' --accountId bob.$ID --amount 0.00125 Check balance of Bob's account, it should be `0` for now: near view $ID ft_balance_of '{"account_id": "'bob.$ID'"}' Transfer tokens to Bob from the contract that minted these fungible tokens, exactly 1 yoctoNEAR of deposit should be attached: near call $ID ft_transfer '{"receiver_id": "'bob.$ID'", "amount": "19"}' --accountId $ID --amount 0.000000000000000000000001 Check the balance of Bob again with the command from before and it will now return `19`. ## Testing As with many Rust libraries and contracts, there are tests in the main fungible token implementation at `ft/src/lib.rs`. Additionally, this project has [simulation] tests in `tests/sim`. Simulation tests allow testing cross-contract calls, which is crucial to ensuring that the `ft_transfer_call` function works properly. These simulation tests are the reason this project has the file structure it does. Note that the root project has a `Cargo.toml` which sets it up as a workspace. `ft` and `test-contract-defi` are both small & focused contract projects, the latter only existing for simulation tests. The root project imports `near-sdk-sim` and tests interaction between these contracts. You can run all these tests with one command: ```bash cargo test ``` If you want to run only simulation tests, you can use `cargo test simulate`, since all the simulation tests include "simulate" in their names. ## Notes - The maximum balance value is limited by U128 (`2**128 - 1`). - JSON calls should pass U128 as a base-10 string. E.g. "100". - This does not include escrow functionality, as `ft_transfer_call` provides a superior approach. An escrow system can, of course, be added as a separate contract or additional functionality within this contract. ## No AssemblyScript? [near-contract-standards] is currently Rust-only. We strongly suggest using this library to create your own Fungible Token contract to ensure it works as expected. Someday NEAR core or community contributors may provide a similar library for AssemblyScript, at which point this example will be updated to include both a Rust and AssemblyScript version. ## Contributing When making changes to the files in `ft` or `test-contract-defi`, remember to use `./build.sh` to compile all contracts and copy the output to the `res` folder. If you forget this, **the simulation tests will not use the latest versions**. Note that if the `rust-toolchain` file in this repository changes, please make sure to update the `.gitpod.Dockerfile` to explicitly specify using that as default as well.
MELEPORT_meleport-frontend
.gitpod.yml README.md babel.config.js develop.env package.json src App.js __mocks__ fileMock.js assets logo-black.svg logo-white.svg components ModalSale.js ModalTransferNFT.js ModelMintNFT.js config.js global.css index.html index.js jest.init.js layouts MainLayout.js main.test.js pages GameFillter GameFilter.css GameFilter.js MarketPlace.js Profile.js routes NotFound.js Router.js utils.js wallet login index.html text.txt vercel.json
# nft-market-frontend ## Step 1: Config! Change NFT_CONTRACT_NAME and MARKET_CONTRACT_NAME in: config.js ## Step 2: Storage deposit in MARKET CONTRACT! One command: near call MARKET_CONTRACT_NAME storage_deposit --accountId ACCOUNT_ID --deposit 0.01 near call nft-market.test_nft.testnet storage_deposit --accountId haitq6_owner.testnet --deposit 0.01 ## Step 3: Test! One command: yarn start
GRMDS_rmdsnft-contract-near
Cargo.toml README.md build.sh src lib.rs
## Instructions to build NEAR contracts ### Install Rust compiler and the package manager * [Rustup](https://rustup.rs/): Install Rust compiler * [cargo](https://crates.io/): Install Rust package manager ### Install wasm32 ```bash $ rustup target add wasm32-unknown-unknown ``` ### Build the project ```bash $ cargo build --target wasm32-unknown-unknown ``` or run the `build.sh` file ```bash $ chmod +x build.sh $ ./build.sh ``` ### Install near-cli ```bash $ npm install -g near-cli ``` ### Deploy the contract ```bash $ near login $ near create-account rmdsnft.sasikiran.testnet --masterAccount $ID $ near deploy --accountId rmdsnft.sasikiran.testnet --wasmFile res/rmds_nft.wasm ``` You should be able to verify the transaction from the URL of the [output](https://explorer.testnet.near.org/transactions/FcEYGpumLBEZe2BiBj9ADRpx1QSNSjhPPNJJovKe7Z58) ### Initialize the contract ```bash $ near call rmdsnft.sasikiran.testnet new_default_meta '{"owner_id": "sasikiran.testnet"}' --accountId sasikiran.testnet ``` ### View the metadata ```bash $ near view rmdsnft.sasikiran.testnet nft_metadata ``` ### Mint an NFT ```bash $ near call rmdsnft.sasikiran.testnet nft_mint '{"token_id": "0", "receiver_id": "'$ID'", "token_metadata": { "title": "White flowers", "description": "White flowers photo by Yulia", "media": "https://bafybeigyxcifz2eylcpq2a7fnfm3fc3jr5iuplwulz4erw7v4smbvssbsi.ipfs.nftstorage.link/Yulia.png", "copies": 1}}' --accountId $ID --deposit 0.1 ``` You should see a response: ``` Scheduling a call: rmdsnft.sasikiran.testnet.nft_mint({"token_id": "0", "receiver_id": "sasikiran.testnet", "token_metadata": { "title": "White flowers", "description": "White flowers photo by Yulia", "media": "https://bafybeigyxcifz2eylcpq2a7fnfm3fc3jr5iuplwulz4erw7v4smbvssbsi.ipfs.nftstorage.link/Yulia.png", "copies": 1}}) with attached 0.1 NEAR Doing account.functionCall() Receipts: 3odCpJYNq33Kbpf7NwvDT3tQvZEurQ5rzcB7RGj2SoGz, Arbsn9L3mvkxJf3wgZvtg69tLf5S1sNvLtNRsmJnmtuZ Log [rmdsnft.sasikiran.testnet]: EVENT_JSON:{"standard":"nep171","version":"1.0.0","event":"nft_mint","data":[{"owner_id":"sasikiran.testnet","token_ids":["0"]}]} Transaction Id 6VcU6Hzc95cPwg1oAB2wYbpE8PMZttu6vJNQnVuZKDz To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/6VcU6Hzc95cPwg1oAB2wYbpE8PMZttu6vJNQnVuZKDz { token_id: '0', owner_id: 'sasikiran.testnet', metadata: { title: 'White flowers', description: 'White flowers photo by Yulia', media: 'https://bafybeigyxcifz2eylcpq2a7fnfm3fc3jr5iuplwulz4erw7v4smbvssbsi.ipfs.nftstorage.link/Yulia.png', media_hash: null, copies: 1, issued_at: null, expires_at: null, starts_at: null, updated_at: null, extra: null, reference: null, reference_hash: null }, approved_account_ids: {} } ```
phucnt132_fe-near-simple-auction
package.json src config.js index.html index.js main.css utils.js
near-everything_type-creator
.vscode settings.json NOTES.txt README.md firebase.json package.json public index.html manifest.json robots.txt src App.css hooks useTypedNavigator.ts index.css logo.svg react-app-env.d.ts routes NavigationProps.ts services createType.ts getTypeDetails.ts getTypes.ts setupProxy.js utils truncate.ts tsconfig.json
# Type Creator This is the front end for Everything.Create.Type widget. ```json "scripts": { "dev": "pnpm start", "start": "react-scripts start", "build": "react-scripts build && cp -rf build dist && rm -rf build", "test": "react-scripts test", "eject": "react-scripts eject" }, ``` ## Development * Make changes here * Build and deploy or use ngrok * Put external url in Everything.Create.Type
open-web-academy_NCGD-Example
Cargo.toml README.md blobs.json build.sh flags.sh neardev dev-account.env src lib.rs target .rustc_info.json release .fingerprint Inflector-3fe6c4541cf2e4ba lib-inflector.json Inflector-b37f182bf12d138d lib-inflector.json borsh-derive-7e78b0af2f8d433a lib-borsh-derive.json borsh-derive-b877da9a1d0f6fe0 lib-borsh-derive.json borsh-derive-internal-58530aacca89f5ac lib-borsh-derive-internal.json borsh-derive-internal-8d14ff5df2dccb15 lib-borsh-derive-internal.json borsh-schema-derive-internal-7ec0b9de541836d5 lib-borsh-schema-derive-internal.json borsh-schema-derive-internal-b2a01ecfca91aede lib-borsh-schema-derive-internal.json near-sdk-macros-673a1699cc695959 lib-near-sdk-macros.json near-sdk-macros-fe4a088b5454d131 lib-near-sdk-macros.json proc-macro-crate-08b4af305a70ddf6 lib-proc-macro-crate.json proc-macro-crate-37de228bbc983c98 lib-proc-macro-crate.json proc-macro2-0427935320cd666e run-build-script-build-script-build.json proc-macro2-1464cdd7a54fb5f4 lib-proc-macro2.json proc-macro2-3c579a079672fe89 build-script-build-script-build.json proc-macro2-3d897d6e1ac80839 run-build-script-build-script-build.json proc-macro2-a8a2f2bbdc5faed3 build-script-build-script-build.json proc-macro2-fa347b8df92c06f5 lib-proc-macro2.json quote-30508074b234f77a lib-quote.json quote-b142ea98f4fe519c lib-quote.json ryu-2c8a6a40566b292c build-script-build-script-build.json ryu-dbf18d582793b27a build-script-build-script-build.json serde-014e5e1f54859ab3 build-script-build-script-build.json serde-07c72f39338bf12c build-script-build-script-build.json serde-0e1245389dbc2e3c lib-serde.json serde-7ef53811fa3c7e92 run-build-script-build-script-build.json serde-9169f7743616ae1e build-script-build-script-build.json serde-bd22ca3dcfea7c25 run-build-script-build-script-build.json serde-caeb2ffb9811a198 lib-serde.json serde-e988005fb986446c build-script-build-script-build.json serde_derive-3542c165ab4333b2 build-script-build-script-build.json serde_derive-53e4364afe9ad153 run-build-script-build-script-build.json serde_derive-58c3216794665ac7 run-build-script-build-script-build.json serde_derive-64c2979a664a49f3 lib-serde_derive.json serde_derive-688582c02818f4cb build-script-build-script-build.json serde_derive-a4fa543ca13319a5 lib-serde_derive.json serde_json-0e216f0ddede5097 build-script-build-script-build.json serde_json-8bb33cc0b0f8077f build-script-build-script-build.json syn-530373cce944a114 run-build-script-build-script-build.json syn-54a1744cdff2ffbb build-script-build-script-build.json syn-6687025c04b98b1f run-build-script-build-script-build.json syn-b081f0b999e7e2f4 build-script-build-script-build.json syn-bce29fcf75f0e4d9 lib-syn.json syn-d70485a145548b28 lib-syn.json toml-82f648fc380c74ab lib-toml.json toml-d6cbf7f17390aaf0 lib-toml.json unicode-xid-fae3456e6554f949 lib-unicode-xid.json unicode-xid-fcea4615157d93a3 lib-unicode-xid.json wee_alloc-1c861b34a9538744 build-script-build-script-build.json wee_alloc-930b09ca51478ec1 build-script-build-script-build.json wasm32-unknown-unknown release .fingerprint ahash-89ff722b9fc561a9 lib-ahash.json ahash-a9e7a2eb4c8b6b20 lib-ahash.json ahash-e4aff7b4d64dc34d lib-ahash.json base64-15e8122c6d042f0d lib-base64.json base64-5b3ebdee7de535b1 lib-base64.json base64-6f57e5f2ff742858 lib-base64.json borsh-02625cf371425d24 lib-borsh.json borsh-d566b7b7c2a4689c lib-borsh.json borsh-e4668b489bff362d lib-borsh.json bs58-016598fc3306fc3b lib-bs58.json bs58-7b1fa957726a33fc lib-bs58.json bs58-f2b475fc3ad0ee87 lib-bs58.json burritos-8ff76eb5c5209da3 lib-burritos.json cfg-if-37ef06d10bab2744 lib-cfg-if.json cfg-if-b33a73a19094630b lib-cfg-if.json cfg-if-fc51e6839c361fb5 lib-cfg-if.json example-videogame-7e14a023333b6831 lib-example-videogame.json example_videogame-b136bd08d2bbbcf9 lib-example_videogame.json hashbrown-0f38abaacccefd87 lib-hashbrown.json hashbrown-86bdd568053dd338 lib-hashbrown.json hashbrown-b6c3b1995f6f04d8 lib-hashbrown.json itoa-0000ef3252b48a58 lib-itoa.json itoa-9160739f7f612d55 lib-itoa.json itoa-dfd41cc8a04cd2a2 lib-itoa.json memory_units-70164b414646a2d3 lib-memory_units.json memory_units-759c1444a2770055 lib-memory_units.json memory_units-975e76477f41cffa lib-memory_units.json near-sdk-25a07fefb76b66b8 lib-near-sdk.json near-sdk-9364f331df57113b lib-near-sdk.json near-sdk-968e02eab437148c lib-near-sdk.json near-sys-17e86362d8f51181 lib-near-sys.json near-sys-9308eb8e753ce7c7 lib-near-sys.json near-sys-b9bcaa313dde3745 lib-near-sys.json nft_simple-322841616f66c026 lib-nft_simple.json pve-5b5854ee41633f09 lib-pve.json ryu-28314bba5866d760 lib-ryu.json ryu-5b43f48bce5fbfd2 run-build-script-build-script-build.json ryu-85d51293d2c7f717 lib-ryu.json ryu-de623448d02ccde9 run-build-script-build-script-build.json ryu-e0edf089a45d1cf9 lib-ryu.json serde-3a7cf4a3ed96ba70 lib-serde.json serde-3b11f7d1d172877c run-build-script-build-script-build.json serde-49951e94aa533514 lib-serde.json serde-50db3577d8de5476 run-build-script-build-script-build.json serde-edd7e444b143486f lib-serde.json serde_json-035c4319e70898b8 run-build-script-build-script-build.json serde_json-1cd658966a46af93 lib-serde_json.json serde_json-3d5501acac0cdb98 lib-serde_json.json serde_json-4ca5dbafca7a2be1 lib-serde_json.json serde_json-61f5490cb7ad9296 run-build-script-build-script-build.json wee_alloc-22497db7cf616fe1 run-build-script-build-script-build.json wee_alloc-3dbc041e3be8a3f7 lib-wee_alloc.json wee_alloc-472ec3be1e3ba846 run-build-script-build-script-build.json wee_alloc-4ed9747105933016 lib-wee_alloc.json wee_alloc-de152dbd4f81720e lib-wee_alloc.json build wee_alloc-22497db7cf616fe1 out wee_alloc_static_array_backend_size_bytes.txt wee_alloc-472ec3be1e3ba846 out wee_alloc_static_array_backend_size_bytes.txt
ID=dev-1652728160134-47102512188392 echo $ID Inicializar contrato: near call $ID init_contract '{"owner_id":"'$ID'"}' --accountId $ID Obtener todas las puntuaciones: near view $ID obtener_puntuaciones Obtener puntuacion de jugador: near call $ID obtener_puntuacion '{"owner_id":"'yairnava.testnet'"}' --accountId yairnava.testnet Guardar puntuación near call $ID guardar_puntuacion '{"puntuacion": 40}' --accountId yairnava.testnet
MakC-Ukr_near-staking-data-extraction
README.md RELEVANT_VALIDATORS.json back_populate.py daily_bot.py global_import.py google_sheet_updates send_historical_file.py send_val_file.py update_all.py helpers.py historical_script.py requirements.txt validate.py
# Near staking data extraction pipeline
nearsplit_nearsplit
.eslintrc.js .vscode settings.json README.md apps contract README.md babel.config.json build.sh deploy.sh neardev dev-account.env package.json src contract.ts tsconfig.json docs .eslintrc.js README.md next-env.d.ts next.config.js package.json tsconfig.json integration ava.config.js package.json src main.ava.ts tsconfig.json web .eslintrc.js README.md core fetch coinGecko.ts near interfaces.ts next-env.d.ts next.config.js package.json pages _app.js public vercel.svg styles Home.module.css globals.css tsconfig.json package.json packages eslint-config-custom index.js package.json tsconfig README.md base.json nextjs.json package.json react-library.json ui package.json tsconfig.json turbo.json
# `tsconfig` These are base shared `tsconfig.json`s from which all other `tsconfig.json`'s inherit from. # NEAR Split 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>`. # Turborepo starter This is an official pnpm starter turborepo. ## What's inside? This turborepo uses [pnpm](https://pnpm.io) as a package manager. It includes the following packages/apps: ### Apps and Packages - `docs`: near-split docs [Next.js](https://nextjs.org) app - `web`: near-split [Next.js](https://nextjs.org) app - `contract`: near-split contract - `ui`: a stub React component library shared by both `web` and `docs` applications - `eslint-config-custom`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`) - `tsconfig`: `tsconfig.json`s used throughout the monorepo Each package/app is 100% [TypeScript](https://www.typescriptlang.org/). ### Utilities This turborepo has some additional tools already setup for you: - [TypeScript](https://www.typescriptlang.org/) for static type checking - [ESLint](https://eslint.org/) for code linting ### Build To build all apps and packages, run the following command: ``` cd my-turborepo pnpm run build ``` ### Develop To develop all apps and packages, run the following command: ``` cd my-turborepo pnpm run dev ``` ### Remote Caching Turborepo can use a technique known as [Remote Caching](https://turborepo.org/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines. By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup), then enter the following commands: ``` cd my-turborepo pnpm dlx turbo login ``` This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview). Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your turborepo: ``` pnpm dlx turbo link ``` ## Useful Links Learn more about the power of Turborepo: - [Pipelines](https://turborepo.org/docs/core-concepts/pipelines) - [Caching](https://turborepo.org/docs/core-concepts/caching) - [Remote Caching](https://turborepo.org/docs/core-concepts/remote-caching) - [Scoped Tasks](https://turborepo.org/docs/core-concepts/scopes) - [Configuration Options](https://turborepo.org/docs/reference/configuration) - [CLI Usage](https://turborepo.org/docs/reference/command-line-reference) ## Getting Started First, run the development server: ```bash 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_source=github.com&utm_medium=referral&utm_campaign=turborepo-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details. ## Getting Started First, run the development server: ```bash 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_source=github.com&utm_medium=referral&utm_campaign=turborepo-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
Kana-v1_blockchain-auction
Cargo.toml README.md build.bat build.sh deploy.sh frontend README.md package.json public index.html manifest.json robots.txt src components Accounts Accounts.css Accounts.js AdminPanel AdminPanel.css AdminPanel.js App.css App.js Items Items.css Items.js Lots Lots.css Lots.js MainPage MainPage.css MainPage.js Sidebar Sidebar.js SidebarData.js contract config.js utils.js index.js reportWebVitals.js src helper.rs lib.rs supplier.rs test.sh tests sim main.rs
# 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: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm 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. ### `npm run 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. ### `npm run 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) ### `npm run 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) # Description The core idea is just a traditinal auction where sellers can sell items and buyers can make bids and win items # File structure src -> contract code by itself frontend -> frontend # Tests ``` cargo test ``` # Run locally ``` cd frontend npm i npm start ```
IMEF-FEMI_NEAR-NFT-bridge-contract
.gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh src bridge.rs lib.rs integration-tests package-lock.json package.json src main.ava.ts utils.ts package-lock.json package.json scripts build deploy.js mint.js src deploy.ts mint.ts types.d.ts tsconfig.json
# 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
jorgeavaldez_champagne
README.md babel.config.js compile.js docker-compose.yml next-env.d.ts next.config.js package.json pages api auth twitter callback.ts index.ts wallet index.ts logout.ts linkdrop index.ts prisma migrations 20210917024350_init_keys_and_accounts migration.sql 20210919003251_social_account_manual_tokens migration.sql migration_lock.toml src __mocks__ fileMock.js backend hooks.ts keyGenerator.ts middleware.ts passport index.ts twitter.ts wallet.ts prisma.ts session.ts ceramic index.ts components AdminHeader AdminHeader.module.css AdminLayout AdminLayout.module.css AdminPageContainer AdminPageContainer.module.css AdminPageSectionContainer AdminPageSectionContainer.module.css Calendar Calendar.module.css CampaignCard CampaignCard.module.css CampaignDetails CampaignDetails.module.css ComputerAdminLayout ComputerAdminLayout.module.css EditCampaignModal EditCampaignModal.module.css FeatureCards FeatureCards.module.css Footer Footer.module.css Home Home.module.css HomeFooter HomeFooter.module.css HomeHeader HomeHeader.module.css HomeLayout HomeLayout.module.css HomeSection HomeSection.module.css Layout Layout.module.css Login Login.module.css LoginLayout LoginLayout.module.css LoginSections LoginSections.module.css MobileAdminLayout MobileAdminLayout.module.css MobileNav MobileNav.module.css Navbar Navbar.module.css PlatformCards PlatformCards.module.css PostCard PostCard.module.css RewardCards RewardCards.module.css SchedulePostModal SchedulePostModal.module.css SideNav SideNav.module.css StatsContainer StatsContainer.module.css Tables Tables.module.css jest.init.js main.test.js near config.ts helpers.ts hooks.ts index.ts wallet login index.html styles global.css pages admin.module.css campaign.module.css home.module.css index.module.css tsconfig.json
# champagne ## Quick Start To run this project locally: **Prerequisites**: Make sure you've installed docker ```bash # install deps yarn # Deploy smart contracts yarn build:contract && yarn dev:deploy:contract # Start in docker docker-compose up ``` 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 - Contracts live in contracts.near-linkdrop, a submodule pointing to [this repo](https://github.com/jorgeavaldez/contracts.near-linkdrop) - `pages` contains a list of Next.js pages and api routes - `src` contains components and helper modules for talking to the blockchain and social networks ## 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 `champagne.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `champagne.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 champagne.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 || 'champagne.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 --- This [React] app was initialized with [create-near-app]
kaan-nacaroglu_NCD-course-practices
Practice I starter--near-sdk-as-main README.md as-pect.config.js asconfig.json neardev dev-account.env 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 Practice II README.md as-pect.config.js asconfig.json neardev dev-account.env 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 README.md
# NCD-course-practices A repo for all practices of NCD course
near_near-stats
.eslintrc.json CONTRIBUTING.md README.md components Background.js Footer.js Graphcard.js Header.js areaChart.js barChart.js brushChart.js brushedAreaChart.js datatable.js tooltip.js usePrevious.js helpers 2dCanvasCapture.js formatNumbers.js theme.js next.config.js package.json pages _app.js _document.js index.js public images logo_nm.svg signal.svg server.js start.sh
# NEAR Stats Welcome to the NEAR Stats Repo. NEAR Stats is a dashboard to track the growth of apps on the NEAR Platform. The data behind the NEAR Stats Project comes from the [NEAR Analytics](https://github.com/near/near-analytics) Database for aggregated data, and the [NEAR Ecosystem Repo](https://github.com/near/ecosystem) for app data. Alongside the dashboard is an API that provides that data behind all of the NEAR Stats visualizations. Please visit the [API Wiki](../../wiki/API) for API Documentation. Details of the structure and code for the dashboard can be found in the [Front End Wiki](../../wiki/Front-end). # Running NEAR Stats ## Environment Variables Environment variables required for connection to the NEAR Analytics database are required in a ```.env``` file. An example of the required variables are included in the [.env-example](.env-example). This file can be renamed ```.env```, however the credentials should be checked against the [NEAR Analytics](https://github.com/near/near-analytics) Repo. ## Running NEAR Stats Locally NEAR Stats is developed using [Next.js](https://nextjs.org/). To install the dependencies needed for the project, run ```yarn```. The project can be ran in development mode using ```yarn dev``` or alternatively in production mode with ```yarn build``` followed by ```yarn start```. ## Additional Dependencies ### Redis Cache Server A Redis Caching Server is highly recommended to improve loadings time and load on the NEAR Analytics Database. Running NEAR Stats without a Redis Caching Server is possible without any additional modification however queries to the NEAR Analytics Database may be blocked during times of high volume. The Redis Caching Server will cache all results for a period of 24 hours. #### Redis Installation Mac The following terminal commands will install and run a local Redis Server on a Mac. Additional information and instructions for alternative systems can be found on the [Redis Website](https://redis.io/). ``` mkdir redis && cd redis curl -O http://download.redis.io/redis-stable.tar.gz tar xzvf redis-stable.tar.gz cd redis-stable make make test sudo make install redis-server ``` #### Flushing Redis server cache In the event you would like to clear the cached database results, the following results will flush (reset) the cache. ```redis-cli FLUSHDB``` # DOCKER The following steps will build a docker container that will automatically run the NEAR Stats dashboard and Redis server. ## Install Docker Download [Docker Desktop](https://www.docker.com/products/docker-desktop) and ensure it is open and running to start the docker daemon. ## Docker Build ```docker build -t nearstats .``` ## Docker Start The docker container can be started from Docker Desktop Run the image and set the local host port to 3000 visit http://localhost:3000 in your browser. # Contributing To contribute to NEAR Stats, please see [CONTRIBUTING](CONTRIBUTING.md). # License NEAR Stats is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE-MIT](LICENSE-MIT) and [LICENSE-APACHE](LICENSE-APACHE) for details.
piorot_near-document-cloud
README.md as-pect.config.js asconfig.json config.js lib utils.js package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src agreement __tests__ index.unit.spec.ts asconfig.json assembly index.ts as_types.d.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 Document Cloud **Robust and trustless solution to use NEAR blockchain for managing and signing documents** *project created form template `near-sdk-as` Starter Kit* ## Problem Description Everyday we sign agreements with various companies like financial institutions, mobile operators and other individuals like real-estate agents and landlords. Similarily comapnies need to have thousands of various agreements, policies and docs signed by consumers, contractors, business partners. In many cases storing and tracking those documents is cumbersome. Not to mention several documents versions for a single topic like for instance fluctating bank fees that each of us need to sign on regular basis. For this reason individuals & companies seek solution to manage their agreements with various parties in easy, managable and **trustless** way. ## Solution Description ### Solution Requirements: * List all agreements user has signed and has issued to be signed by someone else. * Allow to add revisions (documents versions) * Allow to sign documents * Documents should be stored in ipfs; link should be stored on-chain ### Solution UI concept *Since I believe image is best explainer I added those wireframes to make the reader get the whole idea quiclky. The UI layer is not implemented, however the smart-contract itself has already most of needed code. So to have it fully working one will only need to add some (view) filtering capabilities and do the UI layer* ### Listing all agreements Project should potentially allow to show all agreements (especially all agreements related to logged user). There should be clear distinction for: * `Issued by others` - agreements the user is supposed to sign or has already signed (top row) * `Issued by You` - agreements user has issued and expects someone to sign (bottom row) ![List of all agreements of particular user](./docs/list-of-agreements.png) ### Ading new agreement Any user can add an agreement. Adding agreement requires to input at least ipfs link to initial document version and intended signer. All remaining details are a matter of potential extension and decision where to store these (on-chain vs off-chain). ![Adding new revision](./docs/add-agreement.png) Agreements are immutable with exception to adding new agreement revision and signing it ### Signing agreement User can sign agreement only if it has been issued with explicit indication he/she is intended signer. Trying to sign agreement that has not been issued for acting user will throw (reject tx). ![An agreement that can be signed](./docs/signing.png) In the image above we can see Agreement with credit cart operator is `not signed` because it has been updated - issuer has added `revision two` and to formaly be in force this agreement needs to be signed again. This can be easily achieved by clicking sign with wallet button and acknowledging the tx. ### Adding new revision User can only add revision for those agreements he/she has issued. Trying to add revision to agreement issued by someone else will result in transaction rejection. ![Adding new revision](./docs/adding-revision.png) Adding new revision could potentially be achieved on separate screen and require just entering `ipfs link` to new document. All other details of agreement like previous links, signing history, or other details should be read only at this stage. Adding new revision sets the whole agreement in `isSigned : false` state, no matter if it has been already signed or not. Conditions have changed and the agreement can not be automatically in force/signed without signer explicitly signing it again. ## Usage ### Unit tests Whole business logic of Agreement has been covered with unit tests. Run unit tests by: `yarn test` ### 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 `yarn build` 4. run `./scripts/1.dev-deploy.sh` 5. run `./scripts/2.use-contract.sh` 6. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 7. run `./scripts/3.cleanup.sh` ### Videos https://www.loom.com/share/b2c007bbf766468bb6d8cdaa402ffadf