├── .gitpod.Dockerfile ├── frontend ├── assets │ ├── favicon.ico │ ├── logo-white.svg │ ├── logo-black.svg │ └── global.css ├── .cypress │ ├── tsconfig.json │ ├── cypress.config.js │ └── e2e │ │ └── donation.cy.ts ├── start.sh ├── package.json ├── near-interface.js ├── index.html ├── near-wallet.js └── index.js ├── contract ├── build.sh ├── deploy.sh ├── src │ ├── utils.ts │ ├── model.ts │ └── contract.ts ├── tsconfig.json ├── package.json └── README.md ├── .gitpod.yml ├── integration-tests ├── ava.config.cjs ├── package.json └── src │ └── main.ava.ts ├── .github ├── scripts │ └── runfe.sh └── workflows │ ├── tests.yml │ └── readme.yml ├── .gitignore ├── package.json ├── LICENSE └── README.md /.gitpod.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gitpod/workspace-full 2 | 3 | RUN sudo install-packages xdg-utils -------------------------------------------------------------------------------- /frontend/assets/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ailisp/donation-js/master/frontend/assets/favicon.ico -------------------------------------------------------------------------------- /contract/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | echo ">> Building contract" 4 | 5 | near-sdk-js build src/contract.ts build/contract.wasm -------------------------------------------------------------------------------- /contract/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # build the contract 4 | npm run build 5 | 6 | # deploy the contract 7 | near dev-deploy --wasmFile build/contract.wasm -------------------------------------------------------------------------------- /contract/src/utils.ts: -------------------------------------------------------------------------------- 1 | export function assert(statement, message) { 2 | if (!statement) { 3 | throw Error(`Assertion failed: ${message}`) 4 | } 5 | } -------------------------------------------------------------------------------- /contract/src/model.ts: -------------------------------------------------------------------------------- 1 | export const STORAGE_COST: bigint = BigInt("1000000000000000000000") 2 | 3 | export class Donation { 4 | account_id: string; 5 | total_amount: string; 6 | } -------------------------------------------------------------------------------- /frontend/.cypress/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["es5", "dom"], 5 | "types": ["cypress"] 6 | }, 7 | "include": ["**/*.ts"] 8 | } -------------------------------------------------------------------------------- /contract/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "experimentalDecorators": true, 4 | "target": "es5", 5 | "noEmit": true 6 | }, 7 | "exclude": [ 8 | "node_modules" 9 | ], 10 | } -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | image: 2 | file: .gitpod.Dockerfile 3 | 4 | tasks: 5 | - init: echo "welcome" 6 | command: npm i && npm run deploy && npm run start 7 | 8 | ports: 9 | - port: 1234 10 | onOpen: open-browser -------------------------------------------------------------------------------- /integration-tests/ava.config.cjs: -------------------------------------------------------------------------------- 1 | require("util").inspect.defaultOptions.depth = 5; // Increase AVA's printing depth 2 | 3 | module.exports = { 4 | timeout: "300000", 5 | files: ["src/*.ava.ts"], 6 | failWithoutAssertions: false, 7 | extensions: ["ts"], 8 | require: ["ts-node/register"], 9 | }; 10 | -------------------------------------------------------------------------------- /.github/scripts/runfe.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env 2 | 3 | # run yarn start with timeout 30, catch the error code 4 | echo "Running yarn start with timeout 30" 5 | timeout 30 yarn start 6 | EXIT_CODE=$? 7 | # if error code is 124, it means timeout, we exit with 0 8 | if [ $EXIT_CODE -eq 124 ]; then 9 | echo "Timeout reached" 10 | exit 0 11 | fi 12 | # throw error code 13 | exit $EXIT_CODE 14 | -------------------------------------------------------------------------------- /integration-tests/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "integration-tests", 3 | "version": "1.0.0", 4 | "license": "(MIT AND Apache-2.0)", 5 | "scripts": { 6 | "test": "ava" 7 | }, 8 | "devDependencies": { 9 | "@types/bn.js": "^5.1.0", 10 | "@types/node": "^18.6.2", 11 | "ava": "^4.2.0", 12 | "near-workspaces": "^3.2.1", 13 | "ts-node": "^10.8.0", 14 | "typescript": "^4.7.2" 15 | }, 16 | "dependencies": {} 17 | } 18 | -------------------------------------------------------------------------------- /frontend/.cypress/cypress.config.js: -------------------------------------------------------------------------------- 1 | const { defineConfig } = require("cypress"); 2 | 3 | module.exports = defineConfig({ 4 | e2e: { 5 | baseUrl: "http://localhost:1234", 6 | specPattern: ["e2e/*.cy.*"], 7 | supportFile: false, 8 | chromeWebSecurity: false, 9 | env: { 10 | seed: "give laugh youth nice fossil common neutral since best biology swift unhappy", 11 | accountId: "cypress-guest-book.testnet", 12 | }, 13 | }, 14 | }); -------------------------------------------------------------------------------- /contract/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "contract", 3 | "version": "1.0.0", 4 | "license": "(MIT AND Apache-2.0)", 5 | "type": "module", 6 | "scripts": { 7 | "build": "./build.sh", 8 | "deploy": "./deploy.sh", 9 | "test": "echo no unit testing" 10 | }, 11 | "dependencies": { 12 | "near-cli": "^3.4.0", 13 | "near-sdk-js": "0.7.0" 14 | }, 15 | "devDependencies": { 16 | "typescript": "^4.8.4", 17 | "ts-morph": "^16.0.0" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | on: push 3 | jobs: 4 | workflows: 5 | strategy: 6 | matrix: 7 | platform: [ubuntu-latest, macos-latest, ubuntu-22.04] 8 | runs-on: ${{ matrix.platform }} 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions/setup-node@v2 12 | with: 13 | node-version: "16" 14 | - name: Install modules 15 | run: yarn 16 | - name: Deploy 17 | run: printf 'y\n' | yarn deploy 18 | - name: Run tests 19 | run: yarn test -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | # Developer note: near.gitignore will be renamed to .gitignore upon project creation 3 | # dependencies 4 | node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # build 9 | **/out 10 | **/dist 11 | **/node_modules 12 | 13 | # keys 14 | **/neardev 15 | 16 | # testing 17 | /coverage 18 | **/videos 19 | **/screenshots 20 | 21 | # production 22 | **/build 23 | **/.parcel-cache 24 | 25 | # misc 26 | .DS_Store 27 | .env.local 28 | .env.development.local 29 | .env.test.local 30 | .env.production.local 31 | /.cache 32 | 33 | npm-debug.log* 34 | yarn-debug.log* 35 | yarn-error.log* 36 | -------------------------------------------------------------------------------- /frontend/start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | GREEN='\033[1;32m' 4 | NC='\033[0m' # No Color 5 | 6 | CONTRACT_DIRECTORY=../contract 7 | DEV_ACCOUNT_FILE="${CONTRACT_DIRECTORY}/neardev/dev-account.env" 8 | 9 | start () { 10 | echo The app is starting! 11 | env-cmd -f $DEV_ACCOUNT_FILE parcel index.html --open 12 | } 13 | 14 | alert () { 15 | echo "======================================================" 16 | echo "It looks like you forgot to deploy your contract" 17 | echo ">> Run ${GREEN}'npm run deploy'${NC} from the 'root' directory" 18 | echo "======================================================" 19 | } 20 | 21 | if [ -f "$DEV_ACCOUNT_FILE" ]; then 22 | start 23 | else 24 | alert 25 | fi 26 | -------------------------------------------------------------------------------- /frontend/assets/logo-white.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/assets/logo-black.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "donation-js", 3 | "version": "1.0.0", 4 | "license": "(MIT AND Apache-2.0)", 5 | "scripts": { 6 | "start": "cd frontend && npm run start", 7 | "deploy": "cd contract && npm run deploy", 8 | "build": "npm run build:contract && npm run build:web", 9 | "build:web": "cd frontend && npm run build", 10 | "build:contract": "cd contract && npm run build", 11 | "test": "npm run build:contract && npm run test:unit && npm run test:integration && npm run test:e2e", 12 | "test:unit": "cd contract && npm test", 13 | "test:integration": "cd integration-tests && npm test -- -- \"./contract/build/contract.wasm\"", 14 | "test:e2e": "cd frontend && npm run test:e2e", 15 | "postinstall": "cd frontend && npm install && cd .. && cd integration-tests && npm install && cd .. && cd contract && npm install" 16 | }, 17 | "devDependencies": { 18 | "near-cli": "^3.3.0" 19 | }, 20 | "dependencies": {} 21 | } -------------------------------------------------------------------------------- /.github/workflows/readme.yml: -------------------------------------------------------------------------------- 1 | name: README 2 | on: push 3 | jobs: 4 | readme-ubuntu: 5 | strategy: 6 | matrix: 7 | platform: [ubuntu-latest, ubuntu-22.04] 8 | runs-on: ${{ matrix.platform }} 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions/setup-node@v2 12 | with: 13 | node-version: "16" 14 | - name: Install modules 15 | run: yarn 16 | - name: Deploy 17 | run: printf 'y\n' | yarn deploy 18 | - name: Start 19 | run: bash .github/scripts/runfe.sh 20 | readme-mac: 21 | strategy: 22 | matrix: 23 | platform: [macos-latest] 24 | runs-on: ${{ matrix.platform }} 25 | steps: 26 | - uses: actions/checkout@v2 27 | - uses: actions/setup-node@v2 28 | with: 29 | node-version: "16" 30 | - name: Install modules 31 | run: yarn 32 | - name: Deploy 33 | run: printf 'y\n' | yarn deploy 34 | - name: Install timeout 35 | run: brew install coreutils 36 | - name: Start 37 | run: bash .github/scripts/runfe.sh 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Examples for building on the NEAR blockchain 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-near-app", 3 | "version": "1.0.0", 4 | "license": "(MIT AND Apache-2.0)", 5 | "scripts": { 6 | "start": "./start.sh", 7 | "start:headless": "env-cmd -f '../contract/neardev/dev-account.env' parcel index.html", 8 | "build": "parcel build index.html --public-url ./", 9 | "test:e2e": "npm run start:headless & npm run cypress:run", 10 | "cypress:run": "cd .cypress && cypress run", 11 | "cypress:open": "cypress open --browser chromium" 12 | }, 13 | "devDependencies": { 14 | "env-cmd": "^10.1.0", 15 | "events": "^3.3.0", 16 | "nodemon": "^2.0.16", 17 | "parcel": "^2.7.0", 18 | "process": "^0.11.10", 19 | "typescript": "^4.7.2", 20 | "ts-node": "^10.8.0", 21 | "cypress": "^11.2.0" 22 | }, 23 | "dependencies": { 24 | "@near-wallet-selector/core": "^7.0.0", 25 | "@near-wallet-selector/ledger": "^7.0.0", 26 | "@near-wallet-selector/math-wallet": "^7.0.0", 27 | "@near-wallet-selector/meteor-wallet": "^7.0.0", 28 | "@near-wallet-selector/modal-ui": "^7.0.0", 29 | "@near-wallet-selector/my-near-wallet": "^7.0.0", 30 | "@near-wallet-selector/near-wallet": "^7.0.0", 31 | "@near-wallet-selector/nightly": "^7.0.0", 32 | "@near-wallet-selector/nightly-connect": "^7.0.0", 33 | "@near-wallet-selector/sender": "^7.0.0", 34 | "@near-wallet-selector/wallet-connect": "^7.0.0", 35 | "near-api-js": "^0.44.2" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /frontend/near-interface.js: -------------------------------------------------------------------------------- 1 | /* Talking with a contract often involves transforming data, we recommend you to encapsulate that logic into a class */ 2 | 3 | import { utils } from 'near-api-js' 4 | 5 | export class Contract { 6 | 7 | constructor({ contractId, walletToUse }) { 8 | this.contractId = contractId; 9 | this.wallet = walletToUse; 10 | } 11 | 12 | async getBeneficiary() { 13 | return await this.wallet.viewMethod({ contractId: this.contractId, method: "get_beneficiary" }) 14 | } 15 | 16 | async latestDonations() { 17 | const number_of_donors = await this.wallet.viewMethod({ contractId: this.contractId, method: "number_of_donors" }) 18 | const min = number_of_donors > 10 ? number_of_donors - 9 : 0 19 | 20 | let donations = await this.wallet.viewMethod({ contractId: this.contractId, method: "get_donations", args: { from_index: min.toString(), limit: number_of_donors } }) 21 | 22 | donations.forEach(elem => { 23 | elem.total_amount = utils.format.formatNearAmount(elem.total_amount); 24 | }) 25 | 26 | return donations 27 | } 28 | 29 | async getDonationFromTransaction(txhash) { 30 | let donation_amount = await this.wallet.getTransactionResult(txhash); 31 | return utils.format.formatNearAmount(donation_amount); 32 | } 33 | 34 | async donate(amount) { 35 | let deposit = utils.format.parseNearAmount(amount.toString()) 36 | let response = await this.wallet.callMethod({ contractId: this.contractId, method: "donate", deposit }) 37 | return response 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Donation 💸 2 | [](https://docs.near.org/tutorials/welcome) 3 | [](https://gitpod.io/#/https://github.com/near-examples/donation-js) 4 | [](https://docs.near.org/develop/contracts/anatomy) 5 | [](https://docs.near.org/develop/integrate/frontend) 6 | [](https://actions-badge.atrox.dev/near-examples/donation-js/goto) 7 | 8 | 9 | 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. 10 | 11 |  12 | 13 | 14 | # What This Example Shows 15 | 16 | 1. How to receive and transfer $NEAR on a contract. 17 | 2. How to divide a project into multiple modules. 18 | 3. How to handle the storage costs. 19 | 4. How to handle transaction results. 20 | 5. How to use a `Map`. 21 | 22 | 23 | 24 | # Quickstart 25 | 26 | Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/donation-js). Then follow these steps: 27 | 28 | ### 1. Install Dependencies 29 | ```bash 30 | npm install 31 | ``` 32 | 33 | ### 2. Test the Contract 34 | Deploy your contract in a sandbox and simulate interactions from users. 35 | 36 | ```bash 37 | npm test 38 | ``` 39 | 40 | ### 3. Deploy the Contract 41 | Build the contract and deploy it in a testnet account 42 | ```bash 43 | npm run deploy 44 | ``` 45 | 46 | ### 4. Start the Frontend 47 | Start the web application to interact with your smart contract 48 | ```bash 49 | npm start 50 | ``` 51 | 52 | --- 53 | 54 | # Learn More 55 | 1. Learn more about the contract through its [README](./contract/README.md). 56 | 2. Check [**our documentation**](https://docs.near.org/develop/welcome). -------------------------------------------------------------------------------- /frontend/.cypress/e2e/donation.cy.ts: -------------------------------------------------------------------------------- 1 | const SEED = Cypress.env('seed') 2 | const ACCOUNT_ID = Cypress.env('accountId') 3 | 4 | context("Main Page", () => { 5 | beforeEach(() => { 6 | cy.visit("/"); 7 | }); 8 | 9 | it("should display home page correctly", () => { 10 | // should display the title 11 | cy.get("h4").contains("Latest Donations"); 12 | // should have columns titled: "User" and "Total Donated Ⓝ" 13 | cy.get("th").contains("User"); 14 | cy.get("th").contains("Total Donated Ⓝ"); 15 | // should have a button to Sign in 16 | cy.get("button").contains("Sign in"); 17 | }); 18 | 19 | it("should be able to complete donation flow", () => { 20 | // should be able to click on the Sign in button 21 | cy.get("button").contains("Sign in").click(); 22 | // Select element from left modal list titled: "MyNearWallet" and click on it 23 | cy.get("div").contains("MyNearWallet").click(); 24 | // Wait for new page to load 25 | cy.wait(20000); 26 | // Click on the "Import Existing Account" button 27 | cy.get("button").contains("Import Existing Account").click(); 28 | // Click on the "Recover Account" button 29 | cy.get("button").contains("Recover Account").click(); 30 | // Fill in SEED from the environment variable into the input field 31 | cy.get("input").type(SEED); 32 | // Click on the "Find My Account" button 33 | cy.get("button").contains("Find My Account").click(); 34 | // Wait for new page to load 35 | cy.wait(20000); 36 | // Click on the "Next" button 37 | cy.get("button").contains("Next").click(); 38 | // Click on the "Connect" button 39 | cy.get("button").contains("Connect").click(); 40 | // Wait for new page to load 41 | cy.wait(20000); 42 | 43 | // should be able to enter the amount to donate in input field with id: "donation" 44 | cy.get("input[id=donation]").type("10"); 45 | // should be able to click the donate button 46 | cy.get("button").contains("Donate").click(); 47 | // Wait for new page to load 48 | cy.wait(20000); 49 | // should be able to click "Approve" to confirm the donation 50 | cy.get("button").contains("Approve").click(); 51 | // Wait for new page to load 52 | cy.wait(20000); 53 | // should display the donating account name on page 54 | cy.contains(ACCOUNT_ID); 55 | }); 56 | }); -------------------------------------------------------------------------------- /integration-tests/src/main.ava.ts: -------------------------------------------------------------------------------- 1 | import { Worker, NEAR, NearAccount } from "near-workspaces"; 2 | import anyTest, { TestFn } from "ava"; 3 | 4 | const test = anyTest as TestFn<{ 5 | worker: Worker; 6 | accounts: Record; 7 | }>; 8 | 9 | test.beforeEach(async (t) => { 10 | // Init the worker and start a Sandbox server 11 | const worker = await Worker.init(); 12 | 13 | const root = worker.rootAccount; 14 | 15 | // define users 16 | const beneficiary = await root.createSubAccount("beneficiary", { 17 | initialBalance: NEAR.parse("30 N").toJSON(), 18 | }); 19 | 20 | const alice = await root.createSubAccount("alice", { 21 | initialBalance: NEAR.parse("30 N").toJSON(), 22 | }); 23 | 24 | const bob = await root.createSubAccount("bob", { 25 | initialBalance: NEAR.parse("30 N").toJSON(), 26 | }); 27 | 28 | const contract = await root.createSubAccount("contract", { 29 | initialBalance: NEAR.parse("30 N").toJSON(), 30 | }); 31 | 32 | // Deploy the contract. 33 | await contract.deploy(process.argv[2]); 34 | 35 | // Initialize beneficiary 36 | await contract.call(contract, "init", {beneficiary: beneficiary.accountId}) 37 | 38 | // Save state for test runs, it is unique for each test 39 | t.context.worker = worker; 40 | t.context.accounts = { root, contract, beneficiary, alice, bob }; 41 | }); 42 | 43 | test.afterEach(async (t) => { 44 | // Stop Sandbox server 45 | await t.context.worker.tearDown().catch((error) => { 46 | console.log("Failed to stop the Sandbox:", error); 47 | }); 48 | }); 49 | 50 | test("sends donations to the beneficiary", async (t) => { 51 | const { contract, alice, beneficiary } = t.context.accounts; 52 | 53 | const balance = await beneficiary.balance(); 54 | const available = parseFloat(balance.available.toHuman()); 55 | 56 | await alice.call(contract, "donate", {}, { attachedDeposit: NEAR.parse("1 N").toString() }); 57 | 58 | const new_balance = await beneficiary.balance(); 59 | const new_available = parseFloat(new_balance.available.toHuman()); 60 | 61 | t.is(new_available, available + 1 - 0.001); 62 | }); 63 | 64 | test("records the donation", async (t) => { 65 | const { contract, bob } = t.context.accounts; 66 | 67 | await bob.call(contract, "donate", {}, { attachedDeposit: NEAR.parse("2 N").toString() }); 68 | 69 | const donation: Donation = await contract.view("get_donation_for_account", { account_id: bob.accountId }); 70 | 71 | t.is(donation.account_id, bob.accountId); 72 | t.is(donation.total_amount, NEAR.parse("2 N").toString()); 73 | }); 74 | 75 | class Donation{ 76 | account_id: string = ""; 77 | total_amount: string = ""; 78 | } -------------------------------------------------------------------------------- /contract/src/contract.ts: -------------------------------------------------------------------------------- 1 | import { NearBindgen, near, call, view, initialize, UnorderedMap } from 'near-sdk-js' 2 | 3 | import { assert } from './utils' 4 | import { Donation, STORAGE_COST } from './model' 5 | 6 | @NearBindgen({}) 7 | class DonationContract { 8 | beneficiary: string = "v1.faucet.nonofficial.testnet"; 9 | donations = new UnorderedMap('map-uid-1'); 10 | 11 | @initialize({ privateFunction: true }) 12 | init({ beneficiary }: { beneficiary: string }) { 13 | this.beneficiary = beneficiary 14 | } 15 | 16 | @call({ payableFunction: true }) 17 | donate() { 18 | // Get who is calling the method and how much $NEAR they attached 19 | let donor = near.predecessorAccountId(); 20 | let donationAmount: bigint = near.attachedDeposit() as bigint; 21 | 22 | let donatedSoFar = this.donations.get(donor, {defaultValue: BigInt(0)}) 23 | let toTransfer = donationAmount; 24 | 25 | // This is the user's first donation, lets register it, which increases storage 26 | if (donatedSoFar == BigInt(0)) { 27 | assert(donationAmount > STORAGE_COST, `Attach at least ${STORAGE_COST} yoctoNEAR`); 28 | 29 | // Subtract the storage cost to the amount to transfer 30 | toTransfer -= STORAGE_COST 31 | } 32 | 33 | // Persist in storage the amount donated so far 34 | donatedSoFar += donationAmount 35 | this.donations.set(donor, donatedSoFar) 36 | near.log(`Thank you ${donor} for donating ${donationAmount}! You donated a total of ${donatedSoFar}`); 37 | 38 | // Send the money to the beneficiary 39 | const promise = near.promiseBatchCreate(this.beneficiary) 40 | near.promiseBatchActionTransfer(promise, toTransfer) 41 | 42 | // Return the total amount donated so far 43 | return donatedSoFar.toString() 44 | } 45 | 46 | @call({ privateFunction: true }) 47 | change_beneficiary(beneficiary) { 48 | this.beneficiary = beneficiary; 49 | } 50 | 51 | @view({}) 52 | get_beneficiary(): string { return this.beneficiary } 53 | 54 | @view({}) 55 | number_of_donors(): number { return this.donations.length } 56 | 57 | @view({}) 58 | get_donations({ from_index = 0, limit = 50 }: { from_index: number, limit: number }): Donation[] { 59 | let ret: Donation[] = [] 60 | let end = Math.min(limit, this.donations.length) 61 | for (let i = from_index; i < end; i++) { 62 | const account_id: string = this.donations.keys.get(i) as string 63 | const donation: Donation = this.get_donation_for_account({ account_id }) 64 | ret.push(donation) 65 | } 66 | return ret 67 | } 68 | 69 | @view({}) 70 | get_donation_for_account({ account_id }: { account_id: string }): Donation { 71 | return { 72 | account_id, 73 | total_amount: this.donations.get(account_id).toString() 74 | } 75 | } 76 | } -------------------------------------------------------------------------------- /frontend/assets/global.css: -------------------------------------------------------------------------------- 1 | * { 2 | box-sizing: border-box; 3 | } 4 | 5 | html { 6 | --bg: #e7f3ff; 7 | --fg: #1e1e1e; 8 | --gray: #555; 9 | --light-gray: #ccc; 10 | --shadow: #e6e6e6; 11 | --success: rgb(90, 206, 132); 12 | --primary: #FF585D; 13 | --secondary: #0072CE; 14 | 15 | color: var(--fg); 16 | font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif; 17 | line-height: 1.3; 18 | } 19 | 20 | body { 21 | margin: 0; 22 | background-color: var(--bg); 23 | } 24 | 25 | .donation-box { 26 | max-width: 24em; 27 | box-shadow: #bac4cd 0px 0px 18px; 28 | border-radius: 8px; 29 | } 30 | 31 | .column{ 32 | width: 50%; 33 | float:left; 34 | } 35 | 36 | main { 37 | padding: 2em; 38 | text-align: justify; 39 | background-color: #f2f2f2; 40 | z-index: 1; 41 | border-radius: 8px; 42 | } 43 | 44 | .donation-box-head { 45 | text-align: center; 46 | background-color: #fff; 47 | margin: 0; 48 | border-radius: 8px 8px 0 0; 49 | padding: 1em 0em 2em 0em; 50 | } 51 | 52 | .logo { 53 | background-image: url(logo-black.svg); 54 | background-position: center 0em; 55 | background-repeat: no-repeat; 56 | position: relative; 57 | top: -2em; 58 | transform: translateX(-50%); 59 | background-color: #fff; 60 | padding: 15px 25px; 61 | height: 40px; 62 | border-radius: 50px; 63 | width: 50px; 64 | box-shadow: #bbb 0px 2px 5px; 65 | } 66 | 67 | a, 68 | .link { 69 | color: var(--primary); 70 | text-decoration: none; 71 | } 72 | a:hover, 73 | a:focus, 74 | .link:hover, 75 | .link:focus { 76 | text-decoration: underline; 77 | } 78 | a:active, 79 | .link:active { 80 | color: var(--secondary); 81 | } 82 | 83 | .btn-outline-primary{ 84 | width: 100%; 85 | } 86 | 87 | button, input { 88 | font: inherit; 89 | outline: none; 90 | } 91 | 92 | 93 | button.link { 94 | background: none; 95 | border: none; 96 | box-shadow: none; 97 | display: inline; 98 | } 99 | 100 | fieldset { 101 | border: none; 102 | padding: 2em 0; 103 | } 104 | 105 | form { 106 | margin: 0.2em -0.5em -1em -0.5em; 107 | } 108 | 109 | aside { 110 | animation: notify ease-in-out 10s; 111 | background-color: var(--shadow); 112 | border-radius: 5px; 113 | bottom: 0; 114 | font-size: 0.8em; 115 | margin: 1em; 116 | padding: 1em; 117 | position: fixed; 118 | transform: translateY(10em); 119 | right: 0; 120 | } 121 | aside footer { 122 | display: flex; 123 | font-size: 0.9em; 124 | justify-content: space-between; 125 | margin-top: 0.5em; 126 | } 127 | aside footer *:first-child { 128 | color: var(--success); 129 | } 130 | aside footer *:last-child { 131 | color: var(--gray); 132 | } 133 | @keyframes notify { 134 | 0% { transform: translateY(10em) } 135 | 5% { transform: translateY(0) } 136 | 95% { transform: translateY(0) } 137 | 100% { transform: translateY(10em) } 138 | } 139 | 140 | -------------------------------------------------------------------------------- /contract/README.md: -------------------------------------------------------------------------------- 1 | # Donation Contract 2 | 3 | The smart contract exposes methods to handle donating $NEAR to a `beneficiary`. 4 | 5 | ```ts 6 | @call 7 | donate() { 8 | // Get who is calling the method and how much $NEAR they attached 9 | let donor = near.predecessorAccountId(); 10 | let donationAmount: bigint = near.attachedDeposit() as bigint; 11 | 12 | let donatedSoFar = this.donations.get(donor) === null? BigInt(0) : BigInt(this.donations.get(donor) as string) 13 | let toTransfer = donationAmount; 14 | 15 | // This is the user's first donation, lets register it, which increases storage 16 | if(donatedSoFar == BigInt(0)) { 17 | assert(donationAmount > STORAGE_COST, `Attach at least ${STORAGE_COST} yoctoNEAR`); 18 | 19 | // Subtract the storage cost to the amount to transfer 20 | toTransfer -= STORAGE_COST 21 | } 22 | 23 | // Persist in storage the amount donated so far 24 | donatedSoFar += donationAmount 25 | this.donations.set(donor, donatedSoFar.toString()) 26 | 27 | // Send the money to the beneficiary 28 | const promise = near.promiseBatchCreate(this.beneficiary) 29 | near.promiseBatchActionTransfer(promise, toTransfer) 30 | 31 | // Return the total amount donated so far 32 | return donatedSoFar.toString() 33 | } 34 | ``` 35 | 36 | 37 | 38 | # Quickstart 39 | 40 | 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 41 | 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) 42 | 43 | 44 | 45 | ## 1. Build and Deploy the Contract 46 | You can automatically compile and deploy the contract in the NEAR testnet by running: 47 | 48 | ```bash 49 | npm run deploy 50 | ``` 51 | 52 | Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: 53 | 54 | ```bash 55 | cat ./neardev/dev-account 56 | # e.g. dev-1659899566943-21539992274727 57 | ``` 58 | 59 | The contract will be automatically initialized with a default `beneficiary`. 60 | 61 | To initialize the contract yourself do: 62 | 63 | ```bash 64 | # Use near-cli to initialize contract (optional) 65 | near call init '{"beneficiary":""}' --accountId 66 | ``` 67 | 68 | 69 | 70 | ## 2. Get Beneficiary 71 | `beneficiary` is a read-only method (`view` method) that returns the beneficiary of the donations. 72 | 73 | `View` methods can be called for **free** by anyone, even people **without a NEAR account**! 74 | 75 | ```bash 76 | near view beneficiary 77 | ``` 78 | 79 | 80 | 81 | ## 3. Get Number of Donations 82 | 83 | `donate` forwards any attached money to the `beneficiary` while keeping track of it. 84 | 85 | `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. 86 | 87 | ```bash 88 | # Use near-cli to donate 1 NEAR 89 | near call donate --amount 1 --accountId 90 | ``` 91 | 92 | **Tip:** If you would like to `donate` using your own account, first login into NEAR using: 93 | 94 | ```bash 95 | # Use near-cli to login your NEAR account 96 | near login 97 | ``` 98 | 99 | and then use the logged account to sign the transaction: `--accountId `. -------------------------------------------------------------------------------- /frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | Welcome to NEAR 13 | 14 | 15 | 16 | 17 | 18 | 19 | Latest Donations 20 | 21 | 22 | 23 | 24 | User 25 | Total Donated Ⓝ 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | Donate to 43 | 44 | 45 | 46 | 47 | 48 | Please sign in with your NEAR wallet to make a donation. 49 | 50 | 51 | Sign in 52 | 53 | 54 | 55 | 56 | 57 | $ 10 58 | $ 20 59 | $ 50 60 | $ 100 61 | 62 | 63 | 64 | 65 | 66 | Donation amount (in Ⓝ) 67 | 68 | 69 | 70 | Ⓝ 71 | Donate 72 | 73 | 74 | 75 | 76 | 77 | 78 | Sign out 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 93 | 94 | 95 | 96 | -------------------------------------------------------------------------------- /frontend/near-wallet.js: -------------------------------------------------------------------------------- 1 | /* A helper file that simplifies using the wallet selector */ 2 | 3 | // near api js 4 | import { providers } from 'near-api-js'; 5 | 6 | // wallet selector UI 7 | import '@near-wallet-selector/modal-ui/styles.css'; 8 | import { setupModal } from '@near-wallet-selector/modal-ui'; 9 | import LedgerIconUrl from '@near-wallet-selector/ledger/assets/ledger-icon.png'; 10 | import MyNearIconUrl from '@near-wallet-selector/my-near-wallet/assets/my-near-wallet-icon.png'; 11 | 12 | // wallet selector options 13 | import { setupWalletSelector } from '@near-wallet-selector/core'; 14 | import { setupLedger } from '@near-wallet-selector/ledger'; 15 | import { setupMyNearWallet } from '@near-wallet-selector/my-near-wallet'; 16 | 17 | const THIRTY_TGAS = '30000000000000'; 18 | const NO_DEPOSIT = '0'; 19 | 20 | // Wallet that simplifies using the wallet selector 21 | export class Wallet { 22 | walletSelector; 23 | wallet; 24 | network; 25 | createAccessKeyFor; 26 | 27 | constructor({ createAccessKeyFor = undefined, network = 'testnet' }) { 28 | // Login to a wallet passing a contractId will create a local 29 | // key, so the user skips signing non-payable transactions. 30 | // Omitting the accountId will result in the user being 31 | // asked to sign all transactions. 32 | this.createAccessKeyFor = createAccessKeyFor 33 | this.network = network 34 | } 35 | 36 | // To be called when the website loads 37 | async startUp() { 38 | this.walletSelector = await setupWalletSelector({ 39 | network: this.network, 40 | modules: [setupMyNearWallet({ iconUrl: MyNearIconUrl }), 41 | setupLedger({ iconUrl: LedgerIconUrl })], 42 | }); 43 | 44 | const isSignedIn = this.walletSelector.isSignedIn(); 45 | 46 | if (isSignedIn) { 47 | this.wallet = await this.walletSelector.wallet(); 48 | this.accountId = this.walletSelector.store.getState().accounts[0].accountId; 49 | } 50 | 51 | return isSignedIn; 52 | } 53 | 54 | // Sign-in method 55 | signIn() { 56 | const description = 'Please select a wallet to sign in.'; 57 | const modal = setupModal(this.walletSelector, { contractId: this.createAccessKeyFor, description }); 58 | modal.show(); 59 | } 60 | 61 | // Sign-out method 62 | signOut() { 63 | this.wallet.signOut(); 64 | this.wallet = this.accountId = this.createAccessKeyFor = null; 65 | window.location.replace(window.location.origin + window.location.pathname); 66 | } 67 | 68 | // Make a read-only call to retrieve information from the network 69 | async viewMethod({ contractId, method, args = {} }) { 70 | const { network } = this.walletSelector.options; 71 | const provider = new providers.JsonRpcProvider({ url: network.nodeUrl }); 72 | 73 | let res = await provider.query({ 74 | request_type: 'call_function', 75 | account_id: contractId, 76 | method_name: method, 77 | args_base64: Buffer.from(JSON.stringify(args)).toString('base64'), 78 | finality: 'optimistic', 79 | }); 80 | return JSON.parse(Buffer.from(res.result).toString()); 81 | } 82 | 83 | // Call a method that changes the contract's state 84 | async callMethod({ contractId, method, args = {}, gas = THIRTY_TGAS, deposit = NO_DEPOSIT }) { 85 | // Sign a transaction with the "FunctionCall" action 86 | const outcome = await this.wallet.signAndSendTransaction({ 87 | signerId: this.accountId, 88 | receiverId: contractId, 89 | actions: [ 90 | { 91 | type: 'FunctionCall', 92 | params: { 93 | methodName: method, 94 | args, 95 | gas, 96 | deposit, 97 | }, 98 | }, 99 | ], 100 | }); 101 | 102 | return providers.getTransactionLastResult(outcome) 103 | } 104 | 105 | // Get transaction result from the network 106 | async getTransactionResult(txhash) { 107 | const { network } = this.walletSelector.options; 108 | const provider = new providers.JsonRpcProvider({ url: network.nodeUrl }); 109 | 110 | // Retrieve transaction result from the network 111 | const transaction = await provider.txStatus(txhash, 'unnused'); 112 | return providers.getTransactionLastResult(transaction); 113 | } 114 | } -------------------------------------------------------------------------------- /frontend/index.js: -------------------------------------------------------------------------------- 1 | import 'regenerator-runtime/runtime' 2 | import { Contract } from './near-interface'; 3 | import { Wallet } from './near-wallet' 4 | 5 | // When creating the wallet you can choose to create an access key, so the user 6 | // can skip signing non-payable methods when interacting with the contract 7 | const wallet = new Wallet({ createAccessKeyFor: process.env.CONTRACT_NAME }) 8 | 9 | // Abstract the logic of interacting with the contract to simplify your project 10 | const contract = new Contract({ contractId: process.env.CONTRACT_NAME, walletToUse: wallet }); 11 | 12 | // Setup on page load 13 | window.onload = async () => { 14 | const isSignedIn = await wallet.startUp(); 15 | 16 | if (isSignedIn){ 17 | signedInFlow() 18 | }else{ 19 | signedOutFlow() 20 | } 21 | 22 | fetchBeneficiary() 23 | getAndShowDonations() 24 | } 25 | 26 | // On submit, get the greeting and send it to the contract 27 | document.querySelector('form').onsubmit = async (event) => { 28 | event.preventDefault() 29 | 30 | // get elements from the form using their id attribute 31 | const { fieldset, donation } = event.target.elements 32 | 33 | // disable the form while the value gets updated on-chain 34 | fieldset.disabled = true 35 | 36 | try { 37 | await contract.donate(donation.value) 38 | } catch (e) { 39 | alert( 40 | 'Something went wrong! ' + 41 | 'Maybe you need to sign out and back in? ' + 42 | 'Check your browser console for more info.' 43 | ) 44 | throw e 45 | } 46 | 47 | // re-enable the form, whether the call succeeded or failed 48 | fieldset.disabled = false 49 | } 50 | 51 | document.querySelector('#sign-in-button').onclick = () => { wallet.signIn() } 52 | document.querySelector('#sign-out-button').onclick = () => { wallet.signOut() } 53 | 54 | async function fetchBeneficiary() { 55 | // Get greeting from the contract 56 | const currentGreeting = await contract.getBeneficiary() 57 | 58 | // Set all elements marked as greeting with the current greeting 59 | document.querySelectorAll('[data-behavior=beneficiary]').forEach(el => { 60 | el.innerText = currentGreeting 61 | el.value = currentGreeting 62 | }) 63 | } 64 | 65 | // Display the signed-out-flow container 66 | function signedOutFlow() { 67 | document.querySelector('.signed-out-flow').style.display = 'block' 68 | } 69 | 70 | async function signedInFlow() { 71 | // Displaying the signed in flow container 72 | document.querySelectorAll('.signed-in-flow').forEach(elem => elem.style.display = 'block') 73 | 74 | // Check if there is a transaction hash in the URL 75 | const urlParams = new URLSearchParams(window.location.search); 76 | const txhash = urlParams.get("transactionHashes") 77 | 78 | if(txhash !== null){ 79 | // Get result from the transaction 80 | let result = await contract.getDonationFromTransaction(txhash) 81 | document.querySelector('[data-behavior=donation-so-far]').innerText = result 82 | 83 | // show notification 84 | document.querySelector('[data-behavior=notification]').style.display = 'block' 85 | 86 | // remove notification again after css animation completes 87 | setTimeout(() => { 88 | document.querySelector('[data-behavior=notification]').style.display = 'none' 89 | }, 11000) 90 | } 91 | 92 | } 93 | 94 | async function getAndShowDonations(){ 95 | document.getElementById('donations-table').innerHTML = 'Loading ...' 96 | 97 | // Load last 10 donations 98 | let donations = await contract.latestDonations() 99 | 100 | document.getElementById('donations-table').innerHTML = '' 101 | 102 | donations.forEach(elem => { 103 | let tr = document.createElement('tr') 104 | tr.innerHTML = ` 105 | 106 | ${elem.account_id} 107 | ${elem.total_amount} 108 | 109 | ` 110 | document.getElementById('donations-table').appendChild(tr) 111 | }) 112 | } 113 | 114 | window.set_donation = async function(amount){ 115 | let data = await fetch("https://api.coingecko.com/api/v3/simple/price?ids=near&vs_currencies=usd").then(response => response.json()) 116 | const near2usd = data['near']['usd'] 117 | const amount_in_near = amount / near2usd 118 | const rounded_two_decimals = Math.round(amount_in_near * 100) / 100 119 | document.querySelector('#donation').value = rounded_two_decimals 120 | } --------------------------------------------------------------------------------
48 | Please sign in with your NEAR wallet to make a donation. 49 |
51 | Sign in 52 |