make lib pre-built

This commit is contained in:
jejolare 2025-01-08 23:38:56 +07:00
parent ab7192ea5b
commit f6ab5b53f9
32 changed files with 780 additions and 4 deletions

1
.gitignore vendored
View file

@ -1,2 +1 @@
node_modules
dist

View file

@ -7,8 +7,7 @@
"build:web": "tsc --project tsconfig.web.json",
"build:server": "tsc --project tsconfig.server.json",
"build:shared": "tsc --project tsconfig.shared.json",
"build": "npm run build:web && npm run build:server && npm run build:shared",
"postinstall": "npm run build"
"build": "npm run build:web && npm run build:server && npm run build:shared"
},
"repository": {
"type": "git",

2
server/dist/index.d.ts vendored Normal file
View file

@ -0,0 +1,2 @@
import ServerWallet from "./server";
export { ServerWallet };

3
server/dist/index.js vendored Normal file
View file

@ -0,0 +1,3 @@
import ServerWallet from "./server";
export { ServerWallet };
//# sourceMappingURL=index.js.map

1
server/dist/index.js.map vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,MAAM,UAAU,CAAC;AACpC,OAAO,EAAC,YAAY,EAAC,CAAC"}

38
server/dist/server.d.ts vendored Normal file
View file

@ -0,0 +1,38 @@
import { AuthData, BalanceInfo, TxInfo, AliasDetails } from "./types";
import { APIAsset } from "./types";
interface ConstructorParams {
walletUrl: string;
daemonUrl: string;
walletAuthToken?: string;
}
interface GetTxsParams {
count: number;
offset: number;
exclude_mining_txs?: boolean;
exclude_unconfirmed?: boolean;
order?: string;
update_provision_info?: boolean;
}
declare class ServerWallet {
private walletUrl;
private daemonUrl;
private walletAuthToken;
constructor(params: ConstructorParams);
private generateRandomString;
private createJWSToken;
private generateAccessToken;
private fetchDaemon;
private fetchWallet;
updateWalletRpcUrl(rpcUrl: string): Promise<void>;
updateDaemonRpcUrl(rpcUrl: string): Promise<void>;
getAssetsList(): Promise<APIAsset[]>;
getAssetDetails(assetId: string): Promise<APIAsset>;
getAssetInfo(assetId: string): Promise<any>;
sendTransfer(assetId: string, address: string, amount: string): Promise<any>;
getAliasByAddress(address: string): Promise<any>;
getBalances(): Promise<BalanceInfo[]>;
validateWallet(authData: AuthData): Promise<boolean>;
getTxs(params: GetTxsParams): Promise<TxInfo>;
getAliasDetails(alias: string): Promise<AliasDetails>;
}
export default ServerWallet;

283
server/dist/server.js vendored Normal file
View file

@ -0,0 +1,283 @@
import axios from "axios";
import Big from "big.js";
import { ZANO_ASSET_ID, ZanoError } from "./utils";
import forge from "node-forge";
class ServerWallet {
walletUrl;
daemonUrl;
walletAuthToken;
constructor(params) {
this.walletUrl = params.walletUrl;
this.daemonUrl = params.daemonUrl;
this.walletAuthToken = params.walletAuthToken || "";
}
generateRandomString(length) {
const bytes = forge.random.getBytesSync(Math.ceil(length / 2));
const hexString = forge.util.bytesToHex(bytes);
return hexString.substring(0, length);
}
createJWSToken(payload, secretStr) {
const header = { alg: "HS256", typ: "JWT" };
const encodedHeader = Buffer.from(JSON.stringify(header))
.toString("base64")
.replace(/=/g, "");
const encodedPayload = Buffer.from(JSON.stringify(payload))
.toString("base64")
.replace(/=/g, "");
const signature = forge.hmac.create();
signature.start("sha256", secretStr);
signature.update(`${encodedHeader}.${encodedPayload}`);
const encodedSignature = forge.util
.encode64(signature.digest().getBytes())
.replace(/=/g, "");
return `${encodedHeader}.${encodedPayload}.${encodedSignature}`;
}
generateAccessToken(httpBody) {
// Calculate the SHA-256 hash of the HTTP body
const md = forge.md.sha256.create();
md.update(httpBody);
const bodyHash = md.digest().toHex();
// Example payload
const payload = {
body_hash: bodyHash,
user: "zano_extension",
salt: this.generateRandomString(64),
exp: Math.floor(Date.now() / 1000) + 60, // Expires in 1 minute
};
return this.createJWSToken(payload, this.walletAuthToken);
}
async fetchDaemon(method, params) {
const data = {
jsonrpc: "2.0",
id: 0,
method: method,
params: params,
};
const headers = {
"Content-Type": "application/json",
"Zano-Access-Token": this.generateAccessToken(JSON.stringify(data)),
};
return axios.post(this.daemonUrl, data, { headers });
}
async fetchWallet(method, params) {
const data = {
jsonrpc: "2.0",
id: 0,
method: method,
params: params,
};
const headers = {
"Content-Type": "application/json",
"Zano-Access-Token": this.generateAccessToken(JSON.stringify(data)),
};
return axios.post(this.walletUrl, data, { headers });
}
async updateWalletRpcUrl(rpcUrl) {
this.walletUrl = rpcUrl;
}
async updateDaemonRpcUrl(rpcUrl) {
this.daemonUrl = rpcUrl;
}
async getAssetsList() {
const count = 100;
let offset = 0;
let allAssets = [];
let keepFetching = true;
while (keepFetching) {
try {
const response = await this.fetchDaemon("get_assets_list", {
count,
offset,
});
const assets = response.data.result.assets;
if (assets.length < count) {
keepFetching = false;
}
allAssets = allAssets.concat(assets);
offset += count;
}
catch (error) {
throw new ZanoError("Failed to fetch assets list", "ASSETS_FETCH_ERROR");
}
}
return allAssets;
}
async getAssetDetails(assetId) {
const assets = await this.getAssetsList();
const asset = assets.find((a) => a.asset_id === assetId);
if (!asset) {
throw new ZanoError(`Asset with ID ${assetId} not found`, "ASSET_NOT_FOUND");
}
return asset;
}
async getAssetInfo(assetId) {
try {
const response = await this.fetchDaemon("get_asset_info", {
asset_id: assetId,
});
if (response.data.result) {
return response.data.result;
}
else {
throw new ZanoError(`Error fetching info for asset ID ${assetId}`, "ASSET_INFO_ERROR");
}
}
catch (error) {
console.error(error);
throw new ZanoError("Failed to fetch asset info", "ASSET_INFO_FETCH_ERROR");
}
}
async sendTransfer(assetId, address, amount) {
let decimalPoint;
let auditable;
if (assetId === ZANO_ASSET_ID) {
decimalPoint = 12;
}
else {
const asset = await this.getAssetDetails(assetId);
decimalPoint = asset.decimal_point;
}
try {
const response = await this.fetchWallet("getaddress", {});
auditable = response.data.result.address.startsWith("a");
}
catch (error) {
throw new ZanoError("Failed to fetch address", "ADDRESS_FETCH_ERROR");
}
const bigAmount = new Big(amount)
.times(new Big(10).pow(decimalPoint))
.toString();
try {
const response = await this.fetchWallet("transfer", {
destinations: [{ address, amount: bigAmount, asset_id: assetId }],
fee: "10000000000",
mixin: auditable ? 0 : 15,
});
if (response.data.result) {
return response.data.result;
}
else if (response.data.error &&
response.data.error.message === "WALLET_RPC_ERROR_CODE_NOT_ENOUGH_MONEY") {
throw new ZanoError("Not enough funds", "NOT_ENOUGH_FUNDS");
}
else {
throw new ZanoError("Error sending transfer", "TRANSFER_ERROR");
}
}
catch (error) {
if (error instanceof ZanoError) {
throw error;
}
else {
throw new ZanoError("Failed to send transfer", "TRANSFER_SEND_ERROR");
}
}
}
async getAliasByAddress(address) {
try {
const response = await this.fetchDaemon("get_alias_by_address", address);
if (response.data.result) {
return response.data.result;
}
else {
throw new ZanoError(`Error fetching alias for address ${address}`, "ALIAS_FETCH_ERROR");
}
}
catch (error) {
throw new ZanoError("Failed to fetch alias", "ALIAS_FETCH_ERROR");
}
}
async getBalances() {
try {
const response = await this.fetchWallet("getbalance", {});
const balancesData = response.data.result.balances;
const balances = balancesData.map((asset) => ({
name: asset.asset_info.full_name,
ticker: asset.asset_info.ticker,
id: asset.asset_info.asset_id,
amount: new Big(asset.unlocked)
.div(new Big(10).pow(asset.asset_info.decimal_point))
.toString(),
awaiting_in: new Big(asset.awaiting_in).toString(),
awaiting_out: new Big(asset.awaiting_out).toString(),
total: new Big(asset.total).toString(),
unlocked: new Big(asset.unlocked).toString(),
asset_info: asset.asset_info,
}));
return balances.sort((a, b) => {
if (a.id === ZANO_ASSET_ID)
return -1;
if (b.id === ZANO_ASSET_ID)
return 1;
return 0;
});
}
catch (error) {
throw new ZanoError("Failed to fetch balances", "BALANCES_FETCH_ERROR");
}
}
async validateWallet(authData) {
const { message, address, signature } = authData;
const alias = authData.alias || undefined;
const pkey = authData.pkey || undefined;
if (!message || (!alias && !pkey) || !signature) {
return false;
}
const validationParams = {
buff: Buffer.from(message).toString("base64"),
sig: signature,
};
if (alias) {
validationParams["alias"] = alias;
}
else {
validationParams["pkey"] = pkey;
}
const response = await this.fetchDaemon("validate_signature", validationParams);
const valid = response?.data?.result?.status === "OK";
if (!valid) {
return false;
}
if (alias) {
const aliasDetailsResponse = await this.fetchDaemon("get_alias_details", {
alias: alias,
});
const aliasDetails = aliasDetailsResponse?.data?.result?.alias_details;
const aliasAddress = aliasDetails?.address;
const addressValid = !!aliasAddress && aliasAddress === address;
if (!addressValid) {
return false;
}
}
return valid;
}
async getTxs(params) {
const txs = await this.fetchWallet("get_recent_txs_and_info2", {
count: params.count,
exclude_mining_txs: params.exclude_mining_txs || false,
exclude_unconfirmed: params.exclude_unconfirmed || false,
offset: params.offset,
order: params.order || "FROM_END_TO_BEGIN",
update_provision_info: params.update_provision_info || true,
});
return txs.data.result;
}
async getAliasDetails(alias) {
try {
const response = await this.fetchDaemon("get_alias_details", {
alias,
});
if (response.data.result) {
return response.data.result;
}
else {
throw new ZanoError(`Error fetching alias ${alias}`, "ALIAS_FETCH_ERROR");
}
}
catch {
throw new ZanoError("Failed to fetch alias", "ALIAS_FETCH_ERROR");
}
}
}
export default ServerWallet;
//# sourceMappingURL=server.js.map

1
server/dist/server.js.map vendored Normal file

File diff suppressed because one or more lines are too long

100
server/dist/types.d.ts vendored Normal file
View file

@ -0,0 +1,100 @@
export interface BaseAuthData {
address: string;
signature: string;
message: string;
}
export interface AliasAuth extends BaseAuthData {
alias: string;
}
export interface PkeyAuth extends BaseAuthData {
pkey: string;
}
export type AuthData = AliasAuth | PkeyAuth;
export interface ValidationParams {
buff: string;
sig: string;
alias?: string;
pkey?: string;
}
export interface APIAsset {
asset_id: string;
current_supply: number;
decimal_point: number;
full_name: string;
hidden_supply: boolean;
meta_info: string;
owner: string;
ticker: string;
total_max_supply: number;
}
export interface APIBalance {
asset_info: APIAsset;
awaiting_in: number;
awaiting_out: number;
total: number;
unlocked: number;
}
export interface BalanceInfo {
name: string;
ticker: string;
id: string;
amount: string;
awaiting_in: string;
awaiting_out: string;
total: string;
unlocked: string;
asset_info: APIAsset;
}
export interface SubTransfer {
amount: number;
asset_id: string;
is_income: boolean;
}
export interface EmployedEntry {
amount: number;
asset_id: string;
index: number;
}
export interface Transfer {
employed_entries: {
receive: EmployedEntry[];
spent: EmployedEntry[];
};
subtransfers: SubTransfer[];
comment: string;
fee: number;
height: number;
is_mining: boolean;
is_mixing: boolean;
is_service: boolean;
payment_id: string;
show_sender: boolean;
timestamp: number;
transfer_internal_index: number;
tx_blob_size: number;
tx_hash: string;
tx_type: number;
unlock_time: number;
remote_addresses: string[] | undefined;
remote_aliases: string[] | undefined;
}
export interface TxInfo {
last_item_index: number;
pi: {
balance: number;
curent_height: number;
transfer_entries_count: number;
transfers_count: number;
unlocked_balance: number;
};
total_transfers: number;
transfers: Transfer[];
}
export interface AliasDetails {
alias_details: {
address: string;
comment: string;
tracking_key: string;
};
status: 'OK' | 'NOT_FOUND';
}

2
server/dist/types.js vendored Normal file
View file

@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=types.js.map

1
server/dist/types.js.map vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}

