Skip to content

Commit

Permalink
Merge pull request #614 from kristoferlund/add/ic-pos-example
Browse files Browse the repository at this point in the history
Add ic-pos to motoko examples
  • Loading branch information
letmejustputthishere authored Oct 2, 2023
2 parents 89f44ad + afa3ca6 commit baa6111
Show file tree
Hide file tree
Showing 103 changed files with 12,455 additions and 0 deletions.
17 changes: 17 additions & 0 deletions motoko/ic-pos/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module.exports = {
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': 'warn',
},
globals: {
process: "readonly"
},
}
34 changes: 34 additions & 0 deletions motoko/ic-pos/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Various IDEs and Editors
.vscode/
.idea/
**/*~

# Mac OSX temporary files
.DS_Store
**/.DS_Store

# dfx temporary files
.dfx/

# rust
target/

# frontend code
node_modules/
dist/

# environment variables
.env

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# yarn cache
.yarn/cache

# misc
scratch/
29 changes: 29 additions & 0 deletions motoko/ic-pos/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Changelog

## [0.3.0] - 2022-09-10

### Added

- Now you can charge a set amount, similar to Sumup and the likes. Enter the amount to charge and click the "Charge" button. The generated QR code will contain information about the token and amount to charge. The customer can then scan and pay with any wallet that supports the QR format, NNS for instance. Raad more about ICRC-22 payment requests: https://github.com/dfinity/ICRC/issues/22

### Fixed

- Improved printing styles, QR code now fills more of the page.

## [0.2.0] - 2022-09-06

### Added

- Principal pills are now clickable. Click to copy the principal id to the clipboard.

### Changed

- The `icpos` canister continuoulsy monitors the ckBTC ledger and sends notifications to merchants that choosen to receive email or sms. The ledger id used to be hardcode, now there is a function `setLedgerId` that can be called at runtime.
- `dfx.json`: settings now included to run an ICRC-1 ledger and index locally.
- Upgraded to latest versions of `@dfinity/xxx` packages.
- Removed reliance on the HTTP ckBTC transaction API. Instead, IC-POS now uses the ledger canister directly to monitor transactions.
- ckBTC balances are now updated in the UI after received transfers.

## [0.1.0]

Initial release.
7 changes: 7 additions & 0 deletions motoko/ic-pos/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2023 Kristofer Lund <[email protected]>

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.
220 changes: 220 additions & 0 deletions motoko/ic-pos/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
![](./media/header.png)

# IC-POS

