Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ON-HOLD] feat: initial commit for kadena ledger lib #2458

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions packages/libs/ledger/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
BSD 3-Clause License

Copyright (c) 2018 - 2024 Kadena LLC
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
18 changes: 18 additions & 0 deletions packages/libs/ledger/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!-- genericHeader start -->

# @kadena/ledger

Helper methods to interact with the Kadena Ledger app

<picture>
<source srcset="https://raw.githubusercontent.com/kadena-community/kadena.js/main/common/images/Kadena.JS_logo-white.png" media="(prefers-color-scheme: dark)"/>
<img src="https://raw.githubusercontent.com/kadena-community/kadena.js/main/common/images/Kadena.JS_logo-black.png" width="200" alt="kadena.js logo" />
</picture>

<!-- genericHeader end -->

## Kadena ledger

> Helper methods to interact with the Kadena Ledger app

Build with minimal dependencies for a small bundle size.
10 changes: 10 additions & 0 deletions packages/libs/ledger/build.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defineBuildConfig } from "unbuild";

export default defineBuildConfig({
rollup: {
esbuild: {
minify: true,
},
},
declaration: true,
});
24 changes: 24 additions & 0 deletions packages/libs/ledger/example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
14 changes: 14 additions & 0 deletions packages/libs/ledger/example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Kadena Ledger Example</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
24 changes: 24 additions & 0 deletions packages/libs/ledger/example/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "example",
"version": "1.0.0",
"description": "",
"keywords": [],
"license": "ISC",
"author": "",
"main": "index.js",
"scripts": {
"dev": "vite dev"
},
"devDependencies": {
"@types/react": "^18.2.79",
"@types/react-dom": "^18.2.25",
"@vitejs/plugin-react": "^4.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"vite": "^5.3.3"
},
"dependencies": {
"@ledgerhq/hw-transport-webhid": "^6.28.3",
"buffer": "^6.0.3"
}
}
88 changes: 88 additions & 0 deletions packages/libs/ledger/example/src/app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { useState } from 'react';
import {
getPublicKey,
getVersion,
openApp,
signTransaction,
} from '../../src/index';

function App() {
const [openAppResult, setOpenAppResult] = useState('');
const [getPublicKeyResult, setGetPublicKeyResult] = useState('');
const [getVersionResult, setGetVersionResult] = useState<any>('');
const [signTransactionResult, setSignTransactionResult] = useState<any>('');

return (
<div className="flex flex-col items-center justify-center pt-8">
<h1 className="text-3xl font-bold">Kadena ledger example</h1>
<div className="flex flex-col gap-4 p-8 justify-between">
<div>
<button
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
onClick={() => openApp().then(() => setOpenAppResult('success'))}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

      onClick={async () => {
            await openApp();
            setOpenAppResult('success');
          }}

>
Open App
</button>
<div className="break-all min-h-8">{openAppResult}</div>
</div>

<div>
<button
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
onClick={() =>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

onClick={async () => {
  const result = await getPublicKey(0);
  setGetPublicKeyResult(result);
}}

getPublicKey(0).then((x) => setGetPublicKeyResult(x))
}
>
Get public key
</button>
<div className="break-all min-h-8">
{JSON.stringify(getPublicKeyResult)}
</div>
</div>

<div>
<button
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
onClick={() => getVersion().then((x) => setGetVersionResult(x))}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

onClick={async () => {
  const result = await getVersion();
  setGetVersionResult(result);
}}

>
Get version
</button>
<div className="break-all min-h-8">
{JSON.stringify(getVersionResult)}
</div>
</div>

<div>
<button
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
onClick={() =>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

onClick={async () => {
  const result = await signTransaction(0, 'transfer', {
    recipient: '2017fee3fb15cfe840e5ed34bf101cc7d5579ffdd20dea09e32fd77c1757f946',
    recipientChainId: '0',
    networkId: 'testnet04',
    amount: 0.1,
    namespace_: '',
    module_: '',
    gasPrice: '1.0e-6',
    gasLimit: '2300',
    creationTime: '1723017869',
    chainId: '0',
    nonce: '',
    ttl: '600',
    type: 'transfer',
  });
  setSignTransactionResult(result);
}}

signTransaction(0, 'transfer', {
recipient:
'2017fee3fb15cfe840e5ed34bf101cc7d5579ffdd20dea09e32fd77c1757f946',
recipientChainId: '0',
networkId: 'testnet04',
amount: 0.1,
namespace_: '',
module_: '',
gasPrice: '1.0e-6',
gasLimit: '2300',
creationTime: '1723017869',
chainId: '0',
nonce: '',
ttl: '600',
type: 'transfer',
}).then((x) => setSignTransactionResult(x))
}
>
Sign transaction
</button>
<div className="break-all min-h-8">
{JSON.stringify(signTransactionResult)}
</div>
</div>
</div>
</div>
);
}