6
server/dist/utils.d.ts vendored Normal file
View file

@ -0,0 +1,6 @@
export declare const ZANO_ASSET_ID = "d6329b5b1f7c0805b5c345f4957554002a2f557845f64d7645dae0e051a6498a";
export declare class ZanoError extends Error {
code: string;
name: string;
constructor(message: string, code: string);
}

11
server/dist/utils.js vendored Normal file
View file

@ -0,0 +1,11 @@
export const ZANO_ASSET_ID = "d6329b5b1f7c0805b5c345f4957554002a2f557845f64d7645dae0e051a6498a";
export class ZanoError extends Error {
code;
name;
constructor(message, code) {
super(message);
this.name = "ZanoError";
this.code = code;
}
}
//# sourceMappingURL=utils.js.map

1
server/dist/utils.js.map vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,aAAa,GAAG,kEAAkE,CAAC;AAEhG,MAAM,OAAO,SAAU,SAAQ,KAAK;IAEzB,IAAI,CAAS;IACb,IAAI,CAAS;IAEpB,YAAY,OAAe,EAAE,IAAY;QACrC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACrB,CAAC;CACJ"}

1
shared/dist/index.d.ts vendored Normal file
View file

@ -0,0 +1 @@
export * from "./utils";

2
shared/dist/index.js vendored Normal file
View file