IC-POS is an experimental app to demonstrate a real world use case for [ckBTC](https://internetcomputer.org/ckbtc/) on the Internet Computer. It is a simple Point of Sale app that allows users to accept ckBTC payments.

The Internet Computer [integrates directly with the Bitcoin network](https://internetcomputer.org/docs/current/developer-docs/integrations/bitcoin/). This allows canisters on the Internet Computer to receive, hold, and send Bitcoin, all directly with transactions on the Bitcoin network. Chain-key Bitcoin (ckBTC) is an ICRC-1-compliant token that is backed 1:1 by Bitcoin held 100% on the IC mainnet.

For deeper understanding of the ICP < > BTC integration, see the IC wiki article on [Bitcoin integration](https://wiki.internetcomputer.org/wiki/Bitcoin_Integration).

## Features

- **Create store**: Users logs in with their Internet Identity and configure the store with a name and other settings.
- **Charge customer**: Users can charge a customer by entering an amount. This will generate and display a QR code for the customer to scan and pay. QR code follows the [ICRC-22](https://github.com/dfinity/ICRC/issues/22) standard.
- **Send tokens**: Users can send ckBTC tokens to other users.
- **Receive notifications**: Users can choose to receive notifications by email or SMS when a payment is received. This uses the [HTTP Outcall](https://internetcomputer.org/docs/current/developer-docs/integrations/https-outcalls/) feature of the Internet Computer.
- **Transaction history**: Users can view a list of transactions made to the store.

## Try it!

IC-POS is deployed on the Internet Computer. You can try it out here:

https://hngac-6aaaa-aaaal-qb6tq-cai.icp0.io/

https://github.com/kristoferlund/ic-pos/assets/9698363/f67d9952-3ee1-4876-a5e5-6ed0e29bae9d

## Architecture

### Backend

The backend is written in Motoko and consist of one canister, `icpos`. It exposes four public methods:

- `getMerchant` - returns the store configuration for a given principal.
- `updateMerchant` - updates the store configuration for a given principal.
- `setCourierApiKey` - sets the Courier API key used to send email and SMS notifications. Only the canister controller can call this method.
- `setLedgerId` - sets the ledger id to monitor for transactions. Only the canister controller can call this method.
- `getLogs` - The canister maintains a debug log that can be fetched using this method.

In addition to the public methods, the canister uses a [timer](https://internetcomputer.org/docs/current/motoko/main/timers/) to monitor ledger transactions. When a new transaction is found that matches a configured store – depending on the store settings – the canister will send a notification either by email or SMS.

### Frontend

The frontend is written in Typescript/Vite/React/TailwindCSS. Users authenticate using the Internet Identity to access their store. The first time a user logs in, a store is created for them.

The frontend interacts with the following IC canisters:

- `icpos` - to fetch and update store configuration.
- `ckbtc ledger` - to send ckBTC to other users.
- `ckbtc index` - to fetch transaction history.
- `internet identity` - to authenticate users.

# Local deployment

## Prerequisites

- [x] Install the [IC SDK](https://internetcomputer.org/docs/current/developer-docs/setup/install/index.mdx).
- [x] Install [Node.js](https://nodejs.org/en/).

### Step 1: Start a local instance of the Internet Computer

```bash
dfx start --clean --background
```

### Step 2: Deploy the Internet Identity canister

Integration with the [Internet Identity](https://internetcomputer.org/internet-identity/) allows store owners to securely setup and manage their store. The Internet Identity canister is already deployed on the IC mainnet. For local development, you need to deploy it to your local instance of the IC.

```bash
dfx deploy --network local internet_identity
```

### Step 3: Save current principal as a variable

The principal will be used when deploying the ledger canister.

```bash
export OWNER=$(dfx identity get-principal)
```

### Step 3: Deploy the ckBTC ledger canister

The responsibilities of the ledger canister is to keep track of token balances and handle token transfers.

The ckBTC ledger canister is already deployed on the IC mainnet. ckBTC implements the [ICRC-1](https://internetcomputer.org/docs/current/developer-docs/integrations/icrc-1/) token standard. For local development, we deploy the ledger for an ICRC-1 token mimicking the mainnet setup.

Take a moment to read the details of the call we are making below. Not only are we deploying the ledger canister, we are also:

- Deploying the canister to the same canister ID as the mainnet ledger canister. This is to make it easier to switch between local and mainnet deployments.
- Naming the token `Local ckBTC / LCKBTC`
- Setting the owner principal to the principal we saved in the previous step.
- Minting 100_000_000_000 tokens to the owner principal.
- Setting the transfer fee to 10 LCKBTC.

```bash
dfx deploy --network local --specified-id mxzaz-hqaaa-aaaar-qaada-cai icrc1_ledger --argument '
(variant {
Init = record {
token_name = "Local ckBTC";
token_symbol = "LCKBTC";
minting_account = record {
owner = principal "'${OWNER}'";
};
initial_balances = vec {
record {
record {
owner = principal "'${OWNER}'";
};
100_000_000_000;
};
};
metadata = vec {};
transfer_fee = 10;
archive_options = record {
trigger_threshold = 2000;
num_blocks_to_archive = 1000;
controller_id = principal "'${OWNER}'";
}
}
})
'
```

### Step 4: Deploy the index canister

The index canister syncs the ledger transactions and indexes them by account.

```bash
dfx deploy --network local icrc1_index --argument '
record {
ledger_id = (principal "mxzaz-hqaaa-aaaar-qaada-cai");
}
'
```

### Step 5: Deploy the icpos canister

The icpos canister manages the store configuration and sends notifications when a payment is received.

The `--argument '(0)'` argument is used to initialize the canister with `startBlock` set to 0. This is used to tell the canister to start monitoring the ledger from block 0. When deploying to the IC mainnet, this should be set to the current block height to prevent the canister from processing old transactions.

```bash
dfx deploy --network local icpos --argument '(0)'
```

### Step 6: Configure the icpos canister

ic-pos uses [Courier](https://courier.com/) to send email and SMS notifications. If you want to enable notifications, you need to sign up for a Courier account and and create and API key. Then issue the following command:

```bash
dfx canister --network local call icpos setCourierApiKey "pk_prod_..."
```

### Step 7: Build and run the frontend

Run npm to install dependencies and start the frontend. The frontend will be available at http://localhost:5173.

```bash
npm install
npm run dev
```

Why don't we deploy the frontend as a local canister? Vite uses lazy loading of modules. This does not work when deploying to a local canister. When deploying to the IC mainnet, this is not an issue. Also, running using `npm run dev` allows for hot reloading of the frontend code when making changes.

### Step 8: Make a transfer!

Now that everything is up and running, you can make a transfer to your newly created store.

Transfers made from the owner principal will not trigger notifications in the UI since they are regarded as `mint` transactions. To test notifications, you need to make a transfer from another principal.

The easiest way to do this is to create two stores using two different Internet Identity accounts, using two different web browsers. Then, transfer some tokens from one store to the other.

#### 8.1: Create the first store and supply it with some tokens

Log in to the frontend using the Internet Identity. Configure the store and navigate to the `Receive` page. Click on the principal pill to copy the address to your clipboard. Then, using the `dfx` command, mint some tokens from your owner principal to the store principal.

```bash
dfx canister --network local call icrc1_ledger icrc1_transfer '
(record {
to=(record {
owner=(principal "[STORE PRINCIPAL 1 HERE]")
});
amount=100_000
})
'
```

#### 8.2: Create the second store

Log in to the frontend using **a new Internet Identity on another web browser**. Configure the store and navigate to the `Receive` page. Click on the principal pill to copy the address to your clipboard.

Now, go back to the first browser/store, navigate to the `Send` page and transfer some tokens to the second store.

If everything is working, you should see a notification in the second store.

🎉

## Possible Improvements

- Login state is not persisted. Reloading the app will log the user out. This should be done using `localStorage` or `sessionStorage`.
- Show more information about transactions. A transaction detail page.
- Show a confirmation dialog after user clicks on `Send` button.

## Known issues

-

## Contributing

Contributions are welcome! Please open an issue or submit a pull request.

## Author

- [[email protected]](mailto:[email protected])
- Twitter: [@kristoferlund](https://twitter.com/kristoferlund)
- Discord: kristoferkristofer

## License

[MIT](LICENSE)
8 changes: 8 additions & 0 deletions motoko/ic-pos/canister_ids.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"icpos": {
"ic": "imhb7-2yaaa-aaaal-qb7va-cai"
},
"icpos_frontend": {
"ic": "hngac-6aaaa-aaaal-qb6tq-cai"
}
}
15 changes: 15 additions & 0 deletions motoko/ic-pos/components.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/icpos_frontend/index.css",
"baseColor": "zinc",
"cssVariables": true
},
"aliases": {
"components": "src/icpos_frontend/components",
"utils": "src/icpos_frontend/utils/shadcn"
}
}
56 changes: 56 additions & 0 deletions motoko/ic-pos/dfx.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"canisters": {
"icpos": {
"main": "src/icpos/main.mo",
"type": "motoko",
"dependencies": ["icrc1_ledger"]
},
"icpos_frontend": {
"dependencies": ["icpos"],
"frontend": {
"entrypoint": "dist/index.html"
},
"source": ["dist"],
"type": "assets",
"build": ["npm run build"]
},
"internet_identity": {
"type": "custom",
"candid": "https://github.com/dfinity/internet-identity/releases/latest/download/internet_identity.did",
"wasm": "https://github.com/dfinity/internet-identity/releases/latest/download/internet_identity_dev.wasm.gz",
"remote": {
"id": {
"ic": "rdmx6-jaaaa-aaaaa-aaadq-cai"
}
}
},
"icrc1_ledger": {
"type": "custom",
"candid": "https://raw.githubusercontent.com/dfinity/ic/95787355499f3be929f2ab302ed44cdad7c64061/rs/rosetta-api/icrc1/ledger/ledger.did",
"wasm": "https://download.dfinity.systems/ic/95787355499f3be929f2ab302ed44cdad7c64061/canisters/ic-icrc1-ledger.wasm.gz",
"remote": {
"id": {
"ic": "mxzaz-hqaaa-aaaar-qaada-cai"
}
}
},
"icrc1_index": {
"type": "custom",
"candid": "https://raw.githubusercontent.com/dfinity/ic/95787355499f3be929f2ab302ed44cdad7c64061/rs/rosetta-api/icrc1/index/index.did",
"wasm": "https://download.dfinity.systems/ic/95787355499f3be929f2ab302ed44cdad7c64061/canisters/ic-icrc1-index.wasm.gz",
"remote": {
"id": {
"ic": "n5wcd-faaaa-aaaar-qaaea-cai"
}
}
}
},
"defaults": {
"build": {
"args": "",
"packtool": ""
}
},
"output_env_file": ".env",
"version": 1
}
Binary file added motoko/ic-pos/media/header.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit baa6111

Please sign in to comment.