Skip to content

Commit

Permalink
feat: heplers
Browse files Browse the repository at this point in the history
  • Loading branch information
neptune0xf committed Jun 26, 2022
1 parent 7b6482b commit 03524bb
Show file tree
Hide file tree
Showing 8 changed files with 127 additions and 11 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ verifyConnection();
</details>


### Actor
### Import Actor,Actor Instance Type
```js
import { idlFactory as xxx } from '@nnsdao/nnsdao-kit/market/index';
import type { _SERVICE as xxx } from '@nnsdao/nnsdao-kit/market/market.did';
import { idlFactory } from '@nnsdao/nnsdao-kit/market/index';
import type { _SERVICE } from '@nnsdao/nnsdao-kit/market/market.did';
````
## Config Typescript Path Alias
Expand Down
4 changes: 2 additions & 2 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export { plugLogin, plugLogout } from './src/login/plug';
export { stoicLogin, stoicLogout } from './src/login/stoic';
export { plugLogin, plugLogout } from './src/helper/plug';
export { stoicLogin, stoicLogout } from './src/helper/stoic';
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"main": "./index.ts",
"exports": {
".": "./index.ts",
"./helper/*": "./src/helper/*",
"./*": "./src/*"
},
"scripts": {
Expand Down
29 changes: 29 additions & 0 deletions src/helper/agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Actor, HttpAgent } from '@dfinity/agent';
import storage from './storage';

export const agent = new HttpAgent();
// anonymous agent can more efficient then auth agent;
export const anonymousAgent: HttpAgent = new HttpAgent();

export async function getActor(props: getActorProps): Promise<typeof Actor> {
let { cid, idl, needAuth = true } = props;
const loginType = storage.get('loginType');
const actor =
loginType === 'plug'
? await window.ic.plug.createActor({ canisterId: cid, interfaceFactory: idl })
: Promise.resolve(Actor.createActor(idl, { agent: needAuth ? agent : anonymousAgent, canisterId: cid }));
return actor;
}

export const toHexString = (byteArray: any) => {
return Array.from(byteArray, function (byte: any) {
return ('0' + (byte & 0xff).toString(16)).slice(-2);
}).join('');
};

// Type
interface getActorProps {
needAuth?: boolean;
idl?: any;
cid: string;
}
10 changes: 4 additions & 6 deletions src/login/plug.ts → src/helper/plug.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { HttpAgent } from '@dfinity/agent';
import type { HttpAgent } from '@dfinity/agent';

interface PlugLoginRes {
agent: Omit<HttpAgent, 'invalidateIdentity' | 'replaceIdentity'>;
principalId: string;
accountId: string;
createActor: (params: PlugCreateActorParams) => any;
}
let persistTimer: any = null;

export async function plugLogin(whitelist: string[]): Promise<PlugLoginRes | null> {
if (!globalThis?.ic?.plug) {
console.error('Please make sure the Plug extension is installed!');
Expand Down Expand Up @@ -47,12 +47,10 @@ export async function plugLogin(whitelist: string[]): Promise<PlugLoginRes | nul
persistConnect();
}, 3e3);
};
persistConnect();
console.log('Plug login', globalThis.ic.plug.sessionManager);

return {
...globalThis.ic.plug.sessionManager.sessionData,
createActor: globalThis.ic.plug.createActor,
};
return globalThis.ic.plug.sessionManager.sessionData;
}

export async function plugLogout(): Promise<void> {
Expand Down
File renamed without changes.
35 changes: 35 additions & 0 deletions src/helper/storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Storage {
store: Store;
private _key: string;
constructor() {
this._key = 'cache-store';
// @ts-ignore
this.store = JSON.parse(globalThis.localStorage.getItem(this._key) || null) || Object.create(null);
}
set(key: keyof Store, value: any): void {
Reflect.set(this.store, key, value);
this.cacheStore();
}
get(key: keyof Store) {
return Reflect.get(this.store, key);
}
remove(key: keyof Store): void {
Reflect.deleteProperty(this.store, key);
this.cacheStore();
}
cacheStore() {
requestIdleCallback(
() => {
globalThis.localStorage.setItem(this._key, JSON.stringify(this.store));
},
{ timeout: 1e3 }
);
}
}

export default new Storage();

// Type
type Store = {
loginType: undefined | 'stoic' | 'plug';
};
53 changes: 53 additions & 0 deletions src/helper/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Principal } from '@dfinity/principal';
import { toHexString } from './agent';

export function validPrincipalId(principalId: string) {
try {
principalId === Principal.fromText(principalId).toString();
return true;
} catch (e) {
return false;
}
}

export function validAccountId(accountId: string) {
return accountId.length === 64 && /^[a-zA-Z0-9]+$/.test(accountId);
}

function to32bits(num: number) {
let b = new ArrayBuffer(4);
new DataView(b).setUint32(0, num);
return Array.from(new Uint8Array(b));
}

function from32bits(arr: number[]) {
let value = 0;
for (let i = 0; i < 4; i++) {
value = (value << 8) | arr[i];
}
return value;
}

function canisterIdToTokenId(principal: string, index: number) {
const padding = Buffer.from('\x0Atid');
const array = new Uint8Array([...padding, ...Principal.fromText(principal).toUint8Array(), ...to32bits(index)]);
return Principal.fromUint8Array(array).toText();
}
export function tokenIdToCanisterId(tokenId: string) {
let p = [...Principal.fromText(tokenId).toUint8Array()];
let padding = p.splice(0, 4);

if (toHexString(padding) !== toHexString(Buffer.from('\x0Atid'))) {
return {
index: 0,
canister: tokenId,
token: canisterIdToTokenId(tokenId, 0),
};
} else {
return {
index: from32bits(p.splice(-4)),
canister: Principal.fromUint8Array(p as unknown as Uint8Array).toText(),
token: tokenId,
};
}
}

0 comments on commit 03524bb

Please sign in to comment.