@ -0,0 +1,2 @@
export * from "./utils";
//# sourceMappingURL=index.js.map

1
shared/dist/index.js.map vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC"}

7
shared/dist/utils.d.ts vendored Normal file
View file

@ -0,0 +1,7 @@
export declare function validateTokensInput(input: string | number, decimal_point?: number): {
valid: boolean;
error: string;
} | {
valid: boolean;
error?: undefined;
};

70
shared/dist/utils.js vendored Normal file
View file

@ -0,0 +1,70 @@
import Decimal from "decimal.js";
export function validateTokensInput(input, decimal_point = 12) {
if (typeof input === 'number') {
input = input.toString();
}
if (input === "") {
return {
valid: false,
error: 'Invalid input',
};
}
input = input.replace(/[^0-9.,]/g, '');
const MAX_NUMBER = new Decimal(2).pow(64).minus(1);
if (decimal_point < 0 || decimal_point > 18) {
return {
valid: false,
error: 'Invalid decimal point',
};
}
const dotInput = input.replace(/,/g, '');
const decimalDevider = new Decimal(10).pow(decimal_point);
const maxAllowedNumber = MAX_NUMBER.div(decimalDevider);
const minAllowedNumber = new Decimal(1).div(decimalDevider);
const rounded = (() => {
if (dotInput.replace('.', '').length > 20) {
const decimalParts = dotInput.split('.');
if (decimalParts.length === 2 && decimalParts[1].length > 1) {
const beforeDotLength = decimalParts[0].length;
const roundedInput = new Decimal(dotInput).toFixed(Math.max(20 - beforeDotLength, 0));
if (roundedInput.replace(/./g, '').length <= 20) {
return roundedInput;
}
}
return false;
}
else {
return dotInput;
}
})();
const decimalsAmount = dotInput.split('.')[1]?.length || 0;
if (decimalsAmount > decimal_point) {
return {
valid: false,
error: 'Invalid amount - too many decimal points',
};
}
if (rounded === false) {
return {
valid: false,
error: 'Invalid amount - number is too big or has too many decimal points',
};
}
const dotInputDecimal = new Decimal(rounded);
if (dotInputDecimal.gt(maxAllowedNumber)) {
return {
valid: false,
error: 'Invalid amount - number is too big',
};
}
if (dotInputDecimal.lt(minAllowedNumber)) {
return {
valid: false,
error: 'Invalid amount - number is too small',
};
}
return {
valid: true
};
}
//# sourceMappingURL=utils.js.map