export default App;
57 changes: 57 additions & 0 deletions packages/libs/ledger/example/src/legacy-transport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Buffer } from 'buffer';
globalThis.Buffer = Buffer;

import type TransportWebHID from '@ledgerhq/hw-transport-webhid';

const LEDGER_VENDOR_ID = 0x2c97;
const KADENA_PATH = "m/44'/626'/{index}'/0/0";

const connect = async () => {
let devices = await navigator.hid.getDevices();
let ledger = devices.find((d) => d.vendorId === LEDGER_VENDOR_ID);

if (!ledger) {
await navigator.hid.requestDevice({
filters: [{ vendorId: LEDGER_VENDOR_ID }],
});

devices = await navigator.hid.getDevices();
ledger = devices.find((d) => d.vendorId === LEDGER_VENDOR_ID);
}

if (ledger) {
const { default: TransportWebHID } = await import(
'@ledgerhq/hw-transport-webhid'
);
const transport = await TransportWebHID.open(ledger);
return transport;
}

throw new Error('No transport');
};

export const openApp = async () => {
let transport: TransportWebHID | null = null;

try {
transport = await connect();

await transport.send(
0xe0,
0xd8,
0x00,
0x00,
Buffer.from('Kadena', 'ascii'),
);
await new Promise((resolve) => setTimeout(resolve, 1000));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still don't know why this is here and it probably should not bere here, since is does not make sense.

} catch (error) {
// When the app is already open, the device returns 0x6e01
if (!error.toString().includes('0x6e01')) {
console.error(error);
}
} finally {
if (transport) {
transport.close();
}
}
};
9 changes: 9 additions & 0 deletions packages/libs/ledger/example/src/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { StrictMode } from 'react';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './app.tsx';

const root = createRoot(document.getElementById('root')!);

root.render(
  <StrictMode>
    <App />
  </StrictMode>,
);

import { createRoot } from 'react-dom/client';
import App from './app.tsx';

createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
);
1 change: 1 addition & 0 deletions packages/libs/ledger/example/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
25 changes: 25 additions & 0 deletions packages/libs/ledger/example/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"jsx": "react-jsx",

/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
7 changes: 7 additions & 0 deletions packages/libs/ledger/example/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
});
35 changes: 35 additions & 0 deletions packages/libs/ledger/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "@kadena/ledger",
"version": "0.0.1",
"private": true,
"description": "",
"keywords": [],
"license": "BSD-3-Clause",
"author": "",
"type": "module",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"main": "./dist/index.cjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "unbuild",
"example": "cd example && pnpm dev"
},
"dependencies": {
"blake2b": "^2.1.4",
"ledger-transport-hid": "^0.1.0"
},
"devDependencies": {
"@kadena-dev/shared-config": "workspace:*",
"@types/blake2b": "^2.1.3",
"@types/w3c-web-hid": "^1.0.6",
"unbuild": "^2.0.0"
}
}
2 changes: 2 additions & 0 deletions packages/libs/ledger/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const LEDGER_VENDOR_ID = 0x2c97;
export const KADENA_PATH = "m/44'/626'/{index}'/0/0";
33 changes: 33 additions & 0 deletions packages/libs/ledger/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { KadenaLedger } from './ledger';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add return types:

import { KadenaLedger } from './ledger';
import { TransactionParams } from './transaction';

let ledger: KadenaLedger | null = null;

async function getLedger(): Promise<KadenaLedger> {
  if (!ledger) ledger = await KadenaLedger.findDevice();
  return ledger;
}

export async function openApp(): Promise<void> {
  const ledger = await getLedger();
  return await ledger.openApp();
}

export async function getPublicKey(index: number): Promise<string> {
  const ledger = await getLedger();
  return await ledger.getPublicKey(index);
}

export async function signTransaction(
  index: number,
  type: 'transfer' | 'cross-chain-transfer',
  params: TransactionParams,
): Promise<string> {
  const ledger = await getLedger();
  return await ledger.signTransaction(index, type, params);
}

export async function getVersion(): Promise<string> {
  const ledger = await getLedger();
  return await ledger.getVersion();
}

import { TransactionParams } from './transaction';

let ledger: KadenaLedger | null = null;

async function getLedger(): Promise<KadenaLedger> {
if (!ledger) ledger = await KadenaLedger.findDevice();
return ledger;
}

export async function openApp() {
const ledger = await getLedger();
return await ledger.openApp();
}

export async function getPublicKey(index: number) {
const ledger = await getLedger();
return await ledger.getPublicKey(index);
}

export async function signTransaction(
index: number,
type: 'transfer' | 'cross-chain-transfer',
params: TransactionParams,
) {
const ledger = await getLedger();
return await ledger.signTransaction(index, type, params);
}

export async function getVersion() {
const ledger = await getLedger();
return await ledger.getVersion();
}
Loading
Loading