repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
nepoche/webb.js
packages/api-providers/src/types/currency-config.interface.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { InternalChainId } from '../chains/index.js'; import { WebbCurrencyId } from '../enums/index.js'; import { ReactElement } from './abstracts.js'; // The CurrencyType distinguishes how to interact with a particular currency in terms of // web3 api calls. export enum CurrencyType { ERC20, NATIVE, ORML } // The CurrencyRole distinguishes how a currency may interact in the webb application // - Wrappable refers to a currency that may be converted into a webbToken // - Governable refers to a currency that supports the wrapping of 'Wrappable' currencies, // which can be modified from governance. export enum CurrencyRole { Wrappable, Governable } export interface CurrencyView { id: WebbCurrencyId; icon: ReactElement; imageUrl?: string; type: CurrencyType; name: string; color?: string; symbol: string; } export interface CurrencyConfig extends CurrencyView { addresses: Map<InternalChainId, string>; role: CurrencyRole; }
nepoche/webb.js
packages/api-providers/src/contracts/utils/bridge-utils.ts
<gh_stars>0 /* eslint-disable */ /* tslint:disable */ // TODO resole eslint issue and merge this to protocol solidity //@ts-nocheck import { PoseidonHasher3 } from './poseidon-hash3.js'; /** * Copyright 2021 Webb Technologies * SPDX-License-Identifier: GPL-3.0-or-later-only */ import { ethers } from 'ethers'; import crypto from 'crypto'; import * as ff from 'ffjavascript'; const { utils } = ff; const { leBuff2int, unstringifyBigInts } = utils; const rbigint = (nbytes) => leBuff2int(crypto.randomBytes(nbytes)); const poseidonHasher = new PoseidonHasher3(); const blankFunctionSig = '0x00000000'; const blankFunctionDepositerOffset = 0; const AbiCoder = new ethers.utils.AbiCoder(); function bigNumberToPaddedBytes(num, digits = 32) { var n = num.toString(16).replace(/^0x/, ''); while (n.length < digits * 2) { n = '0' + n; } return '0x' + n; } const toHex = (covertThis, padding) => { return ethers.utils.hexZeroPad(ethers.utils.hexlify(covertThis), padding); }; const toFixedHex = (number, length = 32) => '0x' + BigInt(`${number}`) .toString(16) .padStart(length * 2, '0'); const arrayToFixedHex = (array) => { for (let i = 0; i < array.length; i++) { array[i] = toFixedHex(array[i]); } return array; }; const getRandomRecipient = () => rbigint(20); const abiEncode = (valueTypes, values) => { return AbiCoder.encode(valueTypes, values); }; const getFunctionSignature = (contractInstance, functionName) => { return contractInstance.abi.filter((abiProperty) => abiProperty.name === functionName)[0].signature; }; const createERCDepositData = (tokenAmountOrID, lenRecipientAddress, recipientAddress) => { return ( '0x' + toHex(tokenAmountOrID, 32).substr(2) + // Token amount or ID to deposit (32 bytes) toHex(lenRecipientAddress, 32).substr(2) + // len(recipientAddress) (32 bytes) recipientAddress.substr(2) ); // recipientAddress (?? bytes) }; const createUpdateProposalData = (sourceChainID, blockHeight, merkleRoot) => { return ( '0x' + toHex(sourceChainID, 32).substr(2) + // chainID (32 bytes) toHex(blockHeight, 32).substr(2) + // latest block height of incoming root updates (32 bytes) toHex(merkleRoot, 32).substr(2) ); // Updated Merkle Root (32 bytes) }; const createRootsBytes = (rootArray) :`0x${string}` => { let neighborBytes = '0x'; for (let i = 0; i < rootArray.length; i++) { neighborBytes += toFixedHex(rootArray[i]).substr(2); } return neighborBytes; // root byte string (32 * array.length bytes) }; const advanceBlock = () => { const time = Math.floor(Date.now() / 1000); network.provider.send('evm_increaseTime', [time]); network.provider.send('evm_mine', []); }; const createResourceID = (contractAddress, chainID) => { return toHex(contractAddress + toHex(chainID, 4).substr(2), 32); }; const assertObjectsMatch = (expectedObj, actualObj) => { for (const expectedProperty of Object.keys(expectedObj)) { assert.property(actualObj, expectedProperty, `actualObj does not have property: ${expectedProperty}`); let expectedValue = expectedObj[expectedProperty]; let actualValue = actualObj[expectedProperty]; // If expectedValue is not null, we can expected actualValue to not be null as well if (expectedValue !== null) { // Handling mixed case ETH addresses // If expectedValue is a string, we can expected actualValue to be a string as well if (expectedValue.toLowerCase !== undefined) { expectedValue = expectedValue.toLowerCase(); actualValue = actualValue.toLowerCase(); } // Handling BigNumber.js instances if (actualValue.toNumber !== undefined) { actualValue = actualValue.toNumber(); } // Truffle seems to return uint/ints as strings // Also handles when Truffle returns hex number when expecting uint/int if ( (typeof expectedValue === 'number' && typeof actualValue === 'string') || (ethers.utils.isHexString(actualValue) && typeof expectedValue === 'number') ) { actualValue = parseInt(actualValue); } } assert.deepEqual( expectedValue, actualValue, `expectedValue: ${expectedValue} does not match actualValue: ${actualValue}` ); } }; //uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); const nonceAndId = (nonce, id) => { return ( ethers.utils.hexZeroPad(ethers.utils.hexlify(nonce), 8) + ethers.utils.hexZeroPad(ethers.utils.hexlify(id), 1).substr(2) ); }; function generateDeposit(targetChainID = 0, secret = 31) { let deposit = { chainID: BigInt(targetChainID), secret: rbigint(secret), nullifier: rbigint(31) }; deposit.commitment = poseidonHasher.hash3([deposit.chainID, deposit.nullifier, deposit.secret]); deposit.nullifierHash = poseidonHasher.hash(null, deposit.nullifier, deposit.nullifier); return deposit; } function hexifyBigInts(o) { if (typeof o === 'bigint') { let str = o.toString(16); while (str.length < 64) str = '0' + str; str = '0x' + str; return str; } else if (Array.isArray(o)) { return o.map(hexifyBigInts); } else if (typeof o == 'object') { const res = {}; for (let k in o) { res[k] = hexifyBigInts(o[k]); } return res; } else { return o; } } // Convert a hex string to a byte array function hexStringToBytes(str: string) { if (str.slice(0, 2) === '0x') { str = str.substr(2); } if (!str) { return new Uint8Array(); } var a = []; for (var i = 0, len = str.length; i < len; i += 2) { // @ts-ignore a.push(parseInt(str.substr(i, 2), 16)); } return new Uint8Array(a); } function toSolidityInput(proof, publicSignals) { const result = { pi_a: [proof.pi_a[0], proof.pi_a[1]], pi_b: [ [proof.pi_b[0][1], proof.pi_b[0][0]], [proof.pi_b[1][1], proof.pi_b[1][0]] ], pi_c: [proof.pi_c[0], proof.pi_c[1]] }; result.publicSignals = publicSignals; return hexifyBigInts(unstringifyBigInts(result)); } function p256(n) { let nstr = BigInt(n).toString(16); while (nstr.length < 64) nstr = '0' + nstr; nstr = `"0x${nstr}"`; return nstr; } async function groth16ExportSolidityCallData(proof, pub) { let inputs = ''; for (let i = 0; i < pub.length; i++) { if (inputs != '') inputs = inputs + ','; inputs = inputs + p256(pub[i]); } let S; S = `[${p256(proof.pi_a[0])}, ${p256(proof.pi_a[1])}],` + `[[${p256(proof.pi_b[0][1])}, ${p256(proof.pi_b[0][0])}],[${p256(proof.pi_b[1][1])}, ${p256(proof.pi_b[1][0])}]],` + `[${p256(proof.pi_c[0])}, ${p256(proof.pi_c[1])}],` + `[${inputs}]`; return S; } async function generateWithdrawProofCallData(proof, pub) { const result = await groth16ExportSolidityCallData(proof, pub); const fullProof = JSON.parse('[' + result + ']'); const pi_a = fullProof[0]; const pi_b = fullProof[1]; const pi_c = fullProof[2]; let proofEncoded = [pi_a[0], pi_a[1], pi_b[0][0], pi_b[0][1], pi_b[1][0], pi_b[1][1], pi_c[0], pi_c[1]] .map((elt) => elt.substr(2)) .join(''); return proofEncoded; } export { advanceBlock, blankFunctionSig, blankFunctionDepositerOffset, bigNumberToPaddedBytes, getRandomRecipient, toFixedHex, arrayToFixedHex, toHex, hexStringToBytes, abiEncode, generateDeposit, getFunctionSignature, createERCDepositData, createUpdateProposalData, createRootsBytes, createResourceID, assertObjectsMatch, nonceAndId, poseidonHasher, toSolidityInput, p256, groth16ExportSolidityCallData, generateWithdrawProofCallData };
nepoche/webb.js
packages/api-providers/src/abstracts/networks-storage.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { Storage } from '../storage/index.js'; export type NetworkStore = { networksConfig: Record< number, | { defaultAccount: string; } | undefined >; defaultNetwork?: number; defaultWallet?: number; }; export type NetworkStorage = Storage<NetworkStore>;
nepoche/webb.js
packages/api-providers/src/ext-providers/polkadot/polkadot-provider.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable @typescript-eslint/ban-ts-comment */ import { options } from '@nepoche/api/index.js'; import { ApiInitHandler } from '@nepoche/api-providers/index.js'; import { EventBus, LoggerService } from '@nepoche/app-util/index.js'; import lodash from 'lodash'; import { ApiPromise, WsProvider } from '@polkadot/api'; import { InjectedExtension } from '@polkadot/extension-inject/types'; import { PolkaTXBuilder } from '../../polkadot/index.js'; import { InteractiveFeedback, WebbError, WebbErrorCodes } from '../../webb-error/index.js'; import { PolkadotAccount, PolkadotAccounts } from './polkadot-accounts.js'; const { isNumber } = lodash; type ExtensionProviderEvents = { connected: undefined; disconnected: undefined; error: undefined; ready: undefined; updateMetaData: Record<string, any>; accountsChange: PolkadotAccount[]; }; const logger = LoggerService.get('Polkadot-Provider'); export class PolkadotProvider extends EventBus<ExtensionProviderEvents> { private _accounts: PolkadotAccounts; constructor ( protected apiPromise: ApiPromise, protected injectedExtension: InjectedExtension, readonly txBuilder: PolkaTXBuilder ) { super(); this.hookListeners(); this._accounts = new PolkadotAccounts(this.injectedExtension); } static async fromExtension ( appName: string, [endPoint, ...allEndPoints]: string[], apiInitHandler: ApiInitHandler, txBuilder: PolkaTXBuilder ): Promise<PolkadotProvider> { const [apiPromise, currentExtensions] = await PolkadotProvider.getParams( appName, [endPoint, ...allEndPoints], apiInitHandler.onError ); return new PolkadotProvider(apiPromise, currentExtensions, txBuilder); } static async getApiPromise ( appName: string, [endPoint, ...allEndPoints]: string[], onError: ApiInitHandler['onError'] ) { // eslint-disable-next-line no-async-promise-executor const wsProvider = await new Promise<WsProvider>(async (resolve, reject) => { let wsProvider: WsProvider; let tryNumber = 0; let keepRetrying = true; let reportNewInteractiveError = true; /// Listen for events from the websocket provider to the connect and disconnect and return a promise for blocking const connectWs = async (wsProvider: WsProvider) => { /// perform a connection that won't reconnect if the connection failed to establish or due to broken-pipe (Ping connection) await wsProvider.connect(); return new Promise((resolve, reject) => { wsProvider.on('connected', () => { resolve(wsProvider); }); wsProvider.on('error', (e) => { console.log(e); reject(new Error('WS Error ')); }); }); }; /** * Infinite Looping till * 1- The ws connection is established * 2- The user killed the connection , no other retires * */ /// global interActiveFeedback for access on multiple scopes let interActiveFeedback: InteractiveFeedback; logger.trace('Trying to connect to ', [endPoint, ...allEndPoints], `Try: ${tryNumber}`); while (keepRetrying) { wsProvider = new WsProvider([endPoint, ...allEndPoints], false); /// don't wait for sleep time on the first attempt if (tryNumber !== 0) { /// sleep for 6s await new Promise((resolve) => setTimeout(resolve, 6000)); } try { /// wait for ping connection logger.trace('Performing the ping connection'); await connectWs(wsProvider); /// disconnect the pin connection logger.info(`Ping connection Ok try: ${tryNumber} for `, [endPoint, ...allEndPoints]); await wsProvider.disconnect(); logger.trace('Killed the ping connection'); /// create a new WS Provider that is failure friendly and will retry to connect /// no need to call `.connect` the Promise api will handle this resolve(new WsProvider([endPoint, ...allEndPoints])); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore if (typeof interActiveFeedback !== 'undefined') { /// cancel the feedback as the connection is established interActiveFeedback.cancelWithoutHandler(); } break; } catch (_) { tryNumber++; if (!reportNewInteractiveError) { continue; } const body = InteractiveFeedback.feedbackEntries([ { header: 'Failed to establish WS connection' }, { content: `Attempt to retry (${tryNumber}) after 6s..` } ]); const actions = InteractiveFeedback.actionsBuilder() .action('Wait for connection', () => { interActiveFeedback?.cancelWithoutHandler(); reportNewInteractiveError = false; }) .actions(); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore /// if the connection is established from the first time then there's no interActiveFeedback instance if (typeof interActiveFeedback !== 'undefined') { /// After failure there user is prompted that there is a connection failure the feedback from the previous attempt is canceled (dismissed) interActiveFeedback.cancelWithoutHandler(); } interActiveFeedback = new InteractiveFeedback( 'error', actions, () => { keepRetrying = false; reject(new Error('Disconnected')); }, body ); onError(interActiveFeedback); } } }); const apiPromise = await ApiPromise.create({ provider: wsProvider, rpc: { mt: { getLeaves: { description: 'Query for the tree leaves', params: [ { isOptional: false, name: 'tree_id', type: 'u32' }, { isOptional: false, name: 'from', type: 'u32' }, { isOptional: false, name: 'to', type: 'u32' }, { isOptional: true, name: 'at', type: 'Hash' } ], type: 'Vec<[u8; 32]>' } } } }); return apiPromise; } static async getParams ( appName: string, [endPoint, ...allEndPoints]: string[], onError: ApiInitHandler['onError'] ): Promise<[ApiPromise, InjectedExtension]> { const { web3Enable } = await import('@polkadot/extension-dapp'); const extensions = await web3Enable(appName); logger.info('Extensions', extensions); if (extensions.length === 0) { logger.warn('Polkadot extension isn\'t installed'); throw WebbError.from(WebbErrorCodes.PolkaDotExtensionNotInstalled); } const currentExtensions = extensions[0]; const apiPromise = await PolkadotProvider.getApiPromise(appName, [endPoint, ...allEndPoints], onError); return [apiPromise, currentExtensions]; } hookListeners () { this.apiPromise.on('error', () => { this.emit('error', undefined); }); this.apiPromise.on('ready', () => { this.emit('ready', undefined); }); this.apiPromise.on('connected', () => { this.emit('connected', undefined); }); this.apiPromise.on('disconnected', () => { this.emit('disconnected', undefined); }); this.injectedExtension.accounts?.subscribe((accounts) => { const polkadotAccounts = accounts.map((account) => new PolkadotAccount(account, account.address)); this.emit('accountsChange', polkadotAccounts); }); } destroy () { // close all listeners (Object.keys(this.subscriptions) as Array<keyof ExtensionProviderEvents>).forEach((entry) => { const cbs = this.subscriptions[entry]; // @ts-ignore cbs.forEach((cb) => this.off(entry, cb)); }, this); // disconnect this api return this.apiPromise.disconnect(); } /// metaData:MetadataDef updateMetaData (metaData: any) { return this.injectedExtension.metadata?.provide(metaData); } getMetaData () { if (!this.apiPromise.isConnected) return; const metadataDef = { chain: this.apiPromise.runtimeChain.toString(), genesisHash: this.apiPromise.genesisHash.toHex(), icon: 'substrate', metaCalls: Buffer.from(this.apiPromise.runtimeMetadata.asCallsOnly.toU8a()).toString('base64'), specVersion: this.apiPromise.runtimeVersion.specVersion.toNumber(), ss58Format: isNumber(this.apiPromise.registry.chainSS58) ? this.apiPromise.registry.chainSS58 : 42, tokenDecimals: isNumber(this.apiPromise.registry.chainDecimals) ? this.apiPromise.registry.chainDecimals : 12, tokenSymbol: this.apiPromise.registry.chainTokens[0] || 'Unit', types: options({}).types as any }; logger.trace('Polkadot api metadata', metadataDef); return metadataDef; } async checkMetaDataUpdate () { const metadataDef = this.getMetaData(); const known = await this.injectedExtension?.metadata?.get(); if (!known || !metadataDef) return null; const result = !known.find(({ genesisHash, specVersion }) => { return metadataDef.genesisHash === genesisHash && metadataDef.specVersion === specVersion; }); if (result) this.emit('updateMetaData', metadataDef); return metadataDef; } get accounts () { return this._accounts; } get api () { return this.apiPromise; } }
nepoche/webb.js
packages/api-providers/src/contracts/utils/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './make-deposit.js'; export * from './bridge-utils.js'; export * from './buffer-to-fixed.js'; export * from './evm-note.js'; export * from './pedersen-hash.js'; export * from './poseidon-hash3.js'; export * from './zkp-adapters.js';
nepoche/webb.js
packages/api-providers/src/utils/storage-mock.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { AppConfig } from '@nepoche/api-providers/abstracts/index.js'; import { Storage } from '../storage/index.js'; import { getEVMChainName } from './chain-utils.js'; export type MixerStorage = Record<string, { lastQueriedBlock: number; leaves: string[] }>; export const evmChainStorageFactory = (config: AppConfig, chainId: number) => { // localStorage will have key: <name of chain>, value: { Record<contractAddress: string, info: DynamicMixerInfoStore> } return Storage.newFromCache<MixerStorage>(getEVMChainName(config, chainId), { async commit (key: string, data: MixerStorage): Promise<void> { localStorage.setItem(key, JSON.stringify(data)); }, async fetch (key: string): Promise<MixerStorage> { const storageCached = localStorage.getItem(key); if (storageCached) { return { ...JSON.parse(storageCached) }; } return {}; } }); }; export const anchorDeploymentBlock: Record<string, number> = { '0x09b722aa809a076027fa51902e431a8c03e3f8df': 9973527, '0x12323bcabb342096669d80f968f7a31bdb29d4c4': 23781159, '0x510c6297cc30a058f41eb4af1bfc9953ead8b577': 1, '0x6aa5c74953f7da1556a298c5e129e417410474e2': 6182601, '0x7758f98c1c487e5653795470eeab6c4698be541b': 1, '0x97747a4de7302ff7ee3334e33138879469bfecf8': 11795573, '0xc44a4ecac4f23b6f92485cb1c90dbed75a987bc8': 877902, '0xd8a8f9629a98eabff31cfa9493f274a4d5e768cd': 8301075 }; type BridgeStorage = Record<string, { lastQueriedBlock: number; leaves: string[] }>; export const bridgeCurrencyBridgeStorageFactory = () => { // localStorage will have key: <Currency name>, value: { Record<contractAddress: string, info: DynamicMixerInfoStore> } return Storage.newFromCache<BridgeStorage>('webb-bridge', { async commit (key: string, data: BridgeStorage): Promise<void> { localStorage.setItem(key, JSON.stringify(data)); }, async fetch (key: string): Promise<BridgeStorage> { const storageCached = localStorage.getItem(key); if (storageCached) { return { ...JSON.parse(storageCached) }; } return {}; } }); };
nepoche/webb.js
packages/api-providers/src/contracts/wrappers/anchor-interface.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { Deposit } from '../utils/make-deposit.js'; export type AnchorInterface = { createDeposit(): Deposit; deposit(commitment: string): Promise<void>; };
nepoche/webb.js
packages/api-providers/src/account/Accounts.adapter.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export abstract class Account<T = unknown> { constructor (protected readonly _inner: T, public readonly address: string) {} // TODO abstract create react element abstract get avatar(): unknown; abstract get name(): string; protected get inner () { return this._inner; } } /* * This class is wrapping the accounts and accounts meta data * form multiple providers into a single interface * */ export type PromiseOrT<T> = Promise<T> | T; export abstract class AccountsAdapter<T = unknown, K = unknown> { abstract providerName: string; constructor (protected readonly _inner: T) {} abstract get activeOrDefault(): Promise<Account<K> | null> | Account<K> | null; abstract accounts(): PromiseOrT<Account<T | K>[]>; abstract setActiveAccount(account: Account): PromiseOrT<void>; protected get inner () { return this._inner; } }
nepoche/webb.js
packages/api-providers/src/utils/chain-utils.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { AppConfig } from '@nepoche/api-providers/index.js'; import { ChainTypeId, chainTypeIdToInternalId, InternalChainId } from '../chains/index.js'; import { WebbError, WebbErrorCodes } from '../webb-error/index.js'; export const getEVMChainName = (config: AppConfig, evmId: number): string => { const chain = Object.values(config.chains).find((chainsConfig) => chainsConfig.chainId === evmId); if (chain) { return chain.name; } else { throw WebbError.from(WebbErrorCodes.UnsupportedChain); } }; export const chainNameFromInternalId = (config: AppConfig, internalId: InternalChainId): string => { const chain = config.chains[internalId]; return chain.name; }; export const getChainNameFromChainId = (config: AppConfig, chainIdType: ChainTypeId): string => { const internalId = chainTypeIdToInternalId(chainIdType); return chainNameFromInternalId(config, internalId); }; export const getEVMChainNameFromInternal = (config: AppConfig, chainID: number): string => { const chain = Object.values(config.chains).find((chainsConfig) => chainsConfig.id === chainID); if (chain) { return chain.name; } else { throw WebbError.from(WebbErrorCodes.UnsupportedChain); } }; export const getNativeCurrencySymbol = (config: AppConfig, evmId: number): string => { const chain = Object.values(config.chains).find((chainsConfig) => chainsConfig.chainId === evmId); if (chain) { const nativeCurrency = chain.nativeCurrencyId; return config.currencies[nativeCurrency].symbol; } return 'Unknown'; };
nepoche/webb.js
packages/api-providers/src/contracts/utils/make-deposit.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { JsNote as DepositNote } from '@nepoche/wasm-utils'; import crypto from 'crypto'; // @ts-ignore import * as ff from 'ffjavascript'; // @ts-ignore import tornSnarkjs from 'tornado-snarkjs'; import { PoseidonHasher } from './merkle/index.js'; import { bufferToFixed } from './buffer-to-fixed.js'; import { pedersenHash } from './pedersen-hash.js'; import { poseidonHash3 } from './poseidon-hash3.js'; const { utils } = ff; const { leBuff2int } = utils; // const utils = require('ffjavascript').utils; // const rbigint = (nbytes: number) => utils.leBuff2int(crypto.randomBytes(nbytes)); export type Deposit = { preimage: Uint8Array; commitment: string; nullifierHash: string; secret: string; nullifier: string; chainId?: number; }; export function createTornDeposit () { const preimage = crypto.randomBytes(62); const nullifier = preimage.slice(0, 31); const secret = preimage.slice(31, 62); const commitment = bufferToFixed(pedersenHash(preimage)); const nullifierHash = bufferToFixed(pedersenHash(nullifier)); const deposit: Deposit = { commitment, nullifier: bufferToFixed(nullifier), nullifierHash, preimage, secret: bufferToFixed(secret) }; return deposit; } export function createAnchor2Deposit (chainId: number) { const poseidonHasher = new PoseidonHasher(); const preimage = crypto.randomBytes(62); const nullifier = leBuff2int(preimage.slice(0, 31)); const secret = leBuff2int(preimage.slice(31, 62)); console.log('chainId: ', chainId); const commitmentBN = poseidonHash3([chainId, nullifier, secret]); const nullifierHash = poseidonHasher.hash(null, nullifier, nullifier); console.log('secret: ', secret); console.log('nullifier: ', nullifier); console.log('commitmentBN: ', commitmentBN); const commitment = bufferToFixed(commitmentBN); console.log('commitment when creating deposit note: ', commitment); const deposit: Deposit = { chainId: chainId, commitment, nullifier: bufferToFixed(nullifier).substring(2), nullifierHash, preimage, secret: bufferToFixed(secret).substring(2) }; return deposit; } export function depositFromAnchorNote (note: DepositNote): Deposit { const poseidonHasher = new PoseidonHasher(); const noteSecretParts = note.secrets.split(':'); const chainId = Number(note.targetChainId); const preimageString = note.secrets.replaceAll(':', ''); const preimage = Buffer.from(preimageString); const nullifier = '0x' + noteSecretParts[1]; const secret = '0x' + noteSecretParts[2]; const commitmentBN = poseidonHash3([chainId, nullifier, secret]); const nullifierHash = poseidonHasher.hash(null, nullifier, nullifier); const commitment = bufferToFixed(commitmentBN); const deposit: Deposit = { chainId: chainId, commitment, nullifier: bufferToFixed(nullifier), nullifierHash, preimage, secret: bufferToFixed(secret) }; return deposit; } /// todo change to tornado export function depositFromPreimage (hexString: string): Deposit { const preImage = Buffer.from(hexString, 'hex'); const commitment = pedersenHash(preImage); const nullifier = tornSnarkjs.bigInt.leBuff2int(preImage.slice(0, 31)); const secret = tornSnarkjs.bigInt.leBuff2int(preImage.slice(31, 62)); const nullifierHash = pedersenHash(nullifier.leInt2Buff(31)); const deposit: Deposit = { commitment, nullifier: nullifier, nullifierHash, preimage: preImage, secret: secret }; return deposit; }
nepoche/webb.js
packages/api-providers/__test__/utils/init-polkadot-provider.ts
/* eslint-disable @typescript-eslint/ban-ts-comment */ // eslint-disable-next-line header/header import { InternalChainId } from '@nepoche/api-providers/chains/index.js'; import { PolkadotProvider } from '@nepoche/api-providers/ext-providers/index.js'; import { Account, AccountsAdapter, NotificationPayload, PromiseOrT, RelayerConfig, relayerNameToChainId, WebbPolkadot, WebbRelayerBuilder } from '@nepoche/api-providers/index.js'; import { InteractiveFeedback } from '@nepoche/api-providers/webb-error/index.js'; import { InjectedAccount, InjectedExtension } from '@polkadot/extension-inject/types'; import { mockAppConfig } from './mock-config.js'; const relayerConfig: RelayerConfig[] = [ { endpoint: 'http://localhost:9955' }, { endpoint: 'https://relayer.nepoche.com' }, { endpoint: 'https://relayer.webb.tools' }, { endpoint: 'https://webb.pops.one' }, { endpoint: 'https://relayer.bldnodes.org' } ]; export function relayerSubstrateNameToChainId (name: string): InternalChainId { switch (name) { case 'localnode': return InternalChainId.WebbDevelopment; } throw new Error('unhandled relayed chain name ' + name); } const notificationHandler = (m: NotificationPayload) => { console.log(m); return Math.random(); }; notificationHandler.remove = (id: string | number) => { console.log(id); }; class PolkadotAccounts extends AccountsAdapter<InjectedExtension, InjectedAccount> { private activeAccount: null | Account<InjectedAccount> = null; accounts (): PromiseOrT<Account<InjectedExtension | InjectedAccount>[]> { return []; } get activeOrDefault (): Promise<Account<InjectedAccount> | null> | Account<InjectedAccount> | null { return this.activeAccount; } providerName = 'Polka'; setActiveAccount (account: Account<InjectedAccount>): PromiseOrT<void> { this.activeAccount = account; return undefined; } } export async function initPolkadotProvider (): Promise<WebbPolkadot> { const webbRelayerBuilder = await WebbRelayerBuilder.initBuilder( relayerConfig, (name, basedOn) => { try { return basedOn === 'evm' ? relayerNameToChainId(name) : relayerSubstrateNameToChainId(name); } catch (e) { return null; } }, mockAppConfig ); const apiPromise = await PolkadotProvider.getApiPromise('Webb DApp', ['ws://127.0.0.1:9944'], { // @ts-ignore onError (error: InteractiveFeedback): any { console.log(error.reason); console.log(error); } }); const provider = await WebbPolkadot.initWithCustomAccountsAdapter( 'Webb DApp', ['ws://127.0.0.1:9944'], { onError (error: InteractiveFeedback): any { console.log(error.reason); console.log(error); } }, webbRelayerBuilder, mockAppConfig, notificationHandler, new PolkadotAccounts({} as any), apiPromise, {} as any, () => null ); return provider; }
nepoche/webb.js
packages/api-providers/src/chains/chain-utils.spec.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { expect } from 'chai'; import { ChainType, ChainTypeId } from './chain-id.enum.js'; import { byteArrayToNum, computeChainIdType, numToByteArray, parseChainIdType } from './chain-utils.js'; describe('test various conversion functions', () => { it('byte array to num converts correctly', () => { const arr = [2, 0, 0, 0, 122, 105]; const result = 2199023286889; expect(byteArrayToNum(arr)).to.deep.equal(result); }); it('numToByteArray converts correctly', () => { const arrResult = [2, 0, 0, 0, 122, 105]; const number = 2199023286889; expect(numToByteArray(number, 4)).to.deep.equal(arrResult); }); it('numToByteArray converts hexstring values correctly', () => { const evmResult = [1, 0]; expect(numToByteArray(ChainType.EVM, 2)).to.deep.equal(evmResult); const kusamaParachainResult = [3, 17]; expect(numToByteArray(ChainType.KusamaParachain, 2)).to.deep.equal(kusamaParachainResult); }); it('numToByteArray maintains minimum size with leading zeroes', () => { const arrResult = [0, 0, 122, 105]; const number = 31337; expect(numToByteArray(number, 4)).to.deep.equal(arrResult); }); it('computeChainIdType converts correctly', () => { const chainType = ChainType.Substrate; const chainId = 31337; const chainIdTypeResult = 2199023286889; expect(computeChainIdType(chainType, chainId)).to.deep.equal(chainIdTypeResult); }); it('typeAndIdFromChainIdType converts correctly', () => { const chainIdType = 2199023286889; const chainTypeResult = ChainType.Substrate; const chainIdResult = 31337; const result: ChainTypeId = { chainId: chainIdResult, chainType: chainTypeResult }; expect(parseChainIdType(chainIdType)).to.deep.equal(result); }); });
nepoche/webb.js
packages/api-providers/src/utils/misc/index.ts
<filename>packages/api-providers/src/utils/misc/index.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './app-mode.js'; export * from './get-cached-fixtures-uri.js';
nepoche/webb.js
packages/app-util/src/fixed-18.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import BigNumber from 'bignumber.js'; import { Codec } from '@polkadot/types/types'; /** * @constant * @type {(0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8)} * @description * | Value | Property | Description | * | 0 | ROUND_UP | Rounds away from zero | * | 1 | ROUND_DOWN | Rounds towards zero | * | 2 | ROUND_CEIL | Rounds towards Infinity | * | 3 | ROUND_FLOOR | Rounds towards -Infinity | * | 4 | ROUND_HALF_UP | Rounds towards nearest neighbour, If equidistant, rounds away form zero | * | 5 | ROUND_HALF_DOWN | Rounds towards nearest neighbour, If equidistant, rounds towards zero | * | 6 | ROUND_HALF_EVEN | Rounds towards nearest neighbour, If equidistant, rounds towards even zero | * | 7 | ROUND_HALF_CEIL | Rounds towards nearest neighbour, If equidistant, rounds towards Infinity | * | 8 | ROUND_HALF_FLOOR | Rounds towards nearest neighbour, If equidistant, rounds towards -Infinity | */ export type ROUND_MODE = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; type NumLike = number | string; /** * @class Fixed18 * @description fixed point mathematical operation support with 18 decimals */ export class Fixed18 { private inner: BigNumber; /** * @constant * @description precision to 18 decimals */ static PRECISION = 10 ** 18; /** * @constant * @description zero */ static ZERO = Fixed18.fromNatural(0); /** * @description constructor of Fixed18 * @param {(number | string | BigNumber)} origin - the origin number */ constructor (origin: NumLike | BigNumber) { if (origin instanceof BigNumber) { this.inner = origin; } else { this.inner = new BigNumber(origin || 0); } return this; } /** * @name getInner * @description get the inner BigNumber value */ public getInner (): BigNumber { return this.inner; } /** * @name toString * @description format real number(division by precision) to string * @param {number} [dp=6] - decimal places deafult is 6 * @param {number} [rm=3] - round modle, default is ROUND_FLOOR */ public toString (dp = 6, rm: ROUND_MODE = 3): string { let result = this.inner.div(Fixed18.PRECISION); result = result.decimalPlaces(dp, rm); return result.toString(); } /** * @name toFixed * @description format real number string(division by precision) to string * @param {number} [dp=6] - decimal places deafult is 6 * @param {number} [rm=3] - round modle, default is ROUND_FLOOR */ public toFixed (dp = 6, rm: ROUND_MODE = 3): string { let result = this.inner.div(Fixed18.PRECISION); result = result.decimalPlaces(dp, rm); return result.toFixed(); } /** * @name innerToString * @description format inner BigNumber value to string * @param {number} [dp=0] - decimal places deafult is 0 * @param {number} [rm=3] - round modle, default is ROUND_FLOOR */ public innerToString (dp = 0, rm: ROUND_MODE = 3): string { // return 0 if the value is Infinity, -Infinity and NaN if (!this.isFinity()) { return '0'; } return this.inner.decimalPlaces(dp, rm).toFixed(); } /** * @name innerToNumber * @description format inner BigNumber value to string * @param {number} [dp=0] - decimal places deafult is 0 * @param {number} [rm=3] - round modle, default is ROUND_FLOOR */ public innerToNumber (dp = 0, rm: ROUND_MODE = 3): number { // return 0 if the value is Infinity, -Infinity and NaN if (!this.isFinity()) { return 0; } return this.inner.decimalPlaces(dp, rm).toNumber(); } /** * @name toNumber * @description format real number(division by precision) to number * @param {number} [dp=6] - decimal places deafult is 6 * @param {number} [rm=3] - round modle, default is ROUND_FLOOR */ public toNumber (dp = 6, rm: ROUND_MODE = 3): number { let result = this.inner.div(Fixed18.PRECISION); result = result.decimalPlaces(dp, rm); return result.toNumber(); } /** * @name deciminalPlaces * @description returns a Fixed18 whose value is the value of this Fixed18 rounded by rounding mode roundingMode to a maximum of decimalPlaces decimal places. * @param {number} [dp=18] - decimal places * @param {number} [rm=3] - round modle, default is ROUND_FLOOR */ public decimalPlaces (dp = 18, rm: ROUND_MODE = 3): Fixed18 { return Fixed18.fromNatural(this.toNumber(dp, rm)); } /** * @name fromNatural * @description get Fixed18 from real number, will multiply by precision * @param {(string | number)} target - target number */ static fromNatural (target: NumLike): Fixed18 { return new Fixed18(new BigNumber(target).times(Fixed18.PRECISION)); } /** * @name fromParts * @description get Fixed18 from real number, will not multiply by precision * @param {(string | number)} parts - parts number */ static fromParts (parts: NumLike): Fixed18 { return new Fixed18(parts); } /** * @name formRational * @param {(string | number)} n - numerator * @param {(string | number)} d - denominator */ static fromRational (n: NumLike, d: NumLike): Fixed18 { const _n = new BigNumber(n); const _d = new BigNumber(d); return new Fixed18(_n.times(Fixed18.PRECISION).div(_d).decimalPlaces(0, 3)); } /** * @name add * @description fixed-point addition operator * @param {Fixed18} target - target number */ public add (target: Fixed18): Fixed18 { return new Fixed18(this.inner.plus(target.inner).decimalPlaces(0, 3)); } /** * @name sub * @description fixed-point subtraction operator * @param {Fixed18} target - target number */ public sub (target: Fixed18): Fixed18 { return new Fixed18(this.inner.minus(target.inner).decimalPlaces(0, 3)); } /** * @name mul * @description fixed-point multiplication operator * @param {Fixed18} target - target number */ public mul (target: Fixed18): Fixed18 { const inner = this.inner.times(target.inner).div(Fixed18.PRECISION).decimalPlaces(0, 3); return new Fixed18(inner); } /** * @name div * @description fixed-point divided operator * @param {Fixed18} target - target number */ public div (target: Fixed18): Fixed18 { const inner = this.inner.div(target.inner).times(Fixed18.PRECISION).decimalPlaces(0, 3); return new Fixed18(inner); } /** * @name isLessThan * @description return true if the value is less than the target value * @param {Fixed18} target - target number */ public isLessThan (target: Fixed18): boolean { return this.inner.isLessThan(target.inner); } /** * @name isGreaterThan * @description return true if the value is greater than the target value * @param {Fixed18} target - target number */ public isGreaterThan (target: Fixed18): boolean { return this.inner.isGreaterThan(target.inner); } /** * @name isEqualTo * @description return true if the values are equal * @param {Fixed18} target - target number */ public isEqualTo (target: Fixed18): boolean { return this.inner.isEqualTo(target.inner); } /** * @name max * @description return the max value * @param {...Fixed18} target - target numbers */ public max (...targets: Fixed18[]): Fixed18 { return new Fixed18(BigNumber.max.apply(null, [this.inner, ...targets.map((i) => i.inner)])); } /** * @name min * @description return the min value * @param {...Fixed18} target - target numbers */ public min (...targets: Fixed18[]): Fixed18 { return new Fixed18(BigNumber.min.apply(null, [this.inner, ...targets.map((i) => i.inner)])); } /** * @name nagated * @description return the nageted value */ public negated (): Fixed18 { return new Fixed18(this.inner.negated()); } /** * @name isZero * @description return true if the value of inner is 0 */ public isZero (): boolean { return this.inner.isZero(); } /** * @name isNaN * @description return true if the value of inner is NaN */ public isNaN (): boolean { return this.inner.isNaN(); } /** * @name isFinity * @description return true if the value of inner is finity, only return false when the value is NaN, -Infinity or Infinity. */ public isFinity (): boolean { return this.inner.isFinite(); } } // force to Fixed18 export function convertToFixed18 (data: Codec | number | Fixed18): Fixed18 { if (data instanceof Fixed18) { return data; } else if (typeof data === 'number') { return Fixed18.fromNatural(data); } if ('toString' in data) { return Fixed18.fromParts(data.toString()); // for Codec } return Fixed18.ZERO; }
nepoche/webb.js
packages/app-util/src/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './fixed-18.js'; export * from './logger/index.js'; export * from './shared/event-bus.class.js';
nepoche/webb.js
packages/api-providers/src/ext-providers/web3/web3-accounts.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { Eth } from 'web3-eth'; import { Account, AccountsAdapter, PromiseOrT } from '../../account/Accounts.adapter.js'; export class Web3Account extends Account<Eth> { get avatar () { return ''; } get name (): string { return ''; } } export class Web3Accounts extends AccountsAdapter<Eth> { providerName = 'Eth'; async accounts () { const accounts = await this._inner.getAccounts(); return accounts.map((address) => new Web3Account(this.inner, address)); } get activeOrDefault () { const defaultAccount = this.inner.defaultAccount; return defaultAccount ? new Web3Account(this.inner, defaultAccount) : null; } // eslint-disable-next-line @typescript-eslint/no-unused-vars setActiveAccount (account: Account): PromiseOrT<void> { return undefined; } }
nepoche/webb.js
packages/types/src/interfaces/augment-api-tx.d.ts
<reponame>nepoche/webb.js<gh_stars>0 // Auto-generated via `yarn polkadot-types-from-chain`, do not edit /* eslint-disable */ import type { DarkwebbStandaloneRuntimeElement, PalletAssetRegistryAssetType } from '@nepoche/types/interfaces/pallets'; import type { AccountId32, MultiAddress } from '@nepoche/types/interfaces/runtime'; import type { ApiTypes } from '@polkadot/api-base/types'; import type { Bytes, Compact, Null, Option, Vec, bool, u128, u32, u8 } from '@polkadot/types-codec'; import type { AnyNumber } from '@polkadot/types-codec/types'; import type { DarkwebbStandaloneRuntimeElement, PalletAssetRegistryAssetType } from '@nepoche/types/interfaces/pallets'; import type { AccountId32, MultiAddress } from '@nepoche/types/interfaces/runtime'; declare module '@polkadot/api-base/types/submittable' { export interface AugmentedSubmittables<ApiType extends ApiTypes> { anchorBls381: { create: AugmentedSubmittable<(depositSize: u128 | AnyNumber | Uint8Array, maxEdges: u32 | AnyNumber | Uint8Array, depth: u8 | AnyNumber | Uint8Array, asset: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u128, u32, u8, u32]>; deposit: AugmentedSubmittable<(treeId: u32 | AnyNumber | Uint8Array, leaf: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, DarkwebbStandaloneRuntimeElement]>; /** * Same as [Self::deposit] but with another call to update the linked * anchors cross-chain (if any). **/ depositAndUpdateLinkedAnchors: AugmentedSubmittable<(treeId: u32 | AnyNumber | Uint8Array, leaf: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, DarkwebbStandaloneRuntimeElement]>; withdraw: AugmentedSubmittable<(id: u32 | AnyNumber | Uint8Array, proofBytes: Bytes | string | Uint8Array, chainId: u32 | AnyNumber | Uint8Array, roots: Vec<DarkwebbStandaloneRuntimeElement> | (DarkwebbStandaloneRuntimeElement | string | Uint8Array)[], nullifierHash: DarkwebbStandaloneRuntimeElement | string | Uint8Array, recipient: AccountId32 | string | Uint8Array, relayer: AccountId32 | string | Uint8Array, fee: u128 | AnyNumber | Uint8Array, refund: u128 | AnyNumber | Uint8Array, commitment: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, Bytes, u32, Vec<DarkwebbStandaloneRuntimeElement>, DarkwebbStandaloneRuntimeElement, AccountId32, AccountId32, u128, u128, DarkwebbStandaloneRuntimeElement]>; /** * Generic tx **/ [key: string]: SubmittableExtrinsicFunction<ApiType>; }; anchorBn254: { create: AugmentedSubmittable<(depositSize: u128 | AnyNumber | Uint8Array, maxEdges: u32 | AnyNumber | Uint8Array, depth: u8 | AnyNumber | Uint8Array, asset: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u128, u32, u8, u32]>; deposit: AugmentedSubmittable<(treeId: u32 | AnyNumber | Uint8Array, leaf: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, DarkwebbStandaloneRuntimeElement]>; /** * Same as [Self::deposit] but with another call to update the linked * anchors cross-chain (if any). **/ depositAndUpdateLinkedAnchors: AugmentedSubmittable<(treeId: u32 | AnyNumber | Uint8Array, leaf: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, DarkwebbStandaloneRuntimeElement]>; withdraw: AugmentedSubmittable<(id: u32 | AnyNumber | Uint8Array, proofBytes: Bytes | string | Uint8Array, chainId: u32 | AnyNumber | Uint8Array, roots: Vec<DarkwebbStandaloneRuntimeElement> | (DarkwebbStandaloneRuntimeElement | string | Uint8Array)[], nullifierHash: DarkwebbStandaloneRuntimeElement | string | Uint8Array, recipient: AccountId32 | string | Uint8Array, relayer: AccountId32 | string | Uint8Array, fee: u128 | AnyNumber | Uint8Array, refund: u128 | AnyNumber | Uint8Array, commitment: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, Bytes, u32, Vec<DarkwebbStandaloneRuntimeElement>, DarkwebbStandaloneRuntimeElement, AccountId32, AccountId32, u128, u128, DarkwebbStandaloneRuntimeElement]>; /** * Generic tx **/ [key: string]: SubmittableExtrinsicFunction<ApiType>; }; assetRegistry: { /** * Add an asset to an existing pool. **/ addAssetToPool: AugmentedSubmittable<(pool: Bytes | string | Uint8Array, assetId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes, u32]>; /** * Remove an asset from an existing pool. **/ deleteAssetFromPool: AugmentedSubmittable<(pool: Bytes | string | Uint8Array, assetId: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes, u32]>; /** * Register a new asset. * * Asset is identified by `name` and the name must not be used to * register another asset. * * New asset is given `NextAssetId` - sequential asset id * * Adds mapping between `name` and assigned `asset_id` so asset id can * be retrieved by name too (Note: this approach is used in AMM * implementation (xyk)) * * Emits 'Registered` event when successful. **/ register: AugmentedSubmittable<(name: Bytes | string | Uint8Array, assetType: PalletAssetRegistryAssetType | { Token: any } | { PoolShare: any } | string | Uint8Array, existentialDeposit: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes, PalletAssetRegistryAssetType, u128]>; /** * Set asset native location. * * Adds mapping between native location and local asset id and vice * versa. * * Mainly used in XCM. * * Emits `LocationSet` event when successful. **/ setLocation: AugmentedSubmittable<(assetId: u32 | AnyNumber | Uint8Array, location: Null | null) => SubmittableExtrinsic<ApiType>, [u32, Null]>; /** * Set metadata for an asset. * * - `asset_id`: Asset identifier. * - `symbol`: The exchange symbol for this asset. Limited in length by * `StringLimit`. * - `decimals`: The number of decimals this asset uses to represent * one unit. * * Emits `MetadataSet` event when successful. **/ setMetadata: AugmentedSubmittable<(assetId: u32 | AnyNumber | Uint8Array, symbol: Bytes | string | Uint8Array, decimals: u8 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, Bytes, u8]>; /** * Update registered asset. * * Updates also mapping between name and asset id if provided name is * different than currently registered. * * Emits `Updated` event when successful. **/ update: AugmentedSubmittable<(assetId: u32 | AnyNumber | Uint8Array, name: Bytes | string | Uint8Array, assetType: PalletAssetRegistryAssetType | { Token: any } | { PoolShare: any } | string | Uint8Array, existentialDeposit: Option<u128> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, Bytes, PalletAssetRegistryAssetType, Option<u128>]>; /** * Generic tx **/ [key: string]: SubmittableExtrinsicFunction<ApiType>; }; mixerBls381: { create: AugmentedSubmittable<(depositSize: u128 | AnyNumber | Uint8Array, depth: u8 | AnyNumber | Uint8Array, asset: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u128, u8, u32]>; deposit: AugmentedSubmittable<(treeId: u32 | AnyNumber | Uint8Array, leaf: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, DarkwebbStandaloneRuntimeElement]>; forceSetMaintainer: AugmentedSubmittable<(newMaintainer: AccountId32 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId32]>; setMaintainer: AugmentedSubmittable<(newMaintainer: AccountId32 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId32]>; withdraw: AugmentedSubmittable<(id: u32 | AnyNumber | Uint8Array, proofBytes: Bytes | string | Uint8Array, root: DarkwebbStandaloneRuntimeElement | string | Uint8Array, nullifierHash: DarkwebbStandaloneRuntimeElement | string | Uint8Array, recipient: AccountId32 | string | Uint8Array, relayer: AccountId32 | string | Uint8Array, fee: u128 | AnyNumber | Uint8Array, refund: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, Bytes, DarkwebbStandaloneRuntimeElement, DarkwebbStandaloneRuntimeElement, AccountId32, AccountId32, u128, u128]>; /** * Generic tx **/ [key: string]: SubmittableExtrinsicFunction<ApiType>; }; mixerBn254: { create: AugmentedSubmittable<(depositSize: u128 | AnyNumber | Uint8Array, depth: u8 | AnyNumber | Uint8Array, asset: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u128, u8, u32]>; deposit: AugmentedSubmittable<(treeId: u32 | AnyNumber | Uint8Array, leaf: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, DarkwebbStandaloneRuntimeElement]>; forceSetMaintainer: AugmentedSubmittable<(newMaintainer: AccountId32 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId32]>; setMaintainer: AugmentedSubmittable<(newMaintainer: AccountId32 | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [AccountId32]>; withdraw: AugmentedSubmittable<(id: u32 | AnyNumber | Uint8Array, proofBytes: Bytes | string | Uint8Array, root: DarkwebbStandaloneRuntimeElement | string | Uint8Array, nullifierHash: DarkwebbStandaloneRuntimeElement | string | Uint8Array, recipient: AccountId32 | string | Uint8Array, relayer: AccountId32 | string | Uint8Array, fee: u128 | AnyNumber | Uint8Array, refund: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32, Bytes, DarkwebbStandaloneRuntimeElement, DarkwebbStandaloneRuntimeElement, AccountId32, AccountId32, u128, u128]>; /** * Generic tx **/ [key: string]: SubmittableExtrinsicFunction<ApiType>; }; tokens: { /** * Exactly as `transfer`, except the origin must be root and the source * account may be specified. * * The dispatch origin for this call must be _Root_. * * - `source`: The sender of the transfer. * - `dest`: The recipient of the transfer. * - `currency_id`: currency type. * - `amount`: free balance amount to tranfer. **/ forceTransfer: AugmentedSubmittable<(source: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, dest: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, currencyId: u32 | AnyNumber | Uint8Array, amount: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, MultiAddress, u32, Compact<u128>]>; /** * Set the balances of a given account. * * This will alter `FreeBalance` and `ReservedBalance` in storage. it * will also decrease the total issuance of the system * (`TotalIssuance`). If the new free or reserved balance is below the * existential deposit, it will reap the `AccountInfo`. * * The dispatch origin for this call is `root`. **/ setBalance: AugmentedSubmittable<(who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, currencyId: u32 | AnyNumber | Uint8Array, newFree: Compact<u128> | AnyNumber | Uint8Array, newReserved: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, u32, Compact<u128>, Compact<u128>]>; /** * Transfer some liquid free balance to another account. * * `transfer` will set the `FreeBalance` of the sender and receiver. * It will decrease the total issuance of the system by the * `TransferFee`. If the sender's account is below the existential * deposit as a result of the transfer, the account will be reaped. * * The dispatch origin for this call must be `Signed` by the * transactor. * * - `dest`: The recipient of the transfer. * - `currency_id`: currency type. * - `amount`: free balance amount to tranfer. **/ transfer: AugmentedSubmittable<(dest: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, currencyId: u32 | AnyNumber | Uint8Array, amount: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, u32, Compact<u128>]>; /** * Transfer all remaining balance to the given account. * * NOTE: This function only attempts to transfer _transferable_ * balances. This means that any locked, reserved, or existential * deposits (when `keep_alive` is `true`), will not be transferred by * this function. To ensure that this function results in a killed * account, you might need to prepare the account by removing any * reference counters, storage deposits, etc... * * The dispatch origin for this call must be `Signed` by the * transactor. * * - `dest`: The recipient of the transfer. * - `currency_id`: currency type. * - `keep_alive`: A boolean to determine if the `transfer_all` * operation should send all of the funds the account has, causing * the sender account to be killed (false), or transfer everything * except at least the existential deposit, which will guarantee to * keep the sender account alive (true). **/ transferAll: AugmentedSubmittable<(dest: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, currencyId: u32 | AnyNumber | Uint8Array, keepAlive: bool | boolean | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, u32, bool]>; /** * Same as the [`transfer`] call, but with a check that the transfer * will not kill the origin account. * * 99% of the time you want [`transfer`] instead. * * The dispatch origin for this call must be `Signed` by the * transactor. * * - `dest`: The recipient of the transfer. * - `currency_id`: currency type. * - `amount`: free balance amount to tranfer. **/ transferKeepAlive: AugmentedSubmittable<(dest: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, currencyId: u32 | AnyNumber | Uint8Array, amount: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, u32, Compact<u128>]>; /** * Generic tx **/ [key: string]: SubmittableExtrinsicFunction<ApiType>; }; } // AugmentedSubmittables } // declare module
nepoche/webb.js
packages/app-util/src/logger/logger-service.class.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { LoggerEvent } from './logger-event.class.js'; import { Color } from './logs-colors.enum.js'; import { LogLevel } from './logs-level.enum.js'; type LoggersMaps = Record<string, LoggerService>; type LoggerFn = (...message: any[]) => void; export class LoggerService { public static readonly eventBus = new LoggerEvent(); private static _loggers: LoggersMaps = {}; public static _enabled = true; static new (ctx: string, logLevel: LogLevel = LogLevel.trace): LoggerService { const logger = new LoggerService(ctx, logLevel); LoggerService._loggers[ctx] = logger; return logger; } static get (ctx: string): LoggerService { const cachedLogger = LoggerService._loggers[ctx]; if (cachedLogger) { return cachedLogger; } return LoggerService.new(ctx); } constructor (private readonly ctx: string, private readonly logLevel: LogLevel) { return this; } private logger = (level: LogLevel = LogLevel.trace, color: Color, ...message: any[]): any[] | void => { let m = ''; try { m = JSON.stringify(message, null, 2); } catch (e) { m = 'Cant show message'; } LoggerService.eventBus.sendEvent?.('log', { ctx: this.ctx, level, log: m }); if (!LoggerService._enabled) { return; } if (this.logLevel <= level) { const date = new Date(); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment return [`${color}[${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}] , [${this.ctx}] `, ...message]; } }; mutedLogger = (): null => null; debug = ((...message: any[]) => { const log = this.logger(LogLevel.debug, Color.FgBlack, ...message); if (!log) { return this.mutedLogger; } return Function.prototype.bind.call(console.log, console, ...log) as LoggerFn; })(); error = ((...message: any[]) => { const log = this.logger(LogLevel.error, Color.FgRed, ...message); if (!log) { return this.mutedLogger; } return Function.prototype.bind.call(console.log, console, ...log) as LoggerFn; })(); info = ((...message: any[]) => { const log = this.logger(LogLevel.info, Color.FgCyan, ...message); if (!log) { return this.mutedLogger; } return Function.prototype.bind.call(console.log, console, ...log) as LoggerFn; })(); warn = ((...message: any[]) => { const log = this.logger(LogLevel.warn, Color.FgYellow, ...message); if (!log) { return this.mutedLogger; } return Function.prototype.bind.call(console.log, console, ...log) as LoggerFn; })(); trace = ((...message: any[]) => { const log = this.logger(LogLevel.trace, Color.FgBlack, ...message); if (!log) { return this.mutedLogger; } return Function.prototype.bind.call(console.log, console, ...log) as LoggerFn; })(); log = ((...message: any[]) => { const log = this.logger(LogLevel.log, Color.FgWhite, ...message); if (!log) { return this.mutedLogger; } return Function.prototype.bind.call(console.log, console, ...log) as LoggerFn; })(); }
nepoche/webb.js
packages/api-providers/src/web3/anchor-deposit.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { getEVMChainNameFromInternal } from '@nepoche/api-providers/utils/index.js'; import { LoggerService } from '@nepoche/app-util/index.js'; // eslint-disable-next-line camelcase import { ERC20__factory as ERC20Factory } from '@nepoche/contracts'; import { Note, NoteGenInput } from '@nepoche/sdk-core/index.js'; import { AnchorDeposit, Currency, DepositPayload as IDepositPayload, MixerSize } from '../abstracts/index.js'; import { ChainType, chainTypeIdToInternalId, computeChainIdType, evmIdIntoInternalChainId, InternalChainId, parseChainIdType } from '../chains/index.js'; import { bufferToFixed } from '../contracts/utils/buffer-to-fixed.js'; import { createAnchor2Deposit, Deposit } from '../contracts/utils/make-deposit.js'; import { WebbGovernedToken } from '../contracts/wrappers/index.js'; import { WebbWeb3Provider } from './webb-provider.js'; const logger = LoggerService.get('web3-bridge-deposit'); type DepositPayload = IDepositPayload<Note, [Deposit, number | string, string?]>; export class Web3AnchorDeposit extends AnchorDeposit<WebbWeb3Provider, DepositPayload> { private get bridgeApi () { return this.inner.methods.anchorApi; } private get config () { return this.inner.config; } async deposit (depositPayload: DepositPayload): Promise<void> { const bridge = this.bridgeApi.activeBridge; const currency = this.bridgeApi.currency; if (!bridge || !currency) { throw new Error('api not ready'); } try { const commitment = depositPayload.params[0].commitment; const note = depositPayload.note.note; const sourceEvmId = await this.inner.getChainId(); // const _sourceChainId = computeChainIdType(ChainType.EVM, sourceEvmId); const sourceInternalId = evmIdIntoInternalChainId(sourceEvmId); this.inner.notificationHandler({ data: { amount: note.amount, chain: getEVMChainNameFromInternal(this.inner.config, Number(sourceInternalId)), currency: currency.view.name }, description: 'Depositing', key: 'bridge-deposit', level: 'loading', message: `bridge:${depositPayload.params[2] ? 'wrap and deposit' : 'deposit'}`, name: 'Transaction' }); const anchors = await this.bridgeApi.getAnchors(); // Find the Anchor for this bridge amount const anchor = anchors.find((anchor) => anchor.amount === note.amount); if (!anchor) { throw new Error('not Anchor for amount' + note.amount); } // Get the contract address for the destination chain const contractAddress = anchor.neighbours[sourceInternalId]; if (!contractAddress) { throw new Error(`No Anchor for the chain ${note.targetChainId}`); } const contract = this.inner.getWebbAnchorByAddress(contractAddress as string); // If a wrappableAsset was selected, perform a wrapAndDeposit if (depositPayload.params[2]) { const requiredApproval = await contract.isWrappableTokenApprovalRequired(depositPayload.params[2]); if (requiredApproval) { this.inner.notificationHandler({ description: 'Waiting for token approval', key: 'waiting-approval', level: 'info', message: 'Waiting for token approval', name: 'Approval', persist: true }); const tokenInstance = await ERC20Factory.connect( depositPayload.params[2], this.inner.getEthersProvider().getSigner() ); const webbToken = await contract.getWebbToken(); const tx = await tokenInstance.approve(webbToken.address, await contract.denomination); await tx.wait(); this.inner.notificationHandler.remove('waiting-approval'); } const enoughBalance = await contract.hasEnoughBalance(depositPayload.params[2]); if (enoughBalance) { await contract.wrapAndDeposit(commitment, depositPayload.params[2]); this.inner.notificationHandler({ data: { amount: note.amount, chain: getEVMChainNameFromInternal(this.inner.config, Number(sourceInternalId)), currency: currency.view.name }, description: 'Depositing', key: 'bridge-deposit', level: 'success', message: `${currency.view.name}:wrap and deposit`, name: 'Transaction' }); } else { this.inner.notificationHandler({ data: { amount: note.amount, chain: getEVMChainNameFromInternal(this.inner.config, Number(sourceInternalId)), currency: currency.view.name }, description: 'Not enough token balance', key: 'bridge-deposit', level: 'error', message: `${currency.view.name}:wrap and deposit`, name: 'Transaction' }); } return; } else { const requiredApproval = await contract.isWebbTokenApprovalRequired(); if (requiredApproval) { this.inner.notificationHandler({ description: 'Waiting for token approval', key: 'waiting-approval', level: 'info', message: 'Waiting for token approval', name: 'Approval', persist: true }); const tokenInstance = await contract.getWebbToken(); const tx = await tokenInstance.approve(contract.inner.address, await contract.denomination); await tx.wait(); this.inner.notificationHandler.remove('waiting-approval'); } const enoughBalance = await contract.hasEnoughBalance(); if (enoughBalance) { await contract.deposit(commitment); this.inner.notificationHandler({ data: { amount: note.amount, chain: getEVMChainNameFromInternal(this.inner.config, Number(sourceInternalId)), currency: currency.view.name }, description: 'Depositing', key: 'bridge-deposit', level: 'success', message: `${currency.view.name}:deposit`, name: 'Transaction' }); } else { this.inner.notificationHandler({ data: { amount: note.amount, chain: getEVMChainNameFromInternal(this.inner.config, Number(sourceInternalId)), currency: currency.view.name }, description: 'Not enough token balance', key: 'bridge-deposit', level: 'error', message: `${currency.view.name}deposit`, name: 'Transaction' }); } } } catch (e: any) { console.log(e); if ((e)?.code === 4001) { this.inner.notificationHandler.remove('waiting-approval'); this.inner.notificationHandler({ description: 'user rejected deposit', key: 'bridge-deposit', level: 'error', message: `${currency.view.name}:deposit`, name: 'Transaction' }); } else { this.inner.notificationHandler.remove('waiting-approval'); this.inner.notificationHandler({ description: 'Deposit Transaction Failed', key: 'bridge-deposit', level: 'error', message: `${currency.view.name}:deposit`, name: 'Transaction' }); } } } async getSizes (): Promise<MixerSize[]> { const anchors = await this.bridgeApi.getAnchors(); const currency = this.bridgeApi.currency; if (currency) { return anchors.map((anchor) => ({ amount: Number(anchor.amount), asset: String(currency.id), id: `Bridge=${anchor.amount}@${currency.view.name}`, title: `${anchor.amount} ${currency.view.name}` })); } return []; } async getWrappableAssets (chainId: InternalChainId): Promise<Currency[]> { const bridge = this.bridgeApi.activeBridge; logger.log('getWrappableAssets of chain: ', chainId); if (bridge) { const wrappedTokenAddress = bridge.getTokenAddress(chainId); if (!wrappedTokenAddress) return []; // Get the available token addresses which can wrap into the wrappedToken const wrappedToken = new WebbGovernedToken(this.inner.getEthersProvider(), wrappedTokenAddress); const tokenAddresses = await wrappedToken.tokens; // TODO: dynamic wrappable assets - consider some Currency constructor via address & default token config. // If the tokenAddress matches one of the wrappableCurrencies, return it const wrappableCurrencyIds = this.config.chains[chainId].currencies.filter((currencyId) => { const wrappableTokenAddress = this.config.currencies[currencyId].addresses.get(chainId); return wrappableTokenAddress && tokenAddresses.includes(wrappableTokenAddress); }); if (await wrappedToken.isNativeAllowed()) wrappableCurrencyIds.push(this.config.chains[chainId].nativeCurrencyId); const wrappableCurrencies = wrappableCurrencyIds.map((currencyId) => { return Currency.fromCurrencyId(this.inner.config.currencies, currencyId); }); return wrappableCurrencies; } return []; } /** * Generates a bridge note for the given mixer and target destination chain. * Note: If the wrappableAssetAddress is not provided, it is assumed to be * the address of the webbToken * Note: This functione expects `destChainId` is EXPLICITLY the correctly computed * target chain id with the type encoded in its value. * @param anchorID - the anchorID * @param destChainId - encoded destination chain Id and chain type * @param wrappableAssetAddress - the address of the token to wrap into the bridge * @returns */ /* * * Anchor id => the fixed deposit amount * destChainId => the Chain the token will be bridged to * If the wrappableAssetAddress is not provided, it is assumed to be the address of the webbToken * */ async generateBridgeNote ( anchorId: number | string, destChainId: number, wrappableAssetAddress?: string ): Promise<DepositPayload> { const bridge = this.bridgeApi.activeBridge; const currency = this.bridgeApi.currency; if (!bridge || !currency) { throw new Error('api not ready'); } const tokenSymbol = currency.view.symbol; const sourceEvmId = await this.inner.getChainId(); const sourceChainId = computeChainIdType(ChainType.EVM, sourceEvmId); const deposit = createAnchor2Deposit(destChainId); const srcChainInternal = evmIdIntoInternalChainId(sourceEvmId); const destChainInternal = chainTypeIdToInternalId(parseChainIdType(destChainId)); const target = currency.getAddress(destChainInternal); const srcAddress = currency.getAddress(srcChainInternal); const amount = String(anchorId).replace('Bridge=', '').split('@')[0]; const noteInput: NoteGenInput = { amount: amount, backend: 'Circom', curve: 'Bn254', denomination: '18', exponentiation: '5', hashFunction: 'Poseidon', protocol: 'anchor', secrets: `${bufferToFixed(destChainId, 6).substring(2)}:${deposit.nullifier}:${deposit.secret}`, sourceChain: sourceChainId.toString(), sourceIdentifyingData: srcAddress, targetChain: destChainId.toString(), targetIdentifyingData: target, tokenSymbol: tokenSymbol, version: 'v2', width: '4' }; logger.info(`noteInput to generateNote: ${noteInput}`); const note = await Note.generateNote(noteInput); return { note: note, params: [deposit, anchorId, wrappableAssetAddress] }; } }
nepoche/webb.js
packages/api-providers/src/webb-error/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './interactive-feedback.class.js'; export * from './webb-error.class.js';
nepoche/webb.js
examples/mixer.ts
<reponame>nepoche/webb.js<filename>examples/mixer.ts<gh_stars>0 import { ApiPromise } from '@polkadot/api'; import { WsProvider } from '@polkadot/rpc-provider'; import { options } from '@nepoche/api'; // import { Note } from '@nepoche/sdk-core'; // import { JsNote } from '@nepoche/wasm-utils/njs'; async function connectToLocalChain() { const provider = new WsProvider('wss://localhost:9944'); const api = new ApiPromise(options({ provider })); await api.isReady; return api; } (async () => { await connectToLocalChain(); process.exit(0); })();
nepoche/webb.js
packages/api-providers/src/chains/chain-id.enum.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 // must match u16 in rust export enum ChainType { EVM = 0x0100, Substrate = 0x0200, PolkadotRelayChain = 0x0301, KusamaRelayChain = 0x0302, PolkadotParachain = 0x0310, KusamaParachain = 0x0311, } export interface ChainTypeId { chainType: ChainType; chainId: EVMChainId | SubstrateChainId; } export enum SubstrateChainId { Webb = 1080, Edgeware = 7, } export enum PolkadotRelayChain { Mainnet = 0, } export enum KusamaRelayChain { Mainnet = 2, } // INTERNAL CHAIN IDS export enum InternalChainId { Edgeware, EdgewareTestNet, EdgewareLocalNet, EthereumMainNet, Rinkeby, Ropsten, Kovan, Goerli, HarmonyTestnet1, HarmonyTestnet0, HarmonyMainnet0, Ganache, Shiden, OptimismTestnet, ArbitrumTestnet, PolygonTestnet, WebbDevelopment, HermesLocalnet, AthenaLocalnet, } export enum EVMChainId { /* Default EVM Chains on MetaMask */ EthereumMainNet = 1, Ropsten = 3, Rinkeby = 4, Kovan = 42, Goerli = 5, Ganache = 1337, /* Added EVM Chains on MetaMask */ Edgeware = 2021, Beresheet = 2022, HarmonyTestnet0 = 1666700000, HarmonyTestnet1 = 1666700001, HarmonyMainnet0 = 1666600000, Shiden = 336, OptimismTestnet = 69, ArbitrumTestnet = 421611, PolygonTestnet = 80001, HermesLocalnet = 5001, AthenaLocalnet = 5002, }
nepoche/webb.js
packages/type-definitions/src/runtime.ts
<reponame>nepoche/webb.js<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export default { rpc: {}, types: { ChainId: 'u32' } };
nepoche/webb.js
packages/types/src/interfaces/merkle/definitions.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import merkle from '@nepoche/type-definitions/merkle'; import { Definitions } from '@polkadot/types/types'; export default merkle as unknown as Definitions;
nepoche/webb.js
packages/app-util/src/logger/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './logger-event.class.js'; export * from './logger-service.class.js'; export * from './logs-level.enum.js';
nepoche/webb.js
packages/api-providers/src/types/wallet-config.interface.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { ReactElement } from './abstracts.js'; export interface WalletConfig { id: number; logo: ReactElement; name: string; title: string; platform: string; // the wallet isn't live yet enabled: boolean; /// a function that will tell weather the wallet is installed or reachable detect?(): boolean | Promise<boolean>; supportedChainIds: number[]; } export type ManagedWallet = { connected: boolean; endSession(): Promise<void>; canEndSession: boolean; } & WalletConfig;
nepoche/webb.js
packages/api-providers/src/polkadot/mixer-withdraw.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */ import { OptionalActiveRelayer, OptionalRelayer, RelayedWithdrawResult, WebbRelayer, WithdrawState } from '@nepoche/api-providers/index.js'; import { fetchSubstrateTornadoProvingKey } from '@nepoche/api-providers/ipfs/substrate/tornado.js'; import { LoggerService } from '@nepoche/app-util/index.js'; import { Note, ProvingManager } from '@nepoche/sdk-core/index.js'; import { ProvingManagerSetupInput } from '@nepoche/sdk-core/proving/proving-manager-thread.js'; import { decodeAddress } from '@polkadot/keyring'; import { hexToU8a, u8aToHex } from '@polkadot/util'; import { MixerWithdraw } from '../abstracts/index.js'; import { InternalChainId } from '../chains/index.js'; import { WebbError, WebbErrorCodes } from '../webb-error/index.js'; import { PolkadotMixerDeposit } from './index.js'; import { WebbPolkadot } from './webb-provider.js'; const logger = LoggerService.get('PolkadotMixerWithdraw'); const transactionString = (hexString: string) => { return `${hexString.slice(0, 6)}...${hexString.slice(hexString.length - 4, hexString.length)}`; }; type WithdrawProof = { id: string; proofBytes: string; root: string; nullifierHash: string; recipient: string; relayer: string; fee: number; refund: number; }; export class PolkadotMixerWithdraw extends MixerWithdraw<WebbPolkadot> { readonly loading = false; readonly initialised = true; cancelWithdraw (): Promise<void> { return Promise.resolve(undefined); } get relayers () { return Promise.resolve( this.inner.relayingManager.getRelayer({ baseOn: 'substrate' }) ); } // eslint-disable-next-line @typescript-eslint/no-unused-vars async getRelayersByNote (evmNote: Note) { return Promise.resolve( this.inner.relayingManager.getRelayer({ baseOn: 'substrate' }) ); } // eslint-disable-next-line @typescript-eslint/no-unused-vars async getRelayersByChainAndAddress (_chainId: InternalChainId, _address: string) { // TODO: ! why don't we use ChainId and address? return this.inner.relayingManager.getRelayer({}); } async mapRelayerIntoActive (relayer: OptionalRelayer): Promise<OptionalActiveRelayer> { if (!relayer) { return null; } return WebbRelayer.intoActiveWebRelayer( relayer, { basedOn: 'substrate', chain: InternalChainId.WebbDevelopment }, async () => { return { totalFees: '0', withdrawFeePercentage: 0 }; } ); } async fetchTreeLeaves (treeId: string | number): Promise<Uint8Array[]> { let done = false; let from = 0; let to = 511; const leaves: Uint8Array[] = []; while (done === false) { const treeLeaves: any[] = await (this.inner.api.rpc as any).mt.getLeaves(treeId, from, to); if (treeLeaves.length === 0) { done = true; break; } leaves.push(...treeLeaves.map((i) => i.toU8a())); from = to; to = to + 511; } return leaves; } async submitViaRelayer () { return null; } async withdraw (note: string, recipient: string): Promise<string> { try { // Get the sender account const account = await this.inner.accounts.activeOrDefault; if (!account) { throw WebbError.from(WebbErrorCodes.NoAccountAvailable); } this.emit('stateChange', WithdrawState.GeneratingZk); // parse the note const noteParsed = await Note.deserialize(note); const depositAmount = noteParsed.note.amount; const amount = depositAmount; const sizes = await PolkadotMixerDeposit.getSizes(this.inner); const treeId = sizes.find((s) => s.amount === Number(amount))?.treeId!; logger.trace('Tree Id ', treeId); const leaves = await this.fetchTreeLeaves(treeId); const leaf = u8aToHex(noteParsed.getLeaf()); const leafIndex = leaves.findIndex((l) => u8aToHex(l) === leaf); logger.trace(`leaf ${leaf} has index `, leafIndex); logger.trace(leaves.map((i) => u8aToHex(i))); const activeRelayer = this.activeRelayer[0]; const worker = this.inner.wasmFactory('wasm-utils'); const pm = new ProvingManager(worker); const recipientAccountHex = u8aToHex(decodeAddress(recipient)); // ss58 format const relayerAccountId = activeRelayer ? activeRelayer.beneficiary! : recipient; const relayerAccountHex = u8aToHex(decodeAddress(relayerAccountId)); // fetching the proving key const provingKey = await fetchSubstrateTornadoProvingKey(); const isValidRelayer = Boolean(activeRelayer && activeRelayer.beneficiary); const proofInput: ProvingManagerSetupInput = { fee: 0, leafIndex, leaves, note, provingKey, recipient: recipientAccountHex.replace('0x', ''), refund: 0, relayer: relayerAccountHex.replace('0x', '') }; if (isValidRelayer) { this.inner.notificationHandler({ description: `Withdraw through ${activeRelayer!.endpoint} in progress`, key: 'mixer-withdraw-sub', level: 'loading', message: 'mixerBn254:withdraw', name: 'Transaction' }); } const zkProofMetadata = await pm.prove(proofInput); const withdrawProof: WithdrawProof = { fee: 0, id: String(treeId), nullifierHash: `0x${zkProofMetadata.nullifierHash}`, proofBytes: `0x${zkProofMetadata.proof}` as any, recipient: recipient, refund: 0, relayer: relayerAccountId, root: `0x${zkProofMetadata.root}` }; // withdraw throw relayer if (isValidRelayer) { logger.info('withdrawing through relayer', activeRelayer); this.emit('stateChange', WithdrawState.SendingTransaction); const relayerMixerTx = await activeRelayer!.initWithdraw('mixerRelayTx'); const relayerWithdrawPayload = relayerMixerTx.generateWithdrawRequest( { baseOn: 'substrate', contractAddress: '', endpoint: '', // TODO change this from the config name: 'localnode' }, Array.from(hexToU8a(withdrawProof.proofBytes)), { chain: 'localnode', fee: withdrawProof.fee, id: Number(treeId), nullifierHash: Array.from(hexToU8a(withdrawProof.nullifierHash)), recipient: withdrawProof.recipient, refund: withdrawProof.refund, relayer: withdrawProof.relayer, root: Array.from(hexToU8a(withdrawProof.root)) } ); relayerMixerTx.watcher.subscribe(([results, message]) => { switch (results) { case RelayedWithdrawResult.PreFlight: this.emit('stateChange', WithdrawState.SendingTransaction); break; case RelayedWithdrawResult.OnFlight: break; case RelayedWithdrawResult.Continue: break; case RelayedWithdrawResult.CleanExit: this.emit('stateChange', WithdrawState.Done); this.emit('stateChange', WithdrawState.Ideal); this.inner.notificationHandler({ description: `TX hash: ${transactionString(message || '')}`, key: 'mixer-withdraw-sub', level: 'success', message: 'mixerBn254:withdraw', name: 'Transaction' }); break; case RelayedWithdrawResult.Errored: this.emit('stateChange', WithdrawState.Failed); this.emit('stateChange', WithdrawState.Ideal); this.inner.notificationHandler({ description: message || 'Withdraw failed', key: 'mixer-withdraw-sub', level: 'success', message: 'mixerBn254:withdraw', name: 'Transaction' }); break; } }); this.inner.notificationHandler({ description: 'Sending TX to relayer', key: 'mixer-withdraw-sub', level: 'loading', message: 'mixerBn254:withdraw', name: 'Transaction' }); relayerMixerTx.send(relayerWithdrawPayload); const results = await relayerMixerTx.await(); if (results) { const [, message] = results; return message ?? ''; } return ''; } logger.trace('submitting the transaction of withdraw with params', withdrawProof); this.emit('stateChange', WithdrawState.SendingTransaction); const tx = this.inner.txBuilder.build( { method: 'withdraw', section: 'mixerBn254' }, [ withdrawProof.id, withdrawProof.proofBytes, withdrawProof.root, withdrawProof.nullifierHash, withdrawProof.recipient, withdrawProof.relayer, withdrawProof.fee, withdrawProof.refund ] ); const hash = await tx.call(account.address); this.emit('stateChange', WithdrawState.Done); return hash || ''; } catch (e) { this.emit('error', 'Failed to generate zero knowledge proof'); this.emit('stateChange', WithdrawState.Failed); throw e; } } }
nepoche/webb.js
packages/api-providers/src/polkadot/anchor-api.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { Currency } from '@nepoche/api-providers/index.js'; import { AnchorApi, AnchorBase } from '../abstracts/index.js'; import { ChainTypeId } from '../chains/index.js'; import { BridgeConfig } from '../types/bridge-config.interface.js'; import { CurrencyRole, CurrencyType } from '../types/currency-config.interface.js'; import { WebbPolkadot } from './webb-provider.js'; export class PolkadotAnchorApi extends AnchorApi<WebbPolkadot, BridgeConfig> { private get activeBridgeAsset () { return this.store.activeBridge?.asset ?? null; } // eslint-disable-next-line @typescript-eslint/no-unused-vars getTokenAddress (chainId: ChainTypeId): string | null { return null; } async getCurrencies (): Promise<Currency[]> { const bridgeCurrenciesConfig = Object.values(this.inner.config.currencies).filter((i) => { const isValid = i.type === CurrencyType.ORML && i.role === CurrencyRole.Governable; // TODO : Validate whether the chain supports the token const isSupported = true; return isValid && isSupported; }); return bridgeCurrenciesConfig.map((config) => { return Currency.fromCurrencyId(this.inner.config.currencies, config.id); }); } get currency (): Currency | null { return this.activeBridgeAsset ? Currency.fromCurrencyId(this.inner.config.currencies, this.activeBridgeAsset) : null; } async getAnchors (): Promise<AnchorBase[]> { return ( this.store.activeBridge?.anchors.map((anchor) => ({ amount: anchor.amount, neighbours: anchor.anchorTreeIds })) ?? [] ); } // eslint-disable-next-line @typescript-eslint/no-unused-vars async getWrappableAssets (chainId: ChainTypeId): Promise<Currency[]> { return []; } }
nepoche/webb.js
packages/sdk-core/src/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './fixed-point-number.js'; export * from './proving/index.js'; export * from './note.js'; export * from './token.js';
nepoche/webb.js
packages/api-providers/src/utils/anchor-utils.ts
<filename>packages/api-providers/src/utils/anchor-utils.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { AppConfig } from '@nepoche/api-providers/index.js'; import { InternalChainId } from '../chains/index.js'; import { WebbCurrencyId } from '../enums/index.js'; export const getAnchorAddressForBridge = ( assetId: WebbCurrencyId, chainId: number, amount: number, bridgeConfigByAsset: AppConfig['bridgeByAsset'] ): string | undefined => { const linkedAnchorConfig = bridgeConfigByAsset[assetId]?.anchors.find( (anchor) => anchor.amount === amount.toString() ); if (!linkedAnchorConfig) { throw new Error('Unsupported configuration for bridge'); } const anchorAddress = linkedAnchorConfig.anchorAddresses[chainId as InternalChainId]; return anchorAddress; };
nepoche/webb.js
packages/api-providers/src/web3/webb-provider.ts
<filename>packages/api-providers/src/web3/webb-provider.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { AppConfig, MixerSize, NotificationHandler, Web3AnchorDeposit, WebbApiProvider, WebbMethods, WebbProviderEvents, WebbRelayerBuilder } from '@nepoche/api-providers/index.js'; import { EventBus } from '@nepoche/app-util/index.js'; import { Note } from '@nepoche/sdk-core'; import { providers } from 'ethers'; import { Eth } from 'web3-eth'; import { AccountsAdapter } from '../account/Accounts.adapter.js'; import { EVMChainId, evmIdIntoInternalChainId, parseChainIdType } from '../chains/index.js'; import { AnchorContract, TornadoContract } from '../contracts/wrappers/index.js'; import { Web3Accounts, Web3Provider } from '../ext-providers/index.js'; import { WebbError, WebbErrorCodes } from '../webb-error/index.js'; import { Web3AnchorApi } from './anchor-api.js'; import { Web3AnchorWithdraw } from './anchor-withdraw.js'; import { Web3ChainQuery } from './chain-query.js'; import { EvmChainMixersInfo } from './EvmChainMixersInfo.js'; import { Web3MixerDeposit } from './mixer-deposit.js'; import { Web3MixerWithdraw } from './mixer-withdraw.js'; import { Web3WrapUnwrap } from './wrap-unwrap.js'; export class WebbWeb3Provider extends EventBus<WebbProviderEvents<[number]>> implements WebbApiProvider<WebbWeb3Provider> { readonly methods: WebbMethods<WebbWeb3Provider>; private ethersProvider: providers.Web3Provider; private connectedMixers: EvmChainMixersInfo; // TODO: make the factory configurable if the web3 interface in need of this functionality readonly wasmFactory = () => { return null; }; private constructor ( private web3Provider: Web3Provider, protected chainId: number, readonly relayingManager: WebbRelayerBuilder, readonly config: AppConfig, readonly notificationHandler: NotificationHandler, readonly accounts: AccountsAdapter<Eth> ) { super(); this.ethersProvider = web3Provider.intoEthersProvider(); // TODO: fix types // Remove listeners for chainChanged on the previous object // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore this.ethersProvider.provider?.removeAllListeners('chainChanged'); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore this.ethersProvider.provider?.on?.('accountsChanged', () => { this.emit('newAccounts', this.accounts); }); this.connectedMixers = new EvmChainMixersInfo(this.config, chainId); this.methods = { anchor: { core: null, deposit: { enabled: true, inner: new Web3AnchorDeposit(this) }, withdraw: { enabled: true, inner: new Web3AnchorWithdraw(this) } }, anchorApi: new Web3AnchorApi(this, this.config.bridgeByAsset), chainQuery: new Web3ChainQuery(this), mixer: { deposit: { enabled: true, inner: new Web3MixerDeposit(this) }, withdraw: { enabled: true, inner: new Web3MixerWithdraw(this) } }, wrapUnwrap: { core: { enabled: true, inner: new Web3WrapUnwrap(this) } } }; } getProvider (): Web3Provider { return this.web3Provider; } async setChainListener () { this.ethersProvider = this.web3Provider.intoEthersProvider(); const handler = async () => { const chainId = await this.web3Provider.network; this.emit('providerUpdate', [chainId]); }; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore this.ethersProvider.provider?.on?.('chainChanged', handler); } setStorage (chainId: number) { this.connectedMixers = new EvmChainMixersInfo(this.config, chainId); } async destroy (): Promise<void> { await this.endSession(); this.subscriptions = { interactiveFeedback: [], providerUpdate: [] }; } async getChainId (): Promise<number> { const chainId = (await this.ethersProvider.getNetwork()).chainId; return chainId; } getMixers () { return this.connectedMixers; } getTornadoContractAddressByNote (note: Note) { const evmId = parseChainIdType(Number(note.note.targetChainId)).chainId as EVMChainId; const availableMixers = new EvmChainMixersInfo(this.config, evmId); const mixer = availableMixers.getTornMixerInfoBySize(Number(note.note.amount), note.note.tokenSymbol); if (!mixer) { throw new Error('Mixer not found'); } return mixer.address; } async getContractByAddress (mixerAddress: string): Promise<TornadoContract> { return new TornadoContract(this.connectedMixers, this.ethersProvider, mixerAddress); } getWebbAnchorByAddress (address: string): AnchorContract { return new AnchorContract(this.connectedMixers, this.ethersProvider, address); } getWebbAnchorByAddressAndProvider (address: string, provider: providers.Web3Provider): AnchorContract { return new AnchorContract(this.connectedMixers, provider, address, true); } getMixerInfoBySize (mixerSize: number, tokenSymbol: string) { const mixer = this.connectedMixers.getTornMixerInfoBySize(mixerSize, tokenSymbol); if (!mixer) { throw WebbError.from(WebbErrorCodes.MixerSizeNotFound); } return mixer; } // This function limits the mixer implementation to one type for the token/size pair. // Something like a poseidon hasher implementation instead of mimc hasher cannot // exist alongside each other. async getContractBySize (mixerSize: number, tokenSymbol: string): Promise<TornadoContract> { const mixer = this.connectedMixers.getTornMixerInfoBySize(mixerSize, tokenSymbol); if (!mixer) { throw WebbError.from(WebbErrorCodes.MixerSizeNotFound); } return new TornadoContract(this.connectedMixers, this.ethersProvider, mixer.address); } getEthersProvider (): providers.Web3Provider { return this.ethersProvider; } getMixerSizes (tokenSymbol: string): Promise<MixerSize[]> { return Promise.resolve(this.connectedMixers.getTornMixerSizes(tokenSymbol)); } // Init web3 provider with the `Web3Accounts` as the default account provider static async init ( web3Provider: Web3Provider, chainId: number, relayerBuilder: WebbRelayerBuilder, appConfig: AppConfig, notification: NotificationHandler ) { const accounts = new Web3Accounts(web3Provider.eth); return new WebbWeb3Provider(web3Provider, chainId, relayerBuilder, appConfig, notification, accounts); } // Init web3 provider with a generic account provider static async initWithCustomAccountAdapter ( web3Provider: Web3Provider, chainId: number, relayerBuilder: WebbRelayerBuilder, appConfig: AppConfig, notification: NotificationHandler, web3AccountProvider: AccountsAdapter<Eth> ) { return new WebbWeb3Provider(web3Provider, chainId, relayerBuilder, appConfig, notification, web3AccountProvider); } get capabilities () { return this.web3Provider.capabilities; } endSession (): Promise<void> { return this.web3Provider.endSession(); } switchOrAddChain (evmChainId: number) { return this.web3Provider .switchChain({ chainId: `0x${evmChainId.toString(16)}` }) ?.catch(async (switchError) => { console.log('inside catch for switchChain', switchError); // cannot switch because network not recognized, so fetch configuration const chainId = evmIdIntoInternalChainId(evmChainId); const chain = this.config.chains[chainId]; // prompt to add the chain if (switchError.code === 4902) { const currency = this.config.currencies[chain.nativeCurrencyId]; await this.web3Provider.addChain({ chainId: `0x${evmChainId.toString(16)}`, chainName: chain.name, nativeCurrency: { decimals: 18, name: currency.name, symbol: currency.symbol }, rpcUrls: chain.evmRpcUrls! }); // add network will prompt the switch, check evmId again and throw if user rejected const newChainId = await this.web3Provider.network; if (newChainId !== chain.chainId) { throw switchError; } } else { throw switchError; } }); } public get innerProvider () { return this.web3Provider; } }
nepoche/webb.js
packages/api-providers/src/web3/chain-query.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { Currency } from '@nepoche/api-providers/index.js'; import { ERC20__factory as ERC20Factory } from '@nepoche/contracts'; import { ethers } from 'ethers'; import { ChainQuery } from '../abstracts/index.js'; import { evmIdIntoInternalChainId } from '../chains/index.js'; import { zeroAddress } from '../contracts/wrappers/index.js'; import { WebbCurrencyId } from '../enums/index.js'; import { WebbWeb3Provider } from './webb-provider.js'; export class Web3ChainQuery extends ChainQuery<WebbWeb3Provider> { constructor (protected inner: WebbWeb3Provider) { super(inner); } private get config () { return this.inner.config; } async tokenBalanceByCurrencyId (currencyId: WebbCurrencyId): Promise<string> { const provider = this.inner.getEthersProvider(); // check if the token is the native token of this chain const { chainId: evmId } = await provider.getNetwork(); const webbChain = evmIdIntoInternalChainId(evmId); const accounts = await this.inner.accounts.accounts(); if (!accounts || !accounts.length) { console.log('no account selected'); return ''; } // Return the balance of the account if native currency if (this.config.chains[webbChain].nativeCurrencyId === currencyId) { const tokenBalanceBig = await provider.getBalance(accounts[0].address); const tokenBalance = ethers.utils.formatEther(tokenBalanceBig); return tokenBalance; } else { // Find the currency address on this chain const currency = Currency.fromCurrencyId(this.inner.config, currencyId); const currencyOnChain = currency.getAddress(webbChain); if (!currencyOnChain) return ''; // Create a token instance for this chain const tokenInstance = ERC20Factory.connect(currencyOnChain, provider); const tokenBalanceBig = await tokenInstance.balanceOf(accounts[0].address); const tokenBalance = ethers.utils.formatEther(tokenBalanceBig); return tokenBalance; } } async tokenBalanceByAddress (address: string): Promise<string> { const provider = this.inner.getEthersProvider(); const accounts = await this.inner.accounts.accounts(); if (!accounts || !accounts.length) { console.log('no account selected'); return ''; } // Return the balance of the account if native currency if (address === zeroAddress) { const tokenBalanceBig = await provider.getBalance(accounts[0].address); const tokenBalance = ethers.utils.formatEther(tokenBalanceBig); return tokenBalance; } else { // Create a token instance for this chain const tokenInstance = ERC20Factory.connect(address, provider); const tokenBalanceBig = await tokenInstance.balanceOf(accounts[0].address); const tokenBalance = ethers.utils.formatEther(tokenBalanceBig); return tokenBalance; } } }
nepoche/webb.js
packages/api-providers/src/webb-error/interactive-feedback.class.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { EventBus } from '@nepoche/app-util/index.js'; export type FeedbackLevel = 'error' | 'info' | 'warning' | 'success'; export type Action = { /// indication for the Action level to show action controller in a meaning way level: FeedbackLevel; /// trigger the callback for the action onTrigger(): any; /// action name unique for each action of the actions record name: string; /// Used to know which action is registered id: string | null; }; /// This will be iterated over and generate content for the feedback export type FeedbackEntry = { /// Text element could be a <p/> for instance content?: string; /// JS object json?: Record<string, unknown>; /// Header text element header?: string; /// list of strings list?: string[]; /// A function that will return a dynamic value any?(): any; }; /// an object will be used to build the feedback UI export type FeedbackBody = FeedbackEntry[]; /// A builder class to build the `Action` for the `InteractiveFeedback` export class ActionsBuilder { /// list of actions of the `ActionsBuilder` private _actions: Record<string, Action> = {}; /// Static method for `init` static init () { return new ActionsBuilder(); } /// Adds an action for the builder actions action (name: string, handler: () => any, level: FeedbackLevel = 'info', id: string | null = null): ActionsBuilder { this._actions[name] = { id, level, name, onTrigger: handler }; return this; } /// Access the actions to pass them to the constructor of the interactive feedback actions () { return this._actions; } } /// InteractiveFeedback a class that wrappers and error metadata and provide handlers for it /// A `canceled` event is trigger only once, when the state changes to be`_canceled=true` export class InteractiveFeedback extends EventBus<{ canceled: InteractiveFeedback }> { private _canceled = false; private selectedAction: Action | null = null; /// Create a new action builder for the InteractiveFeedback static actionsBuilder () { return ActionsBuilder.init(); } /// Create the body for the InteractiveFeedback static feedbackEntries (feedbackBody: FeedbackBody): FeedbackBody { return feedbackBody; } constructor ( /// Level of the InteractiveFeedback for customised view public readonly level: FeedbackLevel, /// Actions available for the InteractiveFeedback instance without the cancel action public readonly actions: Record<string, Action>, /// handler for the cancel action this is trigger when `interactiveFeedback.cancel` is called private readonly _onCancel: () => any, /// The body of the interactive feedback showing the message public readonly feedbackBody: FeedbackBody, /// this can be used to identify the feedback by reason and hide it public reason?: number | string ) { super(); } /// getter for the user to know if this is canceled get canceled () { return this._canceled; } /// cancel without calling the onCancel handler cancelWithoutHandler () { if (this._canceled) { return; } /// change the state of the interactive feedback to be canceled to prevent from a re-trigger this._canceled = true; /// emit `canceled` event this.emit('canceled', this); } /// cancel this will trigger the `canceled` event and set the interactiveFeedback as canceled cancel () { if (this._canceled) { return; } /// change the state of the interactive feedback to be canceled to prevent from a re-trigger this._canceled = true; /// emit `canceled` event this.emit('canceled', this); /// call the cancel handler this._onCancel(); } trigger<ActionKey extends keyof this['actions']> (key: ActionKey) { if (this._canceled) { return; } // @ts-ignore const action = this.actions[key] as Action; if (action) { this.selectedAction = action; return action.onTrigger?.(); } } wait (): Promise<Action | null> { if (this._canceled) { return Promise.resolve(null); } return new Promise((resolve) => { this.on('canceled', () => { resolve(this.selectedAction); }); }); } }
nepoche/webb.js
packages/api-providers/src/contracts/utils/witness-calculator.ts
/* eslint-disable */ // @ts-nocheck // TODO resole eslint issue and merge this to protocol solidity // @ts-ignore module.exports = async function builder(code, options) { options = options || {}; const wasmModule = await WebAssembly.compile(code); let wc; const instance = await WebAssembly.instantiate(wasmModule, { runtime: { exceptionHandler: function (code) { let errStr; if (code == 1) { errStr = 'Signal not found. '; } else if (code == 2) { errStr = 'Too many signals set. '; } else if (code == 3) { errStr = 'Signal already set. '; } else if (code == 4) { errStr = 'Assert Failed. '; } else if (code == 5) { errStr = 'Not enough memory. '; } else { errStr = 'Unknown error\n'; } // get error message from wasm errStr += getMessage(); throw new Error(errStr); }, showSharedRWMemory: function () { printSharedRWMemory(); }, }, }); const sanityCheck = options; // options && // ( // options.sanityCheck || // options.logGetSignal || // options.logSetSignal || // options.logStartComponent || // options.logFinishComponent // ); wc = new WitnessCalculator(instance, sanityCheck); return wc; function getMessage() { var message = ''; var c = instance.exports.getMessageChar(); while (c != 0) { message += String.fromCharCode(c); c = instance.exports.getMessageChar(); } return message; } function printSharedRWMemory() { const shared_rw_memory_size = instance.exports.getFieldNumLen32(); const arr = new Uint32Array(shared_rw_memory_size); for (let j = 0; j < shared_rw_memory_size; j++) { arr[shared_rw_memory_size - 1 - j] = instance.exports.readSharedRWMemory(j); } console.log(fromArray32(arr)); } }; class WitnessCalculator { constructor(instance, sanityCheck) { this.instance = instance; this.version = this.instance.exports.getVersion(); this.n32 = this.instance.exports.getFieldNumLen32(); this.instance.exports.getRawPrime(); const arr = new Array(this.n32); for (let i = 0; i < this.n32; i++) { arr[this.n32 - 1 - i] = this.instance.exports.readSharedRWMemory(i); } this.prime = fromArray32(arr); this.witnessSize = this.instance.exports.getWitnessSize(); this.sanityCheck = sanityCheck; } circom_version() { return this.instance.exports.getVersion(); } async _doCalculateWitness(input, sanityCheck) { //input is assumed to be a map from signals to arrays of bigints this.instance.exports.init(this.sanityCheck || sanityCheck ? 1 : 0); const keys = Object.keys(input); keys.forEach((k) => { const h = fnvHash(k); const hMSB = parseInt(h.slice(0, 8), 16); const hLSB = parseInt(h.slice(8, 16), 16); const fArr = flatArray(input[k]); for (let i = 0; i < fArr.length; i++) { const arrFr = toArray32(fArr[i], this.n32); for (let j = 0; j < this.n32; j++) { this.instance.exports.writeSharedRWMemory(j, arrFr[this.n32 - 1 - j]); } try { this.instance.exports.setInputSignal(hMSB, hLSB, i); } catch (err) { // console.log(`After adding signal ${i} of ${k}`) throw new Error(err); } } }); } async calculateWitness(input, sanityCheck) { const w = []; await this._doCalculateWitness(input, sanityCheck); for (let i = 0; i < this.witnessSize; i++) { this.instance.exports.getWitness(i); const arr = new Uint32Array(this.n32); for (let j = 0; j < this.n32; j++) { arr[this.n32 - 1 - j] = this.instance.exports.readSharedRWMemory(j); } w.push(fromArray32(arr)); } return w; } async calculateBinWitness(input, sanityCheck) { const buff32 = new Uint32Array(this.witnessSize * this.n32); const buff = new Uint8Array(buff32.buffer); await this._doCalculateWitness(input, sanityCheck); for (let i = 0; i < this.witnessSize; i++) { this.instance.exports.getWitness(i); const pos = i * this.n32; for (let j = 0; j < this.n32; j++) { buff32[pos + j] = this.instance.exports.readSharedRWMemory(j); } } return buff; } async calculateWTNSBin(input, sanityCheck) { const buff32 = new Uint32Array(this.witnessSize * this.n32 + this.n32 + 11); const buff = new Uint8Array(buff32.buffer); await this._doCalculateWitness(input, sanityCheck); //"wtns" buff[0] = 'w'.charCodeAt(0); buff[1] = 't'.charCodeAt(0); buff[2] = 'n'.charCodeAt(0); buff[3] = 's'.charCodeAt(0); //version 2 buff32[1] = 2; //number of sections: 2 buff32[2] = 2; //id section 1 buff32[3] = 1; const n8 = this.n32 * 4; //id section 1 length in 64bytes const idSection1length = 8 + n8; const idSection1lengthHex = idSection1length.toString(16); buff32[4] = parseInt(idSection1lengthHex.slice(0, 8), 16); buff32[5] = parseInt(idSection1lengthHex.slice(8, 16), 16); //this.n32 buff32[6] = n8; //prime number this.instance.exports.getRawPrime(); var pos = 7; for (let j = 0; j < this.n32; j++) { buff32[pos + j] = this.instance.exports.readSharedRWMemory(j); } pos += this.n32; // witness size buff32[pos] = this.witnessSize; pos++; //id section 2 buff32[pos] = 2; pos++; // section 2 length const idSection2length = n8 * this.witnessSize; const idSection2lengthHex = idSection2length.toString(16); buff32[pos] = parseInt(idSection2lengthHex.slice(0, 8), 16); buff32[pos + 1] = parseInt(idSection2lengthHex.slice(8, 16), 16); pos += 2; for (let i = 0; i < this.witnessSize; i++) { this.instance.exports.getWitness(i); for (let j = 0; j < this.n32; j++) { buff32[pos + j] = this.instance.exports.readSharedRWMemory(j); } pos += this.n32; } return buff; } } function toArray32(s, size) { const res = []; //new Uint32Array(size); //has no unshift let rem = BigInt(s); const radix = BigInt(0x100000000); while (rem) { res.unshift(Number(rem % radix)); rem = rem / radix; } if (size) { var i = size - res.length; while (i > 0) { res.unshift(0); i--; } } return res; } function fromArray32(arr) { //returns a BigInt var res = BigInt(0); const radix = BigInt(0x100000000); for (let i = 0; i < arr.length; i++) { res = res * radix + BigInt(arr[i]); } return res; } function flatArray(a) { var res = []; fillArray(res, a); return res; function fillArray(res, a) { if (Array.isArray(a)) { for (let i = 0; i < a.length; i++) { fillArray(res, a[i]); } } else { res.push(a); } } } function fnvHash(str) { const uint64_max = BigInt(2) ** BigInt(64); let hash = BigInt('0xCBF29CE484222325'); for (var i = 0; i < str.length; i++) { hash ^= BigInt(str[i].charCodeAt()); hash *= BigInt(0x100000001b3); hash %= uint64_max; } let shash = hash.toString(16); let n = 16 - shash.length; shash = '0'.repeat(n).concat(shash); return shash; }
nepoche/webb.js
packages/api-providers/src/contracts/utils/pedersen-hash.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 // eslint-disable-next-line @typescript-eslint/no-var-requires // @ts-ignore import circomlib from 'tornado-circomlib'; export function pedersenHash (data: Uint8Array) { return circomlib.babyJub.unpackPoint(circomlib.pedersenHash.hash(data))[0]; }
nepoche/webb.js
packages/sdk-core/src/fixed-point-number.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import BigNumber from 'bignumber.js'; /** * @constant * @type {(0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8)} * @description * | Value | Property | Description | * | 0 | ROUND_UP | Rounds away from zero | * | 1 | ROUND_DOWN | Rounds towards zero | * | 2 | ROUND_CEIL | Rounds towards Infinity | * | 3 | ROUND_FLOOR | Rounds towards -Infinity | * | 4 | ROUND_HALF_UP | Rounds towards nearest neighbour, If equidistant, rounds away form zero | * | 5 | ROUND_HALF_DOWN | Rounds towards nearest neighbour, If equidistant, rounds towards zero | * | 6 | ROUND_HALF_EVEN | Rounds towards nearest neighbour, If equidistant, rounds towards even zero | * | 7 | ROUND_HALF_CEIL | Rounds towards nearest neighbour, If equidistant, rounds towards Infinity | * | 8 | ROUND_HALF_FLOOR | Rounds towards nearest neighbour, If equidistant, rounds towards -Infinity | */ export type ROUND_MODE = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; // generate function from BN class function genFnFromBigNumber<T extends keyof BigNumber, U extends boolean> ( fn: T, noRight: U ): BigNumber[typeof fn] extends (...params: any) => any ? typeof noRight extends true ? () => ReturnType<BigNumber[typeof fn]> : (right: FixedPointNumber) => ReturnType<BigNumber[typeof fn]> : () => any { if (noRight) { return function (): number { /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/ban-ts-comment */ // @ts-ignore return this.inner[fn](); /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/ban-ts-comment */ } as any; } return function (right: FixedPointNumber) { /* eslint-disable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/ban-ts-comment */ // @ts-ignore this.alignPrecision(right); // @ts-ignore return this.inner[fn](right._getInner()); /* eslint-enable @typescript-eslint/no-unsafe-member-access, @typescript-eslint/ban-ts-comment */ } as any; } const BN = BigNumber.clone(); export class FixedPointNumber { private precision!: number; private inner: BigNumber; constructor (origin: number | string, precision = 18) { if (typeof origin !== 'number' && typeof origin !== 'string') { throw new Error('FixedPointNumber constructor should use number or string'); } this.precision = precision; this.inner = new BN(origin).shiftedBy(this.precision); } /** * @name fromRational * @description constructor form inner */ public static fromRational ( numerator: number | string | FixedPointNumber, denominator: number | string | FixedPointNumber, precision = 18 ): FixedPointNumber { const _numerator = numerator instanceof FixedPointNumber ? numerator._getInner() : new BN(numerator); const _denominator = denominator instanceof FixedPointNumber ? denominator._getInner() : new BN(denominator); const inner = _numerator.times(10 ** precision).div(_denominator); const temp = new FixedPointNumber(0, precision); temp._setInner(inner); return temp; } /** * @name fromInner * @description constructor form inner */ public static fromInner (origin: number | string, precision = 18): FixedPointNumber { const inner = new BN(origin); const temp = new FixedPointNumber(0, precision); temp._setInner(inner); return temp; } /** * @name _fromBN * @description constructor from BN */ public static _fromBN (origin: BigNumber, precision = 18): FixedPointNumber { const temp = new FixedPointNumber(0, precision); temp._setInner(origin); return temp; } // set inner directly public _setInner (origin: BigNumber): void { this.inner = origin; } // get inner public _getInner (): BigNumber { return this.inner; } private setMode (dp = 0, rm = 3): void { BN.config({ DECIMAL_PLACES: dp, EXPONENTIAL_AT: [-100, 100], ROUNDING_MODE: rm as ROUND_MODE }); } /** * @name toNumber */ public toNumber (dp = 8, rm = 3): number { this.setMode(); return this.inner .shiftedBy(-this.precision) .dp(dp, rm as any) .toNumber(); } /** * @name toStirng */ public toString (dp = 0, rm = 3): string { this.setMode(dp, rm); return this.inner.shiftedBy(-this.precision).toString(); } /** * @name toChainData */ public toChainData (): string { return this.inner.toFixed(0, 3); } /** * @name trunc */ public trunc (): FixedPointNumber { this.setMode(); const DIV = 10 ** this.precision; const inner = this._getInner().abs().div(DIV).dp(0, 3).times(DIV); if (this.isNegative()) { return FixedPointNumber._fromBN(inner.negated()); } else { return FixedPointNumber._fromBN(inner); } } /** * @name frac */ public frac (): FixedPointNumber { const integer = this.trunc(); const fractional = this.minus(integer); if (integer.isZero()) { return fractional; } else { return fractional.abs(); } } // set b's precision to this.precision private alignPrecision (b: FixedPointNumber): void { if (this.precision !== b.precision) { b.setPrecision(this.precision); } } /** * @name setPrecision * @description change the precision and modify the inner */ public setPrecision (precision: number): void { const oldPrecision = this.precision; this.precision = precision; // formula: new inner = old inner / old precision * new precision this._setInner(this.inner.shiftedBy(this.precision - oldPrecision)); } /** * @name getPrecision * @description get the precision */ public getPrecision (): number { return this.precision; } /** * @name abs * @description return a FixedPointNumber whose inner value is the absolute value */ public abs (): FixedPointNumber { return FixedPointNumber._fromBN(this.inner.abs(), this.precision); } /** * @name plus * @description return a FixedPointNumber whose value is origin value plus right value */ public plus (right: FixedPointNumber): FixedPointNumber { this.alignPrecision(right); this.setMode(); return FixedPointNumber._fromBN(this.inner.plus(right.inner), this.precision); } /** * @name minus * @description return a FixedPointNumber whose value is origin value minus right value */ public minus (right: FixedPointNumber): FixedPointNumber { this.alignPrecision(right); this.setMode(); return FixedPointNumber._fromBN(this.inner.minus(right.inner), this.precision); } /** * @name times * @description return a FixedPointNumber whose value is origin value times right value */ public times (right: FixedPointNumber): FixedPointNumber { this.alignPrecision(right); this.setMode(); return FixedPointNumber._fromBN(this.inner.times(right.inner).shiftedBy(-this.precision), this.precision); } /** * @name div * @description return a FixedPointNumber whose value is origin value div right value */ public div (right: FixedPointNumber): FixedPointNumber { this.alignPrecision(right); this.setMode(); return FixedPointNumber._fromBN(this.inner.shiftedBy(this.precision).div(right.inner), this.precision); } /** * @name reciprocal */ public reciprocal (): FixedPointNumber { return FixedPointNumber.ONE.div(this); } /** * @name isGreaterThan */ public isGreaterThan = genFnFromBigNumber('isGreaterThan', false).bind(this); /** * @name isGreaterThanOrEqualTo */ public isGreaterThanOrEqualTo = genFnFromBigNumber('isGreaterThanOrEqualTo', false).bind(this); /** * @name isLessThan */ public isLessThan = genFnFromBigNumber('isLessThan', false).bind(this); /** * @name isLessOrEqualTo */ public isLessOrEqualTo = genFnFromBigNumber('isLessThanOrEqualTo', false).bind(this); /** * @name isEqualTo */ public isEqualTo = genFnFromBigNumber('isEqualTo', false).bind(this); /** * @name isZero */ public isZero = genFnFromBigNumber('isZero', true).bind(this); /** * @name isNaN */ public isNaN = genFnFromBigNumber('isNaN', true).bind(this); /** * @name isFinaite */ public isFinaite = genFnFromBigNumber('isFinite', true).bind(this); /** * @name isNegative */ public isNegative = genFnFromBigNumber('isNegative', true).bind(this); /** * @name isPositive */ public isPositive = genFnFromBigNumber('isPositive', true).bind(this); /** * @name min */ public min (...targets: FixedPointNumber[]): FixedPointNumber { targets.forEach((item) => this.alignPrecision(item)); return FixedPointNumber._fromBN( BigNumber.min.apply(null, [this.inner, ...targets.map((i) => i._getInner())]), this.precision ); } /** * @name max */ public max (...targets: FixedPointNumber[]): FixedPointNumber { targets.forEach((item) => this.alignPrecision(item)); return FixedPointNumber._fromBN( BigNumber.max.apply(null, [this.inner, ...targets.map((i) => i._getInner())]), this.precision ); } static ZERO = new FixedPointNumber(0); static ONE = new FixedPointNumber(1); static TWO = new FixedPointNumber(2); static THREE = new FixedPointNumber(3); static FOUR = new FixedPointNumber(3); static FIVE = new FixedPointNumber(5); static SIX = new FixedPointNumber(6); static TEN = new FixedPointNumber(10); }
nepoche/webb.js
packages/api-providers/src/abstracts/webb-content-state.interface.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { Chain, Wallet } from './common.js'; import { WebbApiProvider } from './webb-provider.interface.js'; export interface WebbContextState<T = unknown> { wallets: Record<number, Wallet>; chains: Record<number, Chain>; activeApi?: WebbApiProvider<T>; activeWallet?: Wallet; activeChain?: Chain; setActiveChain(id: number): void; setActiveWallet(id: number): void; }
nepoche/webb.js
packages/api-providers/src/abstracts/common.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { AnchorConfigEntry } from '../types/anchor-config.interface.js'; import { BridgeConfig } from '../types/bridge-config.interface.js'; import { ChainConfig } from '../types/chain-config.interface.js'; import { CurrencyConfig } from '../types/currency-config.interface.js'; import { MixerConfig } from '../types/mixer-config.interface.js'; import { WalletConfig } from '../types/wallet-config.interface.js'; export type Chain = ChainConfig & { wallets: Record<number, Wallet>; }; export type Wallet = WalletConfig; export type AppConfig = { wallet: Record<number, WalletConfig>; chains: Record<number, ChainConfig>; currencies: Record<number, CurrencyConfig>; bridgeByAsset: Record<number, BridgeConfig>; anchors: Record<number, AnchorConfigEntry[]>; mixers: Record<number, MixerConfig>; };
nepoche/webb.js
packages/api-providers/src/abstracts/mixer/index.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './note.js'; export * from './mixer-deposit.js'; export * from './mixer-withdraw.js';
nepoche/webb.js
packages/api-providers/src/web3/mixer-withdraw.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { parseUnits } from '@ethersproject/units'; import { chainIdToRelayerName, RelayedWithdrawResult, RelayerCMDBase, WebbRelayer } from '@nepoche/api-providers/index.js'; import { LoggerService } from '@nepoche/app-util/index.js'; import { Note } from '@nepoche/sdk-core/index.js'; import { BigNumber } from 'ethers'; import { MixerWithdraw, OptionalActiveRelayer, OptionalRelayer, WithdrawState } from '../abstracts/index.js'; import { chainTypeIdToInternalId, evmIdIntoInternalChainId, InternalChainId, parseChainIdType } from '../chains/index.js'; import { bufferToFixed } from '../contracts/utils/buffer-to-fixed.js'; import { depositFromPreimage } from '../contracts/utils/make-deposit.js'; import { fromDepositIntoZKPTornPublicInputs } from '../contracts/utils/zkp-adapters.js'; import { WebbError, WebbErrorCodes } from '../webb-error/index.js'; import { WebbWeb3Provider } from './webb-provider.js'; const logger = LoggerService.get('Web3MixerWithdraw'); export class Web3MixerWithdraw extends MixerWithdraw<WebbWeb3Provider> { async mapRelayerIntoActive (relayer: OptionalRelayer): Promise<OptionalActiveRelayer> { if (!relayer) { return null; } const evmId = await this.inner.getChainId(); const chainId = evmIdIntoInternalChainId(evmId); return WebbRelayer.intoActiveWebRelayer( relayer, { basedOn: 'evm', chain: chainId }, // Define the function for retrieving fee information for the relayer async (note: string) => { const depositNote = await Note.deserialize(note); const evmNote = depositNote.note; const contractAddress = await this.inner.getTornadoContractAddressByNote(depositNote); const targetChainIdType = parseChainIdType(Number(evmNote.targetChainId)); // Given the note, iterate over the relayer's supported contracts and find the corresponding configuration // for the contract. const supportedContract = relayer.capabilities.supportedChains.evm .get(chainTypeIdToInternalId(targetChainIdType)) ?.contracts.find(({ address, size }) => { // Match on the relayer configuration as well as note return address.toLowerCase() === contractAddress.toLowerCase() && size === Number(evmNote.amount); }); // The user somehow selected a relayer which does not support the mixer. // This should not be possible as only supported mixers should be selectable in the UI. if (!supportedContract) { throw WebbError.from(WebbErrorCodes.RelayerUnsupportedMixer); } const principleBig = parseUnits(supportedContract.size.toString(), evmNote.denomination); const withdrawFeeMill = supportedContract.withdrawFeePercentage * 1000000; const withdrawFeeMillBig = BigNumber.from(withdrawFeeMill); const feeBigMill = principleBig.mul(withdrawFeeMillBig); const feeBig = feeBigMill.div(BigNumber.from(1000000)); return { totalFees: feeBig.toString(), withdrawFeePercentage: supportedContract.withdrawFeePercentage }; } ); } get relayers () { return this.inner.getChainId().then((evmId) => { const chainId = evmIdIntoInternalChainId(evmId); return this.inner.relayingManager.getRelayer({ baseOn: 'evm', chainId }); }); } async getRelayersByNote (evmNote: Note) { return this.inner.relayingManager.getRelayer({ baseOn: 'evm', chainId: chainTypeIdToInternalId(parseChainIdType(Number(evmNote.note.targetChainId))), tornadoSupport: { amount: Number(evmNote.note.amount), tokenSymbol: evmNote.note.tokenSymbol } }); } async getRelayersByChainAndAddress (chainId: InternalChainId, address: string) { return this.inner.relayingManager.getRelayer({ baseOn: 'evm', chainId: chainId, contractAddress: address }); } get hasRelayer () { return this.relayers.then((r) => r.length > 0); } async withdraw (note: string, recipient: string): Promise<string> { this.cancelToken.cancelled = false; const activeRelayer = this.activeRelayer[0]; const evmNote = await Note.deserialize(note); const deposit = depositFromPreimage(evmNote.note.secrets.replace('0x', '')); const chainEvmId = parseChainIdType(Number(evmNote.note.targetChainId)).chainId; const chainId = evmIdIntoInternalChainId(chainEvmId); this.emit('stateChange', WithdrawState.GeneratingZk); if (activeRelayer && (activeRelayer.beneficiary || activeRelayer.account)) { try { this.inner.notificationHandler({ description: `Relaying withdraw through ${activeRelayer.endpoint}`, key: 'mixer-withdraw-evm', level: 'loading', message: 'evm-mixer:withdraw', name: 'Transaction' }); logger.info(`Withdrawing through relayer with address ${activeRelayer.endpoint}`); logger.trace('Note deserialized', evmNote); const mixerInfo = this.inner.getMixerInfoBySize(Number(evmNote.note.amount), evmNote.note.tokenSymbol); logger.info('Withdrawing to mixer info', mixerInfo); const tornadoContract = await this.inner.getContractByAddress(mixerInfo.address); logger.trace('Generating the zkp'); const fees = await activeRelayer.fees(note); const zkpInputWithoutMerkleProof = fromDepositIntoZKPTornPublicInputs(deposit, { fee: Number(fees?.totalFees), recipient, relayer: activeRelayer.account ?? activeRelayer.beneficiary }); const relayerLeaves = await activeRelayer.getLeaves(chainEvmId.toString(16), mixerInfo.address); // This is the part of withdraw that takes a long time this.emit('stateChange', WithdrawState.GeneratingZk); const zkp = await tornadoContract.generateZKPWithLeaves( deposit, zkpInputWithoutMerkleProof, relayerLeaves.leaves, relayerLeaves.lastQueriedBlock ); logger.trace('Generated the zkp', zkp); // Check for cancelled here, abort if it was set. // Mark the withdraw mixer as able to withdraw again. if (this.cancelToken.cancelled) { this.inner.notificationHandler({ description: 'Withdraw cancelled', key: 'mixer-withdraw-evm', level: 'error', message: 'evm-mixer:withdraw', name: 'Transaction' }); this.emit('stateChange', WithdrawState.Ideal); return ''; } this.emit('stateChange', WithdrawState.SendingTransaction); const relayedWithdraw = await activeRelayer.initWithdraw('tornadoRelayTx'); logger.trace('initialized the withdraw WebSocket'); const chainInput = { baseOn: 'evm' as RelayerCMDBase, contractAddress: mixerInfo.address, endpoint: '', name: chainIdToRelayerName(chainId) }; const tx = relayedWithdraw.generateWithdrawRequest<typeof chainInput, 'tornadoRelayTx'>(chainInput, zkp.proof, { chain: chainIdToRelayerName(chainId), contract: mixerInfo.address, fee: bufferToFixed(zkp.input.fee), nullifierHash: bufferToFixed(zkp.input.nullifierHash), recipient: zkp.input.recipient, refund: bufferToFixed(zkp.input.refund), relayer: zkp.input.relayer, root: bufferToFixed(zkp.input.root) }); relayedWithdraw.watcher.subscribe(([nextValue, message]) => { switch (nextValue) { case RelayedWithdrawResult.PreFlight: case RelayedWithdrawResult.OnFlight: this.emit('stateChange', WithdrawState.SendingTransaction); break; case RelayedWithdrawResult.Continue: break; case RelayedWithdrawResult.CleanExit: this.emit('stateChange', WithdrawState.Done); this.emit('stateChange', WithdrawState.Ideal); this.inner.notificationHandler({ description: 'Withdraw success', key: 'mixer-withdraw-evm', level: 'success', message: 'evm-mixer:withdraw', name: 'Transaction' }); break; case RelayedWithdrawResult.Errored: this.emit('stateChange', WithdrawState.Failed); this.emit('stateChange', WithdrawState.Ideal); this.inner.notificationHandler({ description: message || 'Withdraw failed', key: 'mixer-withdraw-evm', level: 'error', message: 'evm-mixer:withdraw', name: 'Transaction' }); break; } }); logger.trace('Sending transaction'); // stringify the request const data2 = JSON.stringify(tx); console.log(data2); relayedWithdraw.send(tx); const txHash = await relayedWithdraw.await(); if (!txHash || !txHash[1]) { return ''; } return txHash[1]; } catch (e) { this.emit('stateChange', WithdrawState.Failed); this.emit('stateChange', WithdrawState.Ideal); logger.trace(e); this.inner.notificationHandler({ description: 'Withdraw failed', key: 'mixer-withdraw-evm', level: 'error', message: 'evm-mixer:withdraw', name: 'Transaction' }); if ((e as any)?.code === WebbErrorCodes.RelayerMisbehaving) { throw e; } } } else { logger.trace('Withdrawing without relayer'); this.inner.notificationHandler({ description: 'Withdraw In Progress', key: 'mixer-withdraw-evm', level: 'loading', message: 'evm-mixer:withdraw', name: 'Transaction' }); const contract = await this.inner.getContractBySize(Number(evmNote.note.amount), evmNote.note.tokenSymbol); // Still retrieve supported relayers for leaf querying const relayers = await this.getRelayersByNote(evmNote); let zkp: any; const zkpInputWithoutMerkleProof = fromDepositIntoZKPTornPublicInputs(deposit, { recipient, relayer: recipient }); try { if (relayers.length) { try { const relayerLeaves = await relayers[0].getLeaves(chainEvmId.toString(16), contract.inner.address); zkp = await contract.generateZKPWithLeaves( deposit, zkpInputWithoutMerkleProof, relayerLeaves.leaves, relayerLeaves.lastQueriedBlock ); } catch (e) { // If attempting to fetch leaves from the available relayer failed, query from chain. if ((e as any)?.code === WebbErrorCodes.RelayerMisbehaving) { zkp = await contract.generateZKP(deposit, zkpInputWithoutMerkleProof); } else { logger.log('error in web3 mixer withdraw: ', e); throw e; } } } else { // This is the part of withdraw that takes a long time zkp = await contract.generateZKP(deposit, zkpInputWithoutMerkleProof); } logger.trace('Generated the zkp', zkp); // Check for cancelled here, abort if it was set. // Mark the withdraw mixer as able to withdraw again. if (this.cancelToken.cancelled) { this.inner.notificationHandler({ description: 'Withdraw canceled', key: 'mixer-withdraw-evm', level: 'error', message: 'evm-mixer:withdraw', name: 'Transaction' }); this.emit('stateChange', WithdrawState.Ideal); return ''; } this.emit('stateChange', WithdrawState.SendingTransaction); const txReset = await contract.withdraw(zkp.proof, zkp.input); const receipt = await txReset.wait(); this.inner.notificationHandler({ description: 'Withdraw success', key: 'mixer-withdraw-evm', level: 'success', message: 'evm-mixer:withdraw', name: 'Transaction' }); this.emit('stateChange', WithdrawState.Ideal); return receipt.transactionHash; } catch (e) { // todo fix this and fetch the error from chain // User rejected transaction from provider if ((e as any)?.code === 4001) { this.inner.notificationHandler({ description: 'Withdraw Rejected', key: 'mixer-withdraw-evm', level: 'error', message: 'evm-mixer:withdraw', name: 'Transaction' }); this.emit('stateChange', WithdrawState.Ideal); return ''; } this.inner.notificationHandler({ description: 'Withdraw Failed', key: 'mixer-withdraw-evm', level: 'error', message: 'evm-mixer:withdraw', name: 'Transaction' }); throw e; } } return ''; } }
nepoche/webb.js
packages/api-providers/src/abstracts/mixer/note.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export interface Note { serialize(): string; // deserialize(noteStr: string): Note; }
nepoche/webb.js
packages/api-providers/src/abstracts/currency/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './currency.js'; export * from './orml-currency.js';
nepoche/webb.js
packages/api-providers/src/abstracts/webb-provider.interface.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { AnchorApi } from '@nepoche/api-providers/index.js'; import { EventBus } from '@nepoche/app-util/index.js'; import { AccountsAdapter } from '../account/Accounts.adapter.js'; import { InteractiveFeedback } from '../webb-error/index.js'; import { AnchorDeposit, AnchorWithdraw, Bridge } from './anchor/index.js'; import { ChainQuery } from './chain-query/index.js'; import { DepositPayload, MixerDeposit, MixerDepositEvents, MixerWithdraw, MixerWithdrawEvents } from './mixer/index.js'; import { WebbRelayerBuilder } from './relayer/index.js'; import { WrapUnWrap } from './wrap-unwrap/index.js'; import { AppConfig } from './common.js'; /// list of the apis that are available for the provider export interface WebbMethods<T extends WebbApiProvider<any>> { // Mixer API mixer: WebbMixer<T>; // Anchor/Bridge API anchor: WebbAnchor<T>; // Wrap and unwrap API wrapUnwrap: WrapAndUnwrap<T>; // Chain query : an API for querying storage used currently for balances chainQuery: ChainQuery<T>; // Anchor API developed initially for to handle the difference between // web3 (Chains that depend on static configs) and chains that will need to query the anchor anchorApi: AnchorApi<T, any>; } export type WebbMethod<T extends EventBus<K>, K extends Record<string, unknown>> = { // The underlying provider for the methods inner: T; enabled: boolean; }; export interface WebbMixer<T extends WebbApiProvider<any>> { // deposit deposit: WebbMethod<MixerDeposit<T, DepositPayload>, MixerDepositEvents>; // withdraw withdraw: WebbMethod<MixerWithdraw<T>, MixerWithdrawEvents>; } export interface WrapAndUnwrap<T> { core: { inner: WrapUnWrap<T>; enabled: boolean; }; } export interface WebbAnchor<T extends WebbApiProvider<any>> { core: Bridge | null; // deposit deposit: WebbMethod<AnchorDeposit<T, DepositPayload>, MixerDepositEvents>; // withdraw withdraw: WebbMethod<AnchorWithdraw<T>, MixerWithdrawEvents>; } /// TODO improve this and add a spec /// An interface for Apis pre-initialization export type ApiInitHandler = { /// an error handler for the Api before init /* * For instance Polkadot provider the dApp will prepare the parameters for the provider * This process may have an error * */ onError(error: InteractiveFeedback): any; }; export type WebbProviderEvents<T = any> = { /// event is trigger to show an interactiveFeedback related to the provider interactiveFeedback: InteractiveFeedback; /// The provider is updated and an action is required to handle this update providerUpdate: T; // /// accountsChange newAccounts: AccountsAdapter<any>; }; export type ProvideCapabilities = { addNetworkRpc: boolean; listenForAccountChange: boolean; listenForChainChane: boolean; hasSessions: boolean; }; export type NotificationKey = string | number; export type VariantType = 'default' | 'error' | 'success' | 'warning' | 'info'; export type NotificationData = { // Either the Notification is kept for future manual removal or by an event persist: boolean; // Main message/ title for the notification message: string; // Description about the Notification description: string; // Notification variant that can be used to style the notification variant: VariantType; // Arbitrary action that can be used for clicking the notification (Not implemented) action: string; }; export type NotificationApi = { addToQueue(data: NotificationData): NotificationKey; remove(key: NotificationKey): void; }; type MethodPath = { // Main section for the Transaction section: string; // The call name method: string; }; export type TXNotificationPayload<T = undefined> = { // Generic data for the transaction payload data: T; // notification key key: NotificationKey; address: string; // More metadata for the transaction path (EX Anchor::Deposit ,VAnchor::Withdraw) path: MethodPath; }; // Transaction notification export type TXNotification = { // Transaction status is in progress loading(payload: TXNotificationPayload<any>): NotificationKey; // Transaction failed failed(payload: TXNotificationPayload<any>): NotificationKey; // Transaction Done with success finalize(payload: TXNotificationPayload<any>): NotificationKey; }; export type NotificationLevel = 'loading' | 'error' | 'success' | 'warning' | 'info'; export type NotificationPayload = { // Title of the notification message: string; // details about the notification description: string; // Event name/ event identifier name: 'Transaction' | 'Approval'; // key for a given notification can be used to remove/dismiss a notification key: string; // level level: NotificationLevel; // Record for more metadata data?: Record<string, string>; // if true the notification will be dismissed by the user or with another action persist?: boolean; }; // Function call to register a notification export type NotificationHandler = ((notification: NotificationPayload) => string | number) & { // remove the notification programmatically remove(key: string | number): void; }; /* * Wasm factory * @params * */ export type WasmFactory = (name?: string) => Worker | null; export interface WebbApiProvider<T> extends EventBus<WebbProviderEvents> { /// Accounts Adapter will have all methods related to the provider accounts accounts: AccountsAdapter<any>; /// All of the available methods and api of the provider methods: WebbMethods<WebbApiProvider<T>>; /// A hook will be called to drop the provider and do cleanup listeners etc.. destroy(): Promise<void> | void; capabilities?: ProvideCapabilities; // Clean up for the provider that will remove the side effects endSession?(): Promise<void>; /// relayer relayingManager: WebbRelayerBuilder; getProvider(): any; // Configs config: AppConfig; // Notification handler notificationHandler: NotificationHandler; // wasm-utils workers factory wasmFactory: WasmFactory; }
nepoche/webb.js
packages/api-providers/src/ipfs/evm/anchors.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { getCachedFixtureURI, withLocalFixtures } from '@nepoche/api-providers/index.js'; export const fetchWasmForEdges = async (maxEdges: number) => { let ipfsHash: string; let cachedURI: string; switch (maxEdges) { case 1: ipfsHash = 'QmNUEukgQZSzZhdrptrzSP6DRRJ3KXZ75ybQ8gkTAhTe7g'; cachedURI = getCachedFixtureURI('anchor_wasm_2.wasm'); break; case 2: ipfsHash = 'QmZcyRgorkHDWf5Tx8jnb1D9mKkwWc5DdYbWYspJLSGNbG'; cachedURI = getCachedFixtureURI('anchor_wasm_3.wasm'); break; case 3: ipfsHash = 'QmWy3pxQt9tYFyDSnqiyNtgjMacex37sPeneZBYCpFTkCz'; cachedURI = getCachedFixtureURI('anchor_wasm_4.wasm'); break; case 4: ipfsHash = 'Qma7YsTpqUuBVGawLEZhrQyobtKSX1kJW25q2rdGQYaGf5'; cachedURI = getCachedFixtureURI('anchor_wasm_5.wasm'); break; case 5: ipfsHash = 'Qme47CdNasWDUz2u1m1HtbqMJG3vLPFyDj2Gr5HT3JAzLn'; cachedURI = getCachedFixtureURI('anchor_wasm_6.wasm'); break; default: ipfsHash = 'QmNUEukgQZSzZhdrptrzSP6DRRJ3KXZ75ybQ8gkTAhTe7g'; cachedURI = getCachedFixtureURI('anchor_wasm_2.wasm'); break; } try { if (withLocalFixtures()) { const cachedWasmRequest = await fetch(cachedURI); const wasmBuf = await cachedWasmRequest.arrayBuffer(); return wasmBuf; } else { const ipfsWasmRequest = await fetch(`https://ipfs.io/ipfs/${ipfsHash}`); const wasmBuf = await ipfsWasmRequest.arrayBuffer(); return wasmBuf; } } catch (e) { console.log('error when fetching wasm from ipfs: ', e); throw e; } }; export const fetchKeyForEdges = async (maxEdges: number) => { let ipfsHash: string; let cachedURI: string; switch (maxEdges) { case 1: ipfsHash = 'QmQrwhvzFF4wi18S9Njhm64uXsf7ZE6LYEsXoXUVhTPATE'; cachedURI = getCachedFixtureURI('anchor_key_2.zkey'); break; case 2: ipfsHash = 'QmeaX6KfJTC9oixvjig4RMS3bMNizAqQXNRTh6sadAnzps'; cachedURI = getCachedFixtureURI('anchor_key_3.zkey'); break; case 3: ipfsHash = 'QmPs3SCyZ2uboSrpzdQAT9JkYyybjrpcAF2Fhb2QYHgWf8'; cachedURI = getCachedFixtureURI('anchor_key_4.zkey'); break; case 4: ipfsHash = 'QmdBsxtCBzYQw1yo3n4goeVyZ5iDhJN33QSBqX88Dz3mVX'; cachedURI = getCachedFixtureURI('anchor_key_5.zkey'); break; case 5: ipfsHash = 'Qmc58Pq8iP3y12crAvjyVdnT2z9hA7TyduhANjSNrJz8Sp'; cachedURI = getCachedFixtureURI('anchor_key_6.zkey'); break; default: ipfsHash = 'QmQrwhvzFF4wi18S9Njhm64uXsf7ZE6LYEsXoXUVhTPATE'; cachedURI = getCachedFixtureURI('anchor_key_2.zkey'); break; } try { if (withLocalFixtures()) { const cachedKeyRequest = await fetch(cachedURI); const cachedKeyArrayBuffer = await cachedKeyRequest.arrayBuffer(); const cachedKey = new Uint8Array(cachedKeyArrayBuffer); return cachedKey; } else { const ipfsKeyRequest = await fetch(`https://ipfs.io/ipfs/${ipfsHash}`); const circuitKeyArrayBuffer = await ipfsKeyRequest.arrayBuffer(); const circuitKey = new Uint8Array(circuitKeyArrayBuffer); return circuitKey; } } catch (e) { console.log('error when fetching circuit key from ipfs: ', e); throw e; } };
nepoche/webb.js
packages/api-providers/src/types/mixer-config.interface.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export interface TornMixerEntry { size: number; address: string; symbol: string; createdAtBlock: number; } export interface MixerConfig { tornMixers: TornMixerEntry[]; }
nepoche/webb.js
tests/utils/substrate-utils.ts
<gh_stars>0 import { ApiPromise, WsProvider } from '@polkadot/api'; import { KeyringPair } from '@polkadot/keyring/types'; import { AnchorMTBn254X5, generate_proof_js, JsNote, JsNoteBuilder, OperationError, ProofInputBuilder, } from '@nepoche/wasm-utils/njs/wasm-utils-njs.js'; import { hexToU8a, u8aToHex } from '@polkadot/util'; import { decodeAddress } from '@polkadot/keyring'; import path from 'path'; import fs from 'fs'; import { SubmittableExtrinsic } from '@polkadot/api/promise/types'; import { BigNumber } from 'ethers'; /// <reference path="@nepoche/types/interfaces/types.d.ts" export function currencyToUnitI128(currencyAmount: number) { let bn = BigNumber.from(currencyAmount); return bn.mul(1_000_000_000_000); } type MethodPath = { section: string; method: string; }; export function polkadotTx( api: ApiPromise, path: MethodPath, params: any[], signer: KeyringPair ) { // @ts-ignore const tx = api.tx[path.section][path.method](...params); return new Promise<string>((resolve, reject) => { tx.signAndSend(signer, (result) => { const status = result.status; const events = result.events.filter( ({ event: { section } }) => section === 'system' ); if (status.isInBlock || status.isFinalized) { for (const event of events) { const { event: { data, method }, } = event; const [dispatchError] = data as any; if (method === 'ExtrinsicFailed') { let message = dispatchError.type; if (dispatchError.isModule) { try { const mod = dispatchError.asModule; const error = dispatchError.registry.findMetaError(mod); message = `${error.section}.${error.name}`; } catch (error) { reject(message); } } else if (dispatchError.isToken) { message = `${dispatchError.type}.${dispatchError.asToken.type}`; } reject(message); } else if (method === 'ExtrinsicSuccess') { resolve(tx.hash.toString()); } } } }).catch((e) => reject(e)); }); } export async function preparePolkadotApi() { const wsProvider = new WsProvider('ws://127.0.0.1:9944'); const api = await ApiPromise.create({ provider: wsProvider, rpc: { mt: { getLeaves: { description: 'Query for the tree leaves', params: [ { name: 'tree_id', type: 'u32', isOptional: false, }, { name: 'from', type: 'u32', isOptional: false, }, { name: 'to', type: 'u32', isOptional: false, }, { name: 'at', type: 'Hash', isOptional: true, }, ], type: 'Vec<[u8; 32]>', }, }, }, }); return api.isReady; } export function awaitPolkadotTxFinalization( tx: SubmittableExtrinsic, signer: KeyringPair ) { return new Promise((resolve, reject) => { tx.signAndSend(signer, { nonce: -1 }, (status) => { if (status.isFinalized || status.isCompleted) { resolve(tx.hash); } if (status.isError) { reject(status.dispatchError); } }).catch((e) => reject(e)); }); } export async function transferBalance( api: ApiPromise, source: KeyringPair, receiverPairs: KeyringPair[], number: number = 1000 ) { // transfer to alice for (const receiverPair of receiverPairs) { await polkadotTx( api, { section: 'balances', method: 'transfer' }, [receiverPair.address, currencyToUnitI128(number).toString()], source ); } } export async function setORMLTokenBalance( api: ApiPromise, sudoPair: KeyringPair, receiverPair: KeyringPair, ORMLCurrencyId: number = 0, amount: number = 1000 ) { return new Promise((resolve, reject) => { const address = api.createType('MultiAddress', { Id: receiverPair.address, }); // @ts-ignore api.tx.sudo .sudo( // @ts-ignore api.tx.currencies.updateBalance( address, ORMLCurrencyId, currencyToUnitI128(amount) ) ) .signAndSend(sudoPair, (res) => { if (res.isFinalized || res.isCompleted) { resolve(null); } if (res.isError) { reject(res.dispatchError); } }); }); } // @ts-ignore export async function fetchLinkableAnchorBn254(apiPromise: ApiPromise) { // Run the } export async function fetchCachedRoot(apiPromise: ApiPromise, treeId: string) { const storage = // @ts-ignore await apiPromise.query.merkleTreeBn254.trees(treeId); // @ts-ignore return storage.toHuman().root; } export async function getAnchors(apiPromise: ApiPromise) { // @ts-ignore const anchors = await apiPromise.query.anchorBn254.anchors.entries(); const anc = anchors.map(([key, entry]) => { const treeId = (key.toHuman() as Array<string>)[0]; return { treeId, anchor: entry.toHuman() }; }); return anc; } export async function fetchRPCTreeLeaves( api: ApiPromise, treeId: string | number ): Promise<Uint8Array[]> { let done = false; let from = 0; let to = 511; const leaves: Uint8Array[] = []; while (done === false) { const treeLeaves: any[] = await (api.rpc as any).mt.getLeaves( treeId, from, to ); if (treeLeaves.length === 0) { done = true; break; } leaves.push(...treeLeaves.map((i) => i.toU8a())); from = to; to = to + 511; } return leaves; } export async function depositMixerBnX5_3( api: ApiPromise, depositor: KeyringPair ) { let noteBuilder = new JsNoteBuilder(); noteBuilder.protocol('mixer'); noteBuilder.version('v2'); noteBuilder.sourceChainId('1'); noteBuilder.targetChainId('1'); noteBuilder.sourceIdentifyingData('3'); noteBuilder.targetIdentifyingData('3'); noteBuilder.tokenSymbol('WEBB'); noteBuilder.amount('1'); noteBuilder.denomination('18'); noteBuilder.backend('Arkworks'); noteBuilder.hashFunction('Poseidon'); noteBuilder.curve('Bn254'); noteBuilder.width('3'); noteBuilder.exponentiation('5'); const note = noteBuilder.build(); const leaf = note.getLeafCommitment(); await polkadotTx( api, { section: 'mixerBn254', method: 'deposit' }, [0, leaf], depositor ); return note; } export type WithdrawProof = { id: string; proofBytes: string; root: string; nullifierHash: string; recipient: string; relayer: string; fee: number; refund: number; }; export type AnchorWithdrawProof = WithdrawProof & { commitment: string; }; export function catchWasmError<T extends (...args: any) => any>( fn: T ): ReturnType<T> { try { return fn(); } catch (e) { const error = e as OperationError; const errorMessage = { code: error.code, errorMessage: error.error_message, data: error.data, }; console.log(errorMessage); throw errorMessage; } } function firstAnchorTreeId(apiPromise: ApiPromise) { return getAnchors(apiPromise).then((i) => i[0]!.treeId) as Promise<string>; } export async function depositAnchorBnX5_4( api: ApiPromise, depositor: KeyringPair ) { const treeId = await firstAnchorTreeId(api); let noteBuilder = new JsNoteBuilder(); noteBuilder.protocol('anchor'); noteBuilder.version('v2'); noteBuilder.sourceChainId('2199023256632'); noteBuilder.targetChainId('2199023256632'); noteBuilder.sourceIdentifyingData(treeId); noteBuilder.targetIdentifyingData(treeId); noteBuilder.tokenSymbol('WEBB'); noteBuilder.amount('1'); noteBuilder.denomination('18'); noteBuilder.backend('Arkworks'); noteBuilder.hashFunction('Poseidon'); noteBuilder.curve('Bn254'); noteBuilder.width('4'); noteBuilder.exponentiation('5'); const note = noteBuilder.build(); const leaf = note.getLeafCommitment(); await polkadotTx( api, { method: 'deposit', section: 'anchorBn254' }, [treeId, leaf], depositor ); return note; } export async function createAnchor( api: ApiPromise, sudoPair: KeyringPair, size: number /* Size should be more the existential balance*/, assetId: number = 0, maxEdges: number = 2, depth: number = 3 ) { return polkadotTx( api, { method: 'sudo', section: 'sudo' }, [ // @ts-ignore api.tx.anchorBn254.create( currencyToUnitI128(size).toString(), maxEdges, depth, assetId ), ], sudoPair ); } export async function withdrawAnchorBnx5_4( api: ApiPromise, signer: KeyringPair, note: JsNote, relayerAccountId: string ): Promise<string> { const accountId = signer.address; const addressHex = u8aToHex(decodeAddress(accountId)); const relayerAddressHex = u8aToHex(decodeAddress(relayerAccountId)); const treeId = await firstAnchorTreeId(api); // fetch leaves const leaves = await fetchRPCTreeLeaves(api, Number(treeId)); const proofInputBuilder = new ProofInputBuilder(); const leafHex = u8aToHex(note.getLeafCommitment()); proofInputBuilder.setNote(note); proofInputBuilder.setLeaves(leaves); const leafIndex = leaves.findIndex((l) => u8aToHex(l) === leafHex); proofInputBuilder.setLeafIndex(String(leafIndex)); proofInputBuilder.setFee('5'); proofInputBuilder.setRefund('1'); const merkeTree = new AnchorMTBn254X5(leaves, String(leafIndex)); const root = `0x${merkeTree.root}`; proofInputBuilder.setRefreshCommitment('0000000000000000000000000000000000000000000000000000000000000000'); // 1 from eth // 1 from substrate proofInputBuilder.setRoots([hexToU8a(root), hexToU8a(root)]); proofInputBuilder.setRecipient(addressHex.replace('0x', '')); proofInputBuilder.setRelayer(relayerAddressHex.replace('0x', '')); const pkPath = path.join( // tests path process.cwd(), 'tests', 'protocol-substrate-fixtures', 'fixed-anchor', 'bn254', 'x5', '2', 'proving_key_uncompressed.bin' ); const pk = fs.readFileSync(pkPath); proofInputBuilder.setPk(pk.toString('hex')); const proofInput = proofInputBuilder.build_js(); const zkProofMetadata = generate_proof_js(proofInput); const withdrawProof: AnchorWithdrawProof = { id: treeId, proofBytes: `0x${zkProofMetadata.proof}` as any, root: `0x${zkProofMetadata.root}`, nullifierHash: `0x${zkProofMetadata.nullifierHash}`, recipient: accountId, relayer: relayerAccountId, fee: 5, refund: 1, commitment: `0x0000000000000000000000000000000000000000000000000000000000000000`, }; const params = [ withdrawProof.id, withdrawProof.proofBytes, zkProofMetadata.roots.map((i: string) => `0x${i}`), withdrawProof.nullifierHash, withdrawProof.recipient, withdrawProof.relayer, withdrawProof.fee, withdrawProof.refund, withdrawProof.commitment, ]; return polkadotTx( api, { method: 'withdraw', section: 'anchorBn254' }, params, signer ); } export async function withdrawMixerBnX5_3( api: ApiPromise, signer: KeyringPair, note: JsNote, relayerAccountId: string ) { const accountId = signer.address; const addressHex = u8aToHex(decodeAddress(accountId)); const relayerAddressHex = u8aToHex(decodeAddress(relayerAccountId)); // fetch leaves const leaves = await fetchRPCTreeLeaves(api, 0); const proofInputBuilder = new ProofInputBuilder(); const leafHex = u8aToHex(note.getLeafCommitment()); proofInputBuilder.setNote(note); proofInputBuilder.setLeaves(leaves); const leafIndex = leaves.findIndex((l) => u8aToHex(l) === leafHex); proofInputBuilder.setLeafIndex(String(leafIndex)); proofInputBuilder.setFee('0'); proofInputBuilder.setRefund('0'); proofInputBuilder.setRecipient(addressHex.replace('0x', '')); proofInputBuilder.setRelayer(relayerAddressHex.replace('0x', '')); const pkPath = path.join( // tests path process.cwd(), 'tests', 'protocol-substrate-fixtures', 'mixer', 'bn254', 'x5', 'proving_key_uncompressed.bin' ); const pk = fs.readFileSync(pkPath); proofInputBuilder.setPk(pk.toString('hex')); const proofInput = proofInputBuilder.build_js(); const zkProofMetadata = generate_proof_js(proofInput); /* const vkPath = path.join( // tests path process.cwd(), 'protocol-substrate-fixtures', 'mixer', 'bn254', 'x5', 'verifying_key_uncompressed.bin' ); const vk = fs.readFileSync(vkPath); const isValid = validate_proof(zkProofMetadata, vk.toString('hex'), 'Bn254'); */ const withdrawProof: WithdrawProof = { id: String(0), proofBytes: `0x${zkProofMetadata.proof}` as any, root: `0x${zkProofMetadata.root}`, nullifierHash: `0x${zkProofMetadata.nullifierHash}`, recipient: accountId, relayer: relayerAccountId, fee: 0, refund: 0, }; const params = [ withdrawProof.id, withdrawProof.proofBytes, withdrawProof.root, withdrawProof.nullifierHash, withdrawProof.recipient, withdrawProof.relayer, withdrawProof.fee, withdrawProof.refund, ]; return polkadotTx( api, { section: 'mixerBn254', method: 'withdraw' }, params, signer ); }
nepoche/webb.js
packages/type-definitions/src/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { jsonrpcFromDefs, typesAliasFromDefs, typesFromDefs } from '@open-web3/orml-type-definitions/utils/index.js'; import versioned from './types-known/versioned.js'; import merkle from './merkle.js'; import mixer from './mixer.js'; import pallets from './pallets.js'; // FIXME: currently we cannot override this in runtime definations because the code generation script cannot handle overrides // This will make it behave correctly in runtime, but wrong types in TS defination. const additionalOverride = { Address: 'AccountId', Keys: 'SessionKeys2', LookupSource: 'AccountId', PalletsOrigin: { _enum: { Aura: 'Null', Authorship: 'Null', Balances: 'Null', Grandpa: 'Null', Historical: 'Null', Indices: 'Null', Merkle: 'Null', Mixer: 'Null', RandomnessCollectiveFlip: 'Null', Session: 'Null', Staking: 'Null', Sudo: 'Null', System: 'SystemOrigin', Timestamp: 'Null', TransactionPayment: 'Null', Utility: 'Null' } } }; const webbDefs = { merkle, mixer, pallets }; export const types = { ...typesFromDefs(webbDefs), ...additionalOverride }; export const typesBundle = { spec: { webb: { types: versioned } } }; export const rpc = jsonrpcFromDefs(webbDefs, {}); export const typesAlias = typesAliasFromDefs(webbDefs, {}); const bundle = { alias: typesAlias, types: [...versioned].map((version) => { return { types: { ...types, ...version.types } }; }) }; // Type overrides have priority issues export const typesBundleForPolkadot = { spec: { webb: bundle } };
nepoche/webb.js
packages/api-providers/src/ext-providers/web3/web3-provider.spec.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { expect } from 'chai'; import { Web3Provider } from './web3-provider.js'; describe('Initialize Web3', () => { it('Is constructable from HTTP', async () => { const web3Provider = Web3Provider.fromUri('https://rinkeby.infura.io/v3/e54b7176271840f9ba62e842ff5d6db4'); const isListening = await web3Provider.eth.net.isListening(); expect(isListening).to.equal(true); }); });
nepoche/webb.js
packages/api-providers/src/abstracts/mixer/mixer-withdraw.ts
<filename>packages/api-providers/src/abstracts/mixer/mixer-withdraw.ts<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { WebbApiProvider } from '@nepoche/api-providers/index.js'; import { EventBus } from '@nepoche/app-util/index.js'; import { Note } from '@nepoche/sdk-core/index.js'; import { BehaviorSubject, Observable } from 'rxjs'; import { InternalChainId } from '../../chains/index.js'; import { ActiveWebbRelayer, WebbRelayer } from '../relayer/index.js'; export enum WithdrawState { Cancelling, // Withdraw canceled Ideal, // initial status where the instance is Idea and ready for a withdraw GeneratingZk, // There is a withdraw in progress, and it's on the step of generating the Zero-knowledge proof SendingTransaction, // There is a withdraw in progress, and it's on the step Sending the Transaction whether directly or through relayers Done, // the withdraw is Done and seceded , the next tic the instance should be ideal Failed // the withdraw is Done with a failure, the next tic the instance should be ideal } // Events that can be emitted using the {EventBus} export type MixerWithdrawEvents = { // Generic Error by the provider or doing an intermediate step error: string; // Validation Error for the withdrawing note // TODO : update this to be more verbose and not just relate to the note but also the params for `generateNote` and `withdraw` validationError: { note: string; recipient: string; }; // The instance State change event to track the current status of the instance stateChange: WithdrawState; // the instance is ready ready: void; loading: boolean; }; export type OptionalRelayer = null | WebbRelayer; export type OptionalActiveRelayer = null | ActiveWebbRelayer; export type CancelToken = { cancelled: boolean; }; /** * Mixer withdraw abstract * The underlying method should be implemented to get a functioning mixerWithdraw for a {WebbApiProvider} * @param {T} the provider WebbApiProvider */ export abstract class MixerWithdraw<T extends WebbApiProvider<any>> extends EventBus<MixerWithdrawEvents> { state: WithdrawState = WithdrawState.Ideal; protected emitter = new BehaviorSubject<OptionalActiveRelayer>(null); readonly watcher: Observable<OptionalActiveRelayer>; private _activeRelayer: OptionalActiveRelayer = null; cancelToken: CancelToken = { cancelled: false }; constructor (protected inner: T) { super(); this.watcher = this.emitter.asObservable(); } // Whether there is an active relayer get hasRelayer (): Promise<boolean> { return Promise.resolve(false); } // Getter for the active relayer First arg of the tuple will be the OptionalActiveRelayer, the other one is a watcher get activeRelayer (): [OptionalActiveRelayer, Observable<OptionalActiveRelayer>] { return [this._activeRelayer, this.watcher]; } /** * This is a default implemented function that must be overridden if the instance is meant to use the relayer * It maps a relayer to the active relayer type that can be used for relaying withdrawing * */ // eslint-disable-next-line @typescript-eslint/no-unused-vars mapRelayerIntoActive (relayer: OptionalRelayer): Promise<OptionalActiveRelayer> { return Promise.resolve(null); } /** * Set/unset the active relayer * */ public async setActiveRelayer (relayer: OptionalRelayer) { this._activeRelayer = await this.mapRelayerIntoActive(relayer); this.emitter.next(this._activeRelayer); } // todo switch to the reactive api get relayers (): Promise<WebbRelayer[]> { return Promise.resolve([]); } /** * This is a default implemented function that must be overridden if the instance is meant to use the relayer * It will get a relayer by the note mapping with relayers capabilities * * */ // eslint-disable-next-line @typescript-eslint/no-unused-vars getRelayersByNote (note: Note): Promise<WebbRelayer[]> { return Promise.resolve([]); } /** * This is a default implemented function that must be overridden if the instance is meant to use the relayer * It will get a relayer by the chain id and contract-address/tree-id mapping the note metadata with relayers capabilities * * */ // eslint-disable-next-line @typescript-eslint/no-unused-vars getRelayersByChainAndAddress (chainId: InternalChainId, address: string): Promise<WebbRelayer[]> { return Promise.resolve([]); } /** * cancel the withdraw */ cancelWithdraw (): Promise<void> { this.cancelToken.cancelled = true; this.emit('stateChange', WithdrawState.Cancelling); return Promise.resolve(undefined); } /** * This should be implemented to do the Transaction call for the withdraw * it should do the side effects on the instance * - Mutate the {loading} status of the instance * - Use the event bus to emit the status of the transaction * - Switch logic for relayer usage * */ abstract withdraw(note: string, recipient: string): Promise<string>; }
nepoche/webb.js
packages/sdk-core/src/note.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-disable @typescript-eslint/no-unsafe-assignment */ /* eslint-disable @typescript-eslint/no-unsafe-member-access */ /* eslint-disable prefer-promise-reject-errors */ import type { Backend, Curve, HashFunction, JsNote, NoteProtocol, Version } from '@nepoche/wasm-utils'; /** * The note input used to generate a `Note` instance. * * @param protocol - The shielded pool protocol to use. * @param version - The version of the note to use. * @param sourceChain - The source chain id. * @param sourceIdentifyingData - Optional source identifying data. * @param targetChain - The target chain id. * @param targetIdentifyingData - Optional target identifying data. * @param backend - The backend to use. * @param hashFunction - The hash function to use. * @param curve - The curve to use. * @param tokenSymbol - The token symbol to use. * @param amount - The amount to use. * @param denomination - The denomination to use. * @param width - The width to use. * @param secrets - Optional secrets to use. * @param exponentiation - The exponentiation to use. */ export type NoteGenInput = { protocol: NoteProtocol; version: string; sourceChain: string; sourceIdentifyingData?: string; targetChain: string; targetIdentifyingData?: string; backend: Backend; hashFunction: HashFunction; curve: Curve; tokenSymbol: string; amount: string; denomination: string; secrets?: string; width: string; exponentiation: string; }; /** * Note class using the WebAssembly note backend. * * The goal of this class is to provide a Note interface * that works both in Node.js and in the browser. */ export class Note { static CURRENT_VERSION: Version = 'v2'; // Default constructor private constructor (readonly note: JsNote) { } /** * Gets the WebAssembly module for the target environment. * Supports the browser and Node.js. */ private static get wasm () { if (typeof process !== 'undefined' && process.versions != null && process.versions.node != null) { return import('@nepoche/wasm-utils/njs/wasm-utils-njs.js'); } else { return import('@nepoche/wasm-utils/wasm-utils.js'); } } /** * Deserializes a note from a string. * * @param value A serialized note. * @returns A note class instance. */ public static async deserialize (value: string): Promise<Note> { try { const wasm = await Note.wasm; const depositNote = wasm.JsNote.deserialize(value); return new Note(depositNote); } catch (e: any) { return Promise.reject({ code: e.code, data: e.data, message: e.error_message }); } } /** * Turns a `Note` into a WebAssembly compatible `JsNote`. * * @returns The `JsNote` struct. */ async toDepositNote (): Promise<JsNote> { const wasm = await Note.wasm; return wasm.JsNote.deserialize(this.serialize()); } /** * Serializes the note to a string. * * @returns The serialized note. */ public serialize (): string { return this.note.serialize(); } /** * Get's the leaf commitment of the note depending * of the protocol. * * @returns Returns the leaf commitment of the note. */ getLeaf (): Uint8Array { return this.note.getLeafCommitment(); } /** * Generates a note using the relevant input data. Supports * the protocols defined in the WebAssembly note backend. * * ```typescript * // Generate an anchor note * const input: NoteGenInput = { * protocol: 'anchor', * version: 'v2', * targetChain: '1', * targetIdentifyingData: '1', * sourceChain: '1', * sourceIdentifyingData: '1', * backend: 'Circom', * hashFunction: 'Poseidon', * curve: 'Bn254', * tokenSymbol: 'WEBB', * amount: '1', * denomination: '18', * width: '4', * exponentiation: '5', * } * * const note = await Note.generateNote(input); * ``` * @param noteGenInput The input data for generating a note. * @returns */ public static async generateNote (noteGenInput: NoteGenInput): Promise<Note> { try { const wasm = await Note.wasm; const noteBuilderInput = new wasm.JsNoteBuilder(); noteBuilderInput.protocol(noteGenInput.protocol); noteBuilderInput.version(Note.CURRENT_VERSION); noteBuilderInput.targetChainId(noteGenInput.targetChain); noteBuilderInput.sourceChainId(noteGenInput.sourceChain); noteBuilderInput.backend(noteGenInput.backend); noteBuilderInput.hashFunction(noteGenInput.hashFunction); noteBuilderInput.curve(noteGenInput.curve); noteBuilderInput.tokenSymbol(noteGenInput.tokenSymbol); noteBuilderInput.amount(noteGenInput.amount); noteBuilderInput.denomination(noteGenInput.denomination); noteBuilderInput.width(noteGenInput.width); noteBuilderInput.exponentiation(noteGenInput.exponentiation); if (noteGenInput.secrets) { noteBuilderInput.setSecrets(noteGenInput.secrets); } if (noteGenInput.targetIdentifyingData) { noteBuilderInput.targetIdentifyingData(noteGenInput.targetIdentifyingData); } if (noteGenInput.sourceIdentifyingData) { noteBuilderInput.sourceIdentifyingData(noteGenInput.sourceIdentifyingData); } const depositNote = noteBuilderInput.build(); return new Note(depositNote); } catch (e: any) { return Promise.reject({ code: e.code, data: e.data, message: e.error_message }); } } }
nepoche/webb.js
packages/api-providers/src/polkadot/anchor-deposit.ts
<filename>packages/api-providers/src/polkadot/anchor-deposit.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { AnchorApi } from '@nepoche/api-providers/index.js'; import { LoggerService } from '@nepoche/app-util/index.js'; import { Note, NoteGenInput } from '@nepoche/sdk-core/index.js'; import { u8aToHex } from '@polkadot/util'; import { AnchorDeposit, AnchorSize, DepositPayload as IDepositPayload } from '../abstracts/index.js'; import { ChainType, computeChainIdType, InternalChainId, SubstrateChainId } from '../chains/index.js'; import { BridgeConfig } from '../types/bridge-config.interface.js'; import { WebbError, WebbErrorCodes } from '../webb-error/index.js'; import { WebbPolkadot } from './webb-provider.js'; const logger = LoggerService.get('PolkadotBridgeDeposit'); type DepositPayload = IDepositPayload<Note, [number, string]>; export class PolkadotBridgeDeposit extends AnchorDeposit<WebbPolkadot, DepositPayload> { async deposit (depositPayload: DepositPayload): Promise<void> { const tx = this.inner.txBuilder.build( { method: 'deposit', section: 'anchorBn254' }, depositPayload.params ); const account = await this.inner.accounts.activeOrDefault; if (!account) { throw WebbError.from(WebbErrorCodes.NoAccountAvailable); } const hash = await tx.call(account.address); console.log(hash); } async generateBridgeNote ( anchorId: number | string, destination: number, // eslint-disable-next-line @typescript-eslint/no-unused-vars wrappableAssetAddress: string | undefined ): Promise<DepositPayload> { const currency = this.bridgeApi.currency; if (!currency) { logger.error('Not currency/active bridge available'); throw new Error('api not ready'); } const tokenSymbol = currency.view.symbol; const destChainId = destination; // TODO: add mappers similar to evm chain id // const chainId = this.inner.api.registry.chainSS58!; const chainId = SubstrateChainId.Webb; const sourceChainId = computeChainIdType(ChainType.Substrate, chainId); const anchorPath = String(anchorId).replace('Bridge=', '').split('@'); const amount = anchorPath[0]; const anchorIndex = anchorPath[2]; const anchors = await this.bridgeApi.getAnchors(); const anchor = anchors[Number(anchorIndex)]; logger.trace({ amount, anchor, anchorId, anchorIndex, anchors, destination, sourceChainId }); const treeId = anchor.neighbours[InternalChainId.WebbDevelopment] as number; // TODO: Anchor in one chain the 0 id contains the treeId const noteInput: NoteGenInput = { amount: amount, backend: 'Arkworks', curve: 'Bn254', denomination: '18', exponentiation: '5', hashFunction: 'Poseidon', protocol: 'anchor', sourceChain: sourceChainId.toString(), sourceIdentifyingData: anchorIndex.toString(), targetChain: destChainId.toString(), targetIdentifyingData: treeId.toString(), tokenSymbol: tokenSymbol, version: 'v1', width: '4' }; logger.log('note input', noteInput); const note = await Note.generateNote(noteInput); logger.log('Generated note: ', note.note); const leaf = note.getLeaf(); const leafHex = u8aToHex(leaf); logger.trace(`treeId ${treeId}, Leaf ${leafHex}`); return { note, params: [treeId, leafHex] }; } private get bridgeApi () { return this.inner.methods.anchorApi as AnchorApi<WebbPolkadot, BridgeConfig>; } async getSizes (): Promise<AnchorSize[]> { const anchors = await this.bridgeApi.getAnchors(); const currency = this.bridgeApi.currency; if (currency) { return anchors.map((anchor, anchorIndex) => ({ amount: Number(anchor.amount), asset: currency.view.symbol, id: `Bridge=${anchor.amount}@${currency.view.name}@${anchorIndex}`, title: `${anchor.amount} ${currency.view.name}` })); } return []; } }
nepoche/webb.js
packages/api-providers/src/webb-error/webb-error.class.ts
<reponame>nepoche/webb.js<filename>packages/api-providers/src/webb-error/webb-error.class.ts<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /// list of know error codes of the dApp export enum WebbErrorCodes { /// Unsupported chain is switch via the extension UnsupportedChain, /// Unselected chain is a mismatch between provider and application UnselectedChain, /// Attempt to find a mixer size on a contract MixerSizeNotFound, /// No accounts are available NoAccountAvailable, /// Failed to parse deposit note NoteParsingFailure, /// PolkaDot extension not installed PolkaDotExtensionNotInstalled, /// MetaMasK extension not installed MetaMaskExtensionNotInstalled, /// Runtime Error on the provider InsufficientProviderInterface, /// EVM session already ended EVMSessionAlreadyEnded, /// Relayer does not support the mixer RelayerUnsupportedMixer, /// Relayer is not operating properly (sending bad leaves, etc.) RelayerMisbehaving, /// Failed to parse the chainId ChainIdTypeUnformatted, } /// An Error message with error metadata type WebbErrorMessage = { message: string; code: WebbErrorCodes; }; /// WebbError an Error class to throw errors and catch them with type export class WebbError extends Error { /// Static `Map` for error messages that will be instilled lazily static errorMessageMap: Map<WebbErrorCodes, WebbErrorMessage> = new Map(); /// error message for this error readonly errorMessage: WebbErrorMessage; constructor (readonly code: WebbErrorCodes) { super(WebbError.getErrorMessage(code).message); this.errorMessage = WebbError.getErrorMessage(code); } /// create a `WebbError` from the error code static from (code: WebbErrorCodes) { return new WebbError(code); } /// Static method to ge the error of the map if it's there , or create it and append the map static getErrorMessage (code: WebbErrorCodes): WebbErrorMessage { const errorMessage = WebbError.errorMessageMap.get(code); if (errorMessage) { return errorMessage; } switch (code) { case WebbErrorCodes.UnsupportedChain: return { code, message: 'you have switched to unsupported chain' }; case WebbErrorCodes.UnselectedChain: return { code, message: 'User did not select the chain' }; case WebbErrorCodes.MixerSizeNotFound: return { code, message: 'Mixer size not found in contract' }; case WebbErrorCodes.NoAccountAvailable: return { code, message: 'No account available' }; case WebbErrorCodes.NoteParsingFailure: return { code, message: 'Failed to parse deposit note' }; case WebbErrorCodes.PolkaDotExtensionNotInstalled: return { code, message: 'PolkaDot extension no installed' }; case WebbErrorCodes.MetaMaskExtensionNotInstalled: return { code, message: 'MetaMask extension no installed' }; case WebbErrorCodes.InsufficientProviderInterface: return { code, message: 'switched to insufficient api interface' }; case WebbErrorCodes.EVMSessionAlreadyEnded: return { code, message: 'Attempt to end session and it\' already ended or unknown error' }; case WebbErrorCodes.RelayerUnsupportedMixer: return { code, message: 'Attempt to use a relayer which does not support the mixer' }; case WebbErrorCodes.RelayerMisbehaving: return { code, message: 'The selected relayer is not operating properly' }; case WebbErrorCodes.ChainIdTypeUnformatted: return { code, message: 'Parsing of a ChainIdType failed' }; default: return { code, message: 'Unknown error' }; } } /// Coercion to sting toString () { return this.message; } }
nepoche/webb.js
packages/api-providers/src/ext-providers/web3/web3-provider.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable @typescript-eslint/ban-ts-comment */ import WalletConnectProvider from '@walletconnect/web3-provider'; import { ProvideCapabilities } from '@nepoche/api-providers/index.js'; import { ethers } from 'ethers'; import Web3 from 'web3'; import { AbstractProvider } from 'web3-core'; import { WebbError, WebbErrorCodes } from '../../webb-error/index.js'; export type AddToken = { address: string; symbol: string; decimals: number; image: string }; export interface AddEthereumChainParameter { chainId: string; // A 0x-prefixed hexadecimal string chainName: string; nativeCurrency: { name: string; symbol: string; // 2-6 characters long decimals: 18; }; rpcUrls: string[]; blockExplorerUrls?: string[]; iconUrls?: string[]; // Currently ignored. } export interface SwitchEthereumChainParameter { chainId: string; // A 0x-prefixed hexadecimal string } export interface ClientMetaData { description: string; url: string; icons: string[]; name: string; } export class Web3Provider<T = unknown> { private helperApi: T | null = null; private _capabilities: ProvideCapabilities = { addNetworkRpc: false, hasSessions: false, listenForAccountChange: false, listenForChainChane: false }; private constructor (private _inner: Web3, readonly clientMeta: ClientMetaData | null = null) {} static get currentProvider () { // @ts-ignore if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') { // @ts-ignore const provider = window.ethereum || window.web3.currentProvider; if (provider) { return provider; } } throw WebbError.from(WebbErrorCodes.MetaMaskExtensionNotInstalled); } static async fromExtension () { // @ts-ignore if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') { // @ts-ignore const provider = Web3Provider.currentProvider; await provider.enable(); const web3Provider = new Web3Provider(new Web3(provider), { description: 'MetaMask', icons: [], name: 'MetaMask', url: 'https://https://metamask.io' }); web3Provider._capabilities = { addNetworkRpc: true, hasSessions: false, listenForAccountChange: true, listenForChainChane: true }; return web3Provider; } throw WebbError.from(WebbErrorCodes.MetaMaskExtensionNotInstalled); } static fromUri (url: string) { const HttpProvider = new Web3.providers.HttpProvider(url); const web3 = new Web3(HttpProvider); return new Web3Provider(web3); } static async fromWalletConnectProvider (WCProvider: WalletConnectProvider) { await WCProvider.enable(); const web3 = new Web3(WCProvider as unknown as any); const web3Provider = new Web3Provider<WalletConnectProvider>(web3, WCProvider.walletMeta); web3Provider._capabilities = { addNetworkRpc: false, hasSessions: true, listenForAccountChange: false, listenForChainChane: false }; web3Provider.helperApi = WCProvider; return web3Provider; } get network () { return this._inner.eth.net.getId(); } get eth () { return this._inner.eth; } get account () { return this._inner.defaultAccount; } get provider () { return this._inner.eth.currentProvider; } public get capabilities () { return this._capabilities; } enable () { // @ts-ignore } intoEthersProvider () { return new ethers.providers.Web3Provider(this.provider as any, 'any'); } async endSession () { try { if (this.capabilities.hasSessions) { if (this.helperApi instanceof WalletConnectProvider) { // TODO : handle the connector not found type error // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore await this.helperApi.connector.killSession({ message: 'Session end error' }); } } } catch (e) { throw WebbError.from(WebbErrorCodes.EVMSessionAlreadyEnded); } } addChain (chainInput: AddEthereumChainParameter) { const provider = this._inner.currentProvider as AbstractProvider; return provider.request?.({ method: 'wallet_addEthereumChain', params: [chainInput] }); } switchChain (chainInput: SwitchEthereumChainParameter) { const provider = this._inner.currentProvider as AbstractProvider; return provider.request?.({ method: 'wallet_switchEthereumChain', params: [chainInput] }); } addToken (addTokenInput: AddToken) { return (this._inner.currentProvider as AbstractProvider).request?.({ method: 'wallet_watchAsset', params: { options: { address: addTokenInput.address, // The address that the token is at. decimals: addTokenInput.decimals, // The number of decimals in the token image: addTokenInput.image, // A string url of the token logo symbol: addTokenInput.symbol // A ticker symbol or shorthand, up to 5 chars. }, type: 'ERC20' // Initially only supports ERC20, but eventually more! } }); } }
nepoche/webb.js
packages/sdk-core/src/proving/proving-manager-thread.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import type { JsProofInput, Leaves, Proof } from '@nepoche/wasm-utils'; import { ProofI } from '@nepoche/sdk-core/proving/proving-manager.js'; import { Note } from '../note.js'; export type ProvingManagerSetupInput = { note: string; relayer: string; recipient: string; leaves: Leaves; leafIndex: number; fee: number; refund: number; provingKey: Uint8Array; roots?: Leaves; refreshCommitment?: string; }; type PMEvents = { proof: ProvingManagerSetupInput; destroy: undefined; }; export class ProvingManagerWrapper { constructor (private ctx: 'worker' | 'direct-call' = 'worker') { // if the Manager is running in side worker it registers an event listener if (ctx === 'worker') { self.addEventListener('message', async (event) => { const message = event.data as Partial<PMEvents>; const key = Object.keys(message)[0] as keyof PMEvents; switch (key) { case 'proof': { const input = message.proof!; const proof = await this.proof(input); (self as unknown as Worker).postMessage({ data: proof, name: key }); } break; case 'destroy': (self as unknown as Worker).terminate(); break; } }); } } private get wasmBlob () { return this.ctx === 'worker' ? import('@nepoche/wasm-utils/wasm-utils.js') : import('@nepoche/wasm-utils/njs/wasm-utils-njs.js'); } private get proofBuilder () { return this.wasmBlob.then((wasm) => { return wasm.ProofInputBuilder; }); } private async generateProof (proofInput: JsProofInput): Promise<Proof> { const wasm = await this.wasmBlob; return wasm.generate_proof_js(proofInput); } async proof (pmSetupInput: ProvingManagerSetupInput): Promise<ProofI> { const Manager = await this.proofBuilder; const pm = new Manager(); const { note } = await Note.deserialize(pmSetupInput.note); // TODO: handle the prefix and validation pm.setLeaves(pmSetupInput.leaves); pm.setRelayer(pmSetupInput.relayer); pm.setRecipient(pmSetupInput.recipient); pm.setLeafIndex(String(pmSetupInput.leafIndex)); pm.setRefund(String(pmSetupInput.refund)); pm.setFee(String(pmSetupInput.fee)); pm.setPk(u8aToHex(pmSetupInput.provingKey).replace('0x', '')); pm.setNote(note); if (pmSetupInput.roots) { pm.setRoots(pmSetupInput.roots); } if (pmSetupInput.refreshCommitment) { pm.setRefreshCommitment(pmSetupInput.refreshCommitment); } const proofInput = pm.build_js(); const proof = await this.generateProof(proofInput); return { nullifierHash: proof.nullifierHash, proof: proof.proof, root: proof.root, roots: proof.roots }; } } /* Copied code from @polkadot.js to avoid calling polkadot dependencies in a web worker context. Issue: https://github.com/polkadot-js/common/issues/1435 */ const U8_TO_HEX = new Array<any>(256); const U16_TO_HEX = new Array<any>(256 * 256); const HEX_TO_U8 = {}; const HEX_TO_U16 = {}; for (let n = 0; n < 256; n++) { const hex = n.toString(16).padStart(2, '0'); U8_TO_HEX[n] = hex; // @ts-ignore HEX_TO_U8[hex] = n; } for (let i = 0; i < 256; i++) { for (let j = 0; j < 256; j++) { const hex = U8_TO_HEX[i] + U8_TO_HEX[j]; const n = i << 8 | j; U16_TO_HEX[n] = hex; // @ts-ignore HEX_TO_U16[hex] = n; } } // @ts-ignore function hex (value) { const mod = value.length % 2; const length = value.length - mod; const dv = new DataView(value.buffer, value.byteOffset); let result = ''; for (let i = 0; i < length; i += 2) { result += U16_TO_HEX[dv.getUint16(i)]; } if (mod) { result += U8_TO_HEX[dv.getUint8(length)]; } return result; } // @ts-ignore export function u8aToHex (value, bitLength = -1, isPrefixed = true) { const length = Math.ceil(bitLength / 8); return `${isPrefixed ? '0x' : ''}${!value || !value.length ? '' : length > 0 && value.length > length ? `${hex(value.subarray(0, length / 2))}…${hex(value.subarray(value.length - length / 2))}` : hex(value)}`; }
nepoche/webb.js
packages/api-providers/src/storage/storage.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { EventBus } from '@nepoche/app-util/index.js'; export interface StorageHandler<T> { inner: T; fetch(key: string): Promise<T>; commit(key: string, data: T): Promise<void>; } export class Storage<Store> extends EventBus<{ update: Store; }> { static instances = new Map<string, Storage<any>>(); static get<Store extends Record<string, unknown>> (key: string): Storage<Store> { return Storage.instances.get(key) as Storage<Store>; } static async newFresh<Store> (name: string, handler: StorageHandler<Store>): Promise<Storage<Store>> { const instance = new Storage<Store>(name, handler); Storage.instances.set(name, instance); await instance.commit(name, handler.inner); return instance; } static async newFromCache<Store> (name: string, data: Omit<StorageHandler<Store>, 'inner'>): Promise<Storage<Store>> { const storage = await data.fetch(name); const instance = new Storage<Store>(name, { ...data, inner: storage }); Storage.instances.set(name, instance); return instance; } readonly fetch: StorageHandler<Store>['fetch']; private readonly commit: StorageHandler<Store>['commit']; private data: Store; private constructor (readonly name: string, data: StorageHandler<Store>) { super(); this.data = data.inner; this.fetch = data.fetch; this.commit = data.commit; } async get<Key extends keyof Store> (key: Key): Promise<Store[Key]> { const data = this.data[key]; return data; } async dump () { return this.data; } async set<Key extends keyof Store> (key: Key, data: Store[Key]) { this.data = { ...this.data, [key]: data }; await this.commit(this.name, this.data); this.emit('update', this.data); } }
nepoche/webb.js
packages/api-providers/src/web3/wrap-unwrap.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { Bridge, Currency, MixerSize, WrapUnWrap } from '@nepoche/api-providers/abstracts/index.js'; import { Amount, WrappingBalance, WrappingEvent } from '@nepoche/api-providers/index.js'; import { ERC20__factory as ERC20Factory } from '@nepoche/contracts'; import { ContractTransaction } from 'ethers'; import { BehaviorSubject, Observable, Subject } from 'rxjs'; import Web3 from 'web3'; import { evmIdIntoInternalChainId, InternalChainId } from '../chains/index.js'; import { WebbGovernedToken, zeroAddress } from '../contracts/index.js'; import { WebbCurrencyId, webbCurrencyIdToString } from '../enums/index.js'; import { CurrencyType } from '../types/currency-config.interface.js'; import { WebbWeb3Provider } from './webb-provider.js'; export type Web3WrapPayload = Amount; export type Web3UnwrapPayload = Amount; const defaultBalance: WrappingBalance = { balance: '0', tokenId: undefined }; export class Web3WrapUnwrap extends WrapUnWrap<WebbWeb3Provider> { private _balances = new BehaviorSubject<[WrappingBalance, WrappingBalance]>([defaultBalance, defaultBalance]); private _liquidity = new BehaviorSubject<[WrappingBalance, WrappingBalance]>([defaultBalance, defaultBalance]); private _currentChainId = new BehaviorSubject<InternalChainId | null>(null); private _event = new Subject<Partial<WrappingEvent>>(); private get config () { return this.inner.config; } get balances (): Observable<[WrappingBalance, WrappingBalance]> { return this._balances.asObservable(); } get liquidity (): Observable<[WrappingBalance, WrappingBalance]> { return this._liquidity.asObservable(); } get subscription (): Observable<Partial<WrappingEvent>> { return this._event.asObservable(); } constructor (protected inner: WebbWeb3Provider) { super(inner); inner.getChainId().then((evmChainId) => { this._currentChainId.next(evmIdIntoInternalChainId(evmChainId)); this._event.next({ ready: null }); }).catch((e) => { throw e; }); inner.on('providerUpdate', ([evmChainId]) => { this._currentChainId.next(evmIdIntoInternalChainId(evmChainId)); this._event.next({ stateUpdate: null }); }); } setGovernedToken (nextToken: WebbCurrencyId | null) { this._governedToken.next(nextToken); this._event.next({ governedTokenUpdate: nextToken }); } setWrappableToken (nextToken: WebbCurrencyId | null) { this._wrappableToken.next(nextToken); this._event.next({ wrappableTokenUpdate: nextToken }); } getSizes (): Promise<MixerSize[]> { return Promise.resolve([]); } private get currentChainId () { return this._currentChainId.value; } // TODO: Dynamic wrappable currencies // async getWrappableTokens (governedCurrency?: WebbCurrencyId | null): Promise<WebbCurrencyId[]> { if (this.currentChainId) { const currenciesOfChain = this.config.chains[this.currentChainId].currencies; const wrappableCurrencies = currenciesOfChain.filter((currencyId) => { return Currency.isWrappableCurrency(this.inner.config.currencies, currencyId); }); if (governedCurrency) { const webbGovernedToken = this.governedTokenWrapper(governedCurrency); return wrappableCurrencies.filter((token) => { const tokenAddress = this.config.currencies[token].addresses.get(this.currentChainId!)!; return webbGovernedToken.canWrap(tokenAddress); }); } else { return wrappableCurrencies; } } return []; } async getGovernedTokens (): Promise<WebbCurrencyId[]> { if (this.currentChainId) { return Bridge.getTokensOfChain(this.inner.config.currencies, this.currentChainId).map( (currency) => currency.view.id ); } return []; } async canUnWrap (unwrapPayload: Web3UnwrapPayload): Promise<boolean> { const { amount } = unwrapPayload; const governedTokenId = this.governedToken!; const webbGovernedToken = this.governedTokenWrapper(governedTokenId); const account = await this.inner.accounts.accounts(); const currentAccount = account[0]; return webbGovernedToken.canUnwrap(currentAccount.address, Number(amount)); } async unwrap (unwrapPayload: Web3UnwrapPayload): Promise<string> { const { amount: amountNumber } = unwrapPayload; const governedTokenId = this.governedToken!; const wrappableTokenId = this.wrappableToken!; const amount = Web3.utils.toWei(String(amountNumber), 'ether'); const webbGovernedToken = this.governedTokenWrapper(governedTokenId); try { this.inner.notificationHandler({ description: `Unwrapping ${amountNumber} of ${webbCurrencyIdToString( governedTokenId )} to ${webbCurrencyIdToString(wrappableTokenId)}`, key: 'unwrap-asset', level: 'loading', message: 'GovernedTokenWrapper:unwrap', name: 'Transaction' }); const tx = await webbGovernedToken.unwrap( this.config.currencies[wrappableTokenId].addresses.get(this.currentChainId!)!, amount ); await tx.wait(); this.inner.notificationHandler({ description: `Unwrapping ${amountNumber} of ${webbCurrencyIdToString( governedTokenId )} to ${webbCurrencyIdToString(wrappableTokenId)}`, key: 'unwrap-asset', level: 'success', message: 'GovernedTokenWrapper:unwrap', name: 'Transaction' }); return tx.hash; } catch (e) { console.log('error while unwrapping: ', e); this.inner.notificationHandler({ description: `Failed to unwrap ${amountNumber} of ${webbCurrencyIdToString( governedTokenId )} to ${webbCurrencyIdToString(wrappableTokenId)}`, key: 'unwrap-asset', level: 'error', message: 'GovernedTokenWrapper:unwrap', name: 'Transaction' }); return ''; } } async canWrap (): Promise<boolean> { const governedToken = this.governedToken!; const wrappableToken = this.wrappableToken!; const webbGovernedToken = this.governedTokenWrapper(governedToken); if (this.config.currencies[wrappableToken].type === CurrencyType.NATIVE) { return webbGovernedToken.isNativeAllowed(); } else { const tokenAddress = this.config.currencies[governedToken].addresses.get(this.currentChainId!)!; return webbGovernedToken.canWrap(tokenAddress); } } async wrap (wrapPayload: Web3WrapPayload): Promise<string> { const { amount: amountNumber } = wrapPayload; const wrappableTokenId = this.wrappableToken!; const governableTokenId = this.governedToken!; const webbGovernedToken = this.governedTokenWrapper(governableTokenId); const amount = Web3.utils.toWei(String(amountNumber), 'ether'); try { this.inner.notificationHandler({ description: `Wrapping ${String(amountNumber)} of ${webbCurrencyIdToString( wrappableTokenId )} to ${webbCurrencyIdToString(governableTokenId)}`, key: 'wrap-asset', level: 'loading', message: 'GovernedTokenWrapper:wrap', name: 'Transaction' }); console.log('address of token to wrap into webbGovernedToken', this.getAddressFromWrapTokenId(wrappableTokenId)); let tx: ContractTransaction; // If wrapping an erc20, check for approvals if (this.getAddressFromWrapTokenId(wrappableTokenId) !== zeroAddress) { const wrappableTokenInstance = ERC20Factory.connect( this.getAddressFromWrapTokenId(wrappableTokenId), this.inner.getEthersProvider().getSigner() ); const wrappableTokenAllowance = await wrappableTokenInstance.allowance( await this.inner.getEthersProvider().getSigner().getAddress(), wrappableTokenInstance.address ); console.log(wrappableTokenAllowance); if (wrappableTokenAllowance.lt(amount)) { this.inner.notificationHandler({ description: 'Waiting for token approval', key: 'waiting-approval', level: 'info', message: 'Waiting for token approval', name: 'Approval', persist: true }); tx = await wrappableTokenInstance.approve(webbGovernedToken.address, amount); await tx.wait(); this.inner.notificationHandler.remove('waiting-approval'); } } tx = await webbGovernedToken.wrap(this.getAddressFromWrapTokenId(wrappableTokenId), amount); await tx.wait(); this.inner.notificationHandler({ description: `Wrapping ${String(amountNumber)} of ${webbCurrencyIdToString( wrappableTokenId )} to ${webbCurrencyIdToString(governableTokenId)}`, key: 'wrap-asset', level: 'success', message: 'GovernedTokenWrapper:wrap', name: 'Transaction' }); return tx.hash; } catch (e) { console.log('error while wrapping: ', e); this.inner.notificationHandler({ description: `Failed to wrap ${String(amountNumber)} of ${webbCurrencyIdToString( wrappableTokenId )} to ${webbCurrencyIdToString(governableTokenId)}`, key: 'wrap-asset', level: 'error', message: 'GovernedTokenWrapper:wrap', name: 'Transaction' }); return ''; } } private getAddressFromWrapTokenId (id: WebbCurrencyId): string { const currentNetwork = this.currentChainId!; const address = this.config.currencies[id].addresses.get(currentNetwork)!; return address; } governedTokenWrapper (id: WebbCurrencyId): WebbGovernedToken { const contractAddress = this.getAddressFromWrapTokenId(id); return new WebbGovernedToken(this.inner.getEthersProvider(), contractAddress); } }
nepoche/webb.js
tests/integration_tests/substrate/mixerTests.spec.ts
<filename>tests/integration_tests/substrate/mixerTests.spec.ts import { JsNote, OperationError } from '@nepoche/wasm-utils/njs/wasm-utils-njs.js'; import { ApiPromise } from '@polkadot/api'; import { Keyring } from '@polkadot/keyring'; import { KeyringPair } from '@polkadot/keyring/types'; import { catchWasmError, depositMixerBnX5_3, KillTask, preparePolkadotApi, sleep, startWebbNode, transferBalance, withdrawMixerBnX5_3, } from '../../utils/index.js'; let apiPromise: ApiPromise | null = null; let keyring: { bob: KeyringPair; alice: KeyringPair; charlie: KeyringPair; } | null = null; let nodes: KillTask | undefined; const BOBPhrase = 'asthma early danger glue satisfy spatial decade wing organ bean census announce'; function getKeyring() { if (keyring) { return keyring; } const k = new Keyring({ type: 'sr25519' }); const bob = k.addFromMnemonic(BOBPhrase); const alice = k.addFromUri('//Alice'); const charlie = k.addFromUri('//Charlie'); keyring = { bob, alice, charlie, }; return keyring; } describe('Mixer tests', function () { this.timeout(120_000); before(async function () { // If LOCAL_NODE is set the tests will continue to use the already running node nodes = startWebbNode(); apiPromise = await preparePolkadotApi(); }); it('Mixer should work', async function () { try { const { bob, charlie, alice } = getKeyring(); // transfer some funds to sudo & test account console.log(`Transferring 10,000 balance to Alice and Bob`) await transferBalance(apiPromise!, charlie, [alice, bob], 10_000); let note: JsNote; // deposit to the mixer console.log(`Depositing to the mixer`) note = await catchWasmError(() => depositMixerBnX5_3(apiPromise!, bob)); ///Give the chain sometime to insure the leaf is there await sleep(10_000); // withdraw fro the mixer console.log(`Withdrawing from the mixer`) await catchWasmError(() => withdrawMixerBnX5_3(apiPromise!, bob, note!, bob.address)); } catch (e) { if (e instanceof OperationError) { const errorMessage = { code: e.code, errorMessage: e.error_message, data: e.data, }; console.log(errorMessage); throw errorMessage; } else { throw e; } } }); after(async function () { await nodes?.(); }); });
nepoche/webb.js
packages/types/src/interfaces/augment-api.d.ts
<gh_stars>0 /* eslint-disable */ /// <reference path="./augment-api-consts.d.ts" /> /// <reference path="./augment-api-tx.d.ts" /> /// <reference path="./augment-api-query.d.ts" /> /// <reference path="./augment-types.d.ts" />
nepoche/webb.js
packages/type-definitions/src/mixer.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export default { rpc: {}, types: { Amount: 'i128', AmountOf: 'Amount', CurrencyId: 'u64', CurrencyIdOf: 'CurrencyId', ScalarData: '[u8; 32]' }, typesAlias: {} };
nepoche/webb.js
packages/api-providers/src/utils/fixtures.ts
<reponame>nepoche/webb.js<filename>packages/api-providers/src/utils/fixtures.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export const fetchTornadoCircuitData = async () => { const IPFSUrl = 'https://ipfs.io/ipfs/QmbX8PzkcU1SQwUis3zDWEKsn8Yjgy2vALNeghVM2uh31B'; const ipfsRequest = await fetch(IPFSUrl); const circuitData = await ipfsRequest.json(); return circuitData; }; export const fetchTornadoProvingKey = async () => { const IPFSUrl = 'https://ipfs.io/ipfs/QmQwgF8aWJzGSXoe1o3jrEPdcfBysWctB2Uwu7uRebXe2D'; const ipfsRequest = await fetch(IPFSUrl); const provingKey = await ipfsRequest.arrayBuffer(); return provingKey; };
nepoche/webb.js
packages/api-providers/src/polkadot/transaction.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable @typescript-eslint/ban-ts-comment */ import { NotificationHandler } from '@nepoche/api-providers/index.js'; import { EventBus, LoggerService } from '@nepoche/app-util/index.js'; import lodash from 'lodash'; import { ApiPromise, SubmittableResult } from '@polkadot/api'; import { SubmittableExtrinsic } from '@polkadot/api/submittable/types'; import { IKeyringPair } from '@polkadot/types/types'; import { ReactElement } from '../types/abstracts.js'; const { uniqueId } = lodash; type AddressOrPair = string | IKeyringPair; export type QueueTxStatus = | 'future' | 'ready' | 'finalized' | 'finalitytimeout' | 'usurped' | 'dropped' | 'inblock' | 'invalid' | 'broadcast' | 'cancelled' | 'completed' | 'error' | 'incomplete' | 'queued' | 'qr' | 'retracted' | 'sending' | 'signing' | 'sent' | 'blocked'; type MethodPath = { section: string; method: string; }; type PolkadotTXEventsPayload<T = undefined> = { data: T; key: string; address: string; path: MethodPath; }; type PolkadotTXEvents = { beforeSend: PolkadotTXEventsPayload; afterSend: PolkadotTXEventsPayload; failed: PolkadotTXEventsPayload<string>; finalize: PolkadotTXEventsPayload<string | void | undefined>; inBlock: PolkadotTXEventsPayload; extrinsicSuccess: PolkadotTXEventsPayload; loading: PolkadotTXEventsPayload<any>; }; export type NotificationConfig = { loading: (data: PolkadotTXEventsPayload<ReactElement>) => string | number; finalize: (data: PolkadotTXEventsPayload<string | void | undefined>) => string | number; failed: (data: PolkadotTXEventsPayload<string>) => string | number; }; const txLogger = LoggerService.get('PolkadotTx'); export class PolkadotTx<P extends Array<any>> extends EventBus<PolkadotTXEvents> { public notificationKey = ''; private transactionAddress: AddressOrPair | null = null; private isWrapped = false; constructor (private apiPromise: ApiPromise, private path: MethodPath, private parms: P) { super(); } async call (signAddress: AddressOrPair) { txLogger.info(`Sending ${this.path.section} ${this.path.method} transaction by`, signAddress, this.parms); this.transactionAddress = signAddress; const api = this.apiPromise; await api.isReady; if (!api.tx[this.path.section] || !api.tx[this.path.section][this.path.method]) { txLogger.error(`can not find api.tx.${this.path.section}.${this.path.method}`); return; } this.notificationKey = uniqueId(`${this.path.section}-${this.path.method}`); if ((signAddress as IKeyringPair)?.address === undefined) { // passed an account id or string of address const { web3FromAddress } = await import('@polkadot/extension-dapp'); const injector = await web3FromAddress(signAddress as string); await api.setSigner(injector.signer); } const txResults = await api.tx[this.path.section][this.path.method](...this.parms).signAsync(signAddress, { nonce: -1 }); await this.emitWithPayload('beforeSend', undefined); await this.emitWithPayload('loading', ''); const hash = txResults.hash.toString(); await this.send(txResults); await this.emitWithPayload('afterSend', undefined); this.transactionAddress = null; txLogger.info(`Tx ${this.path.section} ${this.path.method} is Done: TX hash=`, hash); return hash; } protected async emitWithPayload<E extends keyof PolkadotTXEvents> ( event: E, data: PolkadotTXEvents[E]['data'] ): Promise<void> { if (this.isWrapped) { return; } this.emit(event, { address: this.transactionAddress ?? '', data: data, key: this.notificationKey, path: this.path } as any); } private errorHandler (r: SubmittableResult) { // @ts-ignore let message = r.dispatchError?.type || r.type || r.message; if (r.dispatchError?.isModule) { try { const mod = r.dispatchError.asModule; const error = this.apiPromise.registry.findMetaError( new Uint8Array([mod.index.toNumber(), mod.error.toNumber()]) ); message = `${error.section}.${error.name}`; } catch (error) { message = Reflect.has(error as any, 'toString') ? (error as any)?.toString() : error; } } // eslint-disable-next-line @typescript-eslint/no-floating-promises this.emitWithPayload('failed', message); return message; } private async send (tx: SubmittableExtrinsic<any>) { // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { try { await tx.send(async (result) => { const status = result.status; const events = result.events.filter(({ event: { section } }) => section === 'system'); if (status.isInBlock || status.isFinalized) { for (const event of events) { const { event: { data, method } } = event; const [dispatchError] = data as any; if (method === 'ExtrinsicFailed') { let message = dispatchError.type; if (dispatchError.isModule) { try { const mod = dispatchError.asModule; const error = dispatchError.registry.findMetaError(mod); message = `${error.section}.${error.name}`; } catch (error) { const message = this.errorHandler(error as any); reject(message); } } else if (dispatchError.isToken) { message = `${dispatchError.type}.${dispatchError.asToken.type}`; } this.isWrapped = true; await this.emitWithPayload('failed', message); reject(message); } else if (method === 'ExtrinsicSuccess') { // todo return the TX hash resolve('okay'); await this.emitWithPayload('finalize', undefined); this.isWrapped = true; } } } }); } catch (e) { console.log(e); const errorMessage = this.errorHandler(e as any); await this.emitWithPayload('failed', errorMessage); reject(errorMessage); } }); } } export class PolkaTXBuilder { constructor (private apiPromise: ApiPromise, private notificationHandler: NotificationHandler) { } buildWithoutNotification<P extends Array<any>> ({ method, section }: MethodPath, params: P): PolkadotTx<P> { return new PolkadotTx<P>(this.apiPromise.clone(), { method, section }, params); } build<P extends Array<any>> (path: MethodPath, params: P, notificationHandler?: NotificationHandler): PolkadotTx<P> { const tx = this.buildWithoutNotification(path, params); const handler = notificationHandler || this.notificationHandler; tx.on('loading', (data) => { handler({ description: data.address, key: data.key, level: 'loading', message: `${data.path.section}:${data.path.method}`, name: 'Transaction', persist: true }); }); tx.on('finalize', (data) => { handler({ description: data.address, key: data.key, level: 'success', message: `${data.path.section}:${data.path.method}`, name: 'Transaction', persist: true }); }); tx.on('failed', (data) => { console.log(data); handler({ description: data.data, key: data.key, level: 'error', message: `${data.path.section}:${data.path.method}`, name: 'Transaction', persist: true }); }); return tx; } }
nepoche/webb.js
packages/api-providers/src/contracts/tornado/Tornado__factory.ts
<gh_stars>0 /* Autogenerated file. Do not edit manually. */ /* tslint:disable */ /* eslint-disable */ import { Contract, Signer, utils } from 'ethers'; import { Provider } from '@ethersproject/providers'; import type { Tornado, TornadoInterface } from '../tornado'; const _abi = [ { anonymous: false, inputs: [ { indexed: true, internalType: 'bytes32', name: 'commitment', type: 'bytes32', }, { indexed: false, internalType: 'uint32', name: 'leafIndex', type: 'uint32', }, { indexed: false, internalType: 'uint256', name: 'timestamp', type: 'uint256', }, ], name: 'Deposit', type: 'event', }, { anonymous: false, inputs: [ { indexed: false, internalType: 'address', name: 'to', type: 'address', }, { indexed: false, internalType: 'bytes32', name: 'nullifierHash', type: 'bytes32', }, { indexed: true, internalType: 'address', name: 'relayer', type: 'address', }, { indexed: false, internalType: 'uint256', name: 'fee', type: 'uint256', }, ], name: 'Withdrawal', type: 'event', }, { inputs: [], name: 'FIELD_SIZE', outputs: [ { internalType: 'uint256', name: '', type: 'uint256', }, ], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'ROOT_HISTORY_SIZE', outputs: [ { internalType: 'uint32', name: '', type: 'uint32', }, ], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'ZERO_VALUE', outputs: [ { internalType: 'uint256', name: '', type: 'uint256', }, ], stateMutability: 'view', type: 'function', }, { inputs: [ { internalType: 'bytes32', name: '', type: 'bytes32', }, ], name: 'commitments', outputs: [ { internalType: 'bool', name: '', type: 'bool', }, ], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'currentRootIndex', outputs: [ { internalType: 'uint32', name: '', type: 'uint32', }, ], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'denomination', outputs: [ { internalType: 'uint256', name: '', type: 'uint256', }, ], stateMutability: 'view', type: 'function', }, { inputs: [ { internalType: 'uint256', name: '', type: 'uint256', }, ], name: 'filledSubtrees', outputs: [ { internalType: 'bytes32', name: '', type: 'bytes32', }, ], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'getLastRoot', outputs: [ { internalType: 'bytes32', name: '', type: 'bytes32', }, ], stateMutability: 'view', type: 'function', }, { inputs: [ { internalType: 'contract IHasher', name: '_hasher', type: 'address', }, { internalType: 'bytes32', name: '_left', type: 'bytes32', }, { internalType: 'bytes32', name: '_right', type: 'bytes32', }, ], name: 'hashLeftRight', outputs: [ { internalType: 'bytes32', name: '', type: 'bytes32', }, ], stateMutability: 'pure', type: 'function', }, { inputs: [], name: 'hasher', outputs: [ { internalType: 'contract IHasher', name: '', type: 'address', }, ], stateMutability: 'view', type: 'function', }, { inputs: [ { internalType: 'bytes32', name: '_root', type: 'bytes32', }, ], name: 'isKnownRoot', outputs: [ { internalType: 'bool', name: '', type: 'bool', }, ], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'levels', outputs: [ { internalType: 'uint32', name: '', type: 'uint32', }, ], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'nextIndex', outputs: [ { internalType: 'uint32', name: '', type: 'uint32', }, ], stateMutability: 'view', type: 'function', }, { inputs: [ { internalType: 'bytes32', name: '', type: 'bytes32', }, ], name: 'nullifierHashes', outputs: [ { internalType: 'bool', name: '', type: 'bool', }, ], stateMutability: 'view', type: 'function', }, { inputs: [ { internalType: 'uint256', name: '', type: 'uint256', }, ], name: 'roots', outputs: [ { internalType: 'bytes32', name: '', type: 'bytes32', }, ], stateMutability: 'view', type: 'function', }, { inputs: [], name: 'verifier', outputs: [ { internalType: 'contract IVerifier', name: '', type: 'address', }, ], stateMutability: 'view', type: 'function', }, { inputs: [ { internalType: 'uint256', name: 'i', type: 'uint256', }, ], name: 'zeros', outputs: [ { internalType: 'bytes32', name: '', type: 'bytes32', }, ], stateMutability: 'pure', type: 'function', }, { inputs: [ { internalType: 'bytes32', name: '_commitment', type: 'bytes32', }, ], name: 'deposit', outputs: [], stateMutability: 'payable', type: 'function', }, { inputs: [ { internalType: 'bytes', name: '_proof', type: 'bytes', }, { internalType: 'bytes32', name: '_root', type: 'bytes32', }, { internalType: 'bytes32', name: '_nullifierHash', type: 'bytes32', }, { internalType: 'address payable', name: '_recipient', type: 'address', }, { internalType: 'address payable', name: '_relayer', type: 'address', }, { internalType: 'uint256', name: '_fee', type: 'uint256', }, { internalType: 'uint256', name: '_refund', type: 'uint256', }, ], name: 'withdraw', outputs: [], stateMutability: 'payable', type: 'function', }, { inputs: [ { internalType: 'bytes32', name: '_nullifierHash', type: 'bytes32', }, ], name: 'isSpent', outputs: [ { internalType: 'bool', name: '', type: 'bool', }, ], stateMutability: 'view', type: 'function', }, { inputs: [ { internalType: 'bytes32[]', name: '_nullifierHashes', type: 'bytes32[]', }, ], name: 'isSpentArray', outputs: [ { internalType: 'bool[]', name: 'spent', type: 'bool[]', }, ], stateMutability: 'view', type: 'function', }, ]; export class Tornado__factory { static readonly abi = _abi; static createInterface(): TornadoInterface { return new utils.Interface(_abi) as TornadoInterface; } static connect(address: string, signerOrProvider: Signer | Provider): Tornado { return new Contract(address, _abi, signerOrProvider) as Tornado; } }
nepoche/webb.js
packages/api-providers/src/contracts/utils/poseidon-hash3.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 // @ts-ignore import circomlib from 'circomlibjs'; const hashLeftRight = (left: bigint, right: bigint) => { return circomlib.poseidon([left, right]); }; export function poseidonHash3 (inputs: any[]) { if (inputs.length !== 3) { throw new Error('panic'); } return circomlib.poseidon(inputs); } export class PoseidonHasher3 { hash (_level: any, left: any, right: any) { return hashLeftRight(BigInt(left), BigInt(right)).toString(); } hash3 (inputs: any) { if (inputs.length !== 3) { throw new Error('panic'); } return circomlib.poseidon(inputs); } }
nepoche/webb.js
packages/api-providers/src/web3/anchor-withdraw.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */ import { parseUnits } from '@ethersproject/units'; import { Bridge, OptionalActiveRelayer, OptionalRelayer, RelayedWithdrawResult, RelayerCMDBase, WebbRelayer, WithdrawState } from '@nepoche/api-providers/index.js'; import { anchorDeploymentBlock, bridgeCurrencyBridgeStorageFactory, chainIdToRelayerName, getAnchorAddressForBridge, getEVMChainName, getEVMChainNameFromInternal, MixerStorage } from '@nepoche/api-providers/utils/index.js'; import { LoggerService } from '@nepoche/app-util/index.js'; import { Note } from '@nepoche/sdk-core/index.js'; import { JsNote as DepositNote } from '@nepoche/wasm-utils'; import { BigNumber } from 'ethers'; import { AnchorWithdraw } from '../abstracts/index.js'; import { chainTypeIdToInternalId, evmIdIntoInternalChainId, InternalChainId, parseChainIdType } from '../chains/index.js'; import { generateWithdrawProofCallData, hexStringToBytes } from '../contracts/utils/bridge-utils.js'; import { bufferToFixed } from '../contracts/utils/buffer-to-fixed.js'; import { depositFromAnchorNote } from '../contracts/utils/make-deposit.js'; import { AnchorContract, ZKPWebbAnchorInputWithoutMerkle } from '../contracts/wrappers/index.js'; import { webbCurrencyIdFromString } from '../enums/index.js'; import { Web3Provider } from '../ext-providers/index.js'; import { WebbError, WebbErrorCodes } from '../webb-error/index.js'; import { WebbWeb3Provider } from './webb-provider.js'; const logger = LoggerService.get('Web3BridgeWithdraw'); export class Web3AnchorWithdraw extends AnchorWithdraw<WebbWeb3Provider> { private get config () { return this.inner.config; } async mapRelayerIntoActive (relayer: OptionalRelayer): Promise<OptionalActiveRelayer> { if (!relayer) { return null; } const evmId = await this.inner.getChainId(); const chainId = evmIdIntoInternalChainId(evmId); return WebbRelayer.intoActiveWebRelayer( relayer, { basedOn: 'evm', chain: chainId }, // Define the function for retrieving fee information for the relayer async (note: string) => { const depositNote = await Note.deserialize(note); const evmNote = depositNote.note; const contractAddress = await getAnchorAddressForBridge( webbCurrencyIdFromString(evmNote.tokenSymbol), Number(evmNote.targetChainId), Number(evmNote.amount), this.config.bridgeByAsset ); if (!contractAddress) { throw new Error('Unsupported configuration for bridge'); } // Given the note, iterate over the relayer's supported contracts and find the corresponding configuration // for the contract. const supportedContract = relayer.capabilities.supportedChains.evm .get(Number(evmNote.targetChainId)) ?.contracts.find(({ address, size }) => { // Match on the relayer configuration as well as note return address.toLowerCase() === contractAddress.toLowerCase() && size === Number(evmNote.amount); }); // The user somehow selected a relayer which does not support the mixer. // This should not be possible as only supported mixers should be selectable in the UI. if (!supportedContract) { throw WebbError.from(WebbErrorCodes.RelayerUnsupportedMixer); } const principleBig = parseUnits(supportedContract.size.toString(), evmNote.denomination); const withdrawFeeMill = supportedContract.withdrawFeePercentage * 1000000; const withdrawFeeMillBig = BigNumber.from(withdrawFeeMill); const feeBigMill = principleBig.mul(withdrawFeeMillBig); const feeBig = feeBigMill.div(BigNumber.from(1000000)); return { totalFees: feeBig.toString(), withdrawFeePercentage: supportedContract.withdrawFeePercentage }; } ); } async getRelayersByChainAndAddress (chainId: InternalChainId, address: string) { return this.inner.relayingManager.getRelayer({ baseOn: 'evm', chainId: chainId, contractAddress: address }); } get relayers () { return this.inner.getChainId().then((evmId) => { const chainId = evmIdIntoInternalChainId(evmId); return this.inner.relayingManager.getRelayer({ baseOn: 'evm', chainId }); }); } async getRelayersByNote (evmNote: Note) { return this.inner.relayingManager.getRelayer({ baseOn: 'evm', bridgeSupport: { amount: Number(evmNote.note.amount), tokenSymbol: evmNote.note.tokenSymbol }, chainId: Number(evmNote.note.targetChainId) }); } async sameChainWithdraw (note: DepositNote, recipient: string): Promise<string> { this.cancelToken.cancelled = false; const bridgeCurrencyId = webbCurrencyIdFromString(note.tokenSymbol); const bridge = Bridge.from(bridgeCurrencyId, this.inner.config); const activeChain = await this.inner.getChainId(); const internalId = evmIdIntoInternalChainId(activeChain); const contractAddresses = bridge.anchors.find((anchor) => anchor.amount === note.amount)!; const contractAddress = contractAddresses.anchorAddresses[internalId]!; const contract = this.inner.getWebbAnchorByAddress(contractAddress); const accounts = await this.inner.accounts.accounts(); const account = accounts[0]; const deposit = depositFromAnchorNote(note); logger.info(`Commitment for withdraw is ${deposit.commitment}`); const input = { destinationChainId: activeChain, fee: 0, nullifier: deposit.nullifier, // Todo change this to the RELAYER address nullifierHash: deposit.nullifierHash, recipient: account.address, refund: 0, relayer: account.address, secret: deposit.secret }; logger.trace('input for zkp', input); const section = `Bridge ${bridge.currency .getChainIds() .map((id) => getEVMChainNameFromInternal(this.config, id)) .join('-')}`; const key = 'web3-bridge-withdraw'; this.emit('stateChange', WithdrawState.GeneratingZk); const zkpResults = await contract.generateZKP(deposit, input); this.inner.notificationHandler({ description: 'Withdraw in progress', key, level: 'loading', message: `${section}:withdraw`, name: 'Transaction' }); // Check for cancelled here, abort if it was set. if (this.cancelToken.cancelled) { this.inner.notificationHandler({ description: 'Withdraw canceled', key, level: 'error', message: `${section}:withdraw`, name: 'Transaction' }); this.emit('stateChange', WithdrawState.Ideal); return ''; } let txHash = ''; this.emit('stateChange', WithdrawState.SendingTransaction); try { txHash = await contract.withdraw( zkpResults.proof, { destinationChainId: Number(note.targetChainId), fee: input.fee, nullifier: input.nullifier, nullifierHash: input.nullifierHash, pathElements: zkpResults.input.pathElements, pathIndices: zkpResults.input.pathIndices, recipient: input.recipient, refund: input.refund, relayer: input.relayer, root: zkpResults.root as any, secret: zkpResults.input.secret }, zkpResults.input ); } catch (e) { this.emit('stateChange', WithdrawState.Ideal); this.inner.notificationHandler({ description: (e as any)?.code === 4001 ? 'Withdraw rejected' : 'Withdraw failed', key, level: 'error', message: `${section}:withdraw`, name: 'Transaction' }); return txHash; } this.emit('stateChange', WithdrawState.Ideal); this.inner.notificationHandler({ description: recipient, key, level: 'success', message: `${section}:withdraw`, name: 'Transaction' }); return ''; } async crossChainWithdraw (note: DepositNote, recipient: string) { this.cancelToken.cancelled = false; // TODO: handle provider storage // const bridgeStorageStorage = await bridgeCurrencyBridgeStorageFactory(); const bridgeStorageStorage = await bridgeCurrencyBridgeStorageFactory(); // Setup a provider for the source chain const sourceChainIdType = parseChainIdType(Number(note.sourceChainId)); const sourceEvmId = sourceChainIdType.chainId; const sourceInternalId = evmIdIntoInternalChainId(sourceEvmId); const sourceChainConfig = this.config.chains[sourceInternalId]; const rpc = sourceChainConfig.url; const sourceHttpProvider = Web3Provider.fromUri(rpc); const sourceEthers = sourceHttpProvider.intoEthersProvider(); // get info from the destination chain (should be selected) const destChainIdType = parseChainIdType(Number(note.targetChainId)); const destInternalId = chainTypeIdToInternalId(destChainIdType); // get the deposit info const sourceDeposit = depositFromAnchorNote(note); this.emit('stateChange', WithdrawState.GeneratingZk); // Getting contracts data for source and dest chains const bridgeCurrency = this.inner.methods.anchorApi.currency; // await this.inner.methods.bridgeApi.setActiveBridge() const availableAnchors = await this.inner.methods.anchorApi.getAnchors(); console.log('availableAnchors length: ', availableAnchors.length); const selectedAnchor = availableAnchors.find((anchor) => anchor.amount === note.amount); const destContractAddress = selectedAnchor?.neighbours[destInternalId]! as string; const sourceContractAddress = selectedAnchor?.neighbours[sourceInternalId]! as string; const activeChain = await this.inner.getChainId(); // get root and neighbour root from the dest provider const destAnchor = this.inner.getWebbAnchorByAddress(destContractAddress); // Building the merkle proof const sourceContract = this.inner.getWebbAnchorByAddressAndProvider(sourceContractAddress, sourceEthers); const sourceLatestRoot = await sourceContract.inner.getLastRoot(); logger.trace(`Source latest root ${sourceLatestRoot}`); // get relayers for the source chain const sourceRelayers = this.inner.relayingManager.getRelayer({ baseOn: 'evm', bridgeSupport: { amount: Number(note.amount), tokenSymbol: note.tokenSymbol }, chainId: chainTypeIdToInternalId(parseChainIdType(Number(note.sourceChainId))) }); let leaves: string[] = []; // loop through the sourceRelayers to fetch leaves for (let i = 0; i < sourceRelayers.length; i++) { const relayerLeaves = await sourceRelayers[i].getLeaves(sourceEvmId.toString(16), sourceContractAddress); const validLatestLeaf = await sourceContract.leafCreatedAtBlock( relayerLeaves.leaves[relayerLeaves.leaves.length - 1], relayerLeaves.lastQueriedBlock ); console.log('validLatestLeaf: ', validLatestLeaf); // leaves from relayer somewhat validated, attempt to build the tree if (validLatestLeaf) { const tree = AnchorContract.createTreeWithRoot(relayerLeaves.leaves, sourceLatestRoot); // If we were able to build the tree, set local storage and break out of the loop if (tree) { console.log('tree valid, using relayer leaves'); leaves = relayerLeaves.leaves; await bridgeStorageStorage.set(sourceContract.inner.address.toLowerCase(), { lastQueriedBlock: relayerLeaves.lastQueriedBlock, leaves: relayerLeaves.leaves }); break; } } } // if we weren't able to get leaves from the relayer, get them directly from chain if (!leaves.length) { // check if we already cached some values const storedContractInfo: MixerStorage[0] = (await bridgeStorageStorage.get( sourceContractAddress.toLowerCase() )) || { lastQueriedBlock: anchorDeploymentBlock[sourceContractAddress.toLowerCase()] || 0, leaves: [] as string[] }; const leavesFromChain = await sourceContract.getDepositLeaves(storedContractInfo.lastQueriedBlock + 1, 0); leaves = [...storedContractInfo.leaves, ...leavesFromChain.newLeaves]; } // generate the merkle proof const merkleProof = await destAnchor.generateLinkedMerkleProof(sourceDeposit, leaves, sourceEvmId); if (!merkleProof) { this.emit('stateChange', WithdrawState.Ideal); throw new Error('Failed to generate Merkle proof'); } // Check for cancelled here, abort if it was set. if (this.cancelToken.cancelled) { this.inner.notificationHandler({ description: 'Withdraw cancelled', key: 'mixer-withdraw-evm', level: 'error', message: 'bridge:withdraw', name: 'Transaction' }); this.emit('stateChange', WithdrawState.Ideal); return ''; } const accounts = await this.inner.accounts.accounts(); const account = accounts[0]; this.emit('stateChange', WithdrawState.SendingTransaction); let txHash: string; const activeRelayer = this.activeRelayer[0]; if (activeRelayer && activeRelayer !== null && (activeRelayer?.account || activeRelayer?.beneficiary)) { logger.log('withdrawing through relayer'); const input: ZKPWebbAnchorInputWithoutMerkle = { destinationChainId: Number(note.targetChainId), fee: 0, nullifier: sourceDeposit.nullifier, nullifierHash: sourceDeposit.nullifierHash, recipient: recipient, refund: 0, relayer: String(activeRelayer?.beneficiary ? activeRelayer?.beneficiary : activeRelayer?.account!), secret: sourceDeposit.secret }; let zkp; try { zkp = await destAnchor.merkleProofToZKP(merkleProof, sourceEvmId, sourceDeposit, input); } catch (e) { console.log(e); this.emit('stateChange', WithdrawState.Ideal); this.inner.notificationHandler({ description: 'Deposit not yet available', key: 'mixer-withdraw-evm', level: 'error', message: 'bridge:withdraw', name: 'Transaction' }); return ''; } // convert the proof to solidity calldata const proofBytes = await generateWithdrawProofCallData(zkp.proof, zkp.input); // convert the roots into the format the relayer expects const roots = zkp.input.roots.map((root: string) => { return root.substr(2); }); const relayerRootString = roots.join(''); const relayerRootsBytes = hexStringToBytes(relayerRootString); const relayerRoots = Array.from(relayerRootsBytes); const relayedWithdraw = await activeRelayer.initWithdraw('anchorRelayTx'); logger.trace('initialized the withdraw WebSocket'); const chainInfo = { baseOn: 'evm' as RelayerCMDBase, contractAddress: destContractAddress, endpoint: '', name: chainIdToRelayerName(destInternalId) }; const tx = relayedWithdraw.generateWithdrawRequest<typeof chainInfo, 'anchorRelayTx'>( chainInfo, `0x${proofBytes}`, { chain: chainInfo.name, contract: chainInfo.contractAddress, fee: bufferToFixed(zkp.input.fee), nullifierHash: bufferToFixed(zkp.input.nullifierHash), recipient: zkp.input.recipient, refreshCommitment: '0x0000000000000000000000000000000000000000000000000000000000000000', refund: bufferToFixed(zkp.input.refund), relayer: zkp.input.relayer, roots: relayerRoots } ); relayedWithdraw.watcher.subscribe(([nextValue, message]) => { switch (nextValue) { case RelayedWithdrawResult.PreFlight: case RelayedWithdrawResult.OnFlight: this.emit('stateChange', WithdrawState.SendingTransaction); break; case RelayedWithdrawResult.Continue: break; case RelayedWithdrawResult.CleanExit: this.emit('stateChange', WithdrawState.Done); this.emit('stateChange', WithdrawState.Ideal); this.inner.notificationHandler({ description: 'Withdraw success', key: 'mixer-withdraw-evm', level: 'success', message: 'bridge:withdraw', name: 'Transaction' }); break; case RelayedWithdrawResult.Errored: this.emit('stateChange', WithdrawState.Failed); this.emit('stateChange', WithdrawState.Ideal); this.inner.notificationHandler({ description: message || 'Withdraw failed', key: 'mixer-withdraw-evm', level: 'error', message: 'bridge:withdraw', name: 'Transaction' }); break; } }); logger.trace('Sending transaction'); // stringify the request const data = JSON.stringify(tx); console.log(data); relayedWithdraw.send(tx); const txResult = await relayedWithdraw.await(); if (!txResult || !txResult?.[1]) { return ''; } txHash = txResult?.[1] || ''; } else { try { logger.log('withdrawing without relayer'); const input = { destinationChainId: Number(note.targetChainId), fee: 0, nullifier: sourceDeposit.nullifier, nullifierHash: sourceDeposit.nullifierHash, // Todo change this to the realyer address recipient: recipient, refund: 0, relayer: account.address, secret: sourceDeposit.secret }; let zkpResults; try { zkpResults = await destAnchor.merkleProofToZKP(merkleProof, sourceEvmId, sourceDeposit, input); } catch (e) { console.log(e); this.emit('stateChange', WithdrawState.Ideal); this.inner.notificationHandler({ description: 'Deposit not yet available', key: 'mixer-withdraw-evm', level: 'error', message: 'bridge:withdraw', name: 'Transaction' }); return ''; } txHash = await destAnchor.withdraw( zkpResults.proof, { destinationChainId: activeChain, fee: input.fee, nullifier: input.nullifier, nullifierHash: input.nullifierHash, pathElements: zkpResults.input.pathElements, pathIndices: zkpResults.input.pathIndices, recipient: input.recipient, refund: input.refund, relayer: input.relayer, root: zkpResults.root, secret: zkpResults.input.secret }, zkpResults.input ); } catch (e) { this.emit('stateChange', WithdrawState.Ideal); this.inner.notificationHandler({ description: (e as any)?.code === 4001 ? 'Withdraw rejected' : 'Withdraw failed', key: 'bridge-withdraw-evm', level: 'error', message: `Bridge ${bridgeCurrency ?.getChainIds() .map((id) => getEVMChainNameFromInternal(this.config, id)) .join('-')}:withdraw`, name: 'Transaction' }); return ''; } } this.inner.notificationHandler({ description: 'Withdraw done', key: 'bridge-withdraw-evm', level: 'success', message: `Bridge ${bridgeCurrency ?.getChainIds() .map((id) => getEVMChainNameFromInternal(this.config, id)) .join('-')}:withdraw`, name: 'Transaction' }); this.emit('stateChange', WithdrawState.Done); this.emit('stateChange', WithdrawState.Ideal); return txHash; } async withdraw (note: string, recipient: string): Promise<string> { logger.trace(`Withdraw using note ${note} , recipient ${recipient}`); const parseNote = await Note.deserialize(note); const depositNote = parseNote.note; const sourceChainName = getEVMChainName(this.config, parseChainIdType(Number(depositNote.sourceChainId)).chainId); const targetChainName = getEVMChainName(this.config, parseChainIdType(Number(depositNote.targetChainId)).chainId); logger.trace(`Bridge withdraw from ${sourceChainName} to ${targetChainName}`); if (depositNote.sourceChainId === depositNote.targetChainId) { logger.trace(`Same chain flow ${sourceChainName}`); return this.sameChainWithdraw(depositNote, recipient); } else { logger.trace(`cross chain flow ${sourceChainName} ----> ${targetChainName}`); return this.crossChainWithdraw(depositNote, recipient); } } }
nepoche/webb.js
packages/api-providers/src/ipfs/substrate/anchor.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { getCachedFixtureURI, withLocalFixtures } from '@nepoche/api-providers/index.js'; import { LoggerService } from '@nepoche/app-util/index.js'; const logger = LoggerService.get('IPFS'); export async function fetchSubstrateAnchorProvingKey () { // TODO: change to anchor fixture const IPFSUrl = 'https://ipfs.io/ipfs/QmXRGKJZvFpCRw5ZvdxoeXtyteof4w1tPrdu9Jopz8YzB3'; const cachedURI = getCachedFixtureURI('proving_key_substrate_anchor.bin'); const ipfsKeyRequest = await fetch(withLocalFixtures() ? cachedURI : IPFSUrl); const circuitKeyArrayBuffer = await ipfsKeyRequest.arrayBuffer(); logger.info('Done Fetching key'); const circuitKey = new Uint8Array(circuitKeyArrayBuffer); return circuitKey; }
nepoche/webb.js
packages/api-providers/src/abstracts/anchor/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './anchor.js'; export * from './anchor-deposit.js'; export * from './anchor-withdraw.js'; export * from './anchor-api.js';
nepoche/webb.js
packages/types/src/interfaces/runtime/definitions.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import runtime from '@nepoche/type-definitions/runtime'; import definitions from '@polkadot/types/interfaces/runtime/definitions'; import { Definitions } from '@polkadot/types/types'; export default { rpc: {}, types: { ...definitions.types, ...runtime.types } } as Definitions;
nepoche/webb.js
packages/sdk-core/src/type.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export type KNOWN_MODULES = 'merkle' | 'mixer'; export type CHAIN = 'dev' | 'webb';
nepoche/webb.js
packages/api-providers/src/types/abstracts.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export type ReactElement = any;
nepoche/webb.js
packages/api-providers/src/contracts/tornado/Tornado.d.ts
<filename>packages/api-providers/src/contracts/tornado/Tornado.d.ts /* Autogenerated file. Do not edit manually. */ /* tslint:disable */ /* eslint-disable */ import { ethers, EventFilter, Signer, BigNumber, BigNumberish, PopulatedTransaction, BaseContract, ContractTransaction, PayableOverrides, CallOverrides, } from 'ethers'; import { BytesLike } from '@ethersproject/bytes'; import { Listener, Provider } from '@ethersproject/providers'; import { FunctionFragment, EventFragment, Result } from '@ethersproject/abi'; import type { TypedEventFilter, TypedEvent, TypedListener } from './common'; interface TornadoInterface extends ethers.utils.Interface { functions: { 'FIELD_SIZE()': FunctionFragment; 'ROOT_HISTORY_SIZE()': FunctionFragment; 'ZERO_VALUE()': FunctionFragment; 'commitments(bytes32)': FunctionFragment; 'currentRootIndex()': FunctionFragment; 'denomination()': FunctionFragment; 'filledSubtrees(uint256)': FunctionFragment; 'getLastRoot()': FunctionFragment; 'hashLeftRight(address,bytes32,bytes32)': FunctionFragment; 'hasher()': FunctionFragment; 'isKnownRoot(bytes32)': FunctionFragment; 'levels()': FunctionFragment; 'nextIndex()': FunctionFragment; 'nullifierHashes(bytes32)': FunctionFragment; 'roots(uint256)': FunctionFragment; 'verifier()': FunctionFragment; 'zeros(uint256)': FunctionFragment; 'deposit(bytes32)': FunctionFragment; 'withdraw(bytes,bytes32,bytes32,address,address,uint256,uint256)': FunctionFragment; 'isSpent(bytes32)': FunctionFragment; 'isSpentArray(bytes32[])': FunctionFragment; }; encodeFunctionData(functionFragment: 'FIELD_SIZE', values?: undefined): string; encodeFunctionData(functionFragment: 'ROOT_HISTORY_SIZE', values?: undefined): string; encodeFunctionData(functionFragment: 'ZERO_VALUE', values?: undefined): string; encodeFunctionData(functionFragment: 'commitments', values: [BytesLike]): string; encodeFunctionData(functionFragment: 'currentRootIndex', values?: undefined): string; encodeFunctionData(functionFragment: 'denomination', values?: undefined): string; encodeFunctionData(functionFragment: 'filledSubtrees', values: [BigNumberish]): string; encodeFunctionData(functionFragment: 'getLastRoot', values?: undefined): string; encodeFunctionData(functionFragment: 'hashLeftRight', values: [string, BytesLike, BytesLike]): string; encodeFunctionData(functionFragment: 'hasher', values?: undefined): string; encodeFunctionData(functionFragment: 'isKnownRoot', values: [BytesLike]): string; encodeFunctionData(functionFragment: 'levels', values?: undefined): string; encodeFunctionData(functionFragment: 'nextIndex', values?: undefined): string; encodeFunctionData(functionFragment: 'nullifierHashes', values: [BytesLike]): string; encodeFunctionData(functionFragment: 'roots', values: [BigNumberish]): string; encodeFunctionData(functionFragment: 'verifier', values?: undefined): string; encodeFunctionData(functionFragment: 'zeros', values: [BigNumberish]): string; encodeFunctionData(functionFragment: 'deposit', values: [BytesLike]): string; encodeFunctionData( functionFragment: 'withdraw', values: [BytesLike, BytesLike, BytesLike, string, string, BigNumberish, BigNumberish] ): string; encodeFunctionData(functionFragment: 'isSpent', values: [BytesLike]): string; encodeFunctionData(functionFragment: 'isSpentArray', values: [BytesLike[]]): string; decodeFunctionResult(functionFragment: 'FIELD_SIZE', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'ROOT_HISTORY_SIZE', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'ZERO_VALUE', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'commitments', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'currentRootIndex', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'denomination', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'filledSubtrees', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'getLastRoot', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'hashLeftRight', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'hasher', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'isKnownRoot', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'levels', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'nextIndex', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'nullifierHashes', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'roots', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'verifier', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'zeros', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'deposit', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'withdraw', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'isSpent', data: BytesLike): Result; decodeFunctionResult(functionFragment: 'isSpentArray', data: BytesLike): Result; events: { 'Deposit(bytes32,uint32,uint256)': EventFragment; 'Withdrawal(address,bytes32,address,uint256)': EventFragment; }; getEvent(nameOrSignatureOrTopic: 'Deposit'): EventFragment; getEvent(nameOrSignatureOrTopic: 'Withdrawal'): EventFragment; } export type DepositEvent = TypedEvent< [string, number, BigNumber] & { commitment: string; leafIndex: number; timestamp: BigNumber; } >; export type WithdrawalEvent = TypedEvent< [string, string, string, BigNumber] & { to: string; nullifierHash: string; relayer: string; fee: BigNumber; } >; export class Tornado extends BaseContract { connect(signerOrProvider: Signer | Provider | string): this; attach(addressOrName: string): this; deployed(): Promise<this>; listeners<EventArgsArray extends Array<any>, EventArgsObject>( eventFilter?: TypedEventFilter<EventArgsArray, EventArgsObject> ): Array<TypedListener<EventArgsArray, EventArgsObject>>; off<EventArgsArray extends Array<any>, EventArgsObject>( eventFilter: TypedEventFilter<EventArgsArray, EventArgsObject>, listener: TypedListener<EventArgsArray, EventArgsObject> ): this; on<EventArgsArray extends Array<any>, EventArgsObject>( eventFilter: TypedEventFilter<EventArgsArray, EventArgsObject>, listener: TypedListener<EventArgsArray, EventArgsObject> ): this; once<EventArgsArray extends Array<any>, EventArgsObject>( eventFilter: TypedEventFilter<EventArgsArray, EventArgsObject>, listener: TypedListener<EventArgsArray, EventArgsObject> ): this; removeListener<EventArgsArray extends Array<any>, EventArgsObject>( eventFilter: TypedEventFilter<EventArgsArray, EventArgsObject>, listener: TypedListener<EventArgsArray, EventArgsObject> ): this; removeAllListeners<EventArgsArray extends Array<any>, EventArgsObject>( eventFilter: TypedEventFilter<EventArgsArray, EventArgsObject> ): this; listeners(eventName?: string): Array<Listener>; off(eventName: string, listener: Listener): this; on(eventName: string, listener: Listener): this; once(eventName: string, listener: Listener): this; removeListener(eventName: string, listener: Listener): this; removeAllListeners(eventName?: string): this; queryFilter<EventArgsArray extends Array<any>, EventArgsObject>( event: TypedEventFilter<EventArgsArray, EventArgsObject>, fromBlockOrBlockhash?: string | number | undefined, toBlock?: string | number | undefined ): Promise<Array<TypedEvent<EventArgsArray & EventArgsObject>>>; interface: TornadoInterface; functions: { FIELD_SIZE(overrides?: CallOverrides): Promise<[BigNumber]>; ROOT_HISTORY_SIZE(overrides?: CallOverrides): Promise<[number]>; ZERO_VALUE(overrides?: CallOverrides): Promise<[BigNumber]>; commitments(arg0: BytesLike, overrides?: CallOverrides): Promise<[boolean]>; currentRootIndex(overrides?: CallOverrides): Promise<[number]>; denomination(overrides?: CallOverrides): Promise<[BigNumber]>; filledSubtrees(arg0: BigNumberish, overrides?: CallOverrides): Promise<[string]>; /** * Returns the last root */ getLastRoot(overrides?: CallOverrides): Promise<[string]>; /** * Hash 2 tree leaves, returns MiMC(_left, _right) */ hashLeftRight(_hasher: string, _left: BytesLike, _right: BytesLike, overrides?: CallOverrides): Promise<[string]>; hasher(overrides?: CallOverrides): Promise<[string]>; /** * Whether the root is present in the root history */ isKnownRoot(_root: BytesLike, overrides?: CallOverrides): Promise<[boolean]>; levels(overrides?: CallOverrides): Promise<[number]>; nextIndex(overrides?: CallOverrides): Promise<[number]>; nullifierHashes(arg0: BytesLike, overrides?: CallOverrides): Promise<[boolean]>; roots(arg0: BigNumberish, overrides?: CallOverrides): Promise<[string]>; verifier(overrides?: CallOverrides): Promise<[string]>; /** * provides Zero (Empty) elements for a MiMC MerkleTree. Up to 32 levels */ zeros(i: BigNumberish, overrides?: CallOverrides): Promise<[string]>; /** * Deposit funds into the contract. The caller must send (for ETH) or approve (for ERC20) value equal to or `denomination` of this instance. * @param _commitment the note commitment, which is PedersenHash(nullifier + secret) */ deposit( _commitment: BytesLike, overrides?: PayableOverrides & { from?: string | Promise<string> } ): Promise<ContractTransaction>; /** * Withdraw a deposit from the contract. `proof` is a zkSNARK proof data, and input is an array of circuit public inputs `input` array consists of: - merkle root of all deposits in the contract - hash of unique deposit nullifier to prevent double spends - the recipient of funds - optional fee that goes to the transaction sender (usually a relay) */ withdraw( _proof: BytesLike, _root: BytesLike, _nullifierHash: BytesLike, _recipient: string, _relayer: string, _fee: BigNumberish, _refund: BigNumberish, overrides?: PayableOverrides & { from?: string | Promise<string> } ): Promise<ContractTransaction>; /** * whether a note is already spent */ isSpent(_nullifierHash: BytesLike, overrides?: CallOverrides): Promise<[boolean]>; /** * whether an array of notes is already spent */ isSpentArray(_nullifierHashes: BytesLike[], overrides?: CallOverrides): Promise<[boolean[]] & { spent: boolean[] }>; }; FIELD_SIZE(overrides?: CallOverrides): Promise<BigNumber>; ROOT_HISTORY_SIZE(overrides?: CallOverrides): Promise<number>; ZERO_VALUE(overrides?: CallOverrides): Promise<BigNumber>; commitments(arg0: BytesLike, overrides?: CallOverrides): Promise<boolean>; currentRootIndex(overrides?: CallOverrides): Promise<number>; denomination(overrides?: CallOverrides): Promise<BigNumber>; filledSubtrees(arg0: BigNumberish, overrides?: CallOverrides): Promise<string>; /** * Returns the last root */ getLastRoot(overrides?: CallOverrides): Promise<string>; /** * Hash 2 tree leaves, returns MiMC(_left, _right) */ hashLeftRight(_hasher: string, _left: BytesLike, _right: BytesLike, overrides?: CallOverrides): Promise<string>; hasher(overrides?: CallOverrides): Promise<string>; /** * Whether the root is present in the root history */ isKnownRoot(_root: BytesLike, overrides?: CallOverrides): Promise<boolean>; levels(overrides?: CallOverrides): Promise<number>; nextIndex(overrides?: CallOverrides): Promise<number>; nullifierHashes(arg0: BytesLike, overrides?: CallOverrides): Promise<boolean>; roots(arg0: BigNumberish, overrides?: CallOverrides): Promise<string>; verifier(overrides?: CallOverrides): Promise<string>; /** * provides Zero (Empty) elements for a MiMC MerkleTree. Up to 32 levels */ zeros(i: BigNumberish, overrides?: CallOverrides): Promise<string>; /** * Deposit funds into the contract. The caller must send (for ETH) or approve (for ERC20) value equal to or `denomination` of this instance. * @param _commitment the note commitment, which is PedersenHash(nullifier + secret) */ deposit( _commitment: BytesLike, overrides?: PayableOverrides & { from?: string | Promise<string> } ): Promise<ContractTransaction>; /** * Withdraw a deposit from the contract. `proof` is a zkSNARK proof data, and input is an array of circuit public inputs `input` array consists of: - merkle root of all deposits in the contract - hash of unique deposit nullifier to prevent double spends - the recipient of funds - optional fee that goes to the transaction sender (usually a relay) */ withdraw( _proof: BytesLike, _root: BytesLike, _nullifierHash: BytesLike, _recipient: string, _relayer: string, _fee: BigNumberish, _refund: BigNumberish, overrides?: PayableOverrides & { from?: string | Promise<string> } ): Promise<ContractTransaction>; /** * whether a note is already spent */ isSpent(_nullifierHash: BytesLike, overrides?: CallOverrides): Promise<boolean>; /** * whether an array of notes is already spent */ isSpentArray(_nullifierHashes: BytesLike[], overrides?: CallOverrides): Promise<boolean[]>; callStatic: { FIELD_SIZE(overrides?: CallOverrides): Promise<BigNumber>; ROOT_HISTORY_SIZE(overrides?: CallOverrides): Promise<number>; ZERO_VALUE(overrides?: CallOverrides): Promise<BigNumber>; commitments(arg0: BytesLike, overrides?: CallOverrides): Promise<boolean>; currentRootIndex(overrides?: CallOverrides): Promise<number>; denomination(overrides?: CallOverrides): Promise<BigNumber>; filledSubtrees(arg0: BigNumberish, overrides?: CallOverrides): Promise<string>; /** * Returns the last root */ getLastRoot(overrides?: CallOverrides): Promise<string>; /** * Hash 2 tree leaves, returns MiMC(_left, _right) */ hashLeftRight(_hasher: string, _left: BytesLike, _right: BytesLike, overrides?: CallOverrides): Promise<string>; hasher(overrides?: CallOverrides): Promise<string>; /** * Whether the root is present in the root history */ isKnownRoot(_root: BytesLike, overrides?: CallOverrides): Promise<boolean>; levels(overrides?: CallOverrides): Promise<number>; nextIndex(overrides?: CallOverrides): Promise<number>; nullifierHashes(arg0: BytesLike, overrides?: CallOverrides): Promise<boolean>; roots(arg0: BigNumberish, overrides?: CallOverrides): Promise<string>; verifier(overrides?: CallOverrides): Promise<string>; /** * provides Zero (Empty) elements for a MiMC MerkleTree. Up to 32 levels */ zeros(i: BigNumberish, overrides?: CallOverrides): Promise<string>; /** * Deposit funds into the contract. The caller must send (for ETH) or approve (for ERC20) value equal to or `denomination` of this instance. * @param _commitment the note commitment, which is PedersenHash(nullifier + secret) */ deposit(_commitment: BytesLike, overrides?: CallOverrides): Promise<void>; /** * Withdraw a deposit from the contract. `proof` is a zkSNARK proof data, and input is an array of circuit public inputs `input` array consists of: - merkle root of all deposits in the contract - hash of unique deposit nullifier to prevent double spends - the recipient of funds - optional fee that goes to the transaction sender (usually a relay) */ withdraw( _proof: BytesLike, _root: BytesLike, _nullifierHash: BytesLike, _recipient: string, _relayer: string, _fee: BigNumberish, _refund: BigNumberish, overrides?: CallOverrides ): Promise<void>; /** * whether a note is already spent */ isSpent(_nullifierHash: BytesLike, overrides?: CallOverrides): Promise<boolean>; /** * whether an array of notes is already spent */ isSpentArray(_nullifierHashes: BytesLike[], overrides?: CallOverrides): Promise<boolean[]>; }; filters: { 'Deposit(bytes32,uint32,uint256)'( commitment?: BytesLike | null, leafIndex?: null, timestamp?: null ): TypedEventFilter<[string, number, BigNumber], { commitment: string; leafIndex: number; timestamp: BigNumber }>; Deposit( commitment?: BytesLike | null, leafIndex?: null, timestamp?: null ): TypedEventFilter<[string, number, BigNumber], { commitment: string; leafIndex: number; timestamp: BigNumber }>; 'Withdrawal(address,bytes32,address,uint256)'( to?: null, nullifierHash?: null, relayer?: string | null, fee?: null ): TypedEventFilter< [string, string, string, BigNumber], { to: string; nullifierHash: string; relayer: string; fee: BigNumber } >; Withdrawal( to?: null, nullifierHash?: null, relayer?: string | null, fee?: null ): TypedEventFilter< [string, string, string, BigNumber], { to: string; nullifierHash: string; relayer: string; fee: BigNumber } >; }; estimateGas: { FIELD_SIZE(overrides?: CallOverrides): Promise<BigNumber>; ROOT_HISTORY_SIZE(overrides?: CallOverrides): Promise<BigNumber>; ZERO_VALUE(overrides?: CallOverrides): Promise<BigNumber>; commitments(arg0: BytesLike, overrides?: CallOverrides): Promise<BigNumber>; currentRootIndex(overrides?: CallOverrides): Promise<BigNumber>; denomination(overrides?: CallOverrides): Promise<BigNumber>; filledSubtrees(arg0: BigNumberish, overrides?: CallOverrides): Promise<BigNumber>; /** * Returns the last root */ getLastRoot(overrides?: CallOverrides): Promise<BigNumber>; /** * Hash 2 tree leaves, returns MiMC(_left, _right) */ hashLeftRight(_hasher: string, _left: BytesLike, _right: BytesLike, overrides?: CallOverrides): Promise<BigNumber>; hasher(overrides?: CallOverrides): Promise<BigNumber>; /** * Whether the root is present in the root history */ isKnownRoot(_root: BytesLike, overrides?: CallOverrides): Promise<BigNumber>; levels(overrides?: CallOverrides): Promise<BigNumber>; nextIndex(overrides?: CallOverrides): Promise<BigNumber>; nullifierHashes(arg0: BytesLike, overrides?: CallOverrides): Promise<BigNumber>; roots(arg0: BigNumberish, overrides?: CallOverrides): Promise<BigNumber>; verifier(overrides?: CallOverrides): Promise<BigNumber>; /** * provides Zero (Empty) elements for a MiMC MerkleTree. Up to 32 levels */ zeros(i: BigNumberish, overrides?: CallOverrides): Promise<BigNumber>; /** * Deposit funds into the contract. The caller must send (for ETH) or approve (for ERC20) value equal to or `denomination` of this instance. * @param _commitment the note commitment, which is PedersenHash(nullifier + secret) */ deposit( _commitment: BytesLike, overrides?: PayableOverrides & { from?: string | Promise<string> } ): Promise<BigNumber>; /** * Withdraw a deposit from the contract. `proof` is a zkSNARK proof data, and input is an array of circuit public inputs `input` array consists of: - merkle root of all deposits in the contract - hash of unique deposit nullifier to prevent double spends - the recipient of funds - optional fee that goes to the transaction sender (usually a relay) */ withdraw( _proof: BytesLike, _root: BytesLike, _nullifierHash: BytesLike, _recipient: string, _relayer: string, _fee: BigNumberish, _refund: BigNumberish, overrides?: PayableOverrides & { from?: string | Promise<string> } ): Promise<BigNumber>; /** * whether a note is already spent */ isSpent(_nullifierHash: BytesLike, overrides?: CallOverrides): Promise<BigNumber>; /** * whether an array of notes is already spent */ isSpentArray(_nullifierHashes: BytesLike[], overrides?: CallOverrides): Promise<BigNumber>; }; populateTransaction: { FIELD_SIZE(overrides?: CallOverrides): Promise<PopulatedTransaction>; ROOT_HISTORY_SIZE(overrides?: CallOverrides): Promise<PopulatedTransaction>; ZERO_VALUE(overrides?: CallOverrides): Promise<PopulatedTransaction>; commitments(arg0: BytesLike, overrides?: CallOverrides): Promise<PopulatedTransaction>; currentRootIndex(overrides?: CallOverrides): Promise<PopulatedTransaction>; denomination(overrides?: CallOverrides): Promise<PopulatedTransaction>; filledSubtrees(arg0: BigNumberish, overrides?: CallOverrides): Promise<PopulatedTransaction>; /** * Returns the last root */ getLastRoot(overrides?: CallOverrides): Promise<PopulatedTransaction>; /** * Hash 2 tree leaves, returns MiMC(_left, _right) */ hashLeftRight( _hasher: string, _left: BytesLike, _right: BytesLike, overrides?: CallOverrides ): Promise<PopulatedTransaction>; hasher(overrides?: CallOverrides): Promise<PopulatedTransaction>; /** * Whether the root is present in the root history */ isKnownRoot(_root: BytesLike, overrides?: CallOverrides): Promise<PopulatedTransaction>; levels(overrides?: CallOverrides): Promise<PopulatedTransaction>; nextIndex(overrides?: CallOverrides): Promise<PopulatedTransaction>; nullifierHashes(arg0: BytesLike, overrides?: CallOverrides): Promise<PopulatedTransaction>; roots(arg0: BigNumberish, overrides?: CallOverrides): Promise<PopulatedTransaction>; verifier(overrides?: CallOverrides): Promise<PopulatedTransaction>; /** * provides Zero (Empty) elements for a MiMC MerkleTree. Up to 32 levels */ zeros(i: BigNumberish, overrides?: CallOverrides): Promise<PopulatedTransaction>; /** * Deposit funds into the contract. The caller must send (for ETH) or approve (for ERC20) value equal to or `denomination` of this instance. * @param _commitment the note commitment, which is PedersenHash(nullifier + secret) */ deposit( _commitment: BytesLike, overrides?: PayableOverrides & { from?: string | Promise<string> } ): Promise<PopulatedTransaction>; /** * Withdraw a deposit from the contract. `proof` is a zkSNARK proof data, and input is an array of circuit public inputs `input` array consists of: - merkle root of all deposits in the contract - hash of unique deposit nullifier to prevent double spends - the recipient of funds - optional fee that goes to the transaction sender (usually a relay) */ withdraw( _proof: BytesLike, _root: BytesLike, _nullifierHash: BytesLike, _recipient: string, _relayer: string, _fee: BigNumberish, _refund: BigNumberish, overrides?: PayableOverrides & { from?: string | Promise<string> } ): Promise<PopulatedTransaction>; /** * whether a note is already spent */ isSpent(_nullifierHash: BytesLike, overrides?: CallOverrides): Promise<PopulatedTransaction>; /** * whether an array of notes is already spent */ isSpentArray(_nullifierHashes: BytesLike[], overrides?: CallOverrides): Promise<PopulatedTransaction>; }; }
KevinAiken/BluTracking
angular-frontend/src/app/log.service.ts
import { Injectable } from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Observable, of} from 'rxjs'; import {catchError, tap} from 'rxjs/operators'; import {Log} from './log'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json'}) }; @Injectable({ providedIn: 'root' }) export class LogService { private logUrl = 'http://localhost:8080/logs'; constructor(private http: HttpClient) { } getLogs (): Observable<Log[]> { return this.http.get<Log[]>(this.logUrl) .pipe( tap(logs => this.log('fetched logs')), catchError(this.handleError('getLogs', [])) ); } getAssetLogs (assetID: string): Observable<Log[]> { return this.http.get<Log[]>(this.logUrl, { params: {deviceID: assetID}}) .pipe( tap(logs => this.log('fetched asset logs')), catchError(this.handleError('getAssetLogs', [])) ); } isMissing (assetID: string): void{ const url = `$(this.logUrl)/deviceChance/$(deviceID)`; this.http.get<void>(url, { params : {deviceID: assetID}}). pipe( tap(logs => this.log('check missing')), catchError(this.handleError('isMissing', [])) ); } /** Handle failed Http request and let app continue * @param operation - name of op that failed * @param result - optional result to return as observable result */ private handleError<T> (operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error) return of(result as T); }; } /** Log a message */ private log(message: string) { console.info(message); } }
KevinAiken/BluTracking
angular-frontend/src/app/log.ts
export class Log { logId: number; deviceId: number; time: string; btAddr: string; }
KevinAiken/BluTracking
angular-frontend/src/app/add-asset/add-asset.component.ts
<filename>angular-frontend/src/app/add-asset/add-asset.component.ts import { Component, OnInit } from '@angular/core'; import {Asset} from '../asset'; import {AssetService} from '../asset.service'; import {ActivatedRoute} from '@angular/router'; @Component({ selector: 'app-add-asset', templateUrl: './add-asset.component.html', styleUrls: ['./add-asset.component.css'] }) export class AddAssetComponent implements OnInit { constructor( private route: ActivatedRoute, private assetService: AssetService ) { } ngOnInit() { } add(name: string, addr: string, type: string): void { name = name.trim(); addr = addr.trim(); const asset: Asset = { name: name, btAddr: addr, id: null, dateEnrolled: null, missing: null }; const dev: Asset[] = [asset]; this.assetService.addAsset(dev) .subscribe(() => location.reload()); } }
KevinAiken/BluTracking
angular-frontend/src/app/asset-detail/asset-detail.component.ts
import {Component, Input, OnInit} from '@angular/core'; import {Log} from '../log'; import {Asset} from '../asset'; import {ActivatedRoute} from '@angular/router'; import {AssetService} from '../asset.service'; import {LogService} from '../log.service'; import { Location } from '@angular/common'; @Component({ selector: 'app-asset-detail', templateUrl: './asset-detail.component.html', styleUrls: ['./asset-detail.component.css'] }) export class AssetDetailComponent implements OnInit { @Input() asset: Asset; logs: Log[]; constructor( private route: ActivatedRoute, private assetService: AssetService, private location: Location, private logService: LogService ) { } ngOnInit(): void { this.getAsset(); this.getAssetLogs(); this.getChance(); } getAsset(): void { const id = +this.route.snapshot.paramMap.get('id'); this.assetService.getAsset(id) .subscribe(asset => this.asset = asset); } getAssetLogs(): void { this.logService.getAssetLogs(this.route.snapshot.paramMap.get('id')) .subscribe(logs => this.logs = logs); } getChance() : void { this.logService.isMissing("17"); } goBack(): void { this.location.back(); } }
KevinAiken/BluTracking
angular-frontend/src/app/asset.ts
export class Asset { id: number; btAddr: string; name: string; dateEnrolled: string; missing: string; }
KevinAiken/BluTracking
angular-frontend/src/app/assets/asset.component.ts
import { Component, OnInit } from '@angular/core'; import {AssetService} from '../asset.service'; import {Asset} from '../asset'; @Component({ selector: 'app-asset', templateUrl: './asset.component.html', styleUrls: ['./asset.component.css'] }) export class AssetsComponent implements OnInit { assets: Asset[]; constructor( private assetService: AssetService) { } ngOnInit() { this.getAssets(); } getAssets(): void { console.info('getting assets'); this.assetService.getAssets() .subscribe(assets => this.assets = assets); } assetMissing(date: string): boolean { const date1 = new Date(date); const date2 = new Date(); date2.setMinutes(date2.getMinutes() - 20); if (date1 < date2) { return true; } else { return false; } } }
KevinAiken/BluTracking
angular-frontend/src/app/app-routing.module.ts
<gh_stars>1-10 import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AssetsComponent } from './assets/asset.component'; import { LogsComponent } from './logs/logs.component'; import {AssetDetailComponent} from './asset-detail/asset-detail.component'; import { AddAssetComponent} from './add-asset/add-asset.component'; import {AboutComponent} from './about/about.component'; const routes: Routes = [ { path: '', redirectTo: '/asset', pathMatch: 'full' }, { path: 'asset', component: AssetsComponent }, { path: 'logs', component: LogsComponent }, { path: 'asset/:id', component: AssetDetailComponent}, { path: 'add-asset', component: AddAssetComponent}, { path: 'about', component: AboutComponent} ]; @NgModule({ exports: [ RouterModule ], imports: [ RouterModule.forRoot(routes)] }) export class AppRoutingModule { }
KevinAiken/BluTracking
angular-frontend/src/app/asset.service.ts
<filename>angular-frontend/src/app/asset.service.ts import { Injectable } from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Observable, of} from 'rxjs'; import {catchError, tap} from 'rxjs/operators'; import {Asset} from './asset'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json', 'Cache-Control': 'no-cache' }) }; @Injectable({ providedIn: 'root' }) export class AssetService { private assetUrl = 'http://localhost:8080/devices'; // URL to web api constructor(private http: HttpClient) { } /** GET assets from the server */ getAssets (): Observable<Asset[]> { return this.http.get<Asset[]>(this.assetUrl) .pipe( tap(assets => this.log('fetched assets')), catchError(this.handleError('getAssets', [])) ); } getAsset(id: number): Observable<Asset> { const url = `${this.assetUrl}/${id}`; return this.http.get<Asset>(url).pipe( tap(_ => this.log(`fetched asset id=${id}`)), catchError(this.handleError<Asset>(`getAsset id=${id}`)) ); } addAsset(asset: Asset[]): Observable<Asset> { return this.http.post<Asset>(this.assetUrl, asset, httpOptions).pipe( tap(_ => this.log(`created new asset`)), catchError(this.handleError<Asset>(`addAsset`)) ); } /** Handle failed Http request and let app continue * @param operation - name of op that failed * @param result - optional result to return as observable result */ private handleError<T> (operation = 'operation', result?: T) { return (error: any): Observable<T> => { console.error(error); return of(result as T); }; } /** Log a message */ private log(message: string) { console.info(message); } }
Logub/logub
frontend/models/dto/FieldSearchDto.ts
<reponame>Logub/logub<filename>frontend/models/dto/FieldSearchDto.ts import {LogLevel} from "~/models/LogLevel"; export enum FieldTypeDto { Tag, FullText, Geo, Numeric } export interface FieldSearchDto { type: FieldTypeDto; name?: string; values: string[]; negation: boolean; }
Logub/logub
frontend/models/LogubLog.ts
import { SystemProperties } from '~/models/SystemProperties'; import { LogLevel } from '~/models/LogLevel'; export interface LogubLog { id: string; index: string; timestamp: number; level: LogLevel; tags: SystemProperties; businessProperties: { [key: string]: string }; service?: string; message?: string; logger?: string; thread?: string; source?: string; } export function basicProperties(): Set<string> { return new Set(['service', 'message', 'logger', 'thread', 'source']); } export enum FieldType { BASIC, SYSTEM, BUSINESS } export interface LogFieldFilter { log: LogubLog; value: string; }
Logub/logub
frontend/models/dto/SearchLogsDto.ts
<gh_stars>1-10 import { FieldSearchDto } from '~/models/dto/FieldSearchDto'; export interface SearchLogsDto { texts?: Array<FieldSearchDto>; businessProperties: Array<FieldSearchDto>; systemProperties: Array<FieldSearchDto>; basicProperties: Array<FieldSearchDto>; levels: Array<FieldSearchDto>; sort: SortLogsDto; beginAt?: number; endAt?: number; limit?: number; offset?: number; } export interface SortLogsDto { field?: string; order?: 'ASC' | 'DESC' }
Logub/logub
frontend/models/dto/SchemaFieldDto.ts
<reponame>Logub/logub<filename>frontend/models/dto/SchemaFieldDto.ts import {FieldTypeDto} from "~/models/dto/FieldSearchDto"; export interface SchemaFieldDto { type: FieldTypeDto; name: string; }
Logub/logub
frontend/store/demo.ts
import {Module, VuexAction, VuexModule, VuexMutation} from 'nuxt-property-decorator'; import {Api} from '~/utils/api'; @Module({ name: 'demo', stateFactory: true, namespaced: true, }) export default class Demo extends VuexModule { private _users: any[] = []; get users(): string[] { return this._users; } @VuexAction async updateUser(): Promise<void> { try { const users = await Api.getUsers(); this.setUsers(users); } catch (err) { console.error(err); } } @VuexMutation private setUsers(users: any[]): void { this._users = users; } @VuexAction async addUser(user: any): Promise<void> { try { await Api.addUser(user); await this.updateUser(); } catch (err) { console.error(err); } } @VuexAction async addUsers(users: any[]): Promise<void> { try { for (let user of users) { await Api.addUser(user); } await this.updateUser(); } catch (err) { console.error(err); } } @VuexAction async deleteAll(): Promise<void> { try { await this.updateUser(); for (let user of this._users) { await Api.deleteUser(user.id); } await this.updateUser(); } catch (err) { console.error(err); } } @VuexAction async deleteUser(user: number): Promise<void> { try { await Api.deleteUser(user); await this.updateUser(); } catch (err) { console.error(err); } } @VuexAction async sendCustomLog(log: any): Promise<void> { try { await Api.postCustomLog(log); } catch (err) { console.error(err); } } }
Logub/logub
frontend/store/logs.ts
import { Module, VuexAction, VuexModule, VuexMutation } from 'nuxt-property-decorator'; import { LogubLog } from '~/models/LogubLog'; import { Api } from '~/utils/api'; import { Mapper } from '~/utils/mapper'; import { FieldSearchDto, FieldTypeDto } from '~/models/dto/FieldSearchDto'; import { sleep } from '~/utils/helpers'; import { schema } from "~/utils/store-accessor"; import { SearchLogsDto, SortLogsDto } from "~/models/dto/SearchLogsDto"; @Module({ name: 'logs', stateFactory: true, namespaced: true, }) export default class Logs extends VuexModule { private _loading: boolean = true; get loading(): boolean { return this._loading; } private _logs: LogubLog[] = []; get logs(): LogubLog[] { return this._logs; } @VuexAction async updateLogs(options: { properties?: Array<FieldSearchDto>, sort?: SortLogsDto, size: number, beginAtInMs: number, endAtInMs: number }): Promise<void> { if (schema.schema.length === 0) { await schema.updateSchema(); console.log('schema updated', schema.schema); } const business: Array<string> = schema.businessProperties; const system: Array<string> = schema.systemProperties; //sche const basic: Array<string> = schema.basicProperties; //scma.getSystemProperties(); //Since business and system properties are defined in schema, we don't care about split them before here this.setLoading(true); try { console.log('Update Logs', options); const { properties, size, beginAtInMs, endAtInMs, sort } = options; const texts = properties?.filter(v => v.type === FieldTypeDto.FullText); const businessProperties = properties?.filter(v => v.type === FieldTypeDto.Tag && business.includes(v.name!)); const systemProperties = properties?.filter(v => v.type === FieldTypeDto.Tag && system.includes(v.name!)); const basicProperties = properties?.filter(v => v.type === FieldTypeDto.Tag && basic.includes(v.name!)); const levels = properties?.filter(v => v.type === FieldTypeDto.Tag && v.name!.toLowerCase() === 'level'); const search: SearchLogsDto = { texts: texts ?? [], businessProperties: businessProperties ?? [], systemProperties: systemProperties ?? [], basicProperties: basicProperties ?? [], levels: levels ?? [], sort: sort ?? { field: 'timestamp', order: 'DESC' }, endAt: Math.round(beginAtInMs / 1000), beginAt: Math.round(endAtInMs / 1000), limit: size, offset: 0 }; console.log("search : ", search); const logsPromise = Api.searchLogs(search); const all = await Promise.all([logsPromise, sleep(500)]); const logs = all[0]; this.setLogs(logs.map(log => Mapper.toDomain(log))); } catch (err) { console.error(err); } finally { this.setLoading(false); } } @VuexMutation private setLoading(isLoading: boolean): void { this._loading = isLoading; } @VuexMutation private setLogs(newLogs: LogubLog[]): void { this._logs = newLogs; } }
Logub/logub
frontend/utils/store-accessor.ts
import { Store } from 'vuex'; import { getModule } from 'nuxt-property-decorator'; import Logs from '~/store/logs'; import { NuxtAxiosInstance } from '@nuxtjs/axios'; import Schema from "~/store/schema"; import Demo from "~/store/demo"; import Search from "~/store/search"; let logs: Logs; let schema: Schema; let demo: Demo; let search: Search; function initialiseStores(store: Store<any>): void { logs = getModule(Logs, store); schema = getModule(Schema, store); demo = getModule(Demo, store); search = getModule(Search, store); } export { initialiseStores, logs, schema, demo, search }; let $axios: NuxtAxiosInstance; export function initializeAxios(axiosInstance: NuxtAxiosInstance) { $axios = axiosInstance; } export { $axios };
Logub/logub
frontend/models/LogDateFilter.ts
import moment from 'moment'; export interface LogDateFilter { beginAt: Function; endAt: Function; text: string; } export const defaultLogDateFilter: LogDateFilter = { text: 'Last 15 minutes', beginAt: () => moment().toDate(), endAt: () => moment().subtract(15, "minutes").toDate() };
Logub/logub
frontend/utils/api.ts
<reponame>Logub/logub import {SearchLogsDto} from '~/models/dto/SearchLogsDto'; import {LogubLogDto} from '~/models/dto/LogubLogDto'; import {$axios} from '~/utils/store-accessor'; import {SchemaFieldDto} from "~/models/dto/SchemaFieldDto"; import {FieldTypeDto} from "~/models/dto/FieldSearchDto"; export class Api { private static readonly API_URL: string = process.env.API_URL || 'http://localhost:8080'; private static readonly API_URL_DEMO: string = process.env.API_URL || 'http://localhost:8081'; static async searchLogs(searchDto: SearchLogsDto): Promise<LogubLogDto[]> { return $axios.$post<LogubLogDto[]>(`${this.API_URL}/logs/search`, searchDto); } static async getSchema(): Promise<string[]> { return $axios.$get<string[]>(`${this.API_URL}/logs/schema`); } static async addField(businessProperties: string) { const schemaField: SchemaFieldDto = { type: FieldTypeDto.Tag, name: businessProperties }; return $axios.$post<void>(`${this.API_URL}/logs/schema`, schemaField); } static async getUsers() { return $axios.$get<any[]>(`${this.API_URL_DEMO}/users`); } static async addUser(user :any) { return $axios.$post<void>(`${this.API_URL_DEMO}/users`, user); } static async deleteUser(userId: number) { return $axios.$delete<void>(`${this.API_URL_DEMO}/users/${userId}`); } static async postCustomLog(log :any) { return $axios.$post<void>(`${this.API_URL_DEMO}/logs`, log); } }
Logub/logub
frontend/models/LogLevel.ts
<gh_stars>1-10 export enum LogLevel { INFO = "INFO", WARN = "WARN", ERROR = "ERROR", DEBUG = "DEBUG", UNKNOWN = "UNKNOWN", } export function logLevelColor(logLevel: LogLevel): string { switch (logLevel) { case LogLevel.INFO: return "#73BD15"; case LogLevel.WARN: return "#E0A903"; case LogLevel.ERROR: return "#C72000"; case LogLevel.DEBUG: return "#A896C7"; case LogLevel.UNKNOWN: return "#F0F"; default: return "#FFF"; } }
Logub/logub
frontend/utils/helpers.ts
import {Moment} from "moment-timezone"; import moment from "moment-timezone"; export const sleep = async (ms: number): Promise<void> => new Promise(res => setTimeout(res, ms)); export function formatDate(dateNumber: number, detail: boolean = false): string { const date: Moment = moment(dateNumber); return date.format(detail ? 'MMM DD, YYYY - HH:mm:ss.SSS' : 'MMM DD HH:mm:ss.SSS'); }
Logub/logub
frontend/models/dto/SystemPropertiesDto.ts
<reponame>Logub/logub export interface SystemPropertiesDto { imageName?: string; container_name?: string; env?: string; host?: string; }
Logub/logub
frontend/store/schema.ts
<reponame>Logub/logub<gh_stars>1-10 import { Module, VuexAction, VuexModule, VuexMutation } from 'nuxt-property-decorator'; import { basicProperties } from '~/models/LogubLog'; import { Api } from '~/utils/api'; @Module({ name: 'schema', stateFactory: true, namespaced: true, }) export default class Schema extends VuexModule { private _loading: boolean = true; get loading(): boolean { return this._loading; } private _schema: string[] = []; get schema(): string[] { return this._schema; } private _basicProperties: Set<string> = basicProperties(); get basicProperties(): string[] { console.log(this._basicProperties); return [...this._basicProperties]; } get businessProperties(): string[] { return this.schema.filter(v => v.startsWith("businessProperties.")) .map(v => v.replace('businessProperties.', '')); } get systemProperties(): string[] { return this.schema.filter(v => v.startsWith("systemProperties.")) .map(v => v.replace('systemProperties.', '')); } @VuexAction async updateSchema(): Promise<void> { this.setLoading(true); try { const schema = await Api.getSchema(); this.setSchema(schema); } catch (err) { console.error(err); } finally { this.setLoading(false); } } @VuexAction async addFieldToSchema(businessProperties: string): Promise<void> { try { await Api.addField(businessProperties); const schema = await Api.getSchema(); this.setSchema(schema); } catch (err) { console.error(err); } } @VuexMutation private setLoading(isLoading: boolean): void { this._loading = isLoading; } @VuexMutation private setSchema(newLogs: string[]): void { this._schema = newLogs; } }
Logub/logub
frontend/vuetify.options.ts
<gh_stars>1-10 import colors from 'vuetify/es5/util/colors'; import { UserVuetifyPreset } from 'vuetify'; const vuetifyOptions: UserVuetifyPreset = { theme: { dark: false, themes: { light: { primary: "#2a5f8c", secondary: '#424242', accent: '#82B1FF', error: '#FF5252', info: '#FEFEFE', success: '#4CAF50', warning: '#FFC107', } } }, }; export default vuetifyOptions;
Logub/logub
frontend/models/dto/LogubLogDto.ts
<filename>frontend/models/dto/LogubLogDto.ts import { SystemPropertiesDto } from '~/models/dto/SystemPropertiesDto'; export interface LogubLogDto { id: string; index: string; service?: string; systemProperties: SystemPropertiesDto; businessProperties: { [key: string]: string }; message?: string; logger?: string; thread?: string; source?: string; timestamp: string; level: string; }
Logub/logub
frontend/plugins/axios.ts
import { Context, Plugin } from '@nuxt/types'; import { initializeAxios } from '~/utils/store-accessor'; const accessorAxios: Plugin = (ctx: Context) => { initializeAxios((ctx as any).$axios); }; export default accessorAxios;
Logub/logub
frontend/store/search.ts
<gh_stars>1-10 import {Module, VuexAction, VuexModule, VuexMutation} from 'nuxt-property-decorator'; import {FieldSearchDto, FieldTypeDto} from '~/models/dto/FieldSearchDto'; @Module({ name: 'search', stateFactory: true, namespaced: true, }) export default class Search extends VuexModule { private _searchQuery: string = ''; get searchQuery(): string { return this._searchQuery; } private _matchingQuery: Array<FieldSearchDto> = []; get matchingQuery(): Array<FieldSearchDto> { return this._matchingQuery; } private static isBlank(str: string) { return (!str || /^\s*$/.test(str)); } private static stringToFieldTagSearch(v: string): FieldSearchDto { const tag = v.split(':'); console.log(tag); let negation = tag[0].startsWith("-"); return { name: tag[0].replace('-', ''), type: FieldTypeDto.Tag, values: [tag[1]], negation: negation, }; }; private static stringToFieldTextSearch(v: string): FieldSearchDto { console.log("stringToFieldTextSearch : " + v) let negation = v.startsWith("-"); if (negation) { v = v.substr(1); } return { name: "message", type: FieldTypeDto.FullText, values: [v], negation: negation, }; }; @VuexAction setSearch(search: string): void { this.setSearchQuery(search); console.log("Search string update", search); } @VuexAction updateSearch() { const regex = /\S+:\S+/gm; let m; const textInQuoteRegex = /-?(["'])(?:\\.|[^\\])*?\1/gm; let quotedText = this.searchQuery.match(textInQuoteRegex); if (quotedText) { quotedText .map(v => { if (v.startsWith("-")) { return '-' + v.substr(2, v.length - 3); } else return v.substr(1, v.length - 2); }) .forEach(v => { this.addToMatchingQuery(Search.stringToFieldTextSearch(v)) }); } let str = this.searchQuery.replace(textInQuoteRegex, ''); while ((m = regex.exec(str)) !== null) { // This is necessary to avoid infinite loops with zero-width matches if (m.index === regex.lastIndex) { regex.lastIndex++; } // The result can be accessed through the `m`-variable. m.forEach((match, groupIndex) => { this.addToMatchingQuery(Search.stringToFieldTagSearch(match)); }); } const value = str.replace(regex, '').trim(); console.log("FULL TEXT", value) if (!Search.isBlank(value)) { console.log("FULL TEXT", value) this.addToQuery(Search.stringToFieldTextSearch(value)); } this.setSearchQuery(""); } @VuexAction addToQuery(value: FieldSearchDto) { this.addToMatchingQuery(value); } @VuexAction removeFromQuery(index: number) { this.removeFromMatchingQuery(index); } @VuexMutation private setSearchQuery(search: string): void { this._searchQuery = search; } @VuexMutation private addToMatchingQuery(v: FieldSearchDto) { const match = this._matchingQuery.find(value => value.name === v.name && v.type === value.type && v.negation == value.negation); if (match) { for (let payload of v.values) { if (!match.values.includes(payload)) { match.values.push(payload); } } } else { this._matchingQuery.push(v); } } @VuexMutation private removeFromMatchingQuery(index: number) { this._matchingQuery.splice(index, 1); } }
Logub/logub
frontend/utils/mapper.ts
<gh_stars>1-10 import { LogubLogDto } from '~/models/dto/LogubLogDto'; import { LogubLog } from '~/models/LogubLog'; import moment from 'moment'; import { LogLevel } from '~/models/LogLevel'; export class Mapper { static toDomain(dto: LogubLogDto): LogubLog { const { timestamp, level, systemProperties } = dto; return { ...dto, timestamp: moment(timestamp).toDate().getTime(), level: LogLevel[level as keyof typeof LogLevel], tags: systemProperties, }; } }
Sitocp/mapbox-gl-legend
lib/index.ts
import { accessToken, baseApiUrl, IControl, Map as MapboxMap } from "mapbox-gl"; // @ts-ignore import LegendSymbol from 'legend-symbol/src'; import axios from 'axios'; export type Options = { showDefault: boolean; showCheckbox: boolean; reverseOrder: boolean; onlyRendered: boolean; } /** * Mapbox GL Legend Control. * @param {Object} targets - Object of layer.id and title * @param {boolean} options.showDefault true: it shows legend as default. false: legend will be closed as default * @param {boolean} options.showCheckbox true: checkbox will be added for switching layer's visibility. false: checkbox will not be added. * @param {boolean} options.reverseOrder true: layers will be ordered from top. false: layers will be ordered from bottom. If not specified, default value will be true. * @param {boolean} options.onlyRendered true: only rendered layers will be shown on legend as default. false: all layers' legend will be shown as default. If not specified, default value will be true. */ export default class MapboxLegendControl implements IControl { private controlContainer: HTMLElement; private map?: MapboxMap; private legendContainer: HTMLElement; private legendButton: HTMLButtonElement; private closeButton: HTMLButtonElement; private legendTable: HTMLElement; private targets: { [key: string]: string }; private uncheckedLayers: { [key: string]: string } = {}; private onlyRendered: boolean; private options: Options = { showDefault: true, showCheckbox: true, reverseOrder: true, onlyRendered: true, }; private sprite = { image: HTMLImageElement, json: JSON }; constructor(targets:{ [key: string]: string }, options: Options) { this.targets = targets; if (options){ this.options = Object.assign(this.options, options); } this.onlyRendered = this.options.onlyRendered; this.onDocumentClick = this.onDocumentClick.bind(this); } public getDefaultPosition(): string { const defaultPosition = "top-right"; return defaultPosition; } private changeLayerVisibility(layer_id: string, checked) { if (checked) { if (this.uncheckedLayers[layer_id]) delete this.uncheckedLayers[layer_id]; this.map?.setLayoutProperty(layer_id, 'visibility', 'visible'); }else{ this.uncheckedLayers[layer_id]=layer_id; this.map?.setLayoutProperty(layer_id, 'visibility', 'none'); } const checkboxes: NodeListOf<HTMLElement> = document.getElementsByName(layer_id); for (let i in checkboxes){ if (typeof checkboxes[i] === 'number') continue; // @ts-ignore checkboxes[i].checked = checked; } } /** * create checkbox for switching layer visibility * @param layer mapboxgl.Layer object * @returns HTMLElement | undefined return TD Element */ private createLayerCheckbox(layer: mapboxgl.Layer): HTMLElement | undefined { if (!this.options.showCheckbox) return; const this_ = this; // create checkbox for switching layer visibility const td = document.createElement('TD'); td.className='legend-table-td'; const checklayer = document.createElement('input'); checklayer.setAttribute('type', 'checkbox'); checklayer.setAttribute('name', layer.id); checklayer.setAttribute('value', layer.id); const visibility = this.map?.getLayoutProperty(layer.id, 'visibility'); if (!visibility){ checklayer.checked = true; }else{ let _checked = true; switch(visibility){ case 'none': _checked = false; break; case 'visible': _checked = true; checklayer.checked = true; break; } this_.changeLayerVisibility(layer.id, _checked); } checklayer.addEventListener('click', function(e){ // @ts-ignore const _id = e.target?.value; // @ts-ignore const _checked = e.target?.checked; this_.changeLayerVisibility(_id, _checked); }); td.appendChild(checklayer) return td; } /** * Create and return a layer's legend row * @param layer mapboxgl.Layer object * @returns HTMLElement | undefined return TR Element */ private getLayerLegend(layer: mapboxgl.Layer): HTMLElement | undefined { const map = this.map; const zoom = map?.getZoom(); const sprite = this.sprite; let symbol = LegendSymbol({sprite, zoom, layer}); if (!symbol) return; var tr = document.createElement('TR'); const td0 = this.createLayerCheckbox(layer); if (td0) tr.appendChild(td0); // create legend symbol var td1 = document.createElement('TD'); td1.className='legend-table-td'; switch(symbol.element){ case 'div': if ((symbol.attributes.style.backgroundImage && !["url(undefined)","url(null)"].includes(symbol.attributes.style.backgroundImage))){ var img = document.createElement('img'); img.src = symbol.attributes.style.backgroundImage.replace('url(','').replace(')',''); img.alt = layer.id; img.style.cssText = `height: 17px;` td1.appendChild(img) } td1.style.backgroundColor = symbol.attributes.style.backgroundColor; td1.style.backgroundPosition = symbol.attributes.style.backgroundPosition; td1.style.backgroundSize = symbol.attributes.style.backgroundSize; td1.style.backgroundRepeat = symbol.attributes.style.backgroundRepeat; td1.style.opacity = symbol.attributes.style.opacity; break; case 'svg': let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.style.cssText = 'height: 17px;' svg.setAttributeNS(null, 'version', '1.1') Object.keys(symbol.attributes).forEach(k=>{ svg.setAttribute(k, symbol.attributes[k]); let group = document.createElementNS('http://www.w3.org/2000/svg', 'g'); symbol.children.forEach(child=>{ var c = document.createElementNS('http://www.w3.org/2000/svg', child.element); Object.keys(child.attributes).forEach(k2=>{ c.setAttributeNS(null, k2, child.attributes[k2]); }) group.appendChild(c); }) svg.appendChild(group); }) var label2 = document.createElement('label'); label2.textContent = (this.targets && this.targets[layer.id])?this.targets[layer.id]:layer.id; td1.appendChild(svg) break; default: return; } // create layer label var td2 = document.createElement('TD'); td2.className='legend-table-td'; let label1 = document.createElement('label'); label1.textContent = (this.targets && this.targets[layer.id])?this.targets[layer.id]:layer.id; td2.appendChild(label1) // tr.appendChild(td0); tr.appendChild(td1); tr.appendChild(td2); return tr; } /** update legend contents */ private updateLegendControl() { const map = this.map; // get current rendered layers const visibleLayers = {}; if (map) { const features = map.queryRenderedFeatures(); for (let feature of features) { visibleLayers[feature.layer.id] = feature.layer; } } let layers = map?.getStyle().layers; if (layers) { if (!this.legendTable){ this.legendTable = document.createElement('TABLE'); this.legendTable.className = 'legend-table'; this.legendContainer.appendChild(this.legendTable) } while (this.legendTable.firstChild) { this.legendTable.removeChild(this.legendTable.firstChild); } if (this.options.reverseOrder){ layers = layers.reverse(); } layers.forEach(l=>{ if (visibleLayers[l.id] && this.uncheckedLayers[l.id]){ delete this.uncheckedLayers[l.id]; }else if (this.uncheckedLayers[l.id]) { visibleLayers[l.id]=l }; if ((this.targets === undefined) // if target option is undefined, show all layers. || (this.targets && Object.keys(this.targets).length === 0) // if no layer is specified, show all layers. || (this.targets && Object.keys(this.targets).map((id:string)=>{return id;}).includes(l.id)) // if layers are speficied, only show these specific layers. ){ if (this.onlyRendered){ // only show rendered layer if (!visibleLayers[l.id]) return; } const tr = this.getLayerLegend(l); if (!tr) return; this.legendTable.appendChild(tr); }else{ return; } }) } } public onAdd(map: MapboxMap): HTMLElement { this.map = map; this.controlContainer = document.createElement("div"); this.controlContainer.classList.add("mapboxgl-ctrl"); this.controlContainer.classList.add("mapboxgl-ctrl-group"); this.legendContainer = document.createElement("div"); this.legendContainer.classList.add("mapboxgl-legend-list"); this.legendButton = document.createElement("button"); this.legendButton.classList.add("mapboxgl-ctrl-icon"); this.legendButton.classList.add("mapboxgl-legend-switcher"); this.legendButton.addEventListener("click", () => { this.legendButton.style.display = "none"; this.legendContainer.style.display = "block"; }); document.addEventListener("click", this.onDocumentClick); this.controlContainer.appendChild(this.legendButton); this.controlContainer.appendChild(this.legendContainer); this.closeButton = document.createElement("button"); this.closeButton.textContent = "x"; this.closeButton.classList.add("mapboxgl-legend-close-button"); this.closeButton.addEventListener("click", () => { this.legendButton.style.display = "block"; this.legendContainer.style.display = "none"; }); this.legendContainer.appendChild(this.closeButton); const legendLabel = document.createElement('label'); legendLabel.classList.add("mapboxgl-legend-title-label"); legendLabel.textContent = "Legend"; this.legendContainer.appendChild(legendLabel) this.legendContainer.appendChild(document.createElement("br")); const checkOnlyRendered = document.createElement('input'); checkOnlyRendered.setAttribute('type', 'checkbox'); const checkboxOnlyRenderedId = `mapboxgl-legend-onlyrendered-checkbox-${Math.random()*100}` checkOnlyRendered.setAttribute('id', checkboxOnlyRenderedId); checkOnlyRendered.classList.add("mapboxgl-legend-onlyRendered-checkbox"); checkOnlyRendered.checked = this.onlyRendered; const this_ = this; checkOnlyRendered.addEventListener('click', function(e){ // @ts-ignore const _checked = e.target?.checked; this_.onlyRendered = (_checked)?true:false; this_.updateLegendControl(); }); this.legendContainer.appendChild(checkOnlyRendered); const onlyRenderedLabel = document.createElement('label'); onlyRenderedLabel.classList.add("mapboxgl-legend-onlyRendered-label"); onlyRenderedLabel.textContent = "Only rendered"; onlyRenderedLabel.htmlFor = checkboxOnlyRenderedId; this.legendContainer.appendChild(onlyRenderedLabel); this.legendContainer.appendChild(document.createElement("br")); this.map.on('moveend', (eventData)=> { this.updateLegendControl(); }) const afterLoadListener = async() =>{ if (map.loaded()) { const style = map.getStyle(); let styleUrl = style.sprite; let strToken = ''; if (styleUrl && styleUrl.includes('mapbox://')){ styleUrl = styleUrl .replace(/mapbox:\/\//g, baseApiUrl) .replace(/sprites/g,'/styles/v1'); styleUrl = `${styleUrl}/sprite`; strToken = `?access_token=${accessToken}`; } const promise = Promise.all([ this.loadImage(`${styleUrl}@2x.png${strToken}`), this.loadJson(`${styleUrl}.json${strToken}`), ]); await promise.then(([image, json]) => {this.setSprite(image, json)}); this.updateLegendControl(); map.off('idle', afterLoadListener); } } this.map.on('idle', afterLoadListener); if (this.options && this.options.showDefault == true){ this.legendContainer.style.display = "block"; this.legendButton.style.display = "none"; } return this.controlContainer; } public onRemove(): void { if (!this.controlContainer || !this.controlContainer.parentNode || !this.map || !this.legendButton) { return; } this.legendButton.removeEventListener("click", this.onDocumentClick); this.controlContainer.parentNode.removeChild(this.controlContainer); document.removeEventListener("click", this.onDocumentClick); this.map = undefined; } public redraw(): void { this.updateLegendControl(); } private onDocumentClick(event: MouseEvent): void{ if (this.controlContainer && !this.controlContainer.contains(event.target as Element) && this.legendContainer && this.legendButton) { if (this.options && this.options.showDefault !== true){ this.legendContainer.style.display = "none"; this.legendButton.style.display = "block"; } } } private setSprite(image, json){ this.sprite = { image, json } } private loadImage(url:string){ let cancelled = false; const promise = new Promise((resolve, reject) => { const img = new Image(); img.crossOrigin = "Anonymous"; img.onload = () => { if (!cancelled) resolve(img); } img.onerror = e => { if (!cancelled) reject(e); }; img.src = url; }); //@ts-ignore promise.cancel = () => { cancelled = true; } return promise; } private loadJson (url:string){ return axios.get(url, { responseType: 'json'}).then(res=> res.data) } }
im-coder-lg/comboserdocs
.codedoc/config.ts
<filename>.codedoc/config.ts import { configuration } from '@codedoc/core'; import { theme } from './theme'; export const config = /*#__PURE__*/configuration({ theme, // --> add the theme. modify `./theme.ts` for changing the theme. dest: { namespace: '/docs', // --> your github pages namespace. remove if you are using a custom domain. html: 'dist', assets: 'dist', }, afterBuild: [ function logFinished() { console.log('Build Finished!!!!'); } ], page: { title: { base: 'Comboser Docs' // --> the base title of your doc pages }, favicon: 'assets/favicon.ico' }, misc: { github: { user: 'comboser', // --> your github username (where your repo is hosted) repo: 'comboser', // --> your github repo name action: 'Star', // --> action of the GitHub button count: true, // --> whether to show the `count` on the GitHub button large: false, // --> whether to show a `large` GitHub button standardIcon: false, // --> whether to use the GitHub icon on the GitHub button or use an action specific icon }, gitter: { room: 'combosercommunity/community' } }, });
marvinody/stock-tracker
src/bot/index.ts
import logger from '../util/logger'; import {makeWebhook} from '../util/discord'; import {getExtractor} from '../extractors'; const webhook = makeWebhook(process.env.WEBHOOK_URL, process.env.USERNAME); const randomNumber = (min: number, max: number) => { const range = max - min; return range * Math.random() + min; }; const MIN_DELAY = 5 * 1000; const MAX_DELAY = 1 * 30 * 1000; interface DB { findOrCreate: <T>(id: string, defaults: T) => [boolean, T]; updateById: (id: string, newProps: Object) => Object; } const searchAndUpdate = async (url: string, db: DB) => { try { const extractor = getExtractor(url); const liveItem = await extractor.extract(url); const [newlyCreated, currentItem] = db.findOrCreate(url, liveItem); const message = extractor.makeEmbed( liveItem, newlyCreated ? undefined : currentItem ); if (newlyCreated) { logger.info(`${liveItem.id} first lookup`); } else { // check for our internal logs if (liveItem.status !== currentItem.status) { const partialMessage = `${currentItem.title} updated: ${currentItem.status} -> ${liveItem.status}`; logger.info(partialMessage); db.updateById(url, liveItem); } } if (message !== null) { await webhook(message, liveItem.store); } } catch (err) { logger.error(err); } // queue up again for some time later... setTimeout(searchAndUpdate, randomNumber(MIN_DELAY, MAX_DELAY), url, db); }; export default (urls: string[], db: DB) => { for (const url of urls) { searchAndUpdate(url, db); } };
marvinody/stock-tracker
src/extractors/Giftgift.ts
import logger from '../util/logger'; import {waitBetweenCalls} from '../util/minWait'; import {DiscordEmbed} from '../util/discord'; import {Extractor, Item} from './IExtractor'; import axios from 'axios'; import {promises} from 'fs'; import {parse, HTMLElement} from 'node-html-parser'; const DELAY_BETWEEN_LOOKUPS_IN_MS = 2000; type GiftItem = Item & { imageUrl: string; }; const _TestUrls: string[] = [ 'http://giftshop.jz.shopserve.jp/SHOP/n739_2.html', ]; const regexes = { URL: 'https?://giftshop.jz.shopserve.jp/SHOP/(?<productCode>.*).html', NO_STOCK: 'src="/hpgen/HPB/theme/img/btn_nostock.gif"', IN_STOCK: 'src="/hpgen/HPB/theme/img/btn_cart.gif"', }; const selectors = { TITLE: 'h2.red.no2', IMAGE: 'img.mainImg', }; const store = 'Giftshop'; const urlRegexp = new RegExp(regexes.URL); const isGiftItem = (item: Item): item is GiftItem => { return item.store === store; }; const getStockStatus = (html: string) => { if (new RegExp(regexes.NO_STOCK).test(html)) { return 'Out of stock'; } if (new RegExp(regexes.IN_STOCK).test(html)) { return 'In stock'; } return 'Unknown status'; }; const getTitle = (root: HTMLElement): string => { const title = root.querySelector(selectors.TITLE); return title.text; }; const getImageUrl = (root: HTMLElement): string => { const image = root.querySelector(selectors.IMAGE); const src = image.getAttribute('src'); if (src === undefined) { return 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2Fthumb%2Fa%2Fac%2FNo_image_available.svg%2F1024px-No_image_available.svg.png&f=1&nofb=1'; } if (src.startsWith('//')) { return `http:${src}`; } return src; }; const makeEmbed = (liveItem: Item, oldItem?: Item): DiscordEmbed | null => { if (!isGiftItem(liveItem)) { throw new Error(`Item: ${liveItem.id}@${liveItem.store} is not a GiftItem`); } const embed: DiscordEmbed = { url: liveItem.url, title: `[${liveItem.id}] - ${liveItem.title}`, description: `Initial Stock Update: "${liveItem.status}"`, image: { url: liveItem.imageUrl, }, }; if (!oldItem) { // fresh item return embed; } else { if (liveItem.status !== oldItem.status) { embed.description = `Stock Update: "${oldItem.status}" -> "${liveItem.status}"`; } } return null; }; export const GiftgiftExtractor: Extractor = { _TestUrls, isValidUrl: (url: string) => urlRegexp.test(url), makeEmbed: makeEmbed, extract: waitBetweenCalls(DELAY_BETWEEN_LOOKUPS_IN_MS)( async (url: string): Promise<GiftItem> => { logger.info(`${url}: Searching`); const regexpResult = url.match(urlRegexp); if (!regexpResult?.groups) { const err = new Error(`Could not detect any regexp groups from ${url}`); logger.error(err); throw err; } const {productCode} = regexpResult.groups; const {data: html} = await axios.get(url); const status = getStockStatus(html); const root = parse(html); return { id: productCode, title: getTitle(root), status, url, store, imageUrl: getImageUrl(root), }; } ), };