1
shared/dist/utils.js.map vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AAEjC,MAAM,UAAU,mBAAmB,CAAC,KAAsB,EAAE,gBAAwB,EAAE;IAElF,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,KAAK,GAAG,KAAK,CAAC,QAAQ,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,KAAK,KAAK,EAAE,EAAE,CAAC;QACf,OAAO;YACH,KAAK,EAAE,KAAK;YACZ,KAAK,EAAE,eAAe;SACzB,CAAC;IACN,CAAC;IAED,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;IAEvC,MAAM,UAAU,GAAG,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAEnD,IAAI,aAAa,GAAG,CAAC,IAAI,aAAa,GAAG,EAAE,EAAE,CAAC;QAC1C,OAAO;YACH,KAAK,EAAE,KAAK;YACZ,KAAK,EAAE,uBAAuB;SACjC,CAAC;IACN,CAAC;IAED,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IAEzC,MAAM,cAAc,GAAG,IAAI,OAAO,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAE1D,MAAM,gBAAg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H,KAAK,EAAE,KAAK;YACZ,KAAK,EAAE,mEAAmE;SAC7E,CAAC;IACN,CAAC;IAED,MAAM,eAAe,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAE7C,IAAI,eAAe,CAAC,EAAE,CAAC,gBAAgB,CAAC,EAAE,CAAC;QACvC,OAAO;YACH,KAAK,EAAE,KAAK;YACZ,KAAK,EAAE,oCAAoC;SAC9C,CAAC;IACN,CAAC;IAED,IAAI,eAAe,CAAC,EAAE,CAAC,gBAAgB,CAAC,EAAE,CAAC;QACvC,OAAO;YACH,KAAK,EAAE,KAAK;YACZ,KAAK,EAAE,sCAAsC;SAChD,CAAC;IACN,CAAC;IAED,OAAO;QACH,KAAK,EAAE,IAAI;KACd,CAAC;AACN,CAAC"}

3
web/dist/hooks.d.ts vendored Normal file
View file

@ -0,0 +1,3 @@
import ZanoWallet, { ZanoWalletParams } from './zanoWallet';
declare function useZanoWallet(params: ZanoWalletParams): ZanoWallet | null;
export { useZanoWallet };

14
web/dist/hooks.js vendored Normal file
View file

@ -0,0 +1,14 @@
import ZanoWallet from './zanoWallet';
import { useEffect, useState } from 'react';
function useZanoWallet(params) {
const [zanoWallet, setZanoWallet] = useState(null);
useEffect(() => {
if (typeof window === 'undefined') {
return;
}
setZanoWallet(new ZanoWallet(params));
}, []);
return zanoWallet;
}
export { useZanoWallet };
//# sourceMappingURL=hooks.js.map

1
web/dist/hooks.js.map vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,UAAgC,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAE5C,SAAS,aAAa,CAAC,MAAwB;IAC3C,MAAM,CAAC,UAAU,EAAE,aAAa,CAAC,GAAG,QAAQ,CAAoB,IAAI,CAAC,CAAC;IAEtE,SAAS,CAAC,GAAG,EAAE;QACX,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;YAChC,OAAO;QACX,CAAC;QAED,aAAa,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;IAC1C,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO,UAAU,CAAC;AACtB,CAAC;AAED,OAAO,EAAE,aAAa,EAAE,CAAC"}

5
web/dist/index.d.ts vendored Normal file
View file

@ -0,0 +1,5 @@
import zanoWallet from "./zanoWallet";
import { useZanoWallet } from "./hooks";
export { useZanoWallet };
export * from "./types";
export { zanoWallet };

6
web/dist/index.js vendored Normal file
View file

@ -0,0 +1,6 @@
import zanoWallet from "./zanoWallet";
import { useZanoWallet } from "./hooks";
export { useZanoWallet };
export * from "./types";
export { zanoWallet };
//# sourceMappingURL=index.js.map

1
web/dist/index.js.map vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,cAAc,CAAC;AAEtC,OAAO,EAAC,aAAa,EAAC,MAAM,SAAS,CAAC;AACtC,OAAO,EAAC,aAAa,EAAC,CAAC;AAEvB,cAAc,SAAS,CAAC;AACxB,OAAO,EAAC,UAAU,EAAC,CAAC"}

32
web/dist/types.d.ts vendored Normal file
View file

@ -0,0 +1,32 @@
export interface Asset {
name: string;
ticker: string;
assetId: string;
decimalPoint: number;
balance: string;
unlockedBalance: string;
}
export interface Transfer {
amount: string;
assetId: string;
incoming: boolean;
}
export interface Transaction {
isConfirmed: boolean;
txHash: string;
blobSize: number;
timestamp: number;
height: number;
paymentId: string;
comment: string;
fee: string;
isInitiator: boolean;
transfers: Transfer[];
}
export interface Wallet {
address: string;
alias: string;
balance: string;
assets: Asset[];
transactions: Transaction[];
}

2
web/dist/types.js vendored Normal file
View file

@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=types.js.map

1
web/dist/types.js.map vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}

37
web/dist/zanoWallet.d.ts vendored Normal file
View file

@ -0,0 +1,37 @@
import { Wallet } from './types';
export interface ZanoWalletParams {
authPath: string;
useLocalStorage?: boolean;
aliasRequired?: boolean;
customLocalStorageKey?: string;
customNonce?: string;
customServerPath?: string;
disableServerRequest?: boolean;
onConnectStart?: (...params: any) => any;
onConnectEnd?: (...params: any) => any;
onConnectError?: (...params: any) => any;
beforeConnect?: (...params: any) => any;
onLocalConnectEnd?: (...params: any) => any;
}
interface WalletCredentials {
nonce: string;
signature: string;
publicKey: string;
address: string;
}
declare class ZanoWallet {
private DEFAULT_LOCAL_STORAGE_KEY;
private localStorageKey;
private params;
private zanoWallet;
constructor(params: ZanoWalletParams);
private handleError;
getSavedWalletCredentials(): WalletCredentials | undefined;
setWalletCredentials(credentials: WalletCredentials | undefined): void;
cleanWalletCredentials(): void;
connect(): Promise<true | void>;
getWallet(): Promise<Wallet>;
getAddressByAlias(alias: string): Promise<string | undefined>;
createAlias(alias: string): Promise<any>;
}
export default ZanoWallet;

144
web/dist/zanoWallet.js vendored Normal file
View file

@ -0,0 +1,144 @@
import { v4 as uuidv4 } from 'uuid';
class ZanoWallet {
DEFAULT_LOCAL_STORAGE_KEY = "wallet";
localStorageKey;
params;
zanoWallet;
constructor(params) {
if (typeof window === 'undefined') {
throw new Error('ZanoWallet can only be used in the browser');
}
if (!window.zano) {
console.error('ZanoWallet requires the ZanoWallet extension to be installed');
}
this.params = params;
this.zanoWallet = window.zano;
this.localStorageKey = params.customLocalStorageKey || this.DEFAULT_LOCAL_STORAGE_KEY;
}
handleError({ message }) {
if (this.params.onConnectError) {
this.params.onConnectError(message);
}
else {
console.error(message);
}
}
getSavedWalletCredentials() {
const savedWallet = localStorage.getItem(this.localStorageKey);
if (!savedWallet)
return undefined;
try {
return JSON.parse(savedWallet);
}
catch {
return undefined;
}
}
setWalletCredentials(credentials) {
if (credentials) {
localStorage.setItem(this.localStorageKey, JSON.stringify(credentials));
}
else {
localStorage.removeItem(this.localStorageKey);
}
}
cleanWalletCredentials() {
this.setWalletCredentials(undefined);
}
async connect() {
if (this.params.beforeConnect) {
await this.params.beforeConnect();
}
if (this.params.onConnectStart) {
this.params.onConnectStart();
}
const walletData = (await window.zano.request('GET_WALLET_DATA')).data;
if (!walletData?.address) {
return this.handleError({ message: 'Companion is offline' });
}
if (!walletData?.alias && this.params.aliasRequired) {
return this.handleError({ message: 'Alias not found' });
}
let nonce = "";
let signature = "";
let publicKey = "";
const existingWallet = this.params.useLocalStorage ? this.getSavedWalletCredentials() : undefined;
const existingWalletValid = existingWallet && existingWallet.address === walletData.address;
console.log('existingWalletValid', existingWalletValid);
console.log('existingWallet', existingWallet);
console.log('walletData', walletData);
if (existingWalletValid) {
nonce = existingWallet.nonce;
signature = existingWallet.signature;
publicKey = existingWallet.publicKey;
}
else {
const generatedNonce = this.params.customNonce || uuidv4();
const signResult = await this.zanoWallet.request('REQUEST_MESSAGE_SIGN', {
message: generatedNonce
}, null);
if (!signResult?.data?.result) {
return this.handleError({ message: 'Failed to sign message' });
}
nonce = generatedNonce;
signature = signResult.data.result.sig;
publicKey = signResult.data.result.pkey;
}
const serverData = {
alias: walletData.alias,
address: walletData.address,
signature,
pkey: publicKey,
message: nonce,
isSavedData: existingWalletValid
};
if (this.params.onLocalConnectEnd) {
this.params.onLocalConnectEnd(serverData);
}
if (!this.params.disableServerRequest) {
const result = await fetch(this.params.customServerPath || "/api/auth", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data: serverData
})
})
.then(res => res.json())
.catch((e) => ({
success: false,
error: e.message
}));
if (!result?.success || !result?.data) {
return this.handleError({ message: result.error });
}
if (!existingWalletValid && this.params.useLocalStorage) {
this.setWalletCredentials({
publicKey,
signature,
nonce,
address: walletData.address
});
}
if (this.params.onConnectEnd) {
this.params.onConnectEnd({
...serverData,
token: result.data.token
});
}
}
return true;
}
async getWallet() {
return (await this.zanoWallet.request('GET_WALLET_DATA'))?.data;
}
async getAddressByAlias(alias) {
return ((await this.zanoWallet.request('GET_ALIAS_DETAILS', { alias })) || undefined);
}
async createAlias(alias) {
return ((await this.zanoWallet.request('CREATE_ALIAS', { alias })) || undefined).data;
}
}
export default ZanoWallet;
//# sourceMappingURL=zanoWallet.js.map

1
web/dist/zanoWallet.js.map vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"zanoWallet.js","sourceRoot":"","sources":["../src/zanoWallet.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAqCpC,MAAM,UAAU;IAEJ,yBAAyB,GAAG,QAAQ,CAAC;IACrC,eAAe,CAAS;IAExB,MAAM,CAAmB;IACzB,UAAU,CAAmB;IAErC,YAAY,MAAwB;QAEhC,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;YAChC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAClE,CAAC;QAED,IAAI,CAAG,MAAiC,CAAC,IAAI,EAAE,CAAC;YAC5C,OAAO,CAAC,KAAK,CAAC,8DAA8D,CAAC,CAAC;QAClF,CAAC;QAED,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,UAAU,GAAK,MAAiC,CAAC,IAAI,CAAC;QAC3D,IAAI,CAAC,eAAe,GAAG,MAAM,CAAC,qBAAqB,IAAI,IAAI,CAAC,yBAAyB,CAAC;IAC1F,CAAC;IAGO,WAAW,CAAC,EAAE,OAAO,EAAwB;QACjD,IAAI,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;YAC7B,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;QACxC,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC3B,CAAC;IACL,CAAC;IAED,yBAAyB;QACrB,MAAM,WAAW,GAAG,YAAY,CAAC,OAAO,CAAC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