repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
zhangCan112/stm_web_project
stmproject/src/App.tsx
import React, { Component } from 'react'; import { createStore } from "redux"; import rootReducer from "./reducers/index"; import { Provider } from 'react-redux'; import './App.css'; import { Router, Switch, Redirect, Route as R } from 'react-router'; import Route from "./utils/route"; import browserHistory from './history' import * as Path from './utils/routepaths' import Login from './pages/login/login'; import Forget from './pages/forget/forget'; import Register from './pages/register/register'; import Workbench from './pages/workbench/workbench'; import NotFoundPage from './pages/404/404' const store = createStore(rootReducer) class App extends Component { render() { return ( <Provider store={store}> <Router history={browserHistory}> <Switch> <Redirect exact from={Path.Home} to={Path.Workbench} /> <Route.Login path={Path.Workbench} component={Workbench} /> <Route.Logout path={Path.Login} component={Login} /> <Route.Logout path={Path.Forget} component={Forget} /> <Route.Logout path={Path.Register} component={Register} /> <R component={NotFoundPage} /> </Switch> </Router> </Provider> ); } } export default App;
zhangCan112/stm_web_project
stmproject/src/reducers/index.ts
import { combineReducers } from 'redux' function test(state = {}, action: any) { return state } const rootReducer = combineReducers({ test, }) export default rootReducer; export type StateType = ReturnType<typeof rootReducer>
zhangCan112/stm_web_project
stmproject/src/components/tomato/tomato.tsx
import React, { Component } from 'react'; import { Timeline, List } from 'antd'; import CountdownButton from "./countdownButton"; import css from './tomato.module.css'; import InfiniteScroll from 'react-infinite-scroller' interface IProps { } interface IState { } export default class Tomato extends Component<IProps, IState> { state = { } render() { return ( <div className={css.container}> <CountdownButton title={'Feedback1234'} workMinutes={1} restMinutes={1} /> <div className={css.recordList}> <InfiniteScroll initialLoad={false} pageStart={0} loadMore={()=>{}} hasMore={false} useWindow={false} > <List dataSource={[1, 2]} renderItem={item => ( <List.Item> <div> <div className={css.titleBox}> <span className={css.dateTitle}>2018年03月18日</span> <span className={css.resultTitle}>完成了3个番茄</span> </div> <Timeline pending={item === 1 ? "FeedBack12345": undefined} reverse={true}> <Timeline.Item >9:00-10:20 活动记录草稿 </Timeline.Item> <Timeline.Item>10:30-11:20 紧急bug:Feedback-12315</Timeline.Item> <Timeline.Item>13:30-14:20 多文档上传 </Timeline.Item> <Timeline.Item>14:30-15:20 团队成员继承 </Timeline.Item> </Timeline> </div> </List.Item> )} /> </InfiniteScroll> </div> </div> ) } }
zhangCan112/stm_web_project
stmproject/src/pages/404/404.tsx
import React, { Component } from 'react'; import { Button, Result } from 'antd'; import History from "../../history"; export default class NotFoundPage extends Component { render() { return <Result status="404" title="404" subTitle="Sorry, the page you visited does not exist." extra={ <Button type="primary" onClick={() => History.push('/')}> Back Home </Button> } ></Result> } }
zhangCan112/stm_web_project
stmproject/src/utils/Route.tsx
import React, { Component } from 'react'; import { Route, withRouter, RouteComponentProps } from 'react-router-dom'; import { RouteChildrenProps } from 'react-router'; import cookies from "./cookies" import * as Path from './routepaths' interface IRouteProps extends RouteComponentProps { component?: React.ComponentType<RouteComponentProps<any>> | React.ComponentType<any>; render?: ((props: RouteComponentProps<any>) => React.ReactNode); children?: ((props: RouteChildrenProps<any>) => React.ReactNode) | React.ReactNode; path?: string | string[]; exact?: boolean; sensitive?: boolean; strict?: boolean; } class Login extends Component<IRouteProps> { render() { return <CustomRoute {...this.props} mode="login" /> } } class Logout extends Component<IRouteProps> { render() { return <CustomRoute {...this.props} mode="logout" /> } } interface IProps extends RouteComponentProps, IRouteProps { mode?: "login" | "logout" | "none" } interface IState { isAuthenticated: boolean } class CustomRoute extends Component<IProps, IState> { timeoutID: NodeJS.Timeout | null = null render() { let mode = this.props.mode || "none" switch (mode) { case "login": return this.loginMode() case "logout": return this.logoutMode() default: return <Route {...this.props} /> } } loginMode = () => { let isAuthenticated = cookies.isLogin() let { component, ...rest } = this.props return isAuthenticated ? (<Route {...this.props} />) : <Route {...rest} render={(props: RouteComponentProps<any>) => { if (this.timeoutID == null) { this.timeoutID = setTimeout(() => { const { history } = this.props; history.replace(Path.Login); this.timeoutID = null }, 500) } return <LoginLoading></LoginLoading> }} /> } logoutMode = () => { let isAuthenticated = cookies.isLogin() let { component, ...rest } = this.props return !isAuthenticated ? (<Route {...this.props}> {this.props.children} </Route>) : <Route {...rest} render={(props: RouteComponentProps<any>) => { if (this.timeoutID == null) { this.timeoutID = setTimeout(() => { const { history } = this.props; history.replace(Path.Home); this.timeoutID = null }, 500) } return <HomeLoading></HomeLoading> }} /> } } // LoginLoading 跳转登录页 class LoginLoading extends Component { render() { return <p style={{ width: "100%", textAlign: "center", fontSize: "20px", lineHeight: "50px" }}>请登录...</p> } } // LoginLoading 跳转首页 class HomeLoading extends Component { render() { return <p style={{ width: "100%", textAlign: "center", fontSize: "20px", lineHeight: "50px" }}>返回首页...</p> } } export default { Custom: withRouter(CustomRoute), Login: withRouter(Login), Logout: withRouter(Logout), };
zhangCan112/stm_web_project
stmproject/src/utils/routepaths.ts
/** * 首页 */ export const Home = '/' /** * 工作台 */ export const Workbench = '/workbench' /** * 登陆页 */ export const Login = '/login' /** * 忘记密码 */ export const Forget = '/forget' /** * 用户注册 */ export const Register = '/register'
zhangCan112/stm_web_project
stmproject/src/components/gtd/task.tsx
<reponame>zhangCan112/stm_web_project<gh_stars>0 import React, { Component } from 'react'; import { Checkbox, Icon } from 'antd'; import css from './gtd.module.css'; interface IProps { /** * tag标记 */ tag?: string, /** * 当点击了checkboxIcon时 */ onCheck?: (tag?: string) => void, /** * 当点击了置顶按钮时 */ onTop?: (tag?: string) => void, } interface IState { } export default class TaskCell extends Component<IProps, IState> { render() { return ( <div className={css.taskCell}> <div> <Checkbox /> <span className={css.taskTitle}>{'置顶任务会是番茄时间正在工作的内容'}</span> </div> <div className={css.taskButtonbox}> <Icon type="arrow-up" style={{ fontSize: '20px'}} onClick={()=>{}}/> <Icon type="ellipsis" style={{ fontSize: '20px'}} onClick={()=>{}}/> </div> </div> ) } }
zhangCan112/stm_web_project
stmproject/src/pages/forget/forget.tsx
import React, { Component } from 'react'; import './forget.css'; class Forget extends Component { render() { return ( <div> 忘记密码页面!!! </div> ); } } export default Forget
zhangCan112/stm_web_project
stmproject/src/utils/cookies.ts
import * as cookie from "react-cookie"; import { GET } from "../utils/request"; import URLS from "../utils/urls"; // Cookie数据中的约定值的Key值 const LoginKey = "isLogin" export function isLogin() { GET(URLS.HEALTH) let cookies = new cookie.Cookies() return cookies.get(LoginKey) === "true" } export default { isLogin, }
zhangCan112/stm_web_project
stmproject/src/components/gtd/gtd.tsx
import React, { Component } from 'react'; import { Input, Icon, Timeline, List } from 'antd'; import css from './gtd.module.css'; import TaskCell from "./task"; import InfiniteScroll from 'react-infinite-scroller' interface IProps { } interface IState { } export default class GTD extends Component<IProps, IState> { render() { return ( <div className={css.container}> <div style={{ marginBottom: 16 }}> <Input size={'large'} placeholder="添加新任务" suffix={<Icon type="enter" onClick={()=>{}}/>}/> </div> <TaskCell></TaskCell> <TaskCell></TaskCell> <TaskCell></TaskCell> <TaskCell></TaskCell> <TaskCell></TaskCell> <TaskCell></TaskCell> <TaskCell></TaskCell> </div> ) } }
zhangCan112/stm_web_project
stmproject/src/containers/home/home.tsx
<reponame>zhangCan112/stm_web_project import React, { Component } from 'react'; import { Layout, Icon, Avatar, Button, Popover, message } from 'antd'; import css from './home.module.css'; import { NavLink } from 'react-router-dom'; import * as RoutePath from '../../utils/routepaths'; import { GET, filterSuccessCode } from "../../utils/request"; import URLS from "../../utils/urls"; import { delay } from "../../utils/tools"; import history from '../../history' const { Header, Content, Footer } = Layout; interface IProps { } interface IState { /** * 用户信息点击气泡是否展现 */ visible: boolean, } export default class Home extends Component<IProps, IState> { state = { visible: false, }; /** *  用户信息点击气泡 */ userInfoPopoverContent = ( <Button className={css.userInfoPopoverContent} onClick={() => { this.userInfoPopoverHide() this.logout() }}> <Icon type="logout" /> 退出登录 </Button> ) render() { return ( <Layout style={{ height: '100vh', minHeight:'700px' }}> <Header className={css.header} style={{ background: "#4A90E2" }}> <div className={css.logo} > <img alt="logo" src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" width="32px" height="32px" /> <span className={css.logoTitle}>管理自己的时间</span> </div> <div className={css.navlinksBox}> <NavLink to={RoutePath.Workbench} className={css.navLinkNormal} activeStyle={{ opacity: 1 }}> 工作台 </NavLink> <NavLink to="/home1" className={css.navLinkNormal} activeStyle={{ opacity: 1 }}> 日报 </NavLink> <NavLink to="/home2" className={css.navLinkNormal} activeStyle={{ opacity: 1 }}> 周报 </NavLink> <NavLink to="/home3" className={css.navLinkNormal} activeStyle={{ opacity: 1 }}> 回顾 </NavLink> </div> <div className={css.setting}> <Icon type="search" className={css.settingIcon} onClick={() => { }} /> <Icon type="bell" className={css.settingIcon} onClick={() => { }} /> <Popover placement='bottom' trigger="click" content={this.userInfoPopoverContent} visible={this.state.visible} onVisibleChange={this.handleVisibleChange} > <Button className={css.userInfo} onClick={() => { }} ghost> <Avatar className={css.avatar} icon="user" size={32} /> <span className={css.userName}><NAME></span> </Button> </Popover> </div> </Header> <Content className={css.contentBox}> <div className={css.content}> {this.props.children} </div> </Content> <Footer style={{ textAlign: 'center' }}>©2019 风林火山技术部出品</Footer> </Layout> ) } userInfoPopoverHide = () => { this.setState({ visible: false, }); } handleVisibleChange = (visible: boolean) => { this.setState({ visible }); } logout = async () => { let hide = message.loading("正在退出登录...", 0) let result = await GET(URLS.LOGOUT) .then(filterSuccessCode) .catch((e: Error) => { return e }) await delay(1000) hide() if (result instanceof Error) { let err = result as Error message.error(err.message) return } message.success("登出成功!", 0.5, ()=>{ history.replace('/login') }) } }
zhangCan112/stm_web_project
stmproject/src/pages/workbench/workbench.tsx
import React, { Component } from 'react'; import Home from "../../containers/home/home"; import Tomato from '../../components/tomato/tomato'; import GTD from '../../components/gtd/gtd'; import css from './workbench.module.css'; interface Iprops { } class Workbench extends Component<Iprops> { render() { return ( <Home> <div className={css.container}> <Tomato /> <span className={css.space}/> <GTD /> </div> </Home> ) } } export default Workbench
zhangCan112/stm_web_project
stmproject/src/utils/request.ts
var pkg = require("../../package.json"); const ServiceErrorMsg = "服务器错误!" // 业务Api的commonUrl var commonUrl: string = pkg.projectConfig.proxy // 业务API返回的Body数据格式 export interface ResponseBody<B> { scode: number body?: B msg?: string } //GET GET请求方法 export const GET = <B>(url: string, querry?: {[key: string]: string}) : Promise<ResponseBody<B>> => { let querryStr: string | null = null if (querry && Object.keys(querry).length > 0) { let querryStrArr: string[] = [] Object.keys(querry).forEach((key) => { querryStrArr.push(`${key}=${querry[key]}`) }) querryStr = querryStrArr.join("&") } let querryUrl = url if (querryStr && querryStr.length > 0) { querryUrl = `${url}?${querryStr}` } return request(querryUrl) } //POST POST请求方法 export const POST = <B>(url: string, form?: {[key: string]: any}) : Promise<ResponseBody<B>> => { let init: RequestInit = {} init.method = "POST" init.body = JSON.stringify(form) init.headers = {'Content-Type': 'application/json'} return request(url, init) } //PUT PUT请求方法 export const PUT = <B>(url: string, id?: string, form?: {[key: string]: any}) : Promise<ResponseBody<B>> => { let init: RequestInit = {} init.method = "PUT" init.body = JSON.stringify(form) init.headers = {'Content-Type': 'application/json'} let urlStr = url if (id && id.length > 0) { urlStr = `${url}/${id}` } return request(urlStr, init) } //DELETE DELETE请求方法 export const DELETE = <B>(url: string, id?: string) : Promise<ResponseBody<B>> => { let init: RequestInit = {} init.method = "DELETE" let urlStr = url if (id && id.length > 0) { urlStr = `${url}/${id}` } return request(urlStr, init) } // request 针对后台API服务接口约定封装的基础业务请求接口 const request = <B>(input: string, init?: RequestInit): Promise<ResponseBody<B>> => { let newInit: RequestInit = { ...init } newInit.mode = 'cors'//跨域 newInit.credentials = "include" return fetch(`${commonUrl}${input}`, newInit) .then(checkStatus) .then((response) => { return response.json() as any as ResponseBody<B> }) } //检查请求状态 200才认为网络服务请求成功 function checkStatus(response: Response) { if (response.status === 200) { return response } throw new Error(ServiceErrorMsg) } // 筛选返回scode==0的返回数据,其他scode将作为错误抛出 export function filterSuccessCode<B>(response: ResponseBody<B>) { if (response.scode === 0) { return response; } throw new Error(response.msg || ServiceErrorMsg) }
r0bs/csp-generator
index.spec.ts
import { expect } from "chai"; import { CspSource, generate } from "."; import { readFileSync } from "fs"; describe("index", () => { it("generates a short csp", () => { const csp = generate({ "script-src": ["'self'", "www.example.com"], }); expect(csp).to.equal("script-src 'self' www.example.com;"); }); it("generates a pretty standard secure csp", () => { const csp = generate(JSON.parse(readFileSync("./test/mixed-directives.json", "utf-8"))); expect(csp).to.equal( "connect-src 'self' api.example.com; default-src 'none'; font-src 'self'; form-action 'self'; frame-ancestors 'none'; frame-src 'none'; img-src 'self' *.example.com; manifest-src 'self'; media-src 'none'; navigate-to 'self' example.com; object-src 'none'; script-src 'self' www.example.com; style-src 'self'; worker-src 'none'; upgrade-insecure-requests;" ); }); it("failes validation because input is not an object", () => { expect(() => generate("" as CspSource)) .to.throw() .with.property("message", "Input must be an object"); }); it("failes validation because of empty standard directive", () => { expect(() => generate(JSON.parse(readFileSync("./test/empty-directive.json", "utf-8")))) .to.throw() .with.property("message", "Invalid value for 'style-src'"); }); it("failes validation because of empty a non empty key only directive", () => { expect(() => generate(JSON.parse(readFileSync("./test/non-empty-keyonly-directive.json", "utf-8")))) .to.throw() .with.property("message", "Key-only directive 'block-all-mixed-content' must have an empty array as value"); }); it("failes because directive is not known", () => { expect(() => generate(JSON.parse(readFileSync("./test/wrong-key.json", "utf-8")))) .to.throw() .with.property("message", "Unknown directive 'wrong-key'"); }); it("failes because of an invalid value in a standard directive", () => { expect(() => generate(JSON.parse(readFileSync("./test/wrong-value.json", "utf-8")))) .to.throw() .with.property("message", "Invalid value for 'script-src'"); }); it("failes because of multiple errors: an invalid value in a standard directive and an unknown directive", () => { expect(() => generate(JSON.parse(readFileSync("./test/wrong-key-and-value.json", "utf-8")))) .to.throw() .with.property("message", "Invalid value for 'script-src', Unknown directive 'wrong-src'"); }); });
r0bs/csp-generator
index.ts
enum CspKeywords { "'none'", "'report-sample'", "'self'", "'strict-dynamic'", "'unsafe-allow-redirects'", "'unsafe-eval'", "'unsafe-hashes'", "'unsafe-inline'", "data:", } enum CspDirectiveKeys { "base-uri", "block-all-mixed-content", "connect-src", "default-src", "font-src", "form-action", "frame-ancestors", "frame-src", "img-src", "manifest-src", "media-src", "navigate-to", "object-src", "plugin-types", "prefetch-src", "report-to", "report-uri", "require-sri-for", "require-trusted-types-for", "sandbox", "script-src-attr", "script-src-elem", "script-src", "style-src-attr", "style-src-elem", "style-src", "trusted-types", "upgrade-insecure-requests", "worker-src", } enum KeyOnlyDirectives { "block-all-mixed-content", "upgrade-insecure-requests", } /** * TypeScript's Object.values(enum) creates an array * with values _and_ keys (which are numbers), * hence the typecasting later in the code (as string[]) */ const keyOnlyDirectives = Object.values(KeyOnlyDirectives); const cspDirectiveNames = Object.values(CspDirectiveKeys); type CspDirectiveKey = keyof typeof CspDirectiveKeys; type CspDirectivePredefinedValue = keyof typeof CspKeywords; export type CspSource = { [k in CspDirectiveKey]?: CspDirectivePredefinedValue[] | string[]; }; const validateSource = (input: unknown): { valid: true; source: CspSource } | { valid: false; errors: string[] } => { // Condition: input must be an object if (typeof input !== "object") { return { valid: false, errors: ["Input must be an object"] }; } const errors = Object.entries(input as object) .map((directive) => { const [directiveKey, directiveValuesArray] = directive; // Condition: key must be a known directive if (!cspDirectiveNames.includes(directiveKey)) { return `Unknown directive '${directiveKey}'`; } // Condition: When a key is a known key-only-directive, it's value must be an empty array if (keyOnlyDirectives.includes(directiveKey) && directiveValuesArray.length > 0) { return `Key-only directive '${directiveKey}' must have an empty array as value`; } // Condition: value of known (non key-only) CSP directive must contain only CSP keywords or domain-like strings (more then 3 letters, with at least one dot) if ( (!keyOnlyDirectives.includes(directiveKey) && directiveValuesArray.length === 0) || !directiveValuesArray.every((value: string) => Object.values(CspKeywords).includes(value) || (value.includes(".") && value.length > 3)) ) { return `Invalid value for '${directiveKey}'`; } }) .filter((error) => error); if (errors.length) { return { valid: false, errors: errors as string[] }; } return { valid: true, source: input as CspSource }; }; const reduceCspObjectToString = (source: CspSource) => (csp: string, directiveKey: string) => { const key = directiveKey as CspDirectiveKey; if (keyOnlyDirectives.includes(key)) { csp += `${key}; `; } else { csp += `${key} ${(source[key] as string[]).join(" ")}; `; } return csp; }; export const generate = (input: CspSource): string => { const validationResult = validateSource(input); if (!validationResult.valid) { throw new Error(validationResult.errors.join(", ")); } const { source } = validationResult; return Object.keys(source).reduce(reduceCspObjectToString(source), "").trim(); }; export default generate;
SevereCloud/vk-limits
src/App.tsx
import React from 'react'; import { AppRoot, SplitLayout, SplitCol, ViewWidth, Panel, PanelHeader, Header, Group, Search, PanelHeaderButton, SimpleCell, Footer, withAdaptivity, View, } from '@vkontakte/vkui'; import '@vkontakte/vkui/dist/vkui.css'; import { data, DataGroup, DataItem } from './data'; import Icon28MoonOutline from '@vkontakte/icons/dist/28/moon_outline'; import IconGitHub from './icons/IconGitHub'; import type { AppearanceSchemeType, UpdateConfigData, } from '@vkontakte/vk-bridge'; import type { VKMiniAppAPI } from '@vkontakte/vk-mini-apps-api'; interface AppState { scheme: AppearanceSchemeType; search: string; } interface AppProps { vkAPI: VKMiniAppAPI; mobile: boolean; viewWidth?: ViewWidth; } class App extends React.Component<AppProps, AppState> { constructor(props: AppProps) { super(props); // TODO: хранить схему в локальном хранилище, чтобы восстанавливать тему // TODO: проверка темной темы у браузера this.state = { scheme: 'bright_light', search: '', }; this.onChange = this.onChange.bind(this); this.changeScheme = this.changeScheme.bind(this); } componentDidMount(): void { this.props.vkAPI.onUpdateConfig((data: UpdateConfigData) => { const schemeAttribute = document.createAttribute('scheme'); schemeAttribute.value = data.scheme ? data.scheme : 'client_light'; this.setState({ scheme: data.scheme }); document.body.attributes.setNamedItem(schemeAttribute); }); this.props.vkAPI.initApp(); } onChange(e: React.ChangeEvent<HTMLInputElement>): void { this.setState({ search: e.target.value }); } get limits(): DataGroup[] { const search = this.state.search.toLowerCase(); const groups: DataGroup[] = []; data.forEach((group) => { if (group.name.toLowerCase().indexOf(search) > -1) { groups.push(group); } else { const items: DataItem[] = []; group.items.forEach((item) => { if ( item.name.toLowerCase().indexOf(search) > -1 || item.text.toLowerCase().indexOf(search) > -1 || (item.hint && item.hint.toLowerCase().indexOf(search) > -1) ) { items.push(item); } }); if (items.length > 0) { groups.push({ name: group.name, color: group.color, items: items, }); } } }); return groups; } /** * Меняет цветовую схему */ changeScheme(): void { const scheme = this.state.scheme === 'bright_light' ? 'space_gray' : 'bright_light'; const schemeAttribute = document.createAttribute('scheme'); schemeAttribute.value = scheme; document.body.attributes.setNamedItem(schemeAttribute); this.setState({ scheme: scheme, }); // TODO: хранить схему в локальном хранилище, чтобы восстанавливать тему // TODO: проверка темной темы у браузера } render(): JSX.Element { const { viewWidth } = this.props; const isDesktop = viewWidth && viewWidth >= ViewWidth.TABLET; const navigation = ( <Panel id="nav"> <PanelHeader /> <Group> {this.limits.map((group, groupIndex) => ( <SimpleCell key={groupIndex} href={`#${group.name}`}> {group.name} </SimpleCell> ))} </Group> </Panel> ); return ( <AppRoot> <SplitLayout header={<PanelHeader separator={false} />} style={{ justifyContent: 'center' }} > {isDesktop && ( <SplitCol fixed width={280} maxWidth={280}> {navigation} </SplitCol> )} <SplitCol spaced={isDesktop} animate={!isDesktop} width={isDesktop ? '560px' : '100%'} maxWidth={isDesktop ? '560px' : '100%'} > <View activePanel="main"> <Panel id="main"> <PanelHeader left={ this.props.mobile ? ( <PanelHeaderButton target="_blank" href="https://github.com/SevereCloud/vk-limits" > <IconGitHub /> </PanelHeaderButton> ) : ( <PanelHeaderButton onClick={() => { this.changeScheme(); }} style={{ cursor: 'pointer' }} > <Icon28MoonOutline width={24} height={24} /> </PanelHeaderButton> ) } right={ !this.props.mobile && ( <PanelHeaderButton target="_blank" href="https://github.com/SevereCloud/vk-limits" > <IconGitHub /> </PanelHeaderButton> ) } > Лимиты </PanelHeader> <Group> <Search value={this.state.search} onChange={this.onChange} after={null} /> </Group> {this.limits.map((group, groupIndex) => ( <Group key={groupIndex} header={<Header mode="secondary">{group.name}</Header>} > <a id={group.name} style={{ display: 'block', top: -112, position: 'relative', }} ></a> {group.items.map((item, itemIndex) => ( <SimpleCell key={itemIndex} multiline before={ <item.icon fill={group.color} width={28} height={28} /> } description={item.text} href={item.link} target="_blank" > {item.name} {item.hint && ( <span style={{ color: 'var(--text_secondary)' }}> {' ' + item.hint} </span> )} </SimpleCell> ))} </Group> ))} <Footer></Footer> </Panel> </View> </SplitCol> </SplitLayout> </AppRoot> ); } } export default withAdaptivity(App, { viewWidth: true });
SevereCloud/vk-limits
src/index.tsx
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { VKMiniAppAPI } from '@vkontakte/vk-mini-apps-api'; import bridge from '@vkontakte/vk-bridge'; import { AdaptivityProvider, ConfigProvider } from '@vkontakte/vkui'; const isMobileApps = () => { const url = new URL(window.location.href); const vkPlatform = url.searchParams.get('vk_platform'); return vkPlatform !== null && vkPlatform !== 'desktop_web'; }; ReactDOM.render( <React.StrictMode> <ConfigProvider> <AdaptivityProvider> <App vkAPI={new VKMiniAppAPI(bridge)} mobile={isMobileApps()} /> </AdaptivityProvider> </ConfigProvider> </React.StrictMode>, document.getElementById('root'), ); // Hot Module Replacement (HMR) - Remove this snippet to remove HMR. // Learn more: https://www.snowpack.dev/#hot-module-replacement if (import.meta.hot) { import.meta.hot.accept(); }
SevereCloud/vk-limits
src/data.ts
import { Icon28UserOutline, Icon28NameTagOutline, Icon28PictureStackOutline, Icon28Users3Outline, Icon28DocumentOutline, Icon28UserSquareOutline, Icon28UploadOutline, Icon28MarketOutline, Icon28MarketLikeOutline, Icon24Crop, Icon24Fullscreen, Icon28MusicOutline, Icon28VideocamOutline, Icon28MessageOutline, Icon28UsersOutline, Icon28RecentOutline, Icon28AdvertisingOutline, Icon28WorkOutline, Icon20EducationOutline, Icon28KeySquareOutline, Icon28ArticleOutline, Icon28HorseToyOutline, Icon28FavoriteOutline, Icon28LikeOutline, Icon28AttachOutline, Icon28ServicesOutline, Icon28GridSquareOutline, Icon28ListOutline, Icon28DownloadOutline, Icon28SearchOutline, Icon28Search, } from '@vkontakte/icons'; import type { IconProps } from './types'; export interface DataItem { name: string; icon: React.FunctionComponent<IconProps>; text: string; hint?: string; link?: string; } export interface DataGroup { name: string; // icon: React.FunctionComponent<IconProps>; color: string; items: DataItem[]; } /** * Данные лимитов * * - [Иконки](https://vkcom.github.io/icons/) * - [Цвета](https://github.com/VKCOM/VKUI/blob/master/src/styles/bright_light.css) */ export const data: DataGroup[] = [ { name: 'Пользователь', color: 'var(--dynamic_violet)', items: [ { name: 'Username', icon: Icon28UserOutline, hint: '(адрес страницы)', text: 'от 5 до 32 символов', link: 'https://vk.com/faq16629', }, { name: 'Длина имени или фамилии', icon: Icon28NameTagOutline, text: 'до 32 символов', }, { name: 'Статус', icon: Icon28ArticleOutline, text: 'до 140 символов', }, { name: 'Пароль', icon: Icon28KeySquareOutline, text: 'от 6 символов', }, { name: '<NAME>', icon: Icon28Users3Outline, text: 'до 15 человек', }, { name: '<NAME>', icon: Icon28HorseToyOutline, text: 'до 15 детей и до 15 внуков', }, { name: 'Среднее образования', icon: Icon20EducationOutline, text: 'до 7 учебных заведений', }, { name: 'Высшее образования', icon: Icon20EducationOutline, text: 'до 10 образований', }, { name: 'Карьера', icon: Icon28WorkOutline, text: 'до 7 мест работы', }, { name: '<NAME>', icon: Icon28FavoriteOutline, text: 'до 5 воинских частей', }, { name: 'Мне нравится', icon: Icon28LikeOutline, text: '500 в сутки', }, { name: 'Реклама', icon: Icon28AdvertisingOutline, text: 'появляется через 3 месяца после регистрации', }, ], }, { name: 'Чаты', color: 'var(--dynamic_blue)', items: [ { name: 'Число участников', hint: '(обычный чат)', icon: Icon28UsersOutline, text: 'до 500 человек', }, { name: 'Число участников', hint: '(чат сообщества)', icon: Icon28Users3Outline, text: 'до 3 000 человек', }, { name: '<NAME>', icon: Icon28MessageOutline, text: 'примерно до 4096 байт', }, { name: 'Вложения', hint: 'к сообщению', icon: Icon28AttachOutline, text: 'до 10 вложений', }, ], }, { name: 'Фотографии', color: 'var(--dynamic_green)', items: [ { name: 'Допустимые форматы', icon: Icon28DocumentOutline, text: 'JPG, PNG, GIF', link: 'https://vk.com/dev/upload_files', }, { name: 'Минимальный размер главной фотографии', hint: '(пользователя, сообщества или чата)', icon: Icon28UserSquareOutline, text: '200x200px', link: 'https://vk.com/dev/upload_files', }, { name: 'Минимальный размер фотографии товаров', icon: Icon28MarketOutline, text: '400x400px', link: 'https://vk.com/dev/upload_files_2', }, { name: 'Минимальный размер фотографии подборки товаров', icon: Icon28MarketLikeOutline, text: '1280x720px', link: 'https://vk.com/dev/upload_files_2', }, { name: 'Сумма высоты и ширины', icon: Icon24Fullscreen, text: 'до 14 000 px', link: 'https://vk.com/faq8209', }, { name: 'Размер файла', icon: Icon28UploadOutline, text: 'не более 50 МБ', link: 'https://vk.com/dev/upload_files', }, { name: 'Соотношение сторон', icon: Icon24Crop, text: 'не менее 1:20', link: 'https://vk.com/dev/upload_files', }, { name: 'Фотографий в одном альбоме', icon: Icon28PictureStackOutline, text: 'до 10 000 фотографий', link: 'https://vk.com/faq8209', }, { name: 'Отметки', icon: Icon28Users3Outline, text: 'до 35 человек', link: 'https://vk.com/faq8209', }, ], }, { // Лимитов по максимальному разрешению видео нет name: 'Истории', color: 'var(--dynamic_red)', items: [ { name: 'Допустимые форматы', hint: 'фотографии', icon: Icon28DocumentOutline, text: 'JPG, PNG, GIF', link: 'https://vk.com/dev/upload_files_3', }, { name: 'Максимальная сумма высоты и ширины', icon: Icon24Fullscreen, text: '14 000 px', link: 'https://vk.com/dev/upload_files_3', }, { name: 'Размер файла', icon: Icon28UploadOutline, text: 'не более 10 МБ', link: 'https://vk.com/dev/upload_files_3', }, { name: 'Длительность', hint: 'видео', icon: Icon28RecentOutline, text: 'не более 15 секунд', }, { name: 'Видеокодек', icon: Icon28VideocamOutline, text: 'H.264', link: 'https://vk.com/dev/upload_files_3', }, { name: 'Аудиокодек', icon: Icon28MusicOutline, text: 'AAC', link: 'https://vk.com/dev/upload_files_3', }, ], }, { name: 'Документы', color: 'var(--dynamic_gray)', items: [ { name: 'Допустимые форматы', icon: Icon28DocumentOutline, text: 'любые форматы за исключением музыкальных и исполняемых файлов', link: 'https://vk.com/dev/upload_files_2?f=10.%20%D0%97%D0%B0%D0%B3%D1%80%D1%83%D0%B7%D0%BA%D0%B0%20%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D0%BE%D0%B2', }, { name: 'Размер файла', icon: Icon28UploadOutline, text: 'не более 2048 МБ', link: 'https://vk.com/dev/upload_files_2?f=10.%20%D0%97%D0%B0%D0%B3%D1%80%D1%83%D0%B7%D0%BA%D0%B0%20%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D0%BE%D0%B2', }, ], }, { name: 'API', color: 'var(--dynamic_orange)', items: [ { name: 'Запросы от пользователя', icon: Icon28UserOutline, text: '3 в секунду', link: 'https://vk.com/dev/api_requests', }, { name: 'Запросы от сообщества', icon: Icon28Users3Outline, text: '20 в секунду', link: 'https://vk.com/dev/api_requests', }, { name: 'Запросы от сервиса', icon: Icon28ServicesOutline, text: '3 в секунду', link: 'https://vk.com/dev/api_requests', }, { name: 'Вызовы методов Execute', hint: 'в рамках одного запроса', icon: Icon28GridSquareOutline, text: 'до 25 обращений к разным методам', link: 'https://vk.com/dev/execute', }, { name: 'Операции Execute', hint: 'в рамках одного запроса', icon: Icon28ListOutline, text: 'до 1000 операций', link: 'https://vk.com/dev/execute', }, { name: 'Размер ответа Execute', icon: Icon28DownloadOutline, text: 'не более 5 МБ', link: 'https://vk.com/dev/execute', }, { name: 'Лимит на newsfeed.search', icon: Icon28SearchOutline, text: '1000 вызовов в сутки', link: 'https://vk.com/dev/data_limits', }, { name: 'Лимит на wall.search', icon: Icon28Search, text: '1000 вызовов в сутки', link: 'https://vk.com/dev/data_limits', }, { name: 'Лимит на wall.get', icon: Icon28ArticleOutline, text: '5000 вызовов в сутки', link: 'https://vk.com/dev/data_limits', }, ], }, ];
SevereCloud/vk-limits
src/types.ts
import type { HTMLAttributes, RefObject, RefCallback } from 'react'; export interface IconProps extends HTMLAttributes<HTMLDivElement> { fill?: string; width?: number; height?: number; getRootRef?: RefCallback<HTMLDivElement> | RefObject<HTMLDivElement>; }
64Mega/typestyle
src/tests/supports.ts
<reponame>64Mega/typestyle import { style, getStyles, reinit } from '../index'; import * as assert from 'assert'; describe('@supports', () => { it('standard freestyle', () => { reinit(); style({ color: 'red', $nest: { '@supports (display: flex)': { color: 'white' } } }); assert.equal(getStyles(), '.f5f13tn{color:red}@supports (display: flex){.f5f13tn{color:white}}'); }); });
64Mega/typestyle
src/tests/rule.tsx
<filename>src/tests/rule.tsx import { getStyles, reinit, cssRule } from '../index'; import * as assert from 'assert'; describe("test rules", () => { it("it should provide expected output when used as css framework", () => { reinit(); /** Sample variables */ const colors = { primary: 'blue', info: 'lightblue', success: 'green', warning: 'orange', danger: 'red', bgColor: 'white' }; const fonts = { baseSize: '14pt' }; // set html styles cssRule('html', { height: '100%' }); // set default body styles cssRule('body', { fontSize: fonts.baseSize, margin: 0, padding: 0, height: '100%', backgroundColor: colors.bgColor, color: colors.primary }); assert.equal(getStyles(), 'html{height:100%}body{background-color:white;color:blue;font-size:14pt;height:100%;margin:0;padding:0}'); }); it("support application style layout", () => { reinit(); /** Use full window size for application */ cssRule('html, body', { height: '100%', width: '100%', padding: 0, margin: 0 }); /** Use border box */ cssRule('html', { boxSizing: 'border-box' }); cssRule('*,*:before,*:after', { boxSizing: 'inherit', }); assert.equal(getStyles(), 'html, body{height:100%;margin:0;padding:0;width:100%}html{box-sizing:border-box}*,*:before,*:after{box-sizing:inherit}'); }); it('support global media queries', () => { reinit(); /** Save ink with a white background */ cssRule('@media print', { $nest: { body: { background: 'white' } } }); assert.equal(getStyles(), '@media print{body{background:white}}'); }); });
64Mega/typestyle
src/tests/extend.ts
<filename>src/tests/extend.ts import { extend } from '../index'; import * as assert from 'assert'; describe("extend", () => { it("plain objects should be preserved", () => { assert.deepEqual(extend({ color: 'red' }), { color: 'red' }); }); it("nested objects should not get flattened", () => { assert.deepEqual( extend( { $nest: { '&:hover': { color: 'red' } } }, ), { $nest: { '&:hover': { color: 'red' } } } ); }); it("nested objects should merge into non nested", () => { assert.deepEqual( extend( { color: 'grey' }, { $nest: { '&:hover': { color: 'red' } } }, ), { color: 'grey', $nest: { '&:hover': { color: 'red' } } }); }); it("nested objects should merge together", () => { assert.deepEqual( extend( { color: 'grey' }, { backgroundColor: 'grey' }, { $nest: { '&:hover': { color: 'red' } } }, { $nest: { '&:hover': { backgroundColor: 'red' } } }, ), { color: 'grey', backgroundColor: 'grey', $nest: { '&:hover': { color: 'red', backgroundColor: 'red' } } }); }); it("extend should compose i.e. should be nestable", () => { assert.deepEqual( extend( extend({ $nest: { '&:hover': { color: 'red' } } }), { $nest: { '&:hover': { backgroundColor: 'red' } } }, ), { $nest: { '&:hover': { color: 'red', backgroundColor: 'red' } } }); }); it("extend should compose i.e. should be truly nestable", () => { assert.deepEqual( extend( extend({ $nest: { '&:hover': { color: 'red' } } }), extend({ $nest: { '&:hover': { backgroundColor: 'red' } } }), ), { $nest: { '&:hover': { color: 'red', backgroundColor: 'red' } } }); }); it("different nested keys should not merge", () => { assert.deepEqual( extend( { $nest: { '&:hover': { color: 'red' } } }, { $nest: { '&:hover': { backgroundColor: 'red' } } }, { $nest: { '&:focus': { backgroundColor: 'red' } } }, { $nest: { '&:hover': { fontSize: '14px' }, '&:focus': { fontFamily: 'arial' } } }, ), { $nest: { '&:hover': { fontSize: '14px', color: 'red', backgroundColor: 'red' }, '&:focus': { fontFamily: 'arial', backgroundColor: 'red' } } }); }); });
hellow554/rhino
binding/vue/src/rhino.ts
/* Copyright 2022 Picovoice Inc. You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" file accompanying this source. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { WebVoiceProcessor } from '@picovoice/web-voice-processor'; import { RhinoContext, RhinoInference, RhinoWorkerFactory } from '@picovoice/rhino-web-core'; /** * Type alias for RhinoWorkerFactory arguments. */ export type RhinoWorkerFactoryArgs = { accessKey: string; context: RhinoContext; requireEndpoint?: boolean; start: boolean; }; /** * Type alias for Rhino Vue Mixin. * Use with `Vue as VueConstructor extends {$rhino: RhinoVue}` to get types in typescript. */ export interface RhinoVue { $_rhnWorker_: Worker | null; $_webVp_: WebVoiceProcessor | null; init: ( rhinoFactoryArgs: RhinoWorkerFactoryArgs, rhinoFactory: RhinoWorkerFactory, inferenceCallback: (inference: RhinoInference) => void, contextCallback: (info: string) => void, readyCallback: () => void, errorCallback: (error: Error) => void) => void; start: () => boolean; pause: () => boolean; pushToTalk: () => boolean; delete: () => void; } export default { computed: { /** * Rhino Vue Mixin. */ $rhino(): RhinoVue { return { $_rhnWorker_: null as Worker | null, $_webVp_: null as WebVoiceProcessor | null, /** * Init function for Rhino. * * @param rhinoFactoryArgs Arguments for RhinoWorkerFactory. * @param rhinoFactory The language-specific worker factory * @param inferenceCallback A method invoked upon completion of intent inference. * @param contextCallback A method invoked after context information is ready. * @param readyCallback A method invoked after Rhino has initialized. * @param errorCallback A method invoked if an error occurs within `PorcupineWorkerFactory`. */ async init( rhinoFactoryArgs, rhinoFactory, inferenceCallback = (_: RhinoInference) => {}, contextCallback = (_: string) => {}, readyCallback = () => {}, errorCallback = (error: Error) => {console.error(error)} ) { try { const { accessKey, context, requireEndpoint, start } = rhinoFactoryArgs; this.$_rhnWorker_ = await rhinoFactory.create({ accessKey, context: JSON.parse(JSON.stringify(context)), requireEndpoint, start }); this.$_webVp_ = await WebVoiceProcessor.init({ engines: [this.$_rhnWorker_], }); this.$_rhnWorker_.onmessage = messageEvent => { switch (messageEvent.data.command) { case 'rhn-inference': inferenceCallback(messageEvent.data.inference); // Reset Push-to-Talk this.$_rhnWorker_?.postMessage({ command: 'pause' }); break; case 'rhn-info': const info = messageEvent.data.info; contextCallback(info); break; } }; this.$_rhnWorker_.postMessage({ command: 'info' }); readyCallback(); } catch (error) { errorCallback(error as Error); } }, /** * Start processing audio. */ start() { if (this.$_webVp_ !== null) { this.$_webVp_.start(); return true; } return false; }, /** * Stop processing audio. */ pause() { if (this.$_webVp_ !== null) { this.$_webVp_.pause(); return true; } return false; }, /** * Put Rhino in an active isTalking state. */ pushToTalk() { if (this.$_webVp_ !== null) { this.$_webVp_.resume(); this.$_rhnWorker_?.postMessage({ command: 'resume' }); return true; } return false; }, /** * Delete used resources. */ delete() { this.$_webVp_?.release(); this.$_rhnWorker_?.postMessage({ command: 'release' }); } } } }, // Vue 3 method to clean resources. beforeUnmount(this: any) { this.$rhino.delete(); }, // Vue 2 method to clean resources. beforeDestory(this: any) { this.$rhino.delete(); } };
hellow554/rhino
binding/react/src/index.ts
import { useRhino, RhinoHookArgs } from './use_rhino'; export { useRhino, RhinoHookArgs, };
hellow554/rhino
binding/react-native/src/rhino_errors.tsx
<filename>binding/react-native/src/rhino_errors.tsx // // Copyright 2021 Picovoice Inc. // // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" // file accompanying this source. // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. // class RhinoError extends Error { constructor(message: string) { super(message); this.name = "RhinoError"; } } class RhinoMemoryError extends RhinoError { constructor(message: string) { super(message); this.name = "RhinoMemoryError"; } } class RhinoIOError extends RhinoError { constructor(message: string) { super(message); this.name = "RhinoIOError"; } } class RhinoInvalidArgumentError extends RhinoError { constructor(message: string) { super(message); this.name = "RhinoInvalidArgumentError"; } } class RhinoStopIterationError extends RhinoError { constructor(message: string) { super(message); this.name = "RhinoStopIterationError"; } } class RhinoKeyError extends RhinoError { constructor(message: string) { super(message); this.name = "RhinoKeyError"; } } class RhinoInvalidStateError extends RhinoError { constructor(message: string) { super(message); this.name = "RhinoInvalidStateError"; } } class RhinoRuntimeError extends RhinoError { constructor(message: string) { super(message); this.name = "RhinoRuntimeError"; } } class RhinoActivationError extends RhinoError { constructor(message: string) { super(message); this.name = "RhinoActivationError"; } } class RhinoActivationLimitError extends RhinoError { constructor(message: string) { super(message); this.name = "RhinoActivationLimitError"; } } class RhinoActivationThrottledError extends RhinoError { constructor(message: string) { super(message); this.name = "RhinoActivationThrottledError"; } } class RhinoActivationRefusedError extends RhinoError { constructor(message: string) { super(message); this.name = "RhinoActivationRefusedError"; } } export { RhinoError, RhinoMemoryError, RhinoIOError, RhinoInvalidArgumentError, RhinoStopIterationError, RhinoKeyError, RhinoInvalidStateError, RhinoRuntimeError, RhinoActivationError, RhinoActivationLimitError, RhinoActivationThrottledError, RhinoActivationRefusedError };
hellow554/rhino
binding/react-native/src/index.tsx
// // Copyright 2020-2021 Picovoice Inc. // // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" // file accompanying this source. // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. // 'use strict'; import Rhino, { RhinoInference } from './rhino'; import RhinoManager, { InferenceCallback, ProcessErrorCallback } from './rhino_manager'; import * as RhinoErrors from './rhino_errors'; export { Rhino, RhinoInference, RhinoManager, InferenceCallback, ProcessErrorCallback, RhinoErrors };
hellow554/rhino
binding/vue/src/index.ts
<reponame>hellow554/rhino import rhinoMixin, { RhinoVue, RhinoWorkerFactoryArgs } from './rhino'; // Create module definition for Vue.use() const plugin = { install: function(Vue: any) { Vue.mixin(rhinoMixin); } }; // Auto-install when vue is found (eg. in browser via <script> tag) let GlobalVue = null; if (typeof window !== 'undefined') { // @ts-ignore GlobalVue = window.Vue; } else if (typeof global !== 'undefined') { // @ts-ignore GlobalVue = global.Vue; } if (GlobalVue) { GlobalVue.use(plugin); } // To allow use as module (npm/webpack/etc.) export component export default rhinoMixin; // export types export { RhinoWorkerFactoryArgs, RhinoVue };
hellow554/rhino
binding/web/template/src/rhino.ts
/* Copyright 2018-2022 Picovoice Inc. You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" file accompanying this source. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* eslint camelcase: 0 */ // @ts-ignore import { Mutex } from 'async-mutex'; import { RhinoInference, RhinoContext, RhinoEngine } from '@picovoice/rhino-web-core'; import { aligned_alloc_type, buildWasm, arrayBufferToStringAtIndex, base64ToUint8Array, isAccessKeyValid } from '@picovoice/web-utils'; // @ts-ignore import { RHINO_WASM_BASE64 } from './lang/rhino_b64'; const DEFAULT_SENSITIVITY = 0.5; const PV_STATUS_SUCCESS = 10000; /** * WebAssembly function types */ type pv_rhino_context_info_type = (object: number, contextInfo: number) => Promise<number>; type pv_rhino_delete_type = (object: number) => Promise<void>; type pv_rhino_frame_length_type = () => Promise<number>; type pv_rhino_free_slots_and_values_type = (object: number, slots: number, values: number) => Promise<number>; type pv_rhino_get_intent_type = (object: number, intent: number, numSlots: number, slots: number, values: number) => Promise<number>; type pv_rhino_init_type = ( accessKey: number, context: number, contextSize: number, sensitivity: number, requireEndpoint: boolean, object: number ) => Promise<number>; type pv_rhino_is_understood_type = (object: number, isUnderstood: number) => Promise<number>; type pv_rhino_process_type = (object: number, pcm: number, isFinalized: number) => Promise<number>; type pv_rhino_reset_type = (object: number) => Promise<number>; type pv_rhino_version_type = () => Promise<number>; type pv_status_to_string_type = (status: number) => Promise<number> type pv_sample_rate_type = () => Promise<number>; /** * JavaScript/WebAssembly Binding for the Picovoice Rhino Speech-to-Intent engine. * * It initializes the WebAssembly module and exposes an async factory method `create` for creating * new instances of the engine. * * The instances have JavaScript bindings that wrap the calls to the C library and * do some rudimentary type checking and parameter validation. */ type RhinoWasmOutput = { memory: WebAssembly.Memory; frameLength: number; sampleRate: number; version: string; contextInfo: string; objectAddress: number; inputBufferAddress: number; isFinalizedAddress: number; isUnderstoodAddress: number; intentAddressAddress: number; numSlotsAddress: number; slotsAddressAddressAddress: number; valuesAddressAddressAddress: number; pvRhinoDelete: pv_rhino_delete_type; pvRhinoFreeSlotsAndValues: pv_rhino_free_slots_and_values_type; pvRhinoGetIntent: pv_rhino_get_intent_type; pvRhinoIsUnderstood: pv_rhino_is_understood_type; pvRhinoProcess: pv_rhino_process_type; pvRhinoReset: pv_rhino_reset_type; pvStatusToString: pv_status_to_string_type; }; export class Rhino implements RhinoEngine { private _pvRhinoDelete: pv_rhino_delete_type; private _pvRhinoFreeSlotsAndValues: pv_rhino_free_slots_and_values_type; private _pvRhinoGetIntent: pv_rhino_get_intent_type; private _pvRhinoIsUnderstood: pv_rhino_is_understood_type; private _pvRhinoProcess: pv_rhino_process_type; private _pvRhinoReset: pv_rhino_reset_type; private _pvStatusToString: pv_status_to_string_type; private _wasmMemory: WebAssembly.Memory; private _memoryBuffer: Int16Array; private _memoryBufferUint8: Uint8Array; private _memoryBufferView: DataView; private _processMutex: Mutex; private _objectAddress: number; private _inputBufferAddress: number; private _isFinalizedAddress: number; private _isUnderstoodAddress: number; private _intentAddressAddress: number; private _numSlotsAddress: number; private _slotsAddressAddressAddress: number; private _valuesAddressAddressAddress: number; private static _frameLength: number; private static _sampleRate: number; private static _version: string; private static _contextInfo: string; private static _rhinoMutex = new Mutex; private constructor(handleWasm: RhinoWasmOutput) { Rhino._frameLength = handleWasm.frameLength; Rhino._sampleRate = handleWasm.sampleRate; Rhino._version = handleWasm.version; Rhino._contextInfo = handleWasm.contextInfo; this._pvRhinoDelete = handleWasm.pvRhinoDelete; this._pvRhinoFreeSlotsAndValues = handleWasm.pvRhinoFreeSlotsAndValues; this._pvRhinoGetIntent = handleWasm.pvRhinoGetIntent; this._pvRhinoIsUnderstood = handleWasm.pvRhinoIsUnderstood; this._pvRhinoProcess = handleWasm.pvRhinoProcess; this._pvRhinoReset = handleWasm.pvRhinoReset; this._pvStatusToString = handleWasm.pvStatusToString; this._wasmMemory = handleWasm.memory; this._memoryBuffer = new Int16Array(handleWasm.memory.buffer); this._memoryBufferUint8 = new Uint8Array(handleWasm.memory.buffer); this._memoryBufferView = new DataView(handleWasm.memory.buffer); this._objectAddress = handleWasm.objectAddress; this._inputBufferAddress = handleWasm.inputBufferAddress; this._isFinalizedAddress = handleWasm.isFinalizedAddress; this._isUnderstoodAddress = handleWasm.isUnderstoodAddress; this._intentAddressAddress = handleWasm.intentAddressAddress; this._numSlotsAddress = handleWasm.numSlotsAddress; this._slotsAddressAddressAddress = handleWasm.slotsAddressAddressAddress; this._valuesAddressAddressAddress = handleWasm.valuesAddressAddressAddress; this._processMutex = new Mutex(); } /** * Releases resources acquired by WebAssembly module. */ public async release(): Promise<void> { await this._pvRhinoDelete(this._objectAddress); } /** * Processes a frame of audio. * * @param pcm A frame of audio. The required sample rate can be retrieved from `.sampleRate` and the length * of frame (number of audio samples per frame) can be retrieved from `.frameLength`. The audio needs to be * 16-bit linearly-encoded. Furthermore, the engine operates on single-channel audio. * @returns the Rhino inference (`isFinalized` will always be present: when it's true the entire object will be populated) */ public async process(pcm: Int16Array): Promise<RhinoInference> { if (!(pcm instanceof Int16Array)) { throw new Error("The argument 'pcm' must be provided as an Int16Array"); } const returnPromise = new Promise<RhinoInference>((resolve, reject) => { this._processMutex.runExclusive(async () => { this._memoryBuffer.set( pcm, this._inputBufferAddress / Int16Array.BYTES_PER_ELEMENT ); let status = await this._pvRhinoProcess( this._objectAddress, this._inputBufferAddress, this._isFinalizedAddress ); if (status !== PV_STATUS_SUCCESS) { throw new Error( `'pv_rhino_process' failed with status ${arrayBufferToStringAtIndex( this._memoryBufferUint8, await this._pvStatusToString(status) )}` ); } const isFinalized = this._memoryBufferView.getUint8( this._isFinalizedAddress ); if (isFinalized === 1) { status = await this._pvRhinoIsUnderstood( this._objectAddress, this._isUnderstoodAddress ); if (status !== PV_STATUS_SUCCESS) { throw new Error( `'pv_rhino_is_understood' failed with status ${arrayBufferToStringAtIndex( this._memoryBufferUint8, await this._pvStatusToString(status) )}` ); } const isUnderstood = this._memoryBufferView.getUint8( this._isUnderstoodAddress ); if (isUnderstood === -1) { throw new Error('Rhino failed to process the command'); } let intent = null; const slots = {}; if (isUnderstood === 1) { status = await this._pvRhinoGetIntent( this._objectAddress, this._intentAddressAddress, this._numSlotsAddress, this._slotsAddressAddressAddress, this._valuesAddressAddressAddress, ); if (status !== PV_STATUS_SUCCESS) { throw new Error( `'pv_rhino_get_intent' failed with status ${arrayBufferToStringAtIndex( this._memoryBufferUint8, await this._pvStatusToString(status) )}` ); } const intentAddress = this._memoryBufferView.getInt32( this._intentAddressAddress, true ) intent = arrayBufferToStringAtIndex( this._memoryBufferUint8, intentAddress ); const numSlots = this._memoryBufferView.getInt32( this._numSlotsAddress, true ); if (numSlots === -1) { throw new Error('Rhino failed to get the number of slots'); } for (let i = 0; i < numSlots; i++) { const slot = await this._getSlot(i); if (!slot) { throw new Error('Rhino failed to get the slot'); } const value = await this._getSlotValue(i); if (!value) { throw new Error('Rhino failed to get the slot value'); } slots[slot] = value; } const slotsAddressAddress = this._memoryBufferView.getInt32( this._slotsAddressAddressAddress, true ); const valuesAddressAddress = this._memoryBufferView.getInt32( this._valuesAddressAddressAddress, true ); status = await this._pvRhinoFreeSlotsAndValues( this._objectAddress, slotsAddressAddress, valuesAddressAddress, ); if (status !== PV_STATUS_SUCCESS) { throw new Error( `'pv_rhino_free_slots_values' failed with status ${arrayBufferToStringAtIndex( this._memoryBufferUint8, await this._pvStatusToString(status) )}` ); } } status = await this._pvRhinoReset(this._objectAddress); if (status !== PV_STATUS_SUCCESS) { throw new Error( `'pv_rhino_process' failed with status ${arrayBufferToStringAtIndex( this._memoryBufferUint8, await this._pvStatusToString(status) )}` ); } return { isFinalized: true, isUnderstood: isUnderstood === 1, intent: intent, slots: slots, }; } else if (isFinalized === 0) { return { isFinalized: false, }; } else { throw new Error('Rhino failed to process audio'); } }).then((result: RhinoInference) => { resolve(result); }).catch((error: any) => { reject(error); }); }); return returnPromise; } private _getSlot(index: number): string { const slotsAddressAddress = this._memoryBufferView.getInt32( this._slotsAddressAddressAddress, true ); const slotAddress = this._memoryBufferView.getInt32( slotsAddressAddress + (index * Int32Array.BYTES_PER_ELEMENT), true ) const slot = arrayBufferToStringAtIndex( this._memoryBufferUint8, slotAddress ); return slot; } private _getSlotValue(index: number): string { const valuesAddressAddress = this._memoryBufferView.getInt32( this._valuesAddressAddressAddress, true ); const valueAddress = this._memoryBufferView.getInt32( valuesAddressAddress + (index * Int32Array.BYTES_PER_ELEMENT), true ) const slotValue = arrayBufferToStringAtIndex( this._memoryBufferUint8, valueAddress ); return slotValue; } get version(): string { return Rhino._version; } get sampleRate(): number { return Rhino._sampleRate; } get frameLength(): number { return Rhino._frameLength; } get contextInfo(): string { return Rhino._contextInfo; } /** * Creates an instance of the Rhino speech-to-intent engine. * Behind the scenes, it requires the WebAssembly code to load and initialize before * it can create an instance. * * @param accessKey - AccessKey obtained from Picovoice Console (https://picovoice.ai/console/). * @param contextInfo - Base64 representation of the context and it's sensitivity. * @param requireEndpoint - Boolean. If set to `true`, Rhino requires an endpoint (chunk of silence) before finishing inference. * * @returns An instance of the Rhino engine. */ public static async create( accessKey: string, contextInfo: RhinoContext, requireEndpoint?: boolean, ): Promise<Rhino> { if (!isAccessKeyValid(accessKey)) { throw new Error('Invalid AccessKey'); } const {base64, sensitivity} = contextInfo; if (sensitivity && !(typeof sensitivity === 'number')) { throw new Error('Rhino sensitivity is not a number (in the range [0,1])'); } else if (sensitivity && (sensitivity < 0 || sensitivity > 1)) { throw new Error('Rhino sensitivity is outside of range [0,1]'); } const returnPromise = new Promise<Rhino>((resolve, reject) => { Rhino._rhinoMutex.runExclusive(async () => { const wasmOutput = await Rhino.initWasm( accessKey, base64, sensitivity ?? 0.5, requireEndpoint ?? true ); return new Rhino(wasmOutput); }).then((result: Rhino) => { resolve(result); }).catch((error: any) => { reject(error); }); }); return returnPromise; } private static async initWasm( accessKey: string, context: string, sensitivity: number, requireEndpoint: boolean): Promise<any> { const memory = new WebAssembly.Memory({ initial: 1000, maximum: 2000 }); const memoryBufferUint8 = new Uint8Array(memory.buffer); const exports = await buildWasm(memory, RHINO_WASM_BASE64); const aligned_alloc = exports.aligned_alloc as aligned_alloc_type; const pv_rhino_context_info = exports.pv_rhino_context_info as pv_rhino_context_info_type; const pv_rhino_delete = exports.pv_rhino_delete as pv_rhino_delete_type; const pv_rhino_frame_length = exports.pv_rhino_frame_length as pv_rhino_frame_length_type; const pv_rhino_free_slots_and_values = exports.pv_rhino_free_slots_and_values as pv_rhino_free_slots_and_values_type; const pv_rhino_get_intent = exports.pv_rhino_get_intent as pv_rhino_get_intent_type; const pv_rhino_init = exports.pv_rhino_init as pv_rhino_init_type; const pv_rhino_is_understood = exports.pv_rhino_is_understood as pv_rhino_is_understood_type; const pv_rhino_process = exports.pv_rhino_process as pv_rhino_process_type; const pv_rhino_reset = exports.pv_rhino_reset as pv_rhino_reset_type; const pv_rhino_version = exports.pv_rhino_version as pv_rhino_version_type; const pv_sample_rate = exports.pv_sample_rate as pv_sample_rate_type; const pv_status_to_string = exports.pv_status_to_string as pv_status_to_string_type; const objectAddressAddress = await aligned_alloc( Int32Array.BYTES_PER_ELEMENT, Int32Array.BYTES_PER_ELEMENT ); if (objectAddressAddress === 0) { throw new Error('malloc failed: Cannot allocate memory'); } const accessKeyAddress = await aligned_alloc( Uint8Array.BYTES_PER_ELEMENT, (accessKey.length + 1) * Uint8Array.BYTES_PER_ELEMENT ); if (accessKeyAddress === 0) { throw new Error('malloc failed: Cannot allocate memory'); } for (let i = 0; i < accessKey.length; i++) { memoryBufferUint8[accessKeyAddress + i] = accessKey.charCodeAt(i); } memoryBufferUint8[accessKeyAddress + accessKey.length] = 0; const contextAddress = await aligned_alloc( Uint8Array.BYTES_PER_ELEMENT, (context.length) * Uint8Array.BYTES_PER_ELEMENT ) if (contextAddress === 0) { throw new Error('malloc failed: Cannot allocate memory'); } memoryBufferUint8.set( base64ToUint8Array(context), contextAddress / Uint8Array.BYTES_PER_ELEMENT ); let status = await pv_rhino_init( accessKeyAddress, contextAddress, context.length, sensitivity, requireEndpoint, objectAddressAddress); if (status !== PV_STATUS_SUCCESS) { throw new Error( `'pv_rhino_init' failed with status ${arrayBufferToStringAtIndex( memoryBufferUint8, await pv_status_to_string(status) )}` ); } const memoryBufferView = new DataView(memory.buffer); const objectAddress = memoryBufferView.getInt32( objectAddressAddress, true ); const sampleRate = await pv_sample_rate(); const frameLength = await pv_rhino_frame_length(); const versionAddress = await pv_rhino_version(); const version = arrayBufferToStringAtIndex( memoryBufferUint8, versionAddress ); const contextInfoAddressAddress = await aligned_alloc( Uint8Array.BYTES_PER_ELEMENT, Uint8Array.BYTES_PER_ELEMENT ) if (contextAddress === 0) { throw new Error('malloc failed: Cannot allocate memory'); } status = await pv_rhino_context_info( objectAddress, contextInfoAddressAddress ); if (status !== PV_STATUS_SUCCESS) { throw new Error( `'pv_rhino_context_info' failed with status ${arrayBufferToStringAtIndex( memoryBufferUint8, await pv_status_to_string(status) )}` ); } const contextInfoAddress = memoryBufferView.getInt32( contextInfoAddressAddress, true ); const contextInfo = arrayBufferToStringAtIndex( memoryBufferUint8, contextInfoAddress ); const inputBufferAddress = await aligned_alloc( Int16Array.BYTES_PER_ELEMENT, frameLength * Int16Array.BYTES_PER_ELEMENT ); if (inputBufferAddress === 0) { throw new Error('malloc failed: Cannot allocate memory'); } const isFinalizedAddress = await aligned_alloc( Uint8Array.BYTES_PER_ELEMENT, Uint8Array.BYTES_PER_ELEMENT, ) if (isFinalizedAddress === 0) { throw new Error('malloc failed: Cannot allocate memory'); } const isUnderstoodAddress = await aligned_alloc( Uint8Array.BYTES_PER_ELEMENT, Uint8Array.BYTES_PER_ELEMENT, ) if (isUnderstoodAddress === 0) { throw new Error('malloc failed: Cannot allocate memory'); } const intentAddressAddress = await aligned_alloc( Uint8Array.BYTES_PER_ELEMENT, Uint8Array.BYTES_PER_ELEMENT, ) if (intentAddressAddress === 0) { throw new Error('malloc failed: Cannot allocate memory'); } const numSlotsAddress = await aligned_alloc( Uint8Array.BYTES_PER_ELEMENT, Uint8Array.BYTES_PER_ELEMENT, ) if (numSlotsAddress === 0) { throw new Error('malloc failed: Cannot allocate memory'); } const slotsAddressAddressAddress = await aligned_alloc( Uint8Array.BYTES_PER_ELEMENT, Uint8Array.BYTES_PER_ELEMENT, ) if (slotsAddressAddressAddress === 0) { throw new Error('malloc failed: Cannot allocate memory'); } const valuesAddressAddressAddress = await aligned_alloc( Uint8Array.BYTES_PER_ELEMENT, Uint8Array.BYTES_PER_ELEMENT, ) if (valuesAddressAddressAddress === 0) { throw new Error('malloc failed: Cannot allocate memory'); } return { memory: memory, frameLength: frameLength, sampleRate: sampleRate, version: version, contextInfo: contextInfo, objectAddress: objectAddress, inputBufferAddress: inputBufferAddress, isFinalizedAddress: isFinalizedAddress, isUnderstoodAddress: isUnderstoodAddress, intentAddressAddress: intentAddressAddress, numSlotsAddress: numSlotsAddress, slotsAddressAddressAddress: slotsAddressAddressAddress, valuesAddressAddressAddress: valuesAddressAddressAddress, pvRhinoDelete: pv_rhino_delete, pvRhinoFreeSlotsAndValues: pv_rhino_free_slots_and_values, pvRhinoGetIntent: pv_rhino_get_intent, pvRhinoIsUnderstood: pv_rhino_is_understood, pvRhinoProcess: pv_rhino_process, pvRhinoReset: pv_rhino_reset, pvStatusToString: pv_status_to_string, }; } } export default Rhino;
hellow554/rhino
demo/angular/src/app/app.component.ts
<filename>demo/angular/src/app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'rhino-web-angular-demo-rhino'; show = true toggle() { this.show = !this.show } }
hellow554/rhino
binding/react-native/src/rhino_manager.tsx
<filename>binding/react-native/src/rhino_manager.tsx<gh_stars>100-1000 // // Copyright 2020 Picovoice Inc. // // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" // file accompanying this source. // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. // import { VoiceProcessor, BufferEmitter, } from '@picovoice/react-native-voice-processor'; import { EventSubscription, NativeEventEmitter } from 'react-native'; import Rhino, { RhinoInference } from './rhino'; import * as RhinoErrors from './rhino_errors'; export type InferenceCallback = (inference: RhinoInference) => void; export type ProcessErrorCallback = (error: RhinoErrors.RhinoError) => void; class RhinoManager { private _voiceProcessor: VoiceProcessor; private _rhino: Rhino | null; private _inferenceCallback: InferenceCallback; private _processErrorCallback?: ProcessErrorCallback; private _bufferListener?: EventSubscription; private _bufferEmitter: NativeEventEmitter; private _needsReset: boolean; /** * Creates an instance of the Rhino Manager. * @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/. * @param contextPath Absolute path to context file. * @param inferenceCallback A callback for when Rhino has made an intent inference * @param processErrorCallback Reports errors that are encountered while the engine is processing audio. * @param modelPath Path to the file containing model parameters. If not set it will be set to the default location. * @param sensitivity Inference sensitivity. A higher sensitivity value results in fewer misses at the cost of (potentially) increasing the erroneous inference rate. * Sensitivity should be a floating-point number within [0, 1]. * @param requireEndpoint If true, Rhino requires an endpoint (chunk of silence) before finishing inference. * @returns An instance of the Rhino Manager */ public static async create( accessKey: string, contextPath: string, inferenceCallback: InferenceCallback, processErrorCallback?: ProcessErrorCallback, modelPath?: string, sensitivity: number = 0.5, requireEndpoint: boolean = true ) { let rhino = await Rhino.create(accessKey, contextPath, modelPath, sensitivity, requireEndpoint); return new RhinoManager(rhino, inferenceCallback, processErrorCallback); } private constructor(rhino: Rhino, inferenceCallback: InferenceCallback, processErrorCallback?: ProcessErrorCallback) { this._inferenceCallback = inferenceCallback; this._processErrorCallback = processErrorCallback; this._rhino = rhino; this._voiceProcessor = VoiceProcessor.getVoiceProcessor( rhino.frameLength, rhino.sampleRate ); this._bufferEmitter = new NativeEventEmitter(BufferEmitter); this._needsReset = false; if (typeof inferenceCallback !== 'function') { throw new RhinoErrors.RhinoInvalidArgumentError("'inferenceCallback' must be a function type"); } // function that's executed every time an audio buffer is received const processBuffer = async (buffer: number[]) => { try { if (this._rhino === null) return; // don't process if we've already already received a result if (this._needsReset) return; let inference = await this._rhino.process(buffer); // throw out result if we've already received one if (this._needsReset) return; if (inference.isFinalized) { // send out result and stop audio this._inferenceCallback(inference); await this._voiceProcessor.stop(); this._needsReset = false; } } catch (e) { if (this._processErrorCallback !== undefined && this._processErrorCallback !== null && typeof this._processErrorCallback === 'function') { this._processErrorCallback(e as RhinoErrors.RhinoError); } else { console.error(e); } } }; this._bufferListener = this._bufferEmitter.addListener( BufferEmitter.BUFFER_EMITTER_KEY, async (buffer: number[]) => { await processBuffer(buffer); } ); } /** * Opens audio input stream and sends audio frames to Rhino */ async process() { return await this._voiceProcessor.start(); } /** * Releases resources and listeners */ delete() { this._bufferListener?.remove(); if (this._rhino != null) { this._rhino.delete(); this._rhino = null; } } } export default RhinoManager;
hellow554/rhino
binding/angular/projects/rhino-web-angular/src/public-api.ts
<filename>binding/angular/projects/rhino-web-angular/src/public-api.ts<gh_stars>100-1000 /* * Public API Surface of rhino-web-angular */ export * from './lib/rhino.service';
hellow554/rhino
demo/react-native/App.tsx
import React, { Component } from 'react'; import { PermissionsAndroid, Platform, TouchableOpacity } from 'react-native'; import { StyleSheet, Text, View } from 'react-native'; import { RhinoManager, RhinoInference, RhinoErrors } from '@picovoice/rhino-react-native'; type Props = {}; type State = { buttonText: string; buttonDisabled: boolean; rhinoText: string; isListening: boolean; isError: boolean; errorMessage: string; }; export default class App extends Component<Props, State> { readonly _accessKey: string = "${YOUR_ACCESS_KEY_HERE}" // AccessKey obtained from Picovoice Console (https://picovoice.ai/console/) _rhinoManager: RhinoManager | undefined; constructor(props: Props) { super(props); this.state = { buttonText: 'Start', buttonDisabled: false, rhinoText: '', isListening: false, isError: false, errorMessage: '' }; } async componentDidMount() { let contextPath = `smart_lighting_${Platform.OS}.rhn`; // load context try{ this._rhinoManager = await RhinoManager.create( this._accessKey, contextPath, this.inferenceCallback.bind(this), (error) => { this.errorCallback(error.message); }); } catch(err) { let errorMessage = ''; if (err instanceof RhinoErrors.RhinoInvalidArgumentError) { errorMessage = `${err.message}\nPlease make sure your accessKey '${this._accessKey}'' is a valid access key.`; } else if (err instanceof RhinoErrors.RhinoActivationError) { errorMessage = "AccessKey activation error"; } else if (err instanceof RhinoErrors.RhinoActivationLimitError) { errorMessage = "AccessKey reached its device limit"; } else if (err instanceof RhinoErrors.RhinoActivationRefusedError) { errorMessage = "AccessKey refused"; } else if (err instanceof RhinoErrors.RhinoActivationThrottledError) { errorMessage = "AccessKey has been throttled"; } else { errorMessage = err.toString(); } this.errorCallback(errorMessage); } } inferenceCallback(inference: RhinoInference) { this.setState({ rhinoText: this.prettyPrint(inference), buttonText: 'Start', buttonDisabled: false, isListening: false, }); } errorCallback(error: string) { this.setState({ isError: true, errorMessage: error }); } prettyPrint(inference: RhinoInference): string { let printText = `{\n "isUnderstood" : "${inference.isUnderstood}",\n`; if (inference.isUnderstood) { printText += ` "intent" : "${inference.intent}",\n`; if (Object.entries(inference.slots).length > 0) { printText += ' "slots" : {\n';1 for (let [key, slot] of Object.entries(inference.slots)) { printText += ` "${key}" : "${slot}",\n`; } printText += ' }\n'; } } printText += '}'; return printText; } componentWillUnmount() { this._rhinoManager?.delete(); } async _startProcessing() { if(this.state.isListening){ return; } this.setState({ buttonDisabled: true }); let recordAudioRequest; if (Platform.OS == 'android') { recordAudioRequest = this._requestRecordAudioPermission(); } else { recordAudioRequest = new Promise(function (resolve, _) { resolve(true); }); } recordAudioRequest.then((hasPermission) => { if (!hasPermission) { console.error("Required microphone permission was not granted.") return; } this._rhinoManager.process().then((didStart)=>{ if(didStart){ this.setState({ buttonText: '...', rhinoText: '', buttonDisabled: false, isListening: true, }); } }); }); } async _requestRecordAudioPermission() { try { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, { title: 'Microphone Permission', message: 'Rhino needs access to your microphone to make intent inferences.', buttonNeutral: 'Ask Me Later', buttonNegative: 'Cancel', buttonPositive: 'OK', } ); return (granted === PermissionsAndroid.RESULTS.GRANTED) } catch (err) { this.errorCallback(err.toString()); return false; } } render() { return ( <View style={[ styles.container, ]} > <View style={styles.statusBar}> <Text style={styles.statusBarText}>Rhino</Text> </View> <View style={{flex:0.35, justifyContent:'center', alignContent:'center'}}> <TouchableOpacity style={{ width:'50%', height:'50%', alignSelf:'center', justifyContent:'center', backgroundColor: this.state.isError ? '#cccccc' : '#377DFF', borderRadius: 100, }} onPress={() => this._startProcessing()} disabled={this.state.buttonDisabled || this.state.isError} > <Text style={styles.buttonText}>{this.state.buttonText}</Text> </TouchableOpacity> </View> <View style={{flex:1, padding:20, }}> <View style={{flex:1, flexDirection:'row', justifyContent:'center', padding:30, backgroundColor:'#25187E'}}> <Text style={styles.rhinoText}> {this.state.rhinoText} </Text> </View> </View> {this.state.isError && <View style={styles.errorBox}> <Text style={{ color: 'white', fontSize: 16 }}> {this.state.errorMessage} </Text> </View> } <View style={{ flex: 0.08, justifyContent: 'flex-end', paddingBottom:25}}> <Text style={styles.instructions}> Made in Vancouver, Canada by Picovoice </Text> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', justifyContent: 'center', backgroundColor: '#F5FCFF', }, subContainer: { flex: 1, justifyContent: 'center', }, statusBar: { flex: 0.20, backgroundColor: '#377DFF', justifyContent: 'flex-end' }, statusBarText: { fontSize: 18, color: 'white', fontWeight: 'bold', marginLeft: 15, marginBottom: 10, }, buttonStyle: { backgroundColor: '#377DFF', borderRadius: 100, }, buttonText: { fontSize: 30, fontWeight: 'bold', color: 'white', textAlign: 'center', }, rhinoText: { flex:1, flexWrap:'wrap', color: 'white', fontSize: 20, }, itemStyle: { fontWeight: 'bold', fontSize: 20, textAlign: 'center', }, instructions: { textAlign: 'center', color: '#666666' }, errorBox: { backgroundColor: 'red', borderRadius: 5, margin: 20, padding: 20, textAlign: 'center' }, });
hellow554/rhino
binding/react-native/src/rhino.tsx
<gh_stars>100-1000 // // Copyright 2020-2021 Picovoice Inc. // // You may not use this file except in compliance with the license. A copy of the license is located in the "LICENSE" // file accompanying this source. // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. // import { NativeModules } from 'react-native'; import * as RhinoErrors from './rhino_errors'; export class RhinoInference { private _isFinalized: boolean; private _isUnderstood?: boolean; private _intent?: string; private _slots?: {[key: string]: string}; public constructor(isFinalized: boolean, isUnderstood?: boolean, intent?: string, slots?: {[key: string]: string}) { this._isFinalized = isFinalized; this._isUnderstood = isUnderstood; this._intent = intent; this._slots = slots; } /** * whether Rhino has made an inference */ get isFinalized() { return this._isFinalized; } /** * if isFinalized, whether Rhino understood what it heard based on the context */ get isUnderstood() { return this._isUnderstood; } /** * if isUnderstood, name of intent that was inferred */ get intent() { return this._intent; } /** * if isUnderstood, dictionary of slot keys and values that were inferred */ get slots() { return this._slots; } } type NativeError = { code: string; message: string; } const RCTRhino = NativeModules.PvRhino; class Rhino { private _handle: string; private _frameLength: number; private _sampleRate: number; private _version: string; private _contextInfo: string; /** * Creates an instance of the Rhino Speech-to-Intent engine. * @param accessKey AccessKey obtained from Picovoice Console (https://console.picovoice.ai/. * @param contextPath Absolute path to context file. * @param modelPath Path to the file containing model parameters. If not set it will be set to the default location. * @param sensitivity Inference sensitivity. A higher sensitivity value results in fewer misses at the cost of (potentially) increasing the erroneous inference rate. * Sensitivity should be a floating-point number within [0, 1]. * @param requireEndpoint If true, Rhino requires an endpoint (chunk of silence) before finishing inference. * @returns An instance of the engine. */ public static async create( accessKey: string, contextPath: string, modelPath?: string, sensitivity: number = 0.5, requireEndpoint: boolean = true ): Promise<Rhino> { try { let { handle, frameLength, sampleRate, version, contextInfo, } = await RCTRhino.create(accessKey, modelPath, contextPath, sensitivity, requireEndpoint); return new Rhino(handle, frameLength, sampleRate, version, contextInfo); } catch (err) { if (err instanceof RhinoErrors.RhinoError) { throw err; } else { const nativeError = err as NativeError; throw this.codeToError(nativeError.code, nativeError.message); } } } private constructor( handle: string, frameLength: number, sampleRate: number, version: string, contextInfo: string ) { this._handle = handle; this._frameLength = frameLength; this._sampleRate = sampleRate; this._version = version; this._contextInfo = contextInfo; } /** * Process a frame of pcm audio with the speech-to-intent engine. * @param frame frame 16-bit integers of 16kHz linear PCM mono audio. * The specific array length is obtained from Rhino via the frameLength field. * @returns {RhinoInference} inference result at time of frame being processed with fields: * - isFinalized: whether Rhino has made an inference * - isUnderstood: if isFinalized, whether Rhino understood what it heard based on the context * - intent: if isUnderstood, name of intent that were inferred * - slots: if isUnderstood, dictionary of slot keys and values that were inferred */ async process(frame: number[]): Promise<RhinoInference> { if (frame === undefined || frame === null) { throw new RhinoErrors.RhinoInvalidArgumentError( `Frame array provided to process() is undefined or null` ); } else if (frame.length !== this._frameLength) { throw new RhinoErrors.RhinoInvalidArgumentError( `Size of frame array provided to 'process' (${frame.length}) does not match the engine 'frameLength' (${this._frameLength})` ); } // sample the first frame to check for non-integer values if (!Number.isInteger(frame[0])) { throw new RhinoErrors.RhinoInvalidArgumentError( `Non-integer frame values provided to process(): ${frame[0]}. Rhino requires 16-bit integers` ); } try { const { isFinalized, isUnderstood, intent, slots } = await RCTRhino.process(this._handle, frame); return new RhinoInference(isFinalized, isUnderstood, intent, slots); } catch (err) { const nativeError = err as NativeError; throw Rhino.codeToError(nativeError.code, nativeError.message); } } /** * Frees memory that was allocated for Rhino */ async delete() { return RCTRhino.delete(this._handle); } /** * Gets the source of the Rhino context in YAML format. Shows the list of intents, * which expressions map to those intents, as well as slots and their possible values. * @returns The context YAML */ get contextInfo() { return this._contextInfo; } /** * Gets the required number of audio samples per frame. * @returns Required frame length. */ get frameLength() { return this._frameLength; } /** * Get the audio sample rate required by Rhino. * @returns Required sample rate. */ get sampleRate() { return this._sampleRate; } /** * Gets the version number of the Rhino library. * @returns Version of Rhino */ get version() { return this._version; } /** * Gets the Error type given a code. * @param code Code name of native Error. * @param message Detailed message of the error. */ private static codeToError(code: string, message: string){ switch(code) { case 'RhinoException': return new RhinoErrors.RhinoError(message); case 'RhinoMemoryException': return new RhinoErrors.RhinoMemoryError(message); case 'RhinoIOException': return new RhinoErrors.RhinoIOError(message); case 'RhinoInvalidArgumentException': return new RhinoErrors.RhinoInvalidArgumentError(message); case 'RhinoStopIterationException': return new RhinoErrors.RhinoStopIterationError(message); case 'RhinoKeyException': return new RhinoErrors.RhinoKeyError(message); case 'RhinoInvalidStateException': return new RhinoErrors.RhinoInvalidStateError(message); case 'RhinoRuntimeException': return new RhinoErrors.RhinoRuntimeError(message); case 'RhinoActivationException': return new RhinoErrors.RhinoActivationError(message); case 'RhinoActivationLimitException': return new RhinoErrors.RhinoActivationLimitError(message); case 'RhinoActivationThrottledException': return new RhinoErrors.RhinoActivationThrottledError(message); case 'RhinoActivationRefusedException': return new RhinoErrors.RhinoActivationRefusedError(message); default: throw new RhinoErrors.RhinoError(`unexpected code: ${code}, message: ${message}`); } } } export default Rhino;
nepoche/webb.js
packages/api-providers/src/contracts/utils/merkle/storage.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export class Storage<T = Record<string, unknown>> { private db: T = {} as T; get<K extends keyof T> (key: K): T[K] | undefined { return this.db[key]; } getOrDefault<K extends keyof T> (key: K, defaultElement: T[K]) { return this.db[key] ?? defaultElement; } put<K extends keyof T> (key: K, value: T[K]) { this.db[key] = value; } del<K extends keyof T> (key: K) { delete this.db[key]; } putBatch (keyValues: Partial<T>[]) { keyValues.forEach((element: any) => { // @ts-ignore this.db[element.key] = element.value; }); } }
nepoche/webb.js
packages/api-providers/src/contracts/utils/buffer-to-fixed.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 // @ts-ignore import * as snarkjs from 'tornado-snarkjs'; const { bigInt } = snarkjs; export const bufferToFixed = (number: Buffer | any, length = 32) => { return ( '0x' + (number instanceof Buffer ? number.toString('hex') : bigInt(number).toString(16)).padStart(length * 2, '0') ); };
nepoche/webb.js
packages/app-util/src/__test__/event-bus.class.spec.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { expect } from 'chai'; import { EventBus } from '../shared/event-bus.class.js'; class TestEvent extends EventBus<{ log: number }> { override readonly sendEvent: EventBus<{ log: number }>['emit']; constructor () { super(); this.sendEvent = this.emit; } } describe('event emitting', () => { const testEvent = new TestEvent(); it('event should be emitted', async () => { let a = 0; const unsubscribe = testEvent.on('log', () => { a = a + 1; }); expect(a).to.deep.equal(0); testEvent.sendEvent('log', 5); await 0; expect(a).to.deep.equal(1); if (unsubscribe) { unsubscribe(); } }); it('event value should be 5', () => { let a: number | null = null; testEvent.on('log', (value) => { a = value; }); testEvent.sendEvent('log', 5); setTimeout(() => { expect(a).to.deep.equal(5); }, 1); }); }); describe('Subscriptions', () => { it('should unsubscribe', () => { const testEvent = new TestEvent(); let a = 0; const unsubscribe = testEvent.on('log', () => { a = a + 1; }); expect(a).to.deep.equal(0); testEvent.sendEvent('log', 5); if (unsubscribe) { unsubscribe(); } setTimeout(() => { expect(a).to.deep.equal(1); }, 1); }); it('Once will trigger only one time', () => { const testEvent = new TestEvent(); let a = 0; testEvent.once('log', (log) => { a = log; }); testEvent.sendEvent('log', 1); testEvent.sendEvent('log', 2); expect(a).to.deep.equal(1); }); it('Unsubscribe all', () => { const testEvent = new TestEvent(); let a = 0; testEvent.on('log', (log) => { a = log; }); testEvent.unsubscribeAll(); testEvent.sendEvent('log', 1); testEvent.sendEvent('log', 2); expect(a).to.deep.equal(0); }); });
nepoche/webb.js
packages/api-providers/src/contracts/wrappers/webb-governed-token.ts
<filename>packages/api-providers/src/contracts/wrappers/webb-governed-token.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable camelcase */ import { LoggerService } from '@nepoche/app-util/index.js'; import { GovernedTokenWrapper, GovernedTokenWrapper__factory } from '@nepoche/contracts'; import { BigNumberish, Contract, PayableOverrides, providers, Signer } from 'ethers'; import { zeroAddress } from './webb-utils.js'; const logger = LoggerService.get('WebbGovernedToken'); function checkNativeAddress (tokenAddress: string): boolean { if (tokenAddress === zeroAddress || tokenAddress === '0') { return true; } return false; } export class WebbGovernedToken { private _contract: GovernedTokenWrapper; private readonly signer: Signer; constructor (private web3Provider: providers.Web3Provider, address: string) { this.signer = this.web3Provider.getSigner(); logger.info(`Init with address ${address} `); this._contract = new Contract(address, GovernedTokenWrapper__factory.abi, this.signer) as any; } get address () { return this._contract.address; } get tokens () { return this._contract.getTokens(); } async getInfo () { const [symbol, name] = await Promise.all([this._contract.symbol(), this._contract.name()]); return { name, symbol }; } getBalanceOf (account: string) { return this._contract.balanceOf(account); } /// todo assume native async wrap (address: string, amount: BigNumberish) { const isNative = checkNativeAddress(address); const amountParam = isNative ? 0 : amount; const overrides: PayableOverrides = { gasLimit: 6000000 }; if (isNative) { overrides.value = amount; } logger.info(`Wrapping ${isNative ? 'native' : `non-native (${address})`} amount ${amount.toString()}`); return this._contract.wrap(address, amountParam, overrides); } async unwrap (address: string, amount: BigNumberish) { const overrides: PayableOverrides = { gasLimit: 6000000 }; logger.info( `Unwrapping ${checkNativeAddress(address) ? 'native' : `non-native (${address})`} amount ${amount.toString()}` ); return this._contract.unwrap(address, amount, overrides); } get currentLiquidity () { return this._contract.totalSupply(); } get contractBalance () { return this.web3Provider.getBalance(this._contract.address); } async canUnwrap (account: string, amount: BigNumberish) { const [currentWrappedLiquidity] = await Promise.all([ this.currentLiquidity, this.web3Provider.getBalance(this._contract.address) ]); if (currentWrappedLiquidity.lt(amount) || currentWrappedLiquidity.lt(amount)) { // no enough liquidity return false; } const userBalance = await this._contract.balanceOf(account); if (userBalance.gte(amount)) return true; return false; } async isNativeAllowed () { const nativeAllowed = await this._contract.isNativeAllowed(); return nativeAllowed; } // Checks if the governed token wraps a particular token. // Does NOT check if allowances for ERC20s are satisfied. async canWrap (tokenAddress: string) { const tokens = await this._contract.getTokens(); if (tokens.includes(tokenAddress)) { return true; } if (tokenAddress === zeroAddress) { return this.isNativeAllowed(); } return false; } }
nepoche/webb.js
packages/api-providers/src/utils/misc/app-mode.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { LoggerService } from '@nepoche/app-util/index.js'; export type AppMode = 'development' | 'production'; const appLogger = LoggerService.get('App'); export function appMode (): AppMode { // @ts-ignore return process.env.NODE_ENV; } export function isProduction () { return !isDevelopment(); } export function isDevelopment () { return appMode() === 'development'; } export function isLocalFixtures () { return process.env.LOCAL_FIXTURES === 'true'; } export function withLocalFixtures () { const dev = isDevelopment(); appLogger.info('local fixtures react app env: ', process.env.LOCAL_FIXTURES); appLogger.info('isDevelopment? ', dev); return dev && isLocalFixtures(); }
nepoche/webb.js
packages/api-providers/src/abstracts/anchor/anchor.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { InternalChainId } from '../../chains/index.js'; import { WebbCurrencyId } from '../../enums/index.js'; import { BridgeConfig } from '../../types/bridge-config.interface.js'; import { CurrencyRole } from '../../types/currency-config.interface.js'; import { AppConfig } from '../common.js'; import { Currency } from '../currency/currency.js'; export class Bridge { private constructor (private bridgeConfig: BridgeConfig, private readonly appConfig: AppConfig) {} static from (bridgeCurrency: WebbCurrencyId, appConfig: AppConfig): Bridge { console.log('WebbCurrencyId in Bridge static constructor: ', bridgeCurrency); const bridgeConfig = appConfig.bridgeByAsset[bridgeCurrency]; return new Bridge(bridgeConfig, appConfig); } /* * Get the bridge privy pools * */ get anchors () { return this.bridgeConfig.anchors; } /* * Get the bridge currency * */ get currency () { return Currency.fromCurrencyId(this.appConfig.currencies, this.bridgeConfig.asset); } getTokenAddress (chainId: InternalChainId) { return this.appConfig.currencies[this.bridgeConfig.asset].addresses.get(chainId); } /* * Get all Bridge tokens * */ static getTokens (currenciesConfig: AppConfig['currencies']): Currency[] { const bridgeCurrenciesConfig = Object.values(currenciesConfig).filter((i) => i.role === CurrencyRole.Governable); return bridgeCurrenciesConfig.map((config) => { return Currency.fromCurrencyId(currenciesConfig, config.id); }); } /* * Get all Bridge tokens for a given chain * */ static getTokensOfChain (currenciesConfig: AppConfig['currencies'], chainId: InternalChainId): Currency[] { const tokens = Bridge.getTokens(currenciesConfig); return tokens.filter((token) => token.hasChain(chainId)); } }
nepoche/webb.js
packages/api-providers/src/abstracts/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './anchor/index.js'; export * from './chain-query/index.js'; export * from './currency/index.js'; export * from './common.js'; export * from './mixer/index.js'; export * from './networks-storage.js'; export * from './relayer/index.js'; export * from './webb-content-state.interface.js'; export * from './webb-provider.interface.js'; export * from './wrap-unwrap/index.js';
nepoche/webb.js
packages/api-providers/src/utils/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './anchor-utils.js'; export * from './chain-utils.js'; export * from './fixtures.js'; export * from './relayer-utils.js'; export * from './retry-promise.js'; export * from './storage-mock.js'; export * from './misc/index.js';
nepoche/webb.js
packages/api-providers/src/polkadot/mixer-deposit.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable @typescript-eslint/ban-ts-comment */ import { Currency, DepositPayload as TDepositPayload, MixerSize, ORMLCurrency } from '@nepoche/api-providers/index.js'; import { LoggerService } from '@nepoche/app-util/index.js'; import { Note, NoteGenInput } from '@nepoche/sdk-core/index.js'; import { PalletMixerMixerMetadata } from '@nepoche/types/interfaces/pallets/index.js'; import { u8aToHex } from '@polkadot/util'; import { MixerDeposit } from '../abstracts/index.js'; import { ChainType, computeChainIdType, internalChainIdToChainId } from '../chains/index.js'; import { WebbError, WebbErrorCodes } from '../webb-error/index.js'; import { WebbPolkadot } from './webb-provider.js'; type DepositPayload = TDepositPayload<Note, [number, string]>; const logger = LoggerService.get('tornado-deposit'); export class PolkadotMixerDeposit extends MixerDeposit<WebbPolkadot, DepositPayload> { constructor (protected inner: WebbPolkadot) { super(inner); } static async getSizes (webbPolkadot: WebbPolkadot): Promise<MixerSize[]> { const api = webbPolkadot.api; const ormlCurrency = new ORMLCurrency(webbPolkadot); const ormlAssets = await ormlCurrency.list(); const data = await api.query.mixerBn254.mixers.entries(); // @ts-ignore // const tokenProperty: Array<NativeTokenProperties> = await api.rpc.system.properties(); const groupItem = data .map(([storageKey, info]) => { const mixerInfo = (info as unknown as PalletMixerMixerMetadata).toHuman(); const cId = Number(mixerInfo.asset); const amount = mixerInfo.depositSize; // @ts-ignore const treeId = storageKey.toHuman()[0]; const id = storageKey.toString() + treeId; console.log('id in getSizes: ', id); // parse number from amount string // TODO: Get and parse native / non-native token denomination // TODO replace `replaceAll` or target es2021 // @ts-ignore const amountNumber = (Number(amount?.toString().replaceAll(',', '')) * 1.0) / Math.pow(10, 12); const currency = cId ? Currency.fromORMLAsset( webbPolkadot.config.currencies, ormlAssets.find((asset) => Number(asset.id) === cId)! ) : Currency.fromCurrencyId(webbPolkadot.config.currencies, Number(cId)); return { amount: amountNumber, currency: currency, id, treeId }; }) .map( ({ amount, currency, treeId }) => ({ amount: amount, asset: currency.view.symbol, id: treeId, title: amount + ` ${currency.view.symbol}`, treeId, value: amount } as MixerSize) ) .sort((a, b) => (a.amount > b.amount ? 1 : a.amount < b.amount ? -1 : 0)); return groupItem; } async getSizes () { return PolkadotMixerDeposit.getSizes(this.inner); } async generateNote (mixerId: number, chainId: number): Promise<DepositPayload> { logger.info(`Depositing to mixer id ${mixerId}`); const chainIdType = computeChainIdType(ChainType.Substrate, internalChainIdToChainId(ChainType.Substrate, chainId)); const sizes = await this.getSizes(); const amount = sizes.find((size) => Number(size.id) === mixerId); const properties = await this.inner.api.rpc.system.properties(); const denomination = properties.tokenDecimals.toHuman() || 12; if (!amount) { throw Error('amount not found! for mixer id ' + mixerId); } const treeId = amount.id; logger.info(`Depositing to tree id ${treeId}`); const noteInput: NoteGenInput = { amount: String(amount.amount), backend: 'Arkworks', curve: 'Bn254', denomination: `${denomination}`, exponentiation: '5', hashFunction: 'Poseidon', protocol: 'mixer', sourceChain: chainIdType.toString(), sourceIdentifyingData: treeId.toString(), targetChain: chainIdType.toString(), targetIdentifyingData: treeId.toString(), tokenSymbol: amount.asset, version: 'v2', width: '3' }; logger.info('noteInput in generateNote: ', noteInput); const depositNote = await Note.generateNote(noteInput); logger.info('generated Note from input: ', depositNote.note); const leaf = depositNote.getLeaf(); return { note: depositNote, params: [Number(treeId), u8aToHex(leaf)] }; } async deposit (depositPayload: DepositPayload): Promise<void> { const tx = this.inner.txBuilder.build( { method: 'deposit', section: 'mixerBn254' }, depositPayload.params ); const account = await this.inner.accounts.activeOrDefault; if (!account) { throw WebbError.from(WebbErrorCodes.NoAccountAvailable); } tx.on('finalize', () => { console.log('deposit done'); }); tx.on('failed', (e: any) => { console.log('deposit failed', e); }); tx.on('extrinsicSuccess', () => { console.log('deposit done'); }); await tx.call(account.address); } }
nepoche/webb.js
packages/api-providers/src/polkadot/webb-provider.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { ApiInitHandler, AppConfig, NotificationHandler, ProvideCapabilities, WasmFactory, WebbApiProvider, WebbMethods, WebbProviderEvents, WebbRelayerBuilder } from '@nepoche/api-providers/index.js'; import { EventBus } from '@nepoche/app-util/index.js'; import { ApiPromise } from '@polkadot/api'; import { InjectedAccount, InjectedExtension } from '@polkadot/extension-inject/types'; import { AccountsAdapter } from '../account/Accounts.adapter.js'; import { PolkadotProvider } from '../ext-providers/index.js'; import { ActionsBuilder, InteractiveFeedback, WebbError, WebbErrorCodes } from '../webb-error/index.js'; import { PolkadotAnchorApi } from './anchor-api.js'; import { PolkadotBridgeDeposit } from './anchor-deposit.js'; import { PolkadotAnchorWithdraw } from './anchor-withdraw.js'; import { PolkadotChainQuery } from './chain-query.js'; import { PolkadotMixerDeposit } from './mixer-deposit.js'; import { PolkadotMixerWithdraw } from './mixer-withdraw.js'; import { PolkaTXBuilder } from './transaction.js'; import { PolkadotWrapUnwrap } from './wrap-unwrap.js'; export class WebbPolkadot extends EventBus<WebbProviderEvents> implements WebbApiProvider<WebbPolkadot> { readonly methods: WebbMethods<WebbPolkadot>; readonly api: ApiPromise; readonly txBuilder: PolkaTXBuilder; private constructor ( apiPromise: ApiPromise, injectedExtension: InjectedExtension, readonly relayingManager: WebbRelayerBuilder, public readonly config: AppConfig, readonly notificationHandler: NotificationHandler, private readonly provider: PolkadotProvider, readonly accounts: AccountsAdapter<InjectedExtension, InjectedAccount>, readonly wasmFactory: WasmFactory ) { super(); this.provider = new PolkadotProvider( apiPromise, injectedExtension, new PolkaTXBuilder(apiPromise, notificationHandler) ); this.accounts = this.provider.accounts; this.api = this.provider.api; this.txBuilder = this.provider.txBuilder; this.methods = { anchor: { core: null, deposit: { enabled: true, inner: new PolkadotBridgeDeposit(this) }, withdraw: { enabled: true, inner: new PolkadotAnchorWithdraw(this) } }, anchorApi: new PolkadotAnchorApi(this, this.config.bridgeByAsset), chainQuery: new PolkadotChainQuery(this), mixer: { deposit: { enabled: true, inner: new PolkadotMixerDeposit(this) }, withdraw: { enabled: true, inner: new PolkadotMixerWithdraw(this) } }, wrapUnwrap: { core: { enabled: false, inner: new PolkadotWrapUnwrap(this) } } }; } capabilities?: ProvideCapabilities | undefined; getProvider () { return this.provider; } async awaitMetaDataCheck () { /// delay some time till the UI is instantiated and then check if the dApp needs to update extension meta data await new Promise((resolve) => setTimeout(resolve, 3000)); const metaData = await this.provider.checkMetaDataUpdate(); if (metaData) { /// feedback body const feedbackEntries = InteractiveFeedback.feedbackEntries([ { header: 'Update Polkadot MetaData' } ]); /// feedback actions const actions = ActionsBuilder.init() /// update extension metadata .action('Update MetaData', () => this.provider.updateMetaData(metaData), 'success') .actions(); const feedback = new InteractiveFeedback( 'info', actions, () => { return null; }, feedbackEntries ); /// emit the feedback object this.emit('interactiveFeedback', feedback); } } private async insureApiInterface () { // check for RPC console.log(this.api, 'api'); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const merkleRPC = Boolean(this.api.rpc.mt.getLeaves); // merkle rpc const merklePallet = this.api.query.merkleTreeBn254; const mixerPallet = this.api.query.mixerBn254; if (!merklePallet || !merkleRPC || !mixerPallet) { throw WebbError.from(WebbErrorCodes.InsufficientProviderInterface); } } static async init ( appName: string, // App name Arbitrary name endpoints: string[], // Endpoints of the substrate node errorHandler: ApiInitHandler, // Error handler that will be used to catch errors while initializing the provider relayerBuilder: WebbRelayerBuilder, // Webb Relayer builder for relaying withdraw appConfig: AppConfig, // The whole and current app configuration notification: NotificationHandler, // Notification handler that will be used for the provider wasmFactory: WasmFactory // A Factory Fn that wil return wasm worker that would be supplied eventually to the `sdk-core` ): Promise<WebbPolkadot> { const [apiPromise, injectedExtension] = await PolkadotProvider.getParams(appName, endpoints, errorHandler.onError); const provider = new PolkadotProvider(apiPromise, injectedExtension, new PolkaTXBuilder(apiPromise, notification)); const accounts = provider.accounts; const instance = new WebbPolkadot( apiPromise, injectedExtension, relayerBuilder, appConfig, notification, provider, accounts, wasmFactory ); await instance.insureApiInterface(); /// check metadata update await instance.awaitMetaDataCheck(); await apiPromise.isReady; return instance; } static async initWithCustomAccountsAdapter ( appName: string, // App name Arbitrary name endpoints: string[], // Endpoints of the substrate node errorHandler: ApiInitHandler, // Error handler that will be used to catch errors while initializing the provider relayerBuilder: WebbRelayerBuilder, // Webb Relayer builder for relaying withdraw appConfig: AppConfig, // The whole and current app configuration notification: NotificationHandler, // Notification handler that will be used for the provider accounts: AccountsAdapter<InjectedExtension, InjectedAccount>, apiPromise: ApiPromise, injectedExtension: InjectedExtension, wasmFactory: WasmFactory ): Promise<WebbPolkadot> { const provider = new PolkadotProvider(apiPromise, injectedExtension, new PolkaTXBuilder(apiPromise, notification)); const instance = new WebbPolkadot( apiPromise, injectedExtension, relayerBuilder, appConfig, notification, provider, accounts, wasmFactory ); await instance.insureApiInterface(); /// check metadata update await instance.awaitMetaDataCheck(); await apiPromise.isReady; return instance; } async destroy (): Promise<void> { await this.provider.destroy(); } }
nepoche/webb.js
packages/api-providers/src/types/anchor-config.interface.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { InternalChainId } from '../chains/index.js'; export type ChainAddressConfig = { [key in InternalChainId]?: string }; export type AnchorConfigEntry = { amount: string; // EVM based anchorAddresses: ChainAddressConfig; // Substrate based anchorTreeIds: ChainAddressConfig; };
nepoche/webb.js
packages/api-providers/src/ext-providers/polkadot/polkadot-accounts.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { InjectedAccount, InjectedExtension } from '@polkadot/extension-inject/types'; import { Account, AccountsAdapter, PromiseOrT } from '../../account/Accounts.adapter.js'; export class PolkadotAccount extends Account<InjectedAccount> { get avatar () { return null; } get name (): string { return this.inner.name || this.address; } } export class PolkadotAccounts extends AccountsAdapter<InjectedExtension, InjectedAccount> { providerName = 'Polka'; private activeAccount: null | PolkadotAccount = null; async accounts () { const accounts = await this._inner.accounts.get(); return accounts.map((account) => new PolkadotAccount(account, account.address)); } get activeOrDefault () { // eslint-disable-next-line no-async-promise-executor return new Promise<PolkadotAccount | null>(async (resolve, reject) => { try { if (this.activeAccount) { return resolve(this.activeAccount); } const accounts = await this._inner.accounts.get(); const defaultAccount = accounts[0] ? new PolkadotAccount(accounts[0], accounts[0].address) : null; resolve(defaultAccount); } catch (e) { reject(e); } }); } setActiveAccount (account: PolkadotAccount): PromiseOrT<void> { console.log(account); this.activeAccount = account; return undefined; } }
nepoche/webb.js
packages/api-providers/src/polkadot/anchor-withdraw.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { fetchSubstrateAnchorProvingKey } from '@nepoche/api-providers/ipfs/substrate/anchor.js'; import { LoggerService } from '@nepoche/app-util/index.js'; import { Note, ProvingManager, ProvingManagerSetupInput } from '@nepoche/sdk-core/index.js'; import { decodeAddress } from '@polkadot/keyring'; import { hexToU8a, u8aToHex } from '@polkadot/util'; import { AnchorWithdraw, WithdrawState } from '../abstracts/index.js'; import { InternalChainId } from '../chains/index.js'; import { WebbError, WebbErrorCodes } from '../webb-error/index.js'; import { WebbPolkadot } from './webb-provider.js'; const logger = LoggerService.get('PolkadotBridgeWithdraw'); export type AnchorWithdrawProof = { id: string; proofBytes: string; root: string; nullifierHash: string; recipient: string; relayer: string; fee: number; refund: number; refreshCommitment: string; }; export class PolkadotAnchorWithdraw extends AnchorWithdraw<WebbPolkadot> { async fetchRPCTreeLeaves (treeId: string | number): Promise<Uint8Array[]> { logger.trace(`Fetching leaves for tree with id ${treeId}`); 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 fetchRoot (treeId: string) { logger.trace(`fetching metadata for tree id ${treeId}`); const storage = // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore await this.inner.api.query.merkleTreeBn254.trees(treeId); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return storage.toHuman().root; } async withdraw (note: string, recipient: string): Promise<string> { // TODO: implement cross chain // TODO: Integrate with Substrate relayer // TODO handle the cached roots try { const account = await this.inner.accounts.activeOrDefault; if (!account) { throw WebbError.from(WebbErrorCodes.NoAccountAvailable); } const accountId = account.address; const relayerAccountId = account.address; this.emit('stateChange', WithdrawState.GeneratingZk); logger.trace(`Withdraw using note ${note} , recipient ${recipient}`); const parseNote = await Note.deserialize(note); const depositNote = parseNote.note; const amount = parseNote.note.amount; const anchors = await this.inner.methods.anchorApi.getAnchors(); const anchor = anchors.find((a) => a.amount === amount)!; const treeId = anchor.neighbours[InternalChainId.WebbDevelopment] as string; const leaves = await this.fetchRPCTreeLeaves(treeId); const leaf = depositNote.getLeafCommitment(); const leafHex = u8aToHex(leaf); const leafIndex = leaves.findIndex((leaf) => u8aToHex(leaf) === leafHex); logger.trace(leaves.map((i) => u8aToHex(i))); const worker = this.inner.wasmFactory('wasm-utils'); const pm = new ProvingManager(worker); const recipientAccountHex = u8aToHex(decodeAddress(recipient)); const relayerAccountHex = u8aToHex(decodeAddress(recipient)); const provingKey = await fetchSubstrateAnchorProvingKey(); const refreshCommitment = '0000000000000000000000000000000000000000000000000000000000000000'; const root = await this.fetchRoot(treeId); const proofInput: ProvingManagerSetupInput = { fee: 0, leafIndex, leaves, note, provingKey, recipient: recipientAccountHex.replace('0x', ''), refreshCommitment, refund: 0, relayer: relayerAccountHex.replace('0x', ''), roots: [hexToU8a(root), hexToU8a(root)] }; logger.log('proofInput to webb.js: ', proofInput); const zkProofMetadata = await pm.prove(proofInput); const withdrawProof: AnchorWithdrawProof = { fee: 0, id: treeId, nullifierHash: `0x${zkProofMetadata.nullifierHash}`, proofBytes: `0x${zkProofMetadata.proof}` as any, recipient: accountId, refreshCommitment: `0x${refreshCommitment}`, refund: 0, relayer: relayerAccountId, root: `0x${zkProofMetadata.root}` }; const parms = [ withdrawProof.id, withdrawProof.proofBytes, zkProofMetadata.roots.map((i: string) => `0x${i}`), withdrawProof.nullifierHash, withdrawProof.recipient, withdrawProof.relayer, withdrawProof.fee, withdrawProof.refund, withdrawProof.refreshCommitment ]; this.emit('stateChange', WithdrawState.SendingTransaction); const tx = this.inner.txBuilder.build( { method: 'withdraw', section: 'anchorBn254' }, parms ); const hash = await tx.call(account.address); this.emit('stateChange', WithdrawState.Done); return hash || ''; } catch (e) { this.emit('stateChange', WithdrawState.Failed); throw e; } } }
nepoche/webb.js
packages/api-providers/src/types/chain-config.interface.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { ChainType } from '../chains/index.js'; import { WebbCurrencyId } from '../enums/index.js'; import { ReactElement } from './abstracts.js'; export interface ChainConfig { id: number; chainType: ChainType; name: string; group: string; chainId: number; tag?: 'dev' | 'test' | 'live'; url: string; evmRpcUrls?: string[]; blockExplorerStub?: string; logo: ReactElement; nativeCurrencyId: WebbCurrencyId; currencies: Array<WebbCurrencyId>; }
nepoche/webb.js
packages/api-providers/src/abstracts/anchor/anchor-api.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { WebbCurrencyId } from '@nepoche/api-providers/enums/index.js'; import { ChainTypeId, chainTypeIdToInternalId, Currency, InternalChainId } from '@nepoche/api-providers/index.js'; import { BehaviorSubject, Observable } from 'rxjs'; export type BridgeCurrencyIndex = string | number | WebbCurrencyId; type BridgeStore<BridgeConfigEntry, BridgeConfig = Record<BridgeCurrencyIndex, BridgeConfigEntry>> = { config: BridgeConfig; activeBridge?: BridgeConfigEntry; }; export type AnchorBase = { amount: string | number; neighbours: { [key in InternalChainId]?: string | number; }; }; export abstract class AnchorApi<Api, BridgeConfigEntry> { private readonly _store: BehaviorSubject<BridgeStore<BridgeConfigEntry>>; private readonly _watcher: Observable<BridgeStore<BridgeConfigEntry>>; public constructor (protected inner: Api, initialStore: Record<BridgeCurrencyIndex, BridgeConfigEntry>) { this._store = new BehaviorSubject({ config: initialStore }); this._watcher = this._store.asObservable(); } get $store () { return this._watcher; } get store (): BridgeStore<BridgeConfigEntry> { return this._store.value; } get bridgeIds () { return Object.keys(this.store.config) as BridgeCurrencyIndex[]; } // eslint-disable-next-line @typescript-eslint/adjacent-overload-signatures set store (next: Partial<BridgeStore<BridgeConfigEntry>>) { this._store.next({ ...this.store, ...next }); } abstract get currency(): Currency | null; abstract getCurrencies(): Promise<Currency[]>; // For evm abstract getTokenAddress(chainId: ChainTypeId): string | null; get activeBridge (): BridgeConfigEntry | undefined { return this.store.activeBridge; } abstract getAnchors(): Promise<AnchorBase[]>; setActiveBridge (activeBridge: BridgeConfigEntry | undefined) { this.store = { ...this.store, activeBridge: activeBridge }; } abstract getWrappableAssets(chainId: ChainTypeId): Promise<Currency[]>; /* * Get all Bridge tokens for a given chain * */ async getTokensOfChain (chainId: ChainTypeId): Promise<Currency[]> { const tokens = await this.getCurrencies(); const internalChainId = chainTypeIdToInternalId(chainId); return tokens.filter((token) => token.hasChain(internalChainId)); } }
nepoche/webb.js
packages/app-util/src/logger/logs-level.enum.ts
<filename>packages/app-util/src/logger/logs-level.enum.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export enum LogLevel { trace, log, info, warn, debug, error }
nepoche/webb.js
packages/api-providers/src/utils/misc/get-cached-fixtures-uri.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export function getCachedFixtureURI (fileName: string) { return `/cached-fixtures/${fileName}`; }
nepoche/webb.js
packages/api-providers/src/contracts/utils/merkle/merkle-tree.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { Storage } from './storage.js'; export interface Hasher { hash(level: any, left: any, right: any): any; } interface TraverserHandler { handleIndex(level: number, elementIndex: number, siblingIndex: number): void; } class UpdateTraverser implements TraverserHandler { public originalElement: any; public keyValuesToPut: any = []; constructor ( private prefix: string, private storage: Storage, private hasher: Hasher, public currentElement: any, private zeroValues: any ) { } static new ( prefix: string, storage: Storage, hasher: Hasher, currentElement: any, zeroValues: any ): UpdateTraverser { return new UpdateTraverser( prefix, storage, hasher, currentElement, zeroValues ); } async handleIndex (level: number, elementIndex: number, siblingIndex: number) { if (level === 0) { this.originalElement = this.storage.getOrDefault( MerkleTree.keyFormat(this.prefix, level, elementIndex), this.zeroValues[level] ); } const sibling = this.storage.getOrDefault( MerkleTree.keyFormat(this.prefix, level, siblingIndex), this.zeroValues[level] ); let left, right; if (elementIndex % 2 === 0) { left = this.currentElement; right = sibling; } else { left = sibling; right = this.currentElement; } this.keyValuesToPut.push({ key: MerkleTree.keyFormat(this.prefix, level, elementIndex), value: this.currentElement }); this.currentElement = this.hasher.hash(level, left, right); } } class PathTraverser implements TraverserHandler { public pathElements: any[] = []; public pathIndex: number[] = []; constructor (private prefix: string, private storage: Storage, private zeroValues: any) { } handleIndex (level: number, elementIndex: number, siblingIndex: number) { const sibling = this.storage.getOrDefault( MerkleTree.keyFormat(this.prefix, level, siblingIndex), this.zeroValues[level] ) as any; this.pathElements.push(sibling); this.pathIndex.push(elementIndex % 2); } } export class MerkleTree { private zeroValues: string[] = []; private totalElements = 0; static keyFormat (prefix: string, level: number, index: number) { return `${prefix}_tree_${level}_${index}`; } static new ( prefix: string, nLevel: number, defaultElements: any[] = [], hasher: Hasher, storage: Storage = new Storage() ): MerkleTree { return new MerkleTree(prefix, nLevel, defaultElements, hasher, storage); } constructor ( private prefix: string, private nLevel: number, defaultElements: any[], private hasher: Hasher, private storage: Storage ) { let currentZeroValue = '21663839004416932945382355908790599225266501822907911457504978515578255421292'; this.zeroValues.push(currentZeroValue); for (let i = 0; i < this.nLevel; i++) { currentZeroValue = this.hasher.hash(i, currentZeroValue, currentZeroValue); this.zeroValues.push(currentZeroValue.toString()); } if (defaultElements) { let level = 0; this.totalElements = defaultElements.length; defaultElements.forEach((element, i) => { this.storage.put(MerkleTree.keyFormat(prefix, level, i), element); }); level++; let numberOfElementsInLevel = Math.ceil(defaultElements.length / 2); for (level; level <= this.nLevel; level++) { for (let i = 0; i < numberOfElementsInLevel; i++) { const leftKey = MerkleTree.keyFormat(prefix, level - 1, 2 * i); const rightKey = MerkleTree.keyFormat(prefix, level - 1, 2 * i + 1); const left = this.storage.get(leftKey); const right = this.storage.getOrDefault(rightKey, this.zeroValues[level - 1]); const subRoot = this.hasher.hash(null, left, right); this.storage.put(MerkleTree.keyFormat(prefix, level, i), subRoot); } numberOfElementsInLevel = Math.ceil(numberOfElementsInLevel / 2); } } } traverse (index: number, handler: TraverserHandler) { let currentIndex = index; for (let i = 0; i < this.nLevel; i++) { let siblingIndex = currentIndex; if (currentIndex % 2 === 0) { siblingIndex += 1; } else { siblingIndex -= 1; } handler.handleIndex(i, currentIndex, siblingIndex); currentIndex = Math.floor(currentIndex / 2); } } update (index: number, element: any, insert = false) { if (!insert && index >= this.totalElements) { throw Error('Use insert method for new elements.'); } else if (insert && index < this.totalElements) { throw Error('Use update method for existing elements.'); } try { const traverser = UpdateTraverser.new(this.prefix, this.storage, this.hasher, element, this.zeroValues); this.traverse(index, traverser); traverser.keyValuesToPut.push({ key: MerkleTree.keyFormat(this.prefix, this.nLevel, 0), value: traverser.currentElement }); this.storage.putBatch(traverser.keyValuesToPut); } catch (e) { console.error(e); } } getRoot (): string { const root = this.storage.getOrDefault( MerkleTree.keyFormat(this.prefix, this.nLevel, 0), this.zeroValues[this.nLevel] ) as string; return root; } // Elements must be ordered batchInsert (elements: any[]) { elements.forEach((elem) => { this.insert(elem); }); } insert (element: any) { const index = this.totalElements; this.update(index, element, true); this.totalElements++; } path (index: number) { const traverser = new PathTraverser(this.prefix, this.storage, this.zeroValues); const root = this.storage.getOrDefault( MerkleTree.keyFormat(this.prefix, this.nLevel, 0), this.zeroValues[this.nLevel] ); const element = this.storage.getOrDefault(MerkleTree.keyFormat(this.prefix, 0, index), this.zeroValues[0]); this.traverse(index, traverser); return { element, pathElements: traverser.pathElements, pathIndex: traverser.pathIndex, root }; } getIndexOfElement (element: any): number { for (let i = 0; i < this.totalElements; i++) { if (this.storage.get(MerkleTree.keyFormat(this.prefix, 0, i)) === element) { return i; } } return -1; } getLeaves (): any[] { const leaves = []; for (let i = 0; i < this.totalElements; i++) { leaves.push(this.storage.get(MerkleTree.keyFormat(this.prefix, 0, i))); } return leaves; } }
nepoche/webb.js
packages/sdk-core/src/proving/proving-manager.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { ProvingManagerSetupInput, ProvingManagerWrapper } from '@nepoche/sdk-core/proving/proving-manager-thread.js'; import { Proof } from '@nepoche/wasm-utils'; export type ProofI = Omit<Proof, 'free'>; export class ProvingManager { constructor ( private readonly worker: Worker | null | undefined // Optional WebWorker ) {} /** * @param {ProvingManagerSetupInput} input * @returns {ProofI} * @description Checks the current {ProvingManager} status wither it is proving with a Worker(browser) or directly(Nodejs), * accordingly it will run to write private function * {ProvingManager.proveWithWorker} for browser,And {ProvingManager.proveWithoutWorker} for Nodejs * */ public prove (input: ProvingManagerSetupInput) { const worker = this.worker; if (worker) { return ProvingManager.proveWithWorker(input, worker); } return ProvingManager.proveWithoutWorker(input); } private static proveWithoutWorker (input: ProvingManagerSetupInput) { // If the worker CTX is direct-call const pm = new ProvingManagerWrapper('direct-call'); return pm.proof(input); } private static proveWithWorker (input: ProvingManagerSetupInput, worker: Worker): Promise<ProofI> { return new Promise<ProofI>((resolve, reject) => { try { worker.addEventListener('message', (e) => { const payload = e.data.data as ProofI; resolve(payload); }); worker.postMessage({ proof: input }); } catch (e) { reject(e); } }); } }
nepoche/webb.js
packages/api-providers/src/contracts/tornado/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './Tornado.js'; export * from './Tornado__factory.js';
nepoche/webb.js
packages/types/src/interfaces/merkle/types.ts
<reponame>nepoche/webb.js // Auto-generated via `yarn polkadot-types-from-defs`, do not edit /* eslint-disable */ import type { u32 } from '@polkadot/types-codec'; /** @name KeyId */ export interface KeyId extends u32 {} /** @name TreeId */ export interface TreeId extends u32 {} export type PHANTOM_MERKLE = 'merkle';
nepoche/webb.js
packages/api-providers/src/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './web3/index.js'; export * from './polkadot/index.js'; export * from './abstracts/index.js'; export * from './webb-error/index.js'; export * from './contracts/index.js'; export * from './utils/index.js'; export * from './types/index.js'; export * from './enums/index.js'; export * from './storage/index.js'; export * from './chains/index.js'; export * from './account/index.js'; export * from './ext-providers/index.js'; export * from './chains/index.js';
nepoche/webb.js
packages/app-util/src/__test__/fixed-18.spec.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import BigNumber from 'bignumber.js'; import { expect } from 'chai'; import { Fixed18 } from '../fixed-18.js'; describe('fixed 128 constructor', () => { it('constructor should work', () => { const a = new Fixed18(1); const b = new Fixed18('1'); const c = new Fixed18(new BigNumber(1)); expect(a).to.deep.equal(b); expect(a).to.deep.equal(c); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const d = new Fixed18(); // test for no params expect(d).to.deep.equal(Fixed18.ZERO); }); it('from parts should work', () => { const a = Fixed18.fromParts(1); expect(a.getInner().toNumber()).to.deep.equal(1); }); it('from natural should work', () => { const a = Fixed18.fromNatural(1); expect(a.getInner().toNumber()).to.deep.equal(1e18); }); it('from rational should work', () => { const a = Fixed18.fromRational(10, 2); const b = Fixed18.fromRational(100, 20); // 0.0000000000000000001 will be 0 const c = Fixed18.fromRational(1, 10000000000000000000); expect(a.toNumber()).to.deep.equal(5); expect(a).to.deep.equal(b); expect(c).to.deep.equal(Fixed18.ZERO); }); }); describe('toFixed should work', () => { const a = Fixed18.fromNatural(0.123456789); const b = Fixed18.fromNatural(0.00000000001); expect(a.toFixed(6)).to.deep.equal('0.123456'); expect(a.toFixed(9)).to.deep.equal('0.123456789'); expect(b.toFixed(11)).to.deep.equal('0.00000000001'); expect(b.toFixed(20)).to.deep.equal('0.00000000001'); expect(b.toString(11)).to.deep.equal('1e-11'); }); describe('fixed 128 operation', () => { const a = Fixed18.fromNatural(10); const b = Fixed18.fromNatural(20); it('add should work', () => { const c = Fixed18.fromNatural(30); expect(a.add(b)).to.deep.equal(c); }); it('sub should work', () => { const c = Fixed18.fromNatural(-10); expect(a.sub(b)).to.deep.equal(c); }); it('mul should work', () => { const c = Fixed18.fromNatural(200); expect(a.mul(b)).to.deep.equal(c); }); it('div should work', () => { const c = Fixed18.fromRational(1, 2); expect(a.div(b)).to.deep.equal(c); }); it('div with zero should be Infinity', () => { const b = Fixed18.fromNatural(0); const c = new Fixed18(Infinity); expect(a.div(b)).to.deep.equal(c); }); it('negated should work', () => { const c = Fixed18.fromNatural(-10); expect(a.negated()).to.deep.equal(c); }); }); describe('fixed 128 compare should work', () => { const a = Fixed18.fromNatural(10); const b = Fixed18.fromNatural(20); it('lessThan should work', () => { expect(a.isLessThan(b)).to.deep.equal(true); }); it('greaterThan should work', () => { expect(a.isGreaterThan(b)).to.deep.equal(false); }); it('isEqual should work', () => { const c = Fixed18.fromNatural(10); expect(a.isEqualTo(b)).to.deep.equal(false); expect(a.isEqualTo(c)).to.deep.equal(true); }); it('max should work', () => { expect(a.max(b)).to.deep.equal(b); expect(a.min(b)).to.deep.equal(a); }); it('isZero should work', () => { const c = Fixed18.ZERO; expect(c.isZero()).to.deep.equal(true); expect(a.isZero()).to.deep.equal(false); }); it('isInfinite should work', () => { const c1 = Fixed18.fromNatural(Infinity); const c2 = Fixed18.fromNatural(-Infinity); const c3 = Fixed18.fromNatural(NaN); expect(c1.isFinity()).to.deep.equal(false); expect(c2.isFinity()).to.deep.equal(false); expect(c3.isFinity()).to.deep.equal(false); expect(a.isFinity()).to.deep.equal(true); }); it('isNaN should work', () => { const c = Fixed18.fromNatural(NaN); const d = Fixed18.ZERO.div(Fixed18.ZERO); expect(a.isNaN()).to.deep.equal(false); expect(c.isNaN()).to.deep.equal(true); expect(d.isNaN()).to.deep.equal(true); }); }); describe('fixed 128 format', () => { const a = Fixed18.fromRational(256, 100); it('toNumber should work', () => { expect(a.toNumber()).to.deep.equal(2.56); expect(a.toNumber(1, 2)).to.deep.equal(2.6); // round towards infinity expect(a.toNumber(1, 3)).to.deep.equal(2.5); // roound towards -infinity }); it('toString should work', () => { expect(a.toString()).to.deep.equal('2.56'); expect(a.toString(1, 2)).to.deep.equal('2.6'); // round towards infinity expect(a.toString(1, 3)).to.deep.equal('2.5'); // round towards -intinity }); it('innerToString should work', () => { const b = Fixed18.fromParts(5.5); const c1 = Fixed18.fromNatural(NaN); const c2 = Fixed18.fromNatural(Infinity); expect(a.innerToString()).to.deep.equal('2560000000000000000'); expect(b.innerToString()).to.deep.equal('5'); expect(c1.innerToString()).to.deep.equal('0'); expect(c2.innerToString()).to.deep.equal('0'); }); });
nepoche/webb.js
packages/api-providers/src/contracts/wrappers/index.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './types.js'; export * from './anchor-interface.js'; export * from './tornado-anchor.js'; export * from './webb-anchor.js'; export * from './webb-governed-token.js'; export * from './webb-utils.js';
nepoche/webb.js
packages/api-providers/src/web3/mixer-deposit.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { getEVMChainName, getNativeCurrencySymbol } from '@nepoche/api-providers/utils/index.js'; import { Note, NoteGenInput } from '@nepoche/sdk-core/index.js'; import utils from 'web3-utils'; import { u8aToHex } from '@polkadot/util'; import { DepositPayload as IDepositPayload, MixerDeposit, MixerSize } from '../abstracts/index.js'; import { ChainType, computeChainIdType, parseChainIdType } from '../chains/index.js'; import { createTornDeposit, Deposit } from '../contracts/utils/make-deposit.js'; import { WebbWeb3Provider } from './webb-provider.js'; type DepositPayload = IDepositPayload<Note, [Deposit, number]>; export class Web3MixerDeposit extends MixerDeposit<WebbWeb3Provider, DepositPayload> { async deposit ({ note: depositPayload, params }: DepositPayload): Promise<void> { const chainId = Number(depositPayload.note.targetChainId); const evmChainId = parseChainIdType(chainId).chainId; this.inner.notificationHandler({ data: { amount: String(Number(depositPayload.note.amount)), chain: getEVMChainName(this.inner.config, evmChainId), currency: depositPayload.note.tokenSymbol }, description: 'Depositing', key: 'web3-mixer-deposit', level: 'loading', message: 'mixer:deposit', name: 'Transaction' }); const [deposit, amount] = params; const providerEvmChainId = await this.inner.getChainId(); const contract = await this.inner.getContractBySize( amount, getNativeCurrencySymbol(this.inner.config, providerEvmChainId) ); try { await contract.deposit(deposit.commitment); this.inner.notificationHandler({ description: 'Deposit succeed', key: 'web3-mixer-deposit', level: 'success', message: 'mixer:deposit', name: 'Transaction' }); } catch (e) { if ((e as any)?.code === 4001) { this.inner.notificationHandler({ description: 'User Rejected Deposit', key: 'web3-mixer-deposit', level: 'error', message: 'mixer:deposit', name: 'Transaction' }); } else { this.inner.notificationHandler({ description: 'Deposit Failed', key: 'web3-mixer-deposit', level: 'error', message: 'mixer:deposit', name: 'Transaction' }); } } } async generateNote (mixerAddress: string): Promise<DepositPayload> { const contract = await this.inner.getContractByAddress(mixerAddress); const mixerInfo = this.inner.getMixers().getMixerInfoByAddress(mixerAddress); if (!mixerInfo) { throw new Error('mixer not found from storage'); } const depositSizeBN = await contract.denomination; const depositSize = Number.parseFloat(utils.fromWei(depositSizeBN.toString(), 'ether')); const chainId = await this.inner.getChainId(); const deposit = createTornDeposit(); const noteChain = computeChainIdType(ChainType.EVM, chainId); const secrets = deposit.preimage; const noteInput: NoteGenInput = { amount: String(depositSize), backend: 'Circom', curve: 'Bn254', denomination: '18', exponentiation: '5', hashFunction: 'Poseidon', protocol: 'mixer', secrets: u8aToHex(secrets), sourceChain: noteChain.toString(), sourceIdentifyingData: mixerAddress, targetChain: noteChain.toString(), targetIdentifyingData: mixerAddress, tokenSymbol: mixerInfo.symbol, version: 'v2', width: '3' }; const note = await Note.generateNote(noteInput); return { note: note, params: [deposit, mixerInfo.size] }; } async getSizes (): Promise<MixerSize[]> { const chainId = await this.inner.getChainId(); return this.inner.getMixerSizes(getNativeCurrencySymbol(this.inner.config, chainId)); } }
nepoche/webb.js
packages/api-providers/src/utils/retry-promise.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); export async function retryPromise<T extends () => Promise<any>>( executor: T, maxReties = 20, sleepTime = 0 ): Promise<ReturnType<T>> { let resolved = false; let tries = maxReties; while (!resolved && tries > 0) { try { const val = await executor(); resolved = true; return val; } catch (e) { await sleep(sleepTime); tries--; console.error(e); } } }
nepoche/webb.js
packages/type-definitions/scripts/generate.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { rpc, types, typesBundleForPolkadot } from '@nepoche/type-definitions/index'; import fs from 'fs'; fs.writeFileSync('packages/type-definitions/src/json/types.json', JSON.stringify(types, null, 4)); fs.writeFileSync( 'packages/type-definitions/src/json/typesBundle.json', JSON.stringify(typesBundleForPolkadot, null, 4) ); fs.writeFileSync('packages/type-definitions/src/json/rpc.json', JSON.stringify(rpc, null, 4));
nepoche/webb.js
packages/api-providers/src/contracts/utils/merkle/sponge-hasher.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 // @ts-ignore import circomlib from 'tornado-circomlib'; import { Hasher } from './merkle-tree.js'; const { mimcsponge } = circomlib; export class MimcSpongeHasher implements Hasher { hash (level: any, left: any, right: any) { return mimcsponge.multiHash([BigInt(left), BigInt(right)]).toString(); } }
nepoche/webb.js
packages/api-providers/src/abstracts/anchor/anchor-deposit.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { DepositPayload, MixerDeposit, MixerSize } from '../mixer/mixer-deposit.js'; import { WebbApiProvider } from '../webb-provider.interface.js'; export type AnchorSize = MixerSize; export abstract class AnchorDeposit< T extends WebbApiProvider<any>, K extends DepositPayload = DepositPayload<any> > extends MixerDeposit<T, K> { generateNote (anchorId: number | string): Promise<K> { throw new Error('api not ready:Not mixer api for ' + anchorId); } abstract generateBridgeNote( anchorId: number | string, destination: number, wrappableAssetAddress?: string ): Promise<K>; }
nepoche/webb.js
packages/type-definitions/src/types-known/versioned.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 const typesBundleTypes = [ { types: { Address: 'AccountId', LookupSource: 'AccountId' } } ]; export default typesBundleTypes;
nepoche/webb.js
packages/sdk-core/src/__test__/fixed-point-number.spec.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { expect } from 'chai'; import { FixedPointNumber } from '../fixed-point-number.js'; describe('fixed point number constructor should work', () => { it('toString & toNumber', () => { const a = FixedPointNumber.fromInner('123456789123456789123456789'); const b = FixedPointNumber.fromInner('123456789123456781123456789'); expect(a.toString()).to.deep.equal('123456789.123456789123456789'); expect(a.toNumber()).to.deep.equal(123456789.12345678); expect(b.toNumber()).to.deep.equal(123456789.12345678); }); it('construct from number', () => { const a = new FixedPointNumber(1); const b = new FixedPointNumber(1, 2); const c = FixedPointNumber.fromInner(1e18, 18); expect(a._getInner().toString()).to.deep.equal('1000000000000000000'); expect(a.toString()).to.deep.equal('1'); expect(b._getInner().toString()).to.deep.equal('100'); expect(b.toString()).to.deep.equal('1'); expect(c.toNumber()).to.deep.equal(1); expect(c._getInner().toNumber() + 1).to.deep.equal(1e18 + 1); expect(FixedPointNumber.fromInner(c._getInner().toNumber() + 1).toNumber(18)).to.deep.equal(1 + 1e-18); }); it('construct from inner', () => { const a = FixedPointNumber.fromInner(1000000, 6); expect(a.toNumber()).to.deep.equal(1); }); it('no scientific natation', () => { const a = new FixedPointNumber(1, 99); const b = new FixedPointNumber(1e-99, 1); expect(a._getInner().toString()).to.deep.equal( '1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' ); expect(b._getInner().toString()).to.deep.equal( '0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001' ); }); it('setPrecision', () => { const a = new FixedPointNumber(1000000, 6); const b = new FixedPointNumber(1000000, 6); b.setPrecision(12); expect(a.isEqualTo(b)).to.deep.equal(true); }); }); describe('fixed point number calculation should work', () => { it('get the absolute value', () => { const a = new FixedPointNumber(-1); const b = new FixedPointNumber(1); expect(a.abs().toNumber()).to.deep.equal(1); expect(b.abs().toNumber()).to.deep.equal(1); }); it('plus', () => { const a = new FixedPointNumber(100); const b = new FixedPointNumber(100); const c = new FixedPointNumber(100, 18); const d = new FixedPointNumber(100, 16); const e = FixedPointNumber.fromInner(100, 2); const f = FixedPointNumber.fromInner(100, 4); expect(a.plus(b).toNumber()).to.deep.equal(200); expect(c.plus(d).toNumber()).to.deep.equal(200); expect(e.plus(f).toNumber()).to.deep.equal(1.01); }); it('minus', () => { const a = new FixedPointNumber(200); const b = new FixedPointNumber(100); const c = new FixedPointNumber(200, 18); const d = new FixedPointNumber(100, 16); const e = FixedPointNumber.fromInner(100, 2); const f = FixedPointNumber.fromInner(100, 4); expect(a.minus(b).toNumber()).to.deep.equal(100); expect(c.minus(d).toNumber()).to.deep.equal(100); expect(e.minus(f).toNumber()).to.deep.equal(0.99); }); it('times', () => { const a = new FixedPointNumber(100); const b = new FixedPointNumber(100); const c = new FixedPointNumber(100, 18); const d = new FixedPointNumber(100, 16); const e = FixedPointNumber.fromInner(100, 2); const f = FixedPointNumber.fromInner(100, 4); expect(a.times(b).toNumber()).to.deep.equal(10000); expect(c.times(d).toNumber()).to.deep.equal(10000); expect(e.times(f).toNumber()).to.deep.equal(0.01); }); it('div', () => { const a = new FixedPointNumber(200); const b = new FixedPointNumber(100); const c = new FixedPointNumber(200, 18); const d = new FixedPointNumber(100, 16); const e = FixedPointNumber.fromInner(100, 2); const f = FixedPointNumber.fromInner(100, 4); const n = new FixedPointNumber(100, 2); const m = new FixedPointNumber(3, 2); expect(a.div(b).toNumber()).to.deep.equal(2); expect(c.div(d).toNumber()).to.deep.equal(2); expect(e.div(f).toNumber()).to.deep.equal(100); expect(n.div(m).toNumber(2)).to.deep.equal(33.33); }); }); describe('fixed point number compare should work', () => { it('isZero', () => { const a = new FixedPointNumber(0); const b = new FixedPointNumber(1); expect(a.isZero()).to.deep.equal(true); expect(b.isZero()).to.deep.equal(false); }); it('isNaN', () => { const a = new FixedPointNumber(NaN); const b = new FixedPointNumber(0); const c = new FixedPointNumber(0); const d = new FixedPointNumber(1); expect(a.isNaN()).to.deep.equal(true); expect(b.div(c).isNaN()).to.deep.equal(true); expect(d.isNaN()).to.deep.equal(false); }); it('isNegative', () => { const a = new FixedPointNumber(NaN); const b = new FixedPointNumber(1); const c = new FixedPointNumber(-1); expect(a.isNegative()).to.deep.equal(false); expect(b.isNegative()).to.deep.equal(false); expect(c.isNegative()).to.deep.equal(true); }); it('isPositive', () => { const a = new FixedPointNumber(NaN); const b = new FixedPointNumber(1); const c = new FixedPointNumber(-1); expect(a.isPositive()).to.deep.equal(false); expect(b.isPositive()).to.deep.equal(true); expect(c.isPositive()).to.deep.equal(false); }); it('isGreaterThan', () => { const a = new FixedPointNumber(2); const b = new FixedPointNumber(1); const c = new FixedPointNumber(-1); expect(a.isGreaterThan(b)).to.deep.equal(true); expect(a.isGreaterThan(c)).to.deep.equal(true); expect(b.isGreaterThan(a)).to.deep.equal(false); expect(c.isGreaterThan(a)).to.deep.equal(false); }); it('isGreaterOrEqualThan', () => { const a = new FixedPointNumber(2); const b = new FixedPointNumber(1); const c = new FixedPointNumber(2); expect(a.isGreaterThanOrEqualTo(b)).to.deep.equal(true); expect(a.isGreaterThanOrEqualTo(c)).to.deep.equal(true); }); it('isLessThan', () => { const a = new FixedPointNumber(2); const b = new FixedPointNumber(10); expect(a.isLessThan(b)).to.deep.equal(true); expect(b.isLessThan(a)).to.deep.equal(false); }); it('isLessThan', () => { const a = new FixedPointNumber(2); const b = new FixedPointNumber(10); const c = new FixedPointNumber(2); expect(b.isLessOrEqualTo(a)).to.deep.equal(false); expect(a.isLessOrEqualTo(b)).to.deep.equal(true); expect(a.isLessOrEqualTo(c)).to.deep.equal(true); }); it('isEqualTo', () => { const a = new FixedPointNumber(2, 2); const b = new FixedPointNumber(2, 3); expect(a.isEqualTo(b)).to.deep.equal(true); }); it('min max', () => { const a = new FixedPointNumber(2, 2); const b = new FixedPointNumber(2, 3); const c = new FixedPointNumber(2, 18); const d = new FixedPointNumber(4, 3); expect(a.max(b).toString()).to.deep.equal(b.toString()); expect(a.min(b).toString()).to.deep.equal(b.toString()); expect(a.max(c).toString()).to.deep.equal(c.toString()); expect(a.min(c).toString()).to.deep.equal(c.toString()); expect(a.max(d).toString()).to.deep.equal(d.toString()); expect(a.min(d).toString()).to.deep.equal(a.toString()); }); it('trunc frac', () => { const a = FixedPointNumber.fromRational(5, 2); const a1 = a.trunc(); const a2 = a.frac(); expect(a1.plus(a2).toString()).to.deep.equal(a.toString()); const b = FixedPointNumber.fromRational(5, 2).frac().times(FixedPointNumber.TEN); expect(b.toString()).to.deep.equal(FixedPointNumber.FIVE.toString()); const c = FixedPointNumber.fromRational(-5, 2); const c1 = c.trunc(); const c2 = c.frac(); console.log(c1.toString(), c2.toString()); expect(c1.minus(c2).toString()).to.deep.equal(c.toString()); expect(c2.times(FixedPointNumber.TEN).toString()).to.deep.equal(FixedPointNumber.FIVE.toString()); const d = FixedPointNumber.fromRational(-1, 2).frac().times(FixedPointNumber.TEN); expect(d.toString()).to.deep.equal(FixedPointNumber.ZERO.minus(FixedPointNumber.FIVE).toString()); }); });
nepoche/webb.js
tests/examples/anchor-chain-state.ts
import { createAnchor, getAnchors, KillTask, preparePolkadotApi, setORMLTokenBalance, sleep, startWebbNode, transferBalance, } from '../utils'; import { Keyring } from '@polkadot/keyring'; import { ApiPromise } from '@polkadot/api'; import { KeyringPair } from '@polkadot/keyring/types'; let keyring: { bob: KeyringPair; alice: KeyringPair; charlie: KeyringPair; } | null = null; 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; } let nodes: KillTask | undefined; let apiPromise: ApiPromise | null = null; async function main() { try { nodes = startWebbNode(); await sleep(2000); apiPromise = await preparePolkadotApi(); const { bob, charlie, alice } = getKeyring(); // transfer some funds to sudo & test account await transferBalance(apiPromise!, charlie, [alice, bob]); // set the test account ORML balance of the mixer asset await setORMLTokenBalance(apiPromise!, alice, bob); await createAnchor(apiPromise!, alice, 100); const anchors = await getAnchors(apiPromise!); console.log(anchors); } finally { await apiPromise?.disconnect(); nodes?.(); } } main() .then(() => console.log('done')) .catch(console.error);
nepoche/webb.js
packages/api-providers/src/polkadot/wrap-unwrap.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { Amount, MixerSize, WrappingBalance, WrappingEvent } from '@nepoche/api-providers/index.js'; import { Observable } from 'rxjs'; import { WrapUnWrap } from '../abstracts/index.js'; import { WebbCurrencyId } from '../enums/index.js'; import { WebbPolkadot } from './webb-provider.js'; export class PolkadotWrapUnwrap extends WrapUnWrap<WebbPolkadot> { // eslint-disable-next-line @typescript-eslint/no-unused-vars canWrap (wrapPayload: any): Promise<boolean> { return Promise.resolve(false); } getSizes (): Promise<MixerSize[]> { return Promise.resolve([]); } getTokensAddress (): Promise<string> { return Promise.resolve(''); } // eslint-disable-next-line @typescript-eslint/no-unused-vars unwrap (unwrapPayload: any): Promise<string> { return Promise.resolve(''); } // eslint-disable-next-line @typescript-eslint/no-unused-vars wrap (wrapPayload: any): Promise<string> { return Promise.resolve(''); } get balances (): Observable<[WrappingBalance, WrappingBalance]> { return new Observable(); } // eslint-disable-next-line @typescript-eslint/no-unused-vars canUnWrap (unwrapPayload: Amount): Promise<boolean> { return Promise.resolve(false); } getGovernedTokens (): Promise<WebbCurrencyId[]> { return Promise.resolve([]); } getWrappableTokens (): Promise<WebbCurrencyId[]> { return Promise.resolve([]); } getWrappedTokens (): Promise<WebbCurrencyId[]> { return Promise.resolve([]); } get liquidity (): Observable<[WrappingBalance, WrappingBalance]> { return new Observable(); } get subscription (): Observable<Partial<WrappingEvent>> { return new Observable(); } }
nepoche/webb.js
packages/api-providers/__test__/bootstraping.spec.ts
<filename>packages/api-providers/__test__/bootstraping.spec.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { expect } from 'chai'; import { initPolkadotProvider } from './utils/init-polkadot-provider.js'; describe('Bootstrap providers', function () { this.timeout(120_000); it('Should init Polkadot provider', async () => { const provider = await initPolkadotProvider(); const chainProperties = await provider.api.rpc.system.properties(); expect(chainProperties).not.equal(null); }); });
nepoche/webb.js
tests/utils/backend-utils.ts
<reponame>nepoche/webb.js import { execSync, spawn, SpawnOptionsWithoutStdio } from 'child_process'; import { sleep } from './index.js'; function spawnWithLogger( command: string, options?: SpawnOptionsWithoutStdio, allLogs = false ) { const process = spawn(command, options); if (allLogs) { process.stdout.on('data', (data) => { console.log(data.toString()); }); process.stderr.on('data', (data) => { console.error(data.toString()); }); } process.on('close', (code) => { console.log(` process ${process.pid} exited with code ${code}`); }); return process; } export type KillTask = () => Promise<void>; export function startWebbNode(): KillTask { execSync( 'docker pull ghcr.io/webb-tools/protocol-substrate-standalone-node:edge', { stdio: 'inherit' } ); const DOCKER_NETWORK_NAME = 'webb-network'; try { execSync(`docker network create -d bridge ${DOCKER_NETWORK_NAME}`); } catch (e) { console.log((e as any)?.toString()); } const node1 = 'webb-standalone-node --dev --alice --node-key 0000000000000000000000000000000000000000000000000000000000000001 --ws-port=9944 --rpc-cors all --ws-external'; const node2 = 'webb-standalone-node --dev --bob --port 33334 --tmp --bootnodes /ip4/127.0.0.1/tcp/30333/p2p/12D3KooWEyoppNCUx8Yx66oV9fJnriXwCcXwDDUA2kj6vnc6iDEp --ws-port=9993'; const getDockerCmd = (cmd: string, ports: number[]) => { return `docker run --network ${DOCKER_NETWORK_NAME} --rm ${ports.reduce( (acc, port) => `${acc} -p ${port}:${port}`, '' )} ghcr.io/webb-tools/protocol-substrate-standalone-node:edge ${cmd}`; }; const node1Cmd = getDockerCmd(node1, [9944, 30333]); const node2Cmd = getDockerCmd(node2, [33334, 33334]); const node1Task = spawnWithLogger(node1Cmd, { shell: true, }); const node2task = spawnWithLogger(node2Cmd, { shell: true, }); return async () => { node1Task.kill('SIGINT'); node2task.kill('SIGINT'); await sleep(2000); try { execSync(`docker network rm ${DOCKER_NETWORK_NAME}`); } catch (e) { console.log(e); console.log('Field to removed the docker network , Error ignored '); } }; }
nepoche/webb.js
packages/api-providers/src/abstracts/mixer/mixer-deposit.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { WebbApiProvider } from '@nepoche/api-providers/abstracts/index.js'; import { EventBus } from '@nepoche/app-util/index.js'; import { Note } from './note'; export type DepositPayload<T extends Note = Note, DepositParams = unknown> = { note: T; params: DepositParams; }; export type MixerDepositEvents = { error: string; ready: undefined; }; export type DespotStates = 'ideal' | 'generating-note' | 'depositing'; export type MixerSize = { id: number | string; treeId?: string | number; title: string; amount: number; asset: string; }; /** * Mixer deposit abstract* * The underlying method should be implemented to get a functioning mixerDeposit for a {WebbApiProvider} * @param {T} the provider WebbApiProvider */ export abstract class MixerDeposit<T extends WebbApiProvider<any> = WebbApiProvider<any>, K extends DepositPayload = DepositPayload<any>> extends EventBus<MixerDepositEvents> { constructor (protected inner: T) { super(); } /** * Note generate step this should be called to get the payload {K} * The implementation of the function will be responsible for consuming the provider * and the params {mixerId},{chainId} to generate the wright deposit note and the Payload {K} * the mixerId is passed as a param but the list of mixerId's is got via the {getSizes} call * */ abstract generateNote(mixerId: number | string, chainId?: number | string): Promise<K>; /** * The deposit call it should receive the payload of type {K} * The implementation should * - Mutate the {loading} status of the instance * - Use the event bus to emit the status of the transaction * */ // TODO: update the impls to return the TX hash instead of void abstract deposit(depositPayload: K): Promise<void>; // The current instance status loading: DespotStates = 'ideal'; // Get mixer sizes for display and selection abstract getSizes(): Promise<MixerSize[]>; }
nepoche/webb.js
packages/sdk-core/src/__test__/note.spec.ts
<filename>packages/sdk-core/src/__test__/note.spec.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable @typescript-eslint/no-unsafe-member-access */ import { expect } from 'chai'; import { Note, NoteGenInput } from '../note.js'; describe('Note class', () => { it.only('should test constructor from `NoteGenInput`', async () => { const noteInput: NoteGenInput = { amount: '1', backend: 'Circom', curve: 'Bn254', denomination: '18', exponentiation: '5', hashFunction: 'Poseidon', protocol: 'anchor', sourceChain: '1', sourceIdentifyingData: '1', targetChain: '1', targetIdentifyingData: '1', tokenSymbol: 'WEBB', version: 'v2', width: '4' }; const note = await Note.generateNote(noteInput); expect(note.note.amount).to.deep.equal('1'); expect(note.note.denomination).to.deep.equal('18'); expect(note.note.width).to.deep.equal('4'); expect(note.note.exponentiation).to.deep.equal('5'); expect(note.note.targetChainId).to.deep.equal('1'); expect(note.note.targetIdentifyingData).to.deep.equal('1'); expect(note.note.sourceChainId).to.deep.equal('1'); expect(note.note.sourceIdentifyingData).to.deep.equal('1'); expect(note.note.backend).to.deep.equal('Circom'); expect(note.note.hashFunction).to.deep.equal('Poseidon'); expect(note.note.curve).to.deep.equal('Bn254'); expect(note.note.tokenSymbol).to.deep.equal('WEBB'); }); it.only('should test serializing and deserializing', async () => { const noteInput: NoteGenInput = { amount: '1', backend: 'Circom', curve: 'Bn254', denomination: '18', exponentiation: '5', hashFunction: 'Poseidon', protocol: 'anchor', sourceChain: '1', sourceIdentifyingData: '1', targetChain: '1', targetIdentifyingData: '1', tokenSymbol: 'WEBB', version: 'v2', width: '4' }; const note = await Note.generateNote(noteInput); const serializedNote = note.serialize(); const deserializedNote = await Note.deserialize(serializedNote); expect(deserializedNote.note.sourceChainId).to.deep.equal('1'); expect(deserializedNote.note.sourceIdentifyingData).to.deep.equal('1'); expect(deserializedNote.note.targetChainId).to.deep.equal('1'); expect(deserializedNote.note.targetIdentifyingData).to.deep.equal('1'); expect(deserializedNote.note.backend).to.deep.equal('Circom'); expect(deserializedNote.note.hashFunction).to.deep.equal('Poseidon'); expect(deserializedNote.note.curve).to.deep.equal('Bn254'); expect(deserializedNote.note.tokenSymbol).to.deep.equal('WEBB'); expect(deserializedNote.note.amount).to.deep.equal('1'); expect(deserializedNote.note.denomination).to.deep.equal('18'); expect(deserializedNote.note.width).to.deep.equal('4'); expect(deserializedNote.note.exponentiation).to.deep.equal('5'); }); it.only('should test anchor secrets chain', async () => { const noteInput: NoteGenInput = { amount: '1', backend: 'Circom', curve: 'Bn254', denomination: '18', exponentiation: '5', hashFunction: 'Poseidon', protocol: 'anchor', sourceChain: '1', sourceIdentifyingData: '1', targetChain: '1', targetIdentifyingData: '1', tokenSymbol: 'WEBB', version: 'v2', width: '4' }; const note = await Note.generateNote(noteInput); const targetChainFromSecrets = note.note.secrets.split(':')[0]; const targetChainBuffer = Buffer.from(targetChainFromSecrets, 'hex'); const targetChain = targetChainBuffer.readBigUInt64BE(); expect(targetChain.toString()).to.deep.equal('1'); }); it.only('should fail to deserialize invalid protocol', async () => { const serialized = 'webb://' + 'v2:invalid/' + '1:1/' + '1:1/' + '0000000000000001:ae6c3f92db70334231435b03ca139970e2eeff43860171b9f20a0de4b423741e:339e6c9b0a571e612dbcf60e2c20fc58b4e037f00e9384f0f2c872feea91802b/' + '?curve=Bn254&width=4&exp=5&hf=Poseidon&backend=Circom&token=WEBB&denom=18&amount=1'; try { await Note.deserialize(serialized); } catch (e: any) { expect(e.code).to.equal(4); expect(e.message).to.equal('Invalid note protocol'); } }); it.only('should fail to deserialize invalid version', async () => { const serialized = 'webb://' + 'v3:anchor/' + '1:1/' + '1:1/' + '0000000000000001:ae6c3f92db70334231435b03ca139970e2eeff43860171b9f20a0de4b423741e:339e6c9b0a571e612dbcf60e2c20fc58b4e037f00e9384f0f2c872feea91802b/' + '?curve=Bn254&width=4&exp=5&hf=Poseidon&backend=Circom&token=WEBB&denom=18&amount=1'; try { await Note.deserialize(serialized); } catch (e: any) { expect(e.code).to.equal(5); expect(e.message).to.equal('Invalid note version'); } }); it.only('should fail to deserialize invalid source chain id', async () => { const serialized = 'webb://' + 'v2:anchor/' + 'invalid_source_chain_id:1/' + '1:1/' + '0000000000000001:ae6c3f92db70334231435b03ca139970e2eeff43860171b9f20a0de4b423741e:339e6c9b0a571e612dbcf60e2c20fc58b4e037f00e9384f0f2c872feea91802b/' + '?curve=Bn254&width=4&exp=5&hf=Poseidon&backend=Circom&token=WEBB&denom=18&amount=1'; try { await Note.deserialize(serialized); } catch (e: any) { expect(e.code).to.equal(18); expect(e.message).to.equal('Invalid source chain id'); } }); it.only('should fail to deserialize invalid target chain id', async () => { const serialized = 'webb://' + 'v2:anchor/' + '1:invalid_target_chain_id/' + '1:1/' + '0000000000000001:ae6c3f92db70334231435b03ca139970e2eeff43860171b9f20a0de4b423741e:339e6c9b0a571e612dbcf60e2c20fc58b4e037f00e9384f0f2c872feea91802b/' + '?curve=Bn254&width=4&exp=5&hf=Poseidon&backend=Circom&token=WEBB&denom=18&amount=1'; try { await Note.deserialize(serialized); } catch (e: any) { expect(e.code).to.equal(19); expect(e.message).to.equal('Invalid target chain id'); } }); it.only('should fail to deserialize invalid note length', async () => { const serialized = 'webb://' + 'v2:anchor/' + '1:1/' + // + '1:1/' Nullify the source identify data '0000000000000001:ae6c3f92db70334231435b03ca139970e2eeff43860171b9f20a0de4b423741e:339e6c9b0a571e612dbcf60e2c20fc58b4e037f00e9384f0f2c872feea91802b/' + '?curve=Bn254&width=4&exp=5&hf=Poseidon&backend=Circom&token=WEBB&denom=18&amount=1'; try { await Note.deserialize(serialized); } catch (e: any) { expect(e.code).to.equal(3); expect(e.message).to.equal('Invalid note length'); } }); it.only('should fail to deserialize anchor invalid secrets (invalid chain id item - too large)', async () => { const serialized = 'webb://' + 'v2:anchor/' + '1:1/' + '1:1/' + // Get rid of target chain ID from secrets portion '11010101010101100000000000000001:ae6c3f92db70334231435b03ca139970e2eeff43860171b9f20a0de4b423741e:339e6c9b0a571e612dbcf60e2c20fc58b4e037f00e9384f0f2c872feea91802b/' + '?curve=Bn254&width=4&exp=5&hf=Poseidon&backend=Circom&token=<PASSWORD>&denom=18&amount=1'; try { await Note.deserialize(serialized); } catch (e: any) { expect(e.code).to.equal(8); expect(e.message).to.equal('Invalid note secrets'); } }); it.only('should fail to deserialize anchor invalid secrets (invalid chain id item - too small)', async () => { const serialized = 'webb://' + 'v2:anchor/' + '1:1/' + '1:1/' + // Get rid of target chain ID from secrets portion '0001:ae6c3f92db70334231435b03ca139970e2eeff43860171b9f20a0de4b423741e:339e6c9b0a571e612dbcf60e2c20fc58b4e037f00e9384f0f2c872feea91802b/' + '?curve=Bn254&width=4&exp=5&hf=Poseidon&backend=Circom&token=<PASSWORD>&denom=18&amount=1'; try { await Note.deserialize(serialized); } catch (e: any) { expect(e.code).to.equal(8); expect(e.message).to.equal('Invalid note secrets'); } }); it.only('should fail to deserialize anchor invalid secrets (missing chain id item)', async () => { const serialized = 'webb://' + 'v2:anchor/' + '1:1/' + '1:1/' + // Get rid of target chain ID from secrets portion 'ae6c3f92db70334231435b03ca139970e2eeff43860171b9f20a0de4b423741e:339e6c9b0a571e612dbcf60e2c20fc58b4e037f00e9384f0f2c872feea91802b/' + '?curve=Bn254&width=4&exp=5&hf=Poseidon&backend=Circom&token=WEBB&denom=18&amount=1'; try { await Note.deserialize(serialized); } catch (e: any) { expect(e.code).to.equal(3); expect(e.message).to.equal('Invalid note length'); } }); it.only('should fail to deserialize anchor invalid secrets (nullifier item)', async () => { const serialized = 'webb://' + 'v2:anchor/' + '1:1/' + '1:1/' + // Get rid of target chain ID from secrets portion '0000000000000001:339e6c9b0a571e612dbcf60e2c20fc58b4e037f00e9384f0f2c872feea91802b/' + '?curve=Bn254&width=4&exp=5&hf=Poseidon&backend=Circom&token=WEBB&denom=18&amount=1'; try { await Note.deserialize(serialized); } catch (e: any) { expect(e.code).to.equal(3); expect(e.message).to.equal('Invalid note length'); } }); it.only('should fail to deserialize anchor invalid secrets (multiple colons)', async () => { const serialized = 'webb://' + 'v2:anchor/' + '1:1/' + '1:1/' + // Remove a secret item and leave colon '0000000000000001::339e6c9b0a571e612dbcf60e2c20fc58b4e037f00e9384f0f2c872feea91802b/' + '?curve=Bn254&width=4&exp=5&hf=Poseidon&backend=Circom&token=WEBB&denom=18&amount=1'; try { await Note.deserialize(serialized); } catch (e: any) { expect(e.code).to.equal(8); expect(e.message).to.equal('Invalid note secrets'); } }); it.only('should fail to deserialize anchor invalid secrets (1 colon)', async () => { const serialized = 'webb://' + 'v2:anchor/' + '1:1/' + '1:1/' + // Remove a secret item and also remove colon '0000000000000001:339e6c9b0a571e612dbcf60e2c20fc58b4e037f00e9384f0f2c872feea91802b/' + '?curve=Bn254&width=4&exp=5&hf=Poseidon&backend=Circom&token=WEBB&denom=18&amount=1'; try { await Note.deserialize(serialized); } catch (e: any) { expect(e.code).to.equal(3); expect(e.message).to.equal('Invalid note length'); } }); });
nepoche/webb.js
packages/types/src/interfaces/pallets/definitions.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import pallets from '@nepoche/type-definitions/pallets'; import { Definitions } from '@polkadot/types/types'; export default pallets as Definitions;
nepoche/webb.js
packages/api-providers/src/contracts/wrappers/types.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export type ZKPTornPublicInputs = { nullifierHash: string; relayer: string; recipient: string; fee: number; refund: number; }; export type ZKPTornInputsWithoutMerkle = { nullifierHash: string; relayer: string; recipient: string; fee: number; refund: number; nullifier: string; secret: string; }; export type ZKPTornInputWithMerkle = { /// merkle proof root: string; pathElements: string[]; pathIndices: number[]; } & ZKPTornInputsWithoutMerkle; export type ZKPWebbPublicInputs = { nullifierHash: string; relayer: string; recipient: string; fee: number; refund: number; destinationChainId: number; }; export type ZKPWebbAnchorInputWithoutMerkle = { nullifierHash: string; relayer: string; recipient: string; fee: number; refund: number; nullifier: string; secret: string; destinationChainId: number; }; export type ZKPWebbAnchorInputWithMerkle = { /// merkle proof root: string; pathElements: string[]; pathIndices: number[]; } & ZKPWebbAnchorInputWithoutMerkle; export type AnchorWitnessInput = { nullifierHash: string; recipient: string; refreshCommitment: string; relayer: string; fee: string; refund: string; chainID: bigint; roots: any[]; /// private nullifier: string; secret: string; pathElements: string[]; pathIndices: number[]; };
nepoche/webb.js
packages/api-providers/src/types/bridge-config.interface.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { WebbCurrencyId } from '../enums/index.js'; import { AnchorConfigEntry } from './anchor-config.interface.js'; export interface BridgeConfig { asset: WebbCurrencyId; anchors: AnchorConfigEntry[]; }
nepoche/webb.js
packages/api-providers/src/web3/EvmChainMixersInfo.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { AppConfig, evmChainStorageFactory, MixerSize, MixerStorage } from '@nepoche/api-providers/index.js'; import { EVMChainId, evmIdIntoInternalChainId } from '../chains/index.js'; import { Storage } from '../storage/index.js'; import { MixerConfig } from '../types/mixer-config.interface.js'; export type LeafIntervalInfo = { startingBlock: number; endingBlock: number; leaves: string[]; }; export class EvmChainMixersInfo { private mixerStorage: Storage<MixerStorage> | null = null; private mixerConfig: MixerConfig; constructor (readonly config: AppConfig, public evmId: EVMChainId) { const webbChainId = evmIdIntoInternalChainId(evmId); this.mixerConfig = config.mixers[webbChainId] ?? { tornMixers: [] }; } getTornMixerSizes (tokenSymbol: string): MixerSize[] { const tokenMixers = this.mixerConfig.tornMixers.filter((entry) => entry.symbol === tokenSymbol); return tokenMixers.map((contract) => { return { amount: contract.size, asset: contract.symbol, id: contract.address, title: `${contract.size} ${contract.symbol}` }; }); } async getMixerStorage (contractAddress: string) { // create the mixerStorage if it didn't exist if (!this.mixerStorage) { this.mixerStorage = await evmChainStorageFactory(this.config, this.evmId); } // get the info from localStorage const mixerInfo = this.getMixerInfoByAddress(contractAddress); const storedInfo = await this.mixerStorage.get(contractAddress); if (!storedInfo) { return { lastQueriedBlock: mixerInfo.createdAtBlock, leaves: [] }; } return { createdAtBlock: mixerInfo.createdAtBlock, lastQueriedBlock: storedInfo.lastQueriedBlock, leaves: storedInfo.leaves }; } async setMixerStorage (contractAddress: string, lastQueriedBlock: number, leaves: string[]) { if (!this.mixerStorage) { this.mixerStorage = await evmChainStorageFactory(this.config, this.evmId); } await this.mixerStorage.set(contractAddress, { lastQueriedBlock, leaves }); } getTornMixerInfoBySize (mixerSize: number, tokenSymbol: string) { const mixerInfo = this.mixerConfig.tornMixers.find( (mixer) => mixer.symbol === tokenSymbol && mixer.size === mixerSize ); return mixerInfo; } getMixerInfoByAddress (contractAddress: string) { const allMixers = this.mixerConfig.tornMixers; const mixerInfo = allMixers.find((mixer) => mixer.address === contractAddress); if (!mixerInfo) { throw new Error(`There is no information about the contract ${contractAddress}`); } return mixerInfo; } }
nepoche/webb.js
packages/api-providers/__test__/utils/mock-config.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { ChainType, EVMChainId, InternalChainId, SubstrateChainId } from '@nepoche/api-providers/chains/index.js'; import { ZERO, zeroAddress } from '@nepoche/api-providers/contracts/index.js'; import { WebbCurrencyId } from '@nepoche/api-providers/enums/index.js'; import { AppConfig } from '@nepoche/api-providers/index.js'; import { CurrencyRole, CurrencyType } from '@nepoche/api-providers/types/currency-config.interface.js'; const anchorsConfig: AppConfig['anchors'] = { [WebbCurrencyId.webbWETH]: [ { amount: '0.1', anchorAddresses: { [InternalChainId.Ropsten]: '0x97747a4De7302Ff7Ee3334e33138879469BFEcf8', [InternalChainId.Rinkeby]: '0x09B722aA809A076027FA51902e431a8C03e3f8dF', [InternalChainId.Goerli]: '0x6aA5C74953F7Da1556a298C5e129E417410474E2', [InternalChainId.PolygonTestnet]: '0x12323BcABB342096669d80F968f7a31bdB29d4C4', [InternalChainId.OptimismTestnet]: '0xC44A4EcAC4f23b6F92485Cb1c90dBEd75a987BC8', [InternalChainId.ArbitrumTestnet]: '0xD8a8F9629a98EABFF31CfA9493f274A4D5e768Cd' }, anchorTreeIds: {} } ], [WebbCurrencyId.WEBB]: [ { amount: '10', anchorAddresses: {}, anchorTreeIds: { [InternalChainId.WebbDevelopment]: '3' } }, { amount: '100', anchorAddresses: {}, anchorTreeIds: { [InternalChainId.WebbDevelopment]: '4' } }, { amount: '1000', anchorAddresses: {}, anchorTreeIds: { [InternalChainId.WebbDevelopment]: '5' } } ], [WebbCurrencyId.webbDEV]: [ { amount: '1', anchorAddresses: { [InternalChainId.HermesLocalnet]: '0x510C6297cC30A058F41eb4AF1BFC9953EaD8b577', [InternalChainId.AthenaLocalnet]: '0x7758F98C1c487E5653795470eEab6C4698bE541b' }, anchorTreeIds: {} } ] }; const chainsConfig: AppConfig['chains'] = { [InternalChainId.WebbDevelopment]: { chainId: SubstrateChainId.Webb, chainType: ChainType.Substrate, currencies: [WebbCurrencyId.WEBB], group: 'webb', id: InternalChainId.WebbDevelopment, logo: undefined, name: '<NAME>', nativeCurrencyId: WebbCurrencyId.WEBB, tag: 'dev', url: 'ws://127.0.0.1:9944' }, // this is the EVM edgeware [InternalChainId.EdgewareTestNet]: { chainId: EVMChainId.Beresheet, chainType: ChainType.EVM, currencies: [WebbCurrencyId.TEDG], evmRpcUrls: ['https://beresheet.edgewa.re/evm'], group: 'edgeware', id: InternalChainId.EdgewareTestNet, logo: undefined, name: 'Beresheet (Edgeware Testnet)', nativeCurrencyId: WebbCurrencyId.TEDG, tag: 'test', url: 'wss://beresheet1.edgewa.re' }, // [ChainId.Edgeware]: { // chainType: ChainType, // group: 'edgeware', // tag: 'live', // id: ChainId.Edgeware, // evmId: EVMChain.Edgeware, // name: 'Edgeware', // evmRpcUrls: ['https://mainnet.edgewa.re/evm'], // url: 'wss://mainnet1.edgewa.re', // logo: undefined, // currencies: [ // { // currencyId: WebbCurrencyId.EDG, // enabled: true, // }, // ], // nativeCurrencyId: WebbCurrencyId.EDG, // }, [InternalChainId.Rinkeby]: { blockExplorerStub: 'https://rinkeby.etherscan.io', chainId: EVMChainId.Rinkeby, chainType: ChainType.EVM, currencies: [WebbCurrencyId.ETH, WebbCurrencyId.WETH], evmRpcUrls: ['https://rinkeby.infura.io/v3/e54b7176271840f9ba62e842ff5d6db4'], group: 'eth', id: InternalChainId.Rinkeby, logo: undefined, name: 'Rinkeby', nativeCurrencyId: WebbCurrencyId.ETH, tag: 'test', url: 'https://rinkeby.infura.io/v3/e54b7176271840f9ba62e842ff5d6db4' }, [InternalChainId.Ropsten]: { blockExplorerStub: 'https://ropsten.etherscan.io', chainId: EVMChainId.Ropsten, chainType: ChainType.EVM, currencies: [WebbCurrencyId.ETH, WebbCurrencyId.WETH], evmRpcUrls: ['https://ropsten.infura.io/v3/e54b7176271840f9ba62e842ff5d6db4'], group: 'eth', id: InternalChainId.Ropsten, logo: undefined, name: 'Ropsten', nativeCurrencyId: WebbCurrencyId.ETH, tag: 'test', url: 'https://ropsten.infura.io/v3/e54b7176271840f9ba62e842ff5d6db4' }, [InternalChainId.Goerli]: { blockExplorerStub: 'https://goerli.etherscan.io', chainId: EVMChainId.Goerli, chainType: ChainType.EVM, currencies: [WebbCurrencyId.ETH, WebbCurrencyId.WETH], evmRpcUrls: ['https://goerli.infura.io/v3/e54b7176271840f9ba62e842ff5d6db4'], group: 'eth', id: InternalChainId.Goerli, logo: undefined, name: 'Goerli', nativeCurrencyId: WebbCurrencyId.ETH, tag: 'test', url: 'https://goerli.infura.io/v3/e54b7176271840f9ba62e842ff5d6db4' }, [InternalChainId.Kovan]: { blockExplorerStub: 'https://kovan.etherscan.io', chainId: EVMChainId.Kovan, chainType: ChainType.EVM, currencies: [WebbCurrencyId.ETH, WebbCurrencyId.WETH], evmRpcUrls: ['https://goerli.infura.io/v3/e54b7176271840f9ba62e842ff5d6db4'], group: 'eth', id: InternalChainId.Kovan, logo: undefined, name: 'Kovan', nativeCurrencyId: WebbCurrencyId.ETH, tag: 'test', url: 'https://kovan.infura.io/v3/e54b7176271840f9ba62e842ff5d6db4' }, [InternalChainId.OptimismTestnet]: { blockExplorerStub: 'https://kovan-optimistic.etherscan.io', chainId: EVMChainId.OptimismTestnet, chainType: ChainType.EVM, currencies: [WebbCurrencyId.ETH, WebbCurrencyId.WETH], evmRpcUrls: ['https://kovan.optimism.io'], group: 'eth', id: InternalChainId.OptimismTestnet, logo: undefined, name: 'Optimism Testnet', nativeCurrencyId: WebbCurrencyId.ETH, tag: 'test', url: 'https://kovan.optimism.io' }, [InternalChainId.ArbitrumTestnet]: { blockExplorerStub: 'https://testnet.arbiscan.io', chainId: EVMChainId.ArbitrumTestnet, chainType: ChainType.EVM, currencies: [WebbCurrencyId.ETH, WebbCurrencyId.WETH], evmRpcUrls: ['https://rinkeby.arbitrum.io/rpc'], group: 'eth', id: InternalChainId.ArbitrumTestnet, logo: undefined, name: 'Arbitrum Testnet', nativeCurrencyId: WebbCurrencyId.ETH, tag: 'test', url: 'https://rinkeby.arbitrum.io/rpc' }, [InternalChainId.HarmonyTestnet1]: { chainId: EVMChainId.HarmonyTestnet1, chainType: ChainType.EVM, currencies: [WebbCurrencyId.ONE], evmRpcUrls: ['https://api.s1.b.hmny.io'], group: 'one', id: InternalChainId.HarmonyTestnet1, logo: undefined, name: 'Harmony Testnet Shard 1', nativeCurrencyId: WebbCurrencyId.ONE, tag: 'test', url: 'https://api.s1.b.hmny.io' }, // [ChainId.HarmonyTestnet0]: { // chainType: ChainType, // group: 'one', // id: ChainId.HarmonyTestnet0, // evmId: EVMChain.HarmonyTestnet0, // name: 'Harmony Testnet Shard 0', // tag: 'test', // url: 'https://api.s0.b.hmny.io', // evmRpcUrls: ['https://api.s0.b.hmny.io'], // logo: undefined, // currencies: [ // { // currencyId: WebbCurrencyId.ONE, // enabled: true, // }, // ], // nativeCurrencyId: WebbCurrencyId.ONE, // }, [InternalChainId.HarmonyMainnet0]: { chainId: EVMChainId.HarmonyMainnet0, chainType: ChainType.EVM, currencies: [WebbCurrencyId.ONE], evmRpcUrls: ['https://api.harmony.one'], group: 'one', id: InternalChainId.HarmonyMainnet0, logo: undefined, name: 'Harmony Mainnet Shard 0', nativeCurrencyId: WebbCurrencyId.ONE, tag: 'live', url: 'https://api.harmony.one' }, // [ChainId.EthereumMainNet]: { // chainType: ChainType, // group: 'eth', // id: ChainId.EthereumMainNet, // evmId: EVMChain.EthereumMainNet, // name: 'Ethereum mainnet', // tag: 'live', // url: 'https://mainnet.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161', // evmRpcUrls: ['https://mainnet.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161'], // logo: undefined, // currencies: [ // { // currencyId: WebbCurrencyId.ETH, // enabled: true, // }, // ], // nativeCurrencyId: WebbCurrencyId.ETH, // }, [InternalChainId.Shiden]: { blockExplorerStub: 'https://shiden.subscan.io', chainId: EVMChainId.Shiden, chainType: ChainType.EVM, currencies: [WebbCurrencyId.SDN], evmRpcUrls: ['https://shiden.api.onfinality.io/public'], group: 'sdn', id: InternalChainId.Shiden, logo: undefined, name: 'Shiden', nativeCurrencyId: WebbCurrencyId.SDN, tag: 'live', url: 'https://shiden.api.onfinality.io/public' }, [InternalChainId.PolygonTestnet]: { blockExplorerStub: 'https://mumbai.polygonscan.com/', chainId: EVMChainId.PolygonTestnet, chainType: ChainType.EVM, currencies: [WebbCurrencyId.MATIC, WebbCurrencyId.WETH], evmRpcUrls: ['https://rpc-mumbai.maticvigil.com/'], group: 'matic', id: InternalChainId.PolygonTestnet, logo: undefined, name: 'Polygon Testnet', nativeCurrencyId: WebbCurrencyId.MATIC, tag: 'test', url: 'https://rpc-mumbai.maticvigil.com/' }, [InternalChainId.HermesLocalnet]: { chainId: EVMChainId.HermesLocalnet, chainType: ChainType.EVM, currencies: [WebbCurrencyId.ETH, WebbCurrencyId.DEV], evmRpcUrls: ['http://127.0.0.1:5001'], group: 'eth', id: InternalChainId.HermesLocalnet, logo: undefined, name: 'Hermes Localnet', nativeCurrencyId: WebbCurrencyId.ETH, tag: 'dev', url: 'http://127.0.0.1:5001' }, [InternalChainId.AthenaLocalnet]: { chainId: EVMChainId.AthenaLocalnet, chainType: ChainType.EVM, currencies: [WebbCurrencyId.ETH, WebbCurrencyId.DEV], evmRpcUrls: ['http://127.0.0.1:5002'], group: 'eth', id: InternalChainId.AthenaLocalnet, logo: undefined, name: 'Athena Localnet', nativeCurrencyId: WebbCurrencyId.ETH, tag: 'dev', url: 'http://127.0.0.1:5002' } }; const bridgeConfigByAsset: AppConfig['bridgeByAsset'] = { [WebbCurrencyId.webbWETH]: { anchors: anchorsConfig[WebbCurrencyId.webbWETH], asset: WebbCurrencyId.webbWETH }, [WebbCurrencyId.WEBB]: { anchors: anchorsConfig[WebbCurrencyId.WEBB], asset: WebbCurrencyId.WEBB }, [WebbCurrencyId.webbDEV]: { anchors: anchorsConfig[WebbCurrencyId.webbDEV], asset: WebbCurrencyId.webbDEV } }; const currenciesConfig: AppConfig['currencies'] = { [WebbCurrencyId.EDG]: { addresses: new Map(), color: '', icon: undefined, id: WebbCurrencyId.EDG, name: 'Edgeware token', role: CurrencyRole.Wrappable, symbol: 'EDG', type: CurrencyType.ORML }, [WebbCurrencyId.TEDG]: { addresses: new Map(), color: '', icon: undefined, id: WebbCurrencyId.TEDG, name: 'Edgeware testnet token', role: CurrencyRole.Wrappable, symbol: 'tEDG', type: CurrencyType.ORML }, [WebbCurrencyId.ETH]: { addresses: new Map([ [InternalChainId.Ropsten, zeroAddress], [InternalChainId.Rinkeby, zeroAddress], [InternalChainId.Goerli, zeroAddress], [InternalChainId.Kovan, zeroAddress], [InternalChainId.OptimismTestnet, zeroAddress], [InternalChainId.ArbitrumTestnet, zeroAddress], [InternalChainId.HermesLocalnet, zeroAddress], [InternalChainId.AthenaLocalnet, zeroAddress] ]), color: '', icon: undefined, id: WebbCurrencyId.ETH, name: 'Ethereum', role: CurrencyRole.Wrappable, symbol: 'ETH', type: CurrencyType.NATIVE }, [WebbCurrencyId.ONE]: { addresses: new Map([ [InternalChainId.HarmonyMainnet0, zeroAddress], [InternalChainId.HarmonyTestnet0, zeroAddress], [InternalChainId.HarmonyTestnet1, zeroAddress] ]), color: '', icon: undefined, id: WebbCurrencyId.ONE, name: 'Harmony', role: CurrencyRole.Wrappable, symbol: 'ONE', type: CurrencyType.NATIVE }, [WebbCurrencyId.WEBB]: { // IS THIS AN EVM CHAIN? addresses: new Map([[InternalChainId.WebbDevelopment, ZERO]]), color: '', icon: undefined, id: WebbCurrencyId.WEBB, name: 'WEBB', role: CurrencyRole.Governable, symbol: 'WEBB', type: CurrencyType.ORML }, [WebbCurrencyId.SDN]: { addresses: new Map([[InternalChainId.Shiden, zeroAddress]]), color: '', icon: undefined, id: WebbCurrencyId.SDN, name: 'Shiden', role: CurrencyRole.Wrappable, symbol: 'SDN', type: CurrencyType.NATIVE }, [WebbCurrencyId.WETH]: { addresses: new Map([ [InternalChainId.Ropsten, '0xc778417E063141139Fce010982780140Aa0cD5Ab'], [InternalChainId.Rinkeby, '0xc778417E063141139Fce010982780140Aa0cD5Ab'], [InternalChainId.Goerli, '0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6'], [InternalChainId.Kovan, '0xd0A1E359811322d97991E03f863a0C30C2cF029C'], [InternalChainId.OptimismTestnet, '0xbC6F6b680bc61e30dB47721c6D1c5cde19C1300d'], [InternalChainId.ArbitrumTestnet, '0xEBbc3452Cc911591e4F18f3b36727Df45d6bd1f9'], [InternalChainId.PolygonTestnet, '0x9c3C9283D3e44854697Cd22D3Faa240Cfb032889'] ]), color: '', icon: undefined, id: WebbCurrencyId.WETH, imageUrl: 'https://www.polysa.finance/images/farms/weth.png', name: 'Wrapped Ethereum', role: CurrencyRole.Wrappable, symbol: 'WETH', type: CurrencyType.ERC20 }, [WebbCurrencyId.MATIC]: { addresses: new Map([[InternalChainId.PolygonTestnet, zeroAddress]]), color: '', icon: undefined, id: WebbCurrencyId.MATIC, name: 'Polygon', role: CurrencyRole.Wrappable, symbol: 'MATIC', type: CurrencyType.NATIVE }, [WebbCurrencyId.webbWETH]: { addresses: new Map([ [InternalChainId.Ropsten, '0x105779076d17FAe5EAADF010CA677475549F49E4'], [InternalChainId.Rinkeby, '0x4e7D4BEe028655F2865d9D147cF7B609c516d39C'], [InternalChainId.Goerli, '0x5257c558c246311552A824c491285667B3a445a2'], [InternalChainId.PolygonTestnet, '0x50A7b748F3C50F808a289cA041E48834A41A6d95'], [InternalChainId.OptimismTestnet, '0xEAF873F1F6c91fEf73d4839b5fC7954554BBE518'], [InternalChainId.ArbitrumTestnet, '0xD6F1E78B5F1Ebf8fF5a60C9d52eabFa73E5c5220'] ]), color: '', icon: undefined, id: WebbCurrencyId.webbWETH, name: 'webbETH-test-1', role: CurrencyRole.Governable, symbol: 'webbWETH', type: CurrencyType.ERC20 }, [WebbCurrencyId.DEV]: { addresses: new Map([ [InternalChainId.HermesLocalnet, '0x2946259E0334f33A064106302415aD3391BeD384'], [InternalChainId.AthenaLocalnet, '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b'] ]), color: '', icon: undefined, id: WebbCurrencyId.DEV, name: 'Development Token', role: CurrencyRole.Wrappable, symbol: 'DEV', type: CurrencyType.ERC20 }, [WebbCurrencyId.webbDEV]: { addresses: new Map([ [InternalChainId.HermesLocalnet, '0xD24260C102B5D128cbEFA0F655E5be3c2370677C'], [InternalChainId.AthenaLocalnet, '0xD30C8839c1145609E564b986F667b273Ddcb8496'] ]), color: '', icon: undefined, id: WebbCurrencyId.webbDEV, name: '<NAME> Token', role: CurrencyRole.Governable, symbol: 'webbDEV', type: CurrencyType.ERC20 } }; const mixersConfig: AppConfig['mixers'] = { [InternalChainId.Edgeware]: { tornMixers: [ { address: '0x2B9A7085Afba278BEc6bBfFb399A3C042ED05046', createdAtBlock: 8828000, size: 10000, symbol: 'EDG' } ] }, [InternalChainId.EdgewareTestNet]: { tornMixers: [ { address: '0xf0EA8Fa17daCF79434d10C51941D8Fc24515AbE3', createdAtBlock: 299740, size: 10, symbol: 'tEDG' }, { address: '0xc0d863EE313636F067dCF89e6ea904AD5f8DEC65', createdAtBlock: 299740, size: 100, symbol: 'tEDG' }, { address: '0xc7c6152214d0Db4e161Fa67fB62811Be7326834A', createdAtBlock: 299740, size: 1000, symbol: 'tEDG' }, { address: '0xf0290d80880E3c59512e454E303FcD48f431acA3', createdAtBlock: 299740, size: 10000, symbol: 'tEDG' } ] }, [InternalChainId.Rinkeby]: { tornMixers: [ { address: '0x626FEc5Ffa7Bf1EE8CEd7daBdE545630473E3ABb', createdAtBlock: 8896800, // should be hardcoded to deployed block number size: 0.1, symbol: 'ETH' }, { address: '0x979cBd4917e81447983ef87591B9E1ab21727a61', createdAtBlock: 8896800, size: 1, symbol: 'ETH' } ] }, [InternalChainId.HarmonyTestnet1]: { tornMixers: [ { address: '0x7cd1F52e5EEdf753e99D945276a725CE533AaD1a', createdAtBlock: 12040000, size: 100, symbol: 'ONE' }, { address: '0xD7f9BB9957100310aD397D2bA31771D939BD4731', createdAtBlock: 12892487, size: 1000, symbol: 'ONE' }, { address: '0xeE2eB8F142e48e5D1bDD34e0924Ed3B4aa0d4222', createdAtBlock: 12892648, size: 10000, symbol: 'ONE' }, { address: '0x7cd173094eF78FFAeDee4e14576A73a79aA716ac', createdAtBlock: 12892840, size: 100000, symbol: 'ONE' } ] }, [InternalChainId.HarmonyMainnet0]: { tornMixers: [ { address: '0x2B9A7085Afba278BEc6bBfFb399A3C042ED05046', createdAtBlock: 18796580, size: 100, symbol: 'ONE' }, { address: '0x4b271E1E67B3eE56467599cd46f1F74A5a369c72', createdAtBlock: 18796580, size: 10000, symbol: 'ONE' } ] }, [InternalChainId.Shiden]: { tornMixers: [ { address: '0x2B9A7085Afba278BEc6bBfFb399A3C042ED05046', createdAtBlock: 566000, size: 10, symbol: 'SDN' }, { address: '0x548555a3275B6fadD5d2B9740a7655cB7f856148', createdAtBlock: 568000, size: 1000, symbol: 'SDN' } ] } }; const walletsConfig: AppConfig['wallet'] = {}; export const mockAppConfig: AppConfig = { anchors: anchorsConfig, bridgeByAsset: bridgeConfigByAsset, chains: chainsConfig, currencies: currenciesConfig, mixers: mixersConfig, wallet: walletsConfig };
nepoche/webb.js
packages/api-providers/src/abstracts/currency/orml-currency.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { LoggerService } from '@nepoche/app-util/index.js'; import { WebbPolkadot } from '../../polkadot/index.js'; export type ORMLAsset = { existentialDeposit: string; locked: false; name: string; id: string; }; const logger = LoggerService.get('currencies'); export class ORMLCurrency { constructor (private api: WebbPolkadot) {} async list () { const assets = await this.api.api.query.assetRegistry.assets.entries(); return assets.map(([storageKey, i]) => ({ // @ts-ignore ...i.toHuman(), // @ts-ignore id: storageKey.toHuman()[0] as string })) as ORMLAsset[]; } async getBalance () { const activeAccount = await this.api.accounts.activeOrDefault; logger.info('active account', activeAccount); console.log(this.api.accounts); if (activeAccount) { const ormlBalances = await this.api.api.query.tokens.accounts.entries(activeAccount.address); logger.info(`ORML Balances ${ormlBalances.length}`, ormlBalances); return ormlBalances.map(([storageKey, balance]) => { const currencyId = storageKey[0]; return { balance: balance.toHuman(), id: currencyId }; }); } return []; } }
nepoche/webb.js
packages/api-providers/src/web3/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './webb-provider.js'; export * from './anchor-deposit.js'; export * from './anchor-withdraw.js'; export * from './mixer-withdraw.js'; export * from './mixer-deposit.js'; export * from './wrap-unwrap.js';
nepoche/webb.js
packages/api-providers/src/chains/index.ts
<filename>packages/api-providers/src/chains/index.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './chain-id.enum.js'; export * from './chain-utils.js';
nepoche/webb.js
packages/api-providers/src/contracts/wrappers/webb-anchor.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable camelcase */ import { Log } from '@ethersproject/abstract-provider'; import { anchorDeploymentBlock, bridgeCurrencyBridgeStorageFactory, MixerStorage } from '@nepoche/api-providers/utils/index.js'; import { retryPromise } from '@nepoche/api-providers/utils/retry-promise.js'; import { LoggerService } from '@nepoche/app-util/index.js'; import { ERC20, ERC20__factory as ERC20Factory, FixedDepositAnchor, FixedDepositAnchor__factory } from '@nepoche/contracts'; import { getFixedAnchorExtDataHash } from '@nepoche/utils'; import { BigNumber, Contract, providers, Signer } from 'ethers'; import utils from 'web3-utils'; import { EvmChainMixersInfo } from '../../web3/EvmChainMixersInfo.js'; import { bufferToFixed, createAnchor2Deposit, createRootsBytes, Deposit, EvmNote, generateWithdrawProofCallData } from '../utils/index.js'; import { MerkleTree, PoseidonHasher } from '../utils/merkle/index.js'; import { AnchorWitnessInput, ZKPWebbAnchorInputWithMerkle, ZKPWebbAnchorInputWithoutMerkle } from './types.js'; import { generateWitness, proofAndVerify, zeroAddress } from './webb-utils.js'; const logger = LoggerService.get('AnchorContract'); export interface IPublicInputs { _roots: string; _nullifierHash: string; _refreshCommitment: string; _recipient: string; _relayer: string; _fee: string; _refund: string; } export class AnchorContract { private _contract: FixedDepositAnchor; private readonly signer: Signer; constructor ( public mixersInfo: EvmChainMixersInfo, private web3Provider: providers.Web3Provider, address: string, useProvider = false ) { this.signer = this.web3Provider.getSigner(); logger.info(`Init with address ${address} `); this._contract = new Contract( address, FixedDepositAnchor__factory.abi, useProvider ? this.web3Provider : this.signer ) as any; } get getLastRoot () { return this._contract.getLastRoot(); } get nextIndex () { return this._contract.nextIndex(); } get denomination () { return this._contract.denomination(); } get inner () { return this._contract; } async createDeposit (assetSymbol: string, chainId: number): Promise<{ note: EvmNote; deposit: Deposit }> { const deposit = createAnchor2Deposit(chainId); const depositSizeBN = await this.denomination; const depositSize = Number.parseFloat(utils.fromWei(depositSizeBN.toString(), 'ether')); const note = new EvmNote(assetSymbol, depositSize, chainId, deposit.preimage); return { deposit, note }; } static createTreeWithRoot (leaves: string[], targetRoot: string): MerkleTree | undefined { const tree = MerkleTree.new('eth', 30, [], new PoseidonHasher()); for (let i = 0; i < leaves.length; i++) { tree.insert(leaves[i]); console.log('createTreeWithRoot - leaf: ', leaves[i]); const nextRoot = tree.getRoot(); logger.log(`target root: ${targetRoot} \n this root: ${bufferToFixed(nextRoot)}`); if (bufferToFixed(nextRoot) === targetRoot) { return tree; } } return undefined; } async getWebbToken (): Promise<ERC20> { const tokenAddress = await this._contract.token(); const tokenInstance = ERC20Factory.connect(tokenAddress, this.signer); return tokenInstance; } async isWebbTokenApprovalRequired () { const userAddress = await this.signer.getAddress(); const tokenInstance = await this.getWebbToken(); const tokenAllowance = await tokenInstance.allowance(userAddress, this._contract.address); const depositAmount = await this.denomination; logger.log('tokenAllowance', tokenAllowance); logger.log('depositAmount', depositAmount); if (tokenAllowance < depositAmount) { return true; } return false; } async isWrappableTokenApprovalRequired (tokenAddress: string) { // Native token never requires approval if (tokenAddress === zeroAddress) return false; const userAddress = await this.signer.getAddress(); const webbToken = await this.getWebbToken(); const tokenAllowance = await webbToken.allowance(userAddress, webbToken.address); const depositAmount = await this.denomination; if (tokenAllowance < depositAmount) { return true; } return false; } async hasEnoughBalance (tokenAddress?: string) { const userAddress = await this.signer.getAddress(); const depositAmount = await this.denomination; let tokenBalance: BigNumber; // If a token address was supplied, the user is querying for enough balance of a wrappableToken if (tokenAddress) { // query for native balance if (tokenAddress === zeroAddress) { tokenBalance = await this.signer.getBalance(); } else { const tokenInstance = ERC20Factory.connect(tokenAddress, this.signer); tokenBalance = await tokenInstance.balanceOf(userAddress); } } else { // Querying for balance of the webbToken const tokenInstance = await this.getWebbToken(); tokenBalance = await tokenInstance.balanceOf(userAddress); } if (tokenBalance < depositAmount) { return false; } return true; } async approve (tokenInstance: Contract) { // check the approved spending before attempting deposit if (tokenInstance == null) return; if (tokenInstance != null) { const depositAmount = await this.denomination; const tx = await tokenInstance.approve(this._contract.address, depositAmount); await tx.wait(); } } async deposit (commitment: string) { const overrides = {}; const recipient = await this._contract.deposit(commitment, overrides); await recipient.wait(); } async wrapAndDeposit (commitment: string, tokenAddress: string) { const value = await this._contract.denomination(); if (tokenAddress === zeroAddress) { const overrides = { value: value }; const tx = await this._contract.wrapAndDeposit(zeroAddress, commitment, overrides); await tx.wait(); logger.log('wrapAndDeposit completed for native token to webb token'); } else { const overrides = {}; const tx = await this._contract.wrapAndDeposit(tokenAddress, commitment, overrides); await tx.wait(); logger.log('wrapAndDeposit completed for wrappable asset to webb token'); } } // Verify the leaf occurred at the reported block // This is important to check the behavior of relayers before modifying local storage async leafCreatedAtBlock (leaf: string, blockNumber: number): Promise<boolean> { const filter = this._contract.filters.Deposit(null, null, null); const logs = await this.web3Provider.getLogs({ fromBlock: blockNumber, toBlock: blockNumber, ...filter }); const events = logs.map((log) => this._contract.interface.parseLog(log)); for (let i = 0; i < events.length; i++) { if (events[i].args.commitment === leaf) { return true; } } return false; } async getDepositLeaves ( startingBlock: number, finalBlock: number ): Promise<{ lastQueriedBlock: number; newLeaves: string[] }> { const filter = this._contract.filters.Deposit(null, null, null); logger.trace('Getting leaves with filter', filter); finalBlock = finalBlock || (await this.web3Provider.getBlockNumber()); logger.info(`finalBlock detected as: ${finalBlock}`); let logs: Array<Log> = []; // Read the stored logs into this variable const step = 1024; logger.info(`Fetching leaves with steps of ${step} logs/request`); try { for (let i = startingBlock; i < finalBlock; i += step) { const nextLogs = await retryPromise(() => { return this.web3Provider.getLogs({ fromBlock: i, toBlock: finalBlock - i > step ? i + step : finalBlock, ...filter }); }); logs = [...logs, ...nextLogs]; logger.log(`Getting logs for block range: ${i} through ${i + step}`); } } catch (e) { logger.error(e); throw e; } const events = logs.map((log) => this._contract.interface.parseLog(log)); const newCommitments = events .sort((a, b) => a.args.leafIndex - b.args.leafIndex) // Sort events in chronological order .map((e) => e.args.commitment); return { lastQueriedBlock: finalBlock, newLeaves: newCommitments }; } /* * Generate Merkle Proof * This will * 1- Create the merkle tree with the leaves in local storage * 2- Fetch the missing leaves * 3- Insert the missing leaves * 4- Compare against historical roots before adding to local storage * 5- return the path to the leaf. * */ async generateMerkleProof (deposit: Deposit) { const bridgeStorageStorage = await bridgeCurrencyBridgeStorageFactory(); const storedContractInfo: MixerStorage[0] = (await bridgeStorageStorage.get( this._contract.address.toLowerCase() )) || { lastQueriedBlock: anchorDeploymentBlock[this._contract.address.toString().toLowerCase()] || 0, leaves: [] as string[] }; const treeHeight = await this._contract.levels(); logger.trace(`Generating merkle proof treeHeight ${treeHeight} of deposit`, deposit); const tree = MerkleTree.new('eth', treeHeight, storedContractInfo.leaves, new PoseidonHasher()); // Query for missing blocks starting from the stored endingBlock const lastQueriedBlock = storedContractInfo.lastQueriedBlock; logger.trace('Getting leaves from lastQueriedBlock ', lastQueriedBlock); const fetchedLeaves = await this.getDepositLeaves(lastQueriedBlock + 1, 0); logger.trace(`New Leaves ${fetchedLeaves.newLeaves.length}`, fetchedLeaves.newLeaves); tree.batchInsert(fetchedLeaves.newLeaves); const newRoot = tree.getRoot(); const formattedRoot = bufferToFixed(newRoot); const lastRoot = await this._contract.getLastRoot(); const knownRoot = await this._contract.isKnownRoot(formattedRoot); logger.info(`fromBlock ${formattedRoot} -x- last root ${lastRoot} ---> knownRoot: ${knownRoot}`); // compare root against contract, and store if there is a match const leaves = [...storedContractInfo.leaves, ...fetchedLeaves.newLeaves]; if (knownRoot) { logger.info(`Root is known committing to storage ${this._contract.address}`); await bridgeStorageStorage.set(this._contract.address.toLowerCase(), { lastQueriedBlock: fetchedLeaves.lastQueriedBlock, leaves }); } logger.trace(`Getting leaf index of ${deposit.commitment}`, leaves); const leafIndex = leaves.findIndex((commitment) => commitment === deposit.commitment); logger.info(`Leaf index ${leafIndex}`); return tree.path(leafIndex); } async generateLinkedMerkleProof (sourceDeposit: Deposit, sourceLeaves: string[], sourceChainId: number) { // Grab the root of the source chain to prove against const edgeIndex = await this._contract.edgeIndex(sourceChainId); const edge = await this._contract.edgeList(edgeIndex); logger.log('retrieved edge while generating merkle proof: ', edge); const latestSourceRoot = edge[1]; const tree = AnchorContract.createTreeWithRoot(sourceLeaves, latestSourceRoot); if (tree) { const index = tree.getIndexOfElement(sourceDeposit.commitment); console.log('index of element: ', index); const path = tree.path(index); logger.log('path for proof: ', path); return path; } return undefined; } async merkleProofToZKP ( merkleProof: any, sourceEvmId: number, deposit: Deposit, zkpInputWithoutMerkleProof: ZKPWebbAnchorInputWithoutMerkle ) { const { pathElements, pathIndex: pathIndices, root: merkleRoot } = merkleProof; const localRoot = await this._contract.getLastRoot(); const nr = await this._contract.getLatestNeighborRoots(); const sourceChainRootIndex = (await this._contract.edgeIndex(sourceEvmId)).toNumber(); const root = bufferToFixed(merkleRoot); // create a mutable copy of the returned neighbor roots and overwrite the root used // in the merkle proof const neighborRoots = [...nr]; neighborRoots[sourceChainRootIndex] = root; const input: AnchorWitnessInput = { // public chainID: BigInt(zkpInputWithoutMerkleProof.destinationChainId), fee: String(zkpInputWithoutMerkleProof.fee), nullifier: deposit.nullifier, nullifierHash: deposit.nullifierHash, pathElements, pathIndices, recipient: zkpInputWithoutMerkleProof.recipient, refreshCommitment: bufferToFixed('0'), // private refund: String(zkpInputWithoutMerkleProof.refund), relayer: zkpInputWithoutMerkleProof.relayer, roots: [localRoot, ...neighborRoots], secret: deposit.secret }; const edges = await this._contract.maxEdges(); logger.trace(`Generate witness with edges ${edges}`, input); const witness = await generateWitness(input, edges as any); logger.trace('Generated witness', witness); const proof = await proofAndVerify(witness, edges as any); logger.trace('Zero knowlage proof', proof); return { input, proof: proof.proof, root }; } async generateZKP (deposit: Deposit, zkpInputWithoutMerkleProof: ZKPWebbAnchorInputWithoutMerkle) { logger.trace('Generate zkp with args', { deposit, zkpInputWithoutMerkleProof }); /// which merkle root is the neighbor const merkleProof = await this.generateMerkleProof(deposit); logger.trace('Merkle proof ', merkleProof); const { pathElements, pathIndex: pathIndices, root } = merkleProof; const nr = await this._contract.getLatestNeighborRoots(); logger.trace('Latest Neighbor Roots', nr); const input: AnchorWitnessInput = { // public chainID: BigInt(deposit.chainId!), fee: String(zkpInputWithoutMerkleProof.fee), nullifier: deposit.nullifier, nullifierHash: deposit.nullifierHash, pathElements, pathIndices, recipient: zkpInputWithoutMerkleProof.recipient, refreshCommitment: bufferToFixed('0'), // private refund: String(zkpInputWithoutMerkleProof.refund), relayer: zkpInputWithoutMerkleProof.relayer, roots: [root, ...nr], secret: deposit.secret }; const edges = await this._contract.maxEdges(); logger.trace(`Generate witness with edges ${edges}`, input); const witness = await generateWitness(input, edges as any); logger.trace('Generated witness', witness); const proof = await proofAndVerify(witness, edges as any); logger.trace('Zero knowlage proof', proof); return { input, proof: proof.proof, root }; } async withdraw (proof: any, zkp: ZKPWebbAnchorInputWithMerkle, pub: any): Promise<string> { const overrides = { gasLimit: 6000000 }; const proofBytes = await generateWithdrawProofCallData(proof, pub); const nullifierHash = bufferToFixed(zkp.nullifierHash); const roots = createRootsBytes(pub.roots); const extDataHash = getFixedAnchorExtDataHash({ _fee: bufferToFixed(zkp.fee), _recipient: zkp.recipient, _refreshCommitment: bufferToFixed('0'), _refund: bufferToFixed(zkp.refund), _relayer: zkp.relayer }); const tx = await this._contract.withdraw( { _extDataHash: extDataHash.toHexString(), _nullifierHash: nullifierHash, _roots: roots, proof: `0x${proofBytes}` }, { _fee: bufferToFixed(zkp.fee), _recipient: zkp.recipient, _refreshCommitment: bufferToFixed('0'), _refund: bufferToFixed(zkp.refund), _relayer: zkp.relayer }, overrides ); const receipt = await tx.wait(); return receipt.transactionHash; } /* wrap and unwrap */ }
nepoche/webb.js
packages/api-providers/src/abstracts/wrap-unwrap/index.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { BehaviorSubject, Observable, Subscription } from 'rxjs'; import { WebbCurrencyId } from '../../enums/index.js'; import { MixerSize } from '../mixer/index.js'; /** * * */ export type WrappingEvent = { ready: null; stateUpdate: null; wrappableTokenUpdate: WebbCurrencyId | null; governedTokenUpdate: WebbCurrencyId | null; }; export type WrappingEventNames = keyof WrappingEvent; export type Amount = { amount: number | string; }; export type WrappingBalance = { tokenId?: WebbCurrencyId; balance: string; }; /** * Webb wrap unwrap functionality * Stores two tokens of type {WrappingTokenId} * currentToken , otherEdgeToken * wrap => GovernWrapper<currentToken> and use otherEdgeToken as parameter * unwrap GovernWrapper<otherEdgeToken> and use currentToken as parameter * */ export abstract class WrapUnWrap<T, WrapPayload extends Amount = Amount, UnwrapPayload extends Amount = Amount> { protected _wrappableToken: BehaviorSubject<WebbCurrencyId | null> = new BehaviorSubject<null | WebbCurrencyId>(null); protected _governedToken: BehaviorSubject<WebbCurrencyId | null> = new BehaviorSubject<null | WebbCurrencyId>(null); constructor (protected inner: T) {} abstract get subscription(): Observable<Partial<WrappingEvent>>; setGovernedToken (nextToken: WebbCurrencyId | null) { this._governedToken.next(nextToken); } /** * Current token * */ get governedToken () { return this._governedToken.value; } /** * watcher of the current token * */ get $governedToken () { return this._governedToken.asObservable(); } setWrappableToken (nextToken: WebbCurrencyId | null) { this._wrappableToken.next(nextToken); } /** * Other EDG token * */ get wrappableToken () { return this._wrappableToken.value; } /** * Watcher for other edg token * */ get $wrappableToken () { return this._wrappableToken.asObservable(); } abstract getSizes(): Promise<MixerSize[]>; /** * WrappableTokens available for display, * If a governedTokenId is passed in, get wrappable tokens for that governedTokenId * */ abstract getWrappableTokens(governedTokenId?: WebbCurrencyId | null): Promise<WebbCurrencyId[]>; /** * Get list of all the Governed tokens * */ abstract getGovernedTokens(): Promise<WebbCurrencyId[]>; /** * For validation pre the Wrapping * - Validate the user balance of the token to wrap * - If Wrapping native check if the native token is allowed to be wrapped * */ abstract canWrap(wrapPayload: WrapPayload): Promise<boolean>; /** * Wrap call * - Can wrap a token to a GovernedToken * - Can wrap a token to an ERC20 * */ abstract wrap(wrapPayload: WrapPayload): Promise<string>; /** * For validation * -Check there is enough liquidity * -If UnWrapping to native check if this allowed * */ abstract canUnWrap(unwrapPayload: UnwrapPayload): Promise<boolean>; /** * Unwrap call * - Can Unwrap a token to a GovernedToken * */ abstract unwrap(unwrapPayload: UnwrapPayload): Promise<string>; /** * Observing the balances of the two edges * */ abstract get balances(): Observable<[WrappingBalance, WrappingBalance]>; /** * Observing the liquidity of the two edges * */ abstract get liquidity(): Observable<[WrappingBalance, WrappingBalance]>; } export class WrappingBalanceWatcher { private subscription: Subscription | null = null; constructor ( private token1: WebbCurrencyId | null = null, private token2: WebbCurrencyId | null = null, private signal: Observable<[WebbCurrencyId | null, WebbCurrencyId | null]> ) { this.sub(); } sub () { this.subscription = this.signal.subscribe(([token1, token2]) => { const token1Updated = token1 !== this.token1; const token2Updated = token2 !== this.token2; if (token1Updated) { this.token1 = token1; } if (token2Updated) { this.token2 = token2; } console.log(this.subscription); // **one exists** // ==>one is native // --->> current account balance // one is governed // --->> current account balance // --->> contract balance // two exits // ==>one is native // --->> current account balance // --->> contract balance // ==>two are governed // --->> current account balance // --->> current account balance }); } }
nepoche/webb.js
packages/api-providers/src/contracts/utils/merkle/poseidon-hasher.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 // @ts-ignore import { poseidon } from 'circomlibjs'; import { Hasher } from './merkle-tree.js'; const hashLeftRight = (left: bigint, right: bigint) => { return poseidon([left, right]); }; export class PoseidonHasher implements Hasher { hash (level: any, left: any, right: any): string { return hashLeftRight(BigInt(left), BigInt(right)).toString(); } }
nepoche/webb.js
packages/api-providers/src/abstracts/anchor/anchor-withdraw.ts
<filename>packages/api-providers/src/abstracts/anchor/anchor-withdraw.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { InternalChainId } from '@nepoche/api-providers/chains/chain-id.enum.js'; import { MixerWithdraw } from '../mixer/index.js'; import { WebbApiProvider } from '../webb-provider.interface.js'; import { Bridge } from './anchor.js'; export abstract class AnchorWithdraw<T extends WebbApiProvider<any>> extends MixerWithdraw<T> { get tokens () { return Bridge.getTokens(this.inner.config.currencies); } getTokensOfChain (chainId: InternalChainId) { return Bridge.getTokensOfChain(this.inner.config.currencies, chainId); } }
nepoche/webb.js
packages/api-providers/src/contracts/wrappers/tornado-anchor.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 /* eslint-disable @typescript-eslint/ban-ts-comment */ import { Log } from '@ethersproject/abstract-provider'; import { fetchTornadoCircuitData, fetchTornadoProvingKey, retryPromise } from '@nepoche/api-providers/index.js'; import { LoggerService } from '@nepoche/app-util/index.js'; import { BigNumber, Contract, providers, Signer } from 'ethers'; // @ts-ignore import tornWebSnark from 'tornado-websnark'; import utils from 'web3-utils'; import { EVMChainId } from '../../chains/index.js'; import { EvmChainMixersInfo } from '../../web3/EvmChainMixersInfo.js'; import { WebbError, WebbErrorCodes } from '../../webb-error/index.js'; import { Tornado } from '../tornado/index.js'; import tornadoArtifact from '../tornado/NativeAnchor.json' assert {type: 'json'}; import { bufferToFixed } from '../utils/buffer-to-fixed.js'; import { EvmNote } from '../utils/evm-note.js'; import { createTornDeposit, Deposit } from '../utils/make-deposit.js'; import { MerkleTree, MimcSpongeHasher } from '../utils/merkle/index.js'; import { ZKPTornInputWithMerkle, ZKPTornPublicInputs } from './types.js'; type DepositEvent = [string, number, BigNumber]; const logger = LoggerService.get('anchor'); const mixerLogger = logger; export class TornadoContract { private _contract: Tornado; private readonly signer: Signer; constructor (private mixersInfo: EvmChainMixersInfo, private web3Provider: providers.Web3Provider, address: string) { this.signer = this.web3Provider.getSigner(); this._contract = new Contract(address, tornadoArtifact.abi, this.signer) as any; } get getLastRoot () { return this._contract.getLastRoot(); } get nextIndex () { return this._contract.nextIndex(); } get denomination () { return this._contract.denomination(); } get inner () { return this._contract; } async createDeposit (assetSymbol: string): Promise<{ note: EvmNote; deposit: Deposit }> { const deposit = createTornDeposit(); const chainId = await this.signer.getChainId(); const depositSizeBN = await this.denomination; const depositSize = Number.parseFloat(utils.fromWei(depositSizeBN.toString(), 'ether')); const note = new EvmNote(assetSymbol, depositSize, chainId, deposit.preimage); return { deposit, note }; } async deposit (commitment: string, onComplete?: (event: DepositEvent) => void) { const overrides = { value: await this.denomination }; const filters = await this._contract.filters.Deposit(commitment, null, null); this._contract.once(filters, (commitment: any, insertedIndex: number, timestamp: BigNumber) => { onComplete?.([commitment, insertedIndex, timestamp]); }); const recipient = await this._contract.deposit(commitment, overrides); await recipient.wait(); } private async getDepositLeaves (startingBlock: number): Promise<{ lastQueriedBlock: number; newLeaves: string[] }> { const filter = this._contract.filters.Deposit(null, null, null); const currentBlock = await this.web3Provider.getBlockNumber(); let logs: Array<Log> = []; // Read the stored logs into this variable let step = 20; const chainId = await this.signer.getChainId(); switch (chainId) { case EVMChainId.Beresheet: step = 20; break; case EVMChainId.HarmonyTestnet1: step = 1000; break; case EVMChainId.HarmonyMainnet0: step = 1000; break; case EVMChainId.Rinkeby: step = 5000; break; case EVMChainId.Shiden: step = 1000; break; } try { logs = await this.web3Provider.getLogs({ fromBlock: startingBlock, toBlock: currentBlock, ...filter }); } catch (e) { mixerLogger.log(e); // If there is a timeout, query the logs in block increments. if ((e as any)?.code === -32603) { for (let i = startingBlock; i < currentBlock; i += step) { const nextLogs = await retryPromise(() => { return this.web3Provider.getLogs({ fromBlock: i, toBlock: currentBlock - i > step ? i + step : currentBlock, ...filter }); }); logs = [...logs, ...nextLogs]; mixerLogger.log(`Getting logs for block range: ${i} through ${i + step}`); } } else { throw e; } } const events = logs.map((log) => this._contract.interface.parseLog(log)); const newCommitments = events .sort((a, b) => a.args.leafIndex - b.args.leafIndex) // Sort events in chronological order .map((e) => e.args.commitment); return { lastQueriedBlock: currentBlock, newLeaves: newCommitments }; } /* * Generate Merkle Proof * This will * 1- Create the merkle tree with the leaves in local storage * 2- Fetch the missing leaves * 3- Insert the missing leaves * 4- Compare against historical roots before adding to local storage * 5- return the path to the leaf. * */ async generateMerkleProof (deposit: Deposit) { const storedContractInfo = await this.mixersInfo.getMixerStorage(this._contract.address); const treeHeight = await this._contract.levels(); const tree = MerkleTree.new('eth', treeHeight, storedContractInfo.leaves, new MimcSpongeHasher()); // Query for missing blocks starting from the stored endingBlock const lastQueriedBlock = storedContractInfo.lastQueriedBlock; const fetchedLeaves = await this.getDepositLeaves(lastQueriedBlock + 1); logger.trace(`New Leaves ${fetchedLeaves.newLeaves.length}`, fetchedLeaves.newLeaves); tree.batchInsert(fetchedLeaves.newLeaves); const newRoot = tree.getRoot(); const formattedRoot = bufferToFixed(newRoot); const knownRoot = await this._contract.isKnownRoot(formattedRoot); logger.info(`knownRoot: ${knownRoot}`); // compare root against contract, and store if there is a match if (knownRoot) { await this.mixersInfo.setMixerStorage(this._contract.address, fetchedLeaves.lastQueriedBlock, [ ...storedContractInfo.leaves, ...fetchedLeaves.newLeaves ]); } const leafIndex = [...storedContractInfo.leaves, ...fetchedLeaves.newLeaves].findIndex( (commitment) => commitment === bufferToFixed(deposit.commitment) ); logger.info(`Leaf index ${leafIndex}`); return tree.path(leafIndex); } async generateZKP (deposit: Deposit, zkpPublicInputs: ZKPTornPublicInputs) { const merkleProof = await this.generateMerkleProof(deposit); const { pathElements, pathIndex: pathIndices, root } = merkleProof; const circuitData = await fetchTornadoCircuitData(); const provingKey = await fetchTornadoProvingKey(); const zkpInput: ZKPTornInputWithMerkle = { ...zkpPublicInputs, nullifier: deposit.nullifier, pathElements, pathIndices, root: root as string, secret: deposit.secret }; const proofsData = await tornWebSnark.utils.genWitnessAndProve( // @ts-ignore window.groth16, zkpInput, circuitData, provingKey ); const { proof } = await tornWebSnark.utils.toSolidityInput(proofsData); return { input: zkpInput, proof }; } // function to call when generating ZKP with a relayer async generateZKPWithLeaves ( deposit: Deposit, zkpPublicInputs: ZKPTornPublicInputs, leaves: string[], lastQueriedBlock: number ) { // Build a local merkle tree from the leaves const treeHeight = await this._contract.levels(); const tree = MerkleTree.new('eth', treeHeight, leaves, new MimcSpongeHasher()); const leafIndex = leaves.findIndex((commitment) => commitment === bufferToFixed(deposit.commitment)); logger.info(`Leaf index ${leafIndex}`); const merkleProof = tree.path(leafIndex); // Verify the local merkle tree against what is on chain const newRoot = tree.getRoot(); const formattedRoot = bufferToFixed(newRoot); const knownRoot = await this._contract.isKnownRoot(formattedRoot); if (!knownRoot) { throw WebbError.from(WebbErrorCodes.RelayerMisbehaving); } // verify the last commitment in the leaves occurred at the reported block const filter = this._contract.filters.Deposit(null, null, null); const logs = await this.web3Provider.getLogs({ fromBlock: lastQueriedBlock, toBlock: lastQueriedBlock, ...filter }); const events = logs.map((log) => this._contract.interface.parseLog(log)); let validLatestDeposit = false; events.forEach((event) => { if (event.args.find((elem) => elem === leaves[leaves.length - 1])) { validLatestDeposit = true; } }); // If the last commitment occurred at the reported block and // the block is later than what we have stored, save into storage const storedContractInfo = await this.mixersInfo.getMixerStorage(this._contract.address); if (validLatestDeposit && lastQueriedBlock > storedContractInfo.lastQueriedBlock) { await this.mixersInfo.setMixerStorage(this._contract.address, lastQueriedBlock, [...leaves]); } const { pathElements, pathIndex: pathIndices, root } = merkleProof; const circuitData = await fetchTornadoCircuitData(); const provingKey = await fetchTornadoProvingKey(); const zkpInput: ZKPTornInputWithMerkle = { ...zkpPublicInputs, nullifier: deposit.nullifier, pathElements, pathIndices, root: root as string, secret: deposit.secret }; const proofsData = await tornWebSnark.utils.genWitnessAndProve( // @ts-ignore window.groth16, zkpInput, circuitData, provingKey ); const { proof } = await tornWebSnark.utils.toSolidityInput(proofsData); return { input: zkpInput, proof }; } async withdraw (proof: any, zkp: ZKPTornInputWithMerkle) { // tx config const overrides = {}; const tx = await this._contract.withdraw( proof, bufferToFixed(zkp.root), bufferToFixed(zkp.nullifierHash), zkp.recipient, zkp.relayer, bufferToFixed(zkp.fee), bufferToFixed(zkp.refund), overrides ); return tx; } }
nepoche/webb.js
packages/api-providers/src/polkadot/chain-query.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { ChainQuery } from '../abstracts/index.js'; import { WebbCurrencyId } from '../enums/index.js'; import { WebbPolkadot } from './webb-provider.js'; export class PolkadotChainQuery extends ChainQuery<WebbPolkadot> { constructor (protected inner: WebbPolkadot) { super(inner); } // eslint-disable-next-line @typescript-eslint/no-unused-vars async tokenBalanceByCurrencyId (currency: WebbCurrencyId): Promise<string> { return ''; } // eslint-disable-next-line @typescript-eslint/no-unused-vars async tokenBalanceByAddress (address: string): Promise<string> { return ''; } }
nepoche/webb.js
packages/api-providers/src/utils/relayer-utils.ts
<reponame>nepoche/webb.js<filename>packages/api-providers/src/utils/relayer-utils.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { InternalChainId } from '../chains/index.js'; export function relayerSubstrateNameToChainId (name: string): InternalChainId { switch (name) { case 'localnode': return InternalChainId.WebbDevelopment; } throw new Error('unhandled relayed chain name ' + name); } export function relayerNameToChainId (name: string): InternalChainId { switch (name) { case 'beresheet': return InternalChainId.EdgewareTestNet; case 'harmonytestnet1': return InternalChainId.HarmonyTestnet1; case 'harmonytestnet0': return InternalChainId.HarmonyTestnet0; case 'harmonymainnet0': return InternalChainId.HarmonyMainnet0; case 'ganache': return InternalChainId.Ganache; case 'webb': case 'edgeware': case 'hedgeware': break; case 'ropsten': return InternalChainId.Ropsten; case 'rinkeby': return InternalChainId.Rinkeby; case 'goerli': return InternalChainId.Goerli; case 'kovan': return InternalChainId.Kovan; case 'shiden': return InternalChainId.Shiden; case 'optimismtestnet': return InternalChainId.OptimismTestnet; case 'arbitrumtestnet': return InternalChainId.ArbitrumTestnet; case 'polygontestnet': return InternalChainId.PolygonTestnet; } throw new Error('unhandled relayed chain name ' + name); } enum RelayerChainName { Edgeware = 'edgeware', Webb = 'webb', Ganache = 'ganache', Beresheet = 'beresheet', HarmonyTestnet0 = 'harmonytestnet0', HarmonyTestnet1 = 'harmonytestnet1', HarmonyMainnet0 = 'harmonymainnet0', Ropsten = 'ropsten', Rinkeby = 'rinkeby', Goerli = 'goerli', Kovan = 'kovan', Shiden = 'shiden', OptimismTestnet = 'optimismtestnet', ArbitrumTestnet = 'arbitrumtestnet', PolygonTestnet = 'polygontestnet' } export function chainIdToRelayerName (id: InternalChainId): string { switch (id) { case InternalChainId.Edgeware: return RelayerChainName.Edgeware; case InternalChainId.EdgewareTestNet: return RelayerChainName.Beresheet; case InternalChainId.EdgewareLocalNet: break; case InternalChainId.EthereumMainNet: break; case InternalChainId.Rinkeby: return RelayerChainName.Rinkeby; case InternalChainId.Ropsten: return RelayerChainName.Ropsten; case InternalChainId.Kovan: return RelayerChainName.Kovan; case InternalChainId.Goerli: return RelayerChainName.Goerli; case InternalChainId.HarmonyTestnet0: return RelayerChainName.HarmonyTestnet0; case InternalChainId.HarmonyTestnet1: return RelayerChainName.HarmonyTestnet1; case InternalChainId.HarmonyMainnet0: return RelayerChainName.HarmonyMainnet0; case InternalChainId.Shiden: return RelayerChainName.Shiden; case InternalChainId.OptimismTestnet: return RelayerChainName.OptimismTestnet; case InternalChainId.ArbitrumTestnet: return RelayerChainName.ArbitrumTestnet; case InternalChainId.PolygonTestnet: return RelayerChainName.PolygonTestnet; } throw new Error(`unhandled Chain id ${id}`); }
nepoche/webb.js
packages/api-providers/src/contracts/utils/zkp-adapters.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { bufferToFixed, Deposit } from '../utils/index.js'; import { ZKPTornPublicInputs } from '../wrappers/index.js'; export type ZKPTornFromDepositInput = { relayer?: string; recipient: string; refund?: number; fee?: number; }; export function fromDepositIntoZKPTornPublicInputs ( deposit: Deposit, data: ZKPTornFromDepositInput ): ZKPTornPublicInputs { return { fee: data.fee || 0, // public nullifierHash: deposit.nullifierHash, recipient: data.recipient, refund: data.refund || 0, relayer: data.relayer ? data.relayer : bufferToFixed(0) }; }
nepoche/webb.js
packages/types/src/interfaces/augment-api-query.d.ts
<gh_stars>0 // Auto-generated via `yarn polkadot-types-from-chain`, do not edit /* eslint-disable */ import type { DarkwebbStandaloneRuntimeElement, OrmlTokensAccountData, OrmlTokensBalanceLock, PalletAnchorAnchorMetadata, PalletAssetRegistryAssetDetails, PalletAssetRegistryAssetMetadata, PalletMixerMixerMetadata } from '@nepoche/types/interfaces/pallets'; import type { AccountId32 } from '@nepoche/types/interfaces/runtime'; import type { ApiTypes } from '@polkadot/api-base/types'; import type { Bytes, Null, Option, Vec, bool, u128, u32 } from '@polkadot/types-codec'; import type { AnyNumber } from '@polkadot/types-codec/types'; import type { Observable } from '@polkadot/types/types'; import type { DarkwebbStandaloneRuntimeElement, OrmlTokensAccountData, OrmlTokensBalanceLock, PalletAnchorAnchorMetadata, PalletAssetRegistryAssetDetails, PalletAssetRegistryAssetMetadata, PalletMixerMixerMetadata } from '@nepoche/types/interfaces/pallets'; import type { AccountId32 } from '@nepoche/types/interfaces/runtime'; declare module '@polkadot/api-base/types/storage' { export interface AugmentedQueries<ApiType extends ApiTypes> { anchorBls381: { /** * The map of trees to their anchor metadata **/ anchors: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Option<PalletAnchorAnchorMetadata>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>; /** * The map of trees to their spent nullifier hashes **/ nullifierHashes: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => Observable<bool>, [u32, DarkwebbStandaloneRuntimeElement]> & QueryableStorageEntry<ApiType, [u32, DarkwebbStandaloneRuntimeElement]>; /** * Generic query **/ [key: string]: QueryableStorageEntry<ApiType>; }; anchorBn254: { /** * The map of trees to their anchor metadata **/ anchors: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Option<PalletAnchorAnchorMetadata>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>; /** * The map of trees to their spent nullifier hashes **/ nullifierHashes: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => Observable<bool>, [u32, DarkwebbStandaloneRuntimeElement]> & QueryableStorageEntry<ApiType, [u32, DarkwebbStandaloneRuntimeElement]>; /** * Generic query **/ [key: string]: QueryableStorageEntry<ApiType>; }; assetRegistry: { /** * Mapping between asset name and asset id. **/ assetIds: AugmentedQuery<ApiType, (arg: Bytes | string | Uint8Array) => Observable<Option<u32>>, [Bytes]> & QueryableStorageEntry<ApiType, [Bytes]>; /** * Native location of an asset. **/ assetLocations: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Option<Null>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>; /** * Metadata of an asset. **/ assetMetadataMap: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Option<PalletAssetRegistryAssetMetadata>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>; /** * Details of an asset. **/ assets: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Option<PalletAssetRegistryAssetDetails>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>; /** * Local asset for native location. **/ locationAssets: AugmentedQuery<ApiType, (arg: Null | null) => Observable<Option<u32>>, [Null]> & QueryableStorageEntry<ApiType, [Null]>; /** * Next available asset id. This is sequential id assigned for each new * registered asset. **/ nextAssetId: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>; /** * Generic query **/ [key: string]: QueryableStorageEntry<ApiType>; }; mixerBls381: { /** * The parameter maintainer who can change the parameters **/ maintainer: AugmentedQuery<ApiType, () => Observable<AccountId32>, []> & QueryableStorageEntry<ApiType, []>; /** * The map of trees to their mixer metadata **/ mixers: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Option<PalletMixerMixerMetadata>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>; /** * The map of trees to their spent nullifier hashes **/ nullifierHashes: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => Observable<bool>, [u32, DarkwebbStandaloneRuntimeElement]> & QueryableStorageEntry<ApiType, [u32, DarkwebbStandaloneRuntimeElement]>; /** * Generic query **/ [key: string]: QueryableStorageEntry<ApiType>; }; mixerBn254: { /** * The parameter maintainer who can change the parameters **/ maintainer: AugmentedQuery<ApiType, () => Observable<AccountId32>, []> & QueryableStorageEntry<ApiType, []>; /** * The map of trees to their mixer metadata **/ mixers: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<Option<PalletMixerMixerMetadata>>, [u32]> & QueryableStorageEntry<ApiType, [u32]>; /** * The map of trees to their spent nullifier hashes **/ nullifierHashes: AugmentedQuery<ApiType, (arg1: u32 | AnyNumber | Uint8Array, arg2: DarkwebbStandaloneRuntimeElement | string | Uint8Array) => Observable<bool>, [u32, DarkwebbStandaloneRuntimeElement]> & QueryableStorageEntry<ApiType, [u32, DarkwebbStandaloneRuntimeElement]>; /** * Generic query **/ [key: string]: QueryableStorageEntry<ApiType>; }; tokens: { /** * The balance of a token type under an account. * * NOTE: If the total is ever zero, decrease account ref account. * * NOTE: This is only used in the case that this module is used to store * balances. **/ accounts: AugmentedQuery<ApiType, (arg1: AccountId32 | string | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<OrmlTokensAccountData>, [AccountId32, u32]> & QueryableStorageEntry<ApiType, [AccountId32, u32]>; /** * Any liquidity locks of a token type under an account. * NOTE: Should only be accessed when setting, changing and freeing a lock. **/ locks: AugmentedQuery<ApiType, (arg1: AccountId32 | string | Uint8Array, arg2: u32 | AnyNumber | Uint8Array) => Observable<Vec<OrmlTokensBalanceLock>>, [AccountId32, u32]> & QueryableStorageEntry<ApiType, [AccountId32, u32]>; /** * The total issuance of a token type. **/ totalIssuance: AugmentedQuery<ApiType, (arg: u32 | AnyNumber | Uint8Array) => Observable<u128>, [u32]> & QueryableStorageEntry<ApiType, [u32]>; /** * Generic query **/ [key: string]: QueryableStorageEntry<ApiType>; }; } // AugmentedQueries } // declare module
nepoche/webb.js
packages/api-providers/src/abstracts/currency/currency.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { ChainTypeId, InternalChainId } from '../../chains/index.js'; import { WebbCurrencyId } from '../../enums/index.js'; import { CurrencyConfig, CurrencyRole, CurrencyView } from '../../types/currency-config.interface.js'; import { AppConfig } from '../common.js'; import { ORMLAsset } from './orml-currency.js'; export abstract class CurrencyContent { abstract get view(): CurrencyView; } // This currency class assumes that instances are wrappable assets. export class Currency extends CurrencyContent { constructor (private data: Omit<CurrencyConfig, 'id'> & { id: string | WebbCurrencyId }) { super(); } get id () { return this.data.id; } static fromCurrencyId (currenciesConfig: AppConfig['currencies'], currencyId: WebbCurrencyId) { const currencyConfig = currenciesConfig[currencyId]; return new Currency(currencyConfig); } // TODO: this should be removed instead use the constructor static fromORMLAsset (currenciesConfig: AppConfig['currencies'], asset: ORMLAsset): Currency { return new Currency({ ...currenciesConfig[WebbCurrencyId.WEBB], addresses: new Map([[InternalChainId.WebbDevelopment, asset.id]]), id: `ORML@${asset.id}`, name: asset.name, symbol: asset.name.slice(0, 3).toLocaleUpperCase() }); } static isWrappableCurrency (currenciesConfig: AppConfig['currencies'], currencyId: WebbCurrencyId) { if (currenciesConfig[currencyId].role === CurrencyRole.Wrappable) return true; return false; } getAddress (chain: InternalChainId): string | undefined { return this.data.addresses.get(chain); } hasChain (chain: InternalChainId): boolean { return this.data.addresses.has(chain); } getChainIds (): InternalChainId[] { return Array.from(this.data.addresses.keys()); } getChainIdsAndTypes (chainsConfig: AppConfig['chains']): ChainTypeId[] { return Array.from(this.data.addresses.keys()).map((internalId: any) => { return { chainId: chainsConfig[internalId].chainId, chainType: chainsConfig[internalId].chainType }; }); } get view (): CurrencyView { return { color: this.data.color, icon: this.data.icon, id: this.data.id as any, name: this.data.name, symbol: this.data.symbol, type: this.data.type }; } }
nepoche/webb.js
packages/types/src/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { rpc as webbRpc, types as webbTypes, typesAlias as webbTypeAlias, typesBundle as webbTypesBundle } from '@nepoche/type-definitions/index.js'; import { DefinitionRpc, DefinitionRpcSub, OverrideBundleType, OverrideModuleType, RegistryTypes } from '@polkadot/types/types'; /// <reference path="./interfaces/augment-api-consts.d.ts" /> /// <reference path="./interfaces/augment-api-tx.d.ts" /> /// <reference path="./interfaces/augment-api-query.d.ts" /> /// <reference path="./interfaces/augment-types.d.ts" /> const types: RegistryTypes = webbTypes; const rpc: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>> = webbRpc; const typesAlias: Record<string, OverrideModuleType> = webbTypeAlias; const typesBundle = webbTypesBundle as unknown as OverrideBundleType; export default { rpc, types, typesAlias, typesBundle };
nepoche/webb.js
packages/api-providers/src/abstracts/chain-query/index.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 // The chain query class returns information from the selected provider import { WebbCurrencyId } from '../../enums/index.js'; export abstract class ChainQuery<Provider> { constructor (protected inner: Provider) {} abstract tokenBalanceByCurrencyId(currency: WebbCurrencyId): Promise<string>; abstract tokenBalanceByAddress(address: string): Promise<string>; }
nepoche/webb.js
packages/api-providers/src/ipfs/evm/tornados.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { getCachedFixtureURI, withLocalFixtures } from '@nepoche/api-providers/index.js'; export const fetchTornadoCircuitData = async () => { const IPFSUrl = 'https://ipfs.io/ipfs/QmbX8PzkcU1SQwUis3zDWEKsn8Yjgy2vALNeghVM2uh31B'; const cachedURI = getCachedFixtureURI('circuit_tornado.json'); const ipfsRequest = await fetch(withLocalFixtures() ? cachedURI : IPFSUrl); const circuitData = await ipfsRequest.json(); return circuitData; }; export const fetchTornadoProvingKey = async () => { const IPFSUrl = 'https://ipfs.io/ipfs/QmQwgF8aWJzGSXoe1o3jrEPdcfBysWctB2Uwu7uRebXe2D'; const cachedURI = getCachedFixtureURI('proving_key_tornado.bin'); const ipfsRequest = await fetch(withLocalFixtures() ? cachedURI : IPFSUrl); const provingKey = await ipfsRequest.arrayBuffer(); return provingKey; };
nepoche/webb.js
packages/api/src/index.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import webbTypesPkg from '@nepoche/types/index.js'; import { ApiOptions } from '@polkadot/api/types'; const { rpc: webbRpc, types: webbTypes, typesAlias: webbTypesAlias, typesBundle: webbTypesBundle } = webbTypesPkg; export const defaultOptions: ApiOptions = { rpc: webbRpc, types: webbTypes }; /** * * @returns Returns the `ApiOptions` for a Webb `protocol-substrate` node. */ export const options = ({ types = {}, rpc = {}, typesAlias = {}, typesBundle = {}, ...otherOptions }: ApiOptions = {}): ApiOptions => ({ rpc: { ...webbRpc, ...rpc }, types: { ...webbTypes, ...types }, typesAlias: { ...webbTypesAlias, ...typesAlias }, typesBundle: { ...typesBundle, spec: { ...typesBundle.spec, webb: { ...webbTypesBundle?.spec?.webb, ...typesBundle?.spec?.webb } } }, ...otherOptions }); /** * * @param chainTypes An object containing the `types` and `typesBundle` of another chain * @returns The `ApiOptions` of the chain with Webb's types added. */ export const optionsWithChain = (chainTypes: any) => ({ types = {}, rpc = {}, typesAlias = {}, typesBundle = {}, ...otherOptions }: ApiOptions = {}): ApiOptions => ({ rpc: { ...webbRpc, ...rpc }, types: { ...webbTypes, ...chainTypes.types, ...types, Address: 'MultiAddress', LookupSource: 'MultiAddress' }, typesAlias: { ...webbTypesAlias, ...typesAlias }, typesBundle: { ...typesBundle, spec: { ...typesBundle.spec, ...chainTypes.typesBundle.spec, webb: { ...webbTypesBundle?.spec?.webb, ...typesBundle?.spec?.webb } } }, ...otherOptions });
nepoche/webb.js
packages/api-providers/src/abstracts/relayer/webb-relayer.class.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { getAnchorAddressForBridge } from '@nepoche/api-providers/index.js'; import { LoggerService } from '@nepoche/app-util/index.js'; import { Observable, Subject } from 'rxjs'; import { filter } from 'rxjs/operators'; import { InternalChainId } from '../../chains/index.js'; import { webbCurrencyIdFromString } from '../../enums/index.js'; import { EvmChainMixersInfo } from '../../web3/EvmChainMixersInfo.js'; import { AppConfig } from '../common.js'; import { Capabilities, EVMCMDKeys, RelayedChainConfig, RelayerCMDBase, RelayerCMDKey, RelayerConfig, RelayerEVMCommands, RelayerMessage, RelayerSubstrateCommands, SubstrateCMDKeys } from './types.js'; const logger = LoggerService.get('webb-relayer class'); const shuffleRelayers = (arr: WebbRelayer[]): WebbRelayer[] => { let currentIndex = arr.length; let randomIndex = 0; while (currentIndex !== 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; [arr[currentIndex], arr[randomIndex]] = [arr[randomIndex], arr[currentIndex]]; } return arr; }; type MixerQuery = { amount: number; tokenSymbol: string; }; type RelayerQuery = { baseOn?: 'evm' | 'substrate'; ipService?: true; chainId?: InternalChainId; contractAddress?: string; tornadoSupport?: MixerQuery; bridgeSupport?: MixerQuery; }; export type RelayedChainInput = { endpoint: string; name: string; baseOn: RelayerCMDBase; // TODO: change to just contract contractAddress: string; }; export type TornadoRelayerWithdrawArgs = { root: string; nullifierHash: string; recipient: string; relayer: string; fee: string; refund: string; }; export type BridgeRelayerWithdrawArgs = { roots: number[]; refreshCommitment: string; nullifierHash: string; recipient: string; relayer: string; fee: string; refund: string; }; export type ContractBase = 'tornado' | 'anchor'; type CMDSwitcher<T extends RelayerCMDBase> = T extends 'evm' ? EVMCMDKeys : SubstrateCMDKeys; export type RelayerCMDs<A extends RelayerCMDBase, C extends CMDSwitcher<A>> = A extends 'evm' ? C extends keyof RelayerEVMCommands ? RelayerEVMCommands[C] : never : C extends keyof RelayerSubstrateCommands ? RelayerSubstrateCommands[C] : never; export type WithdrawRelayerArgs<A extends RelayerCMDBase, C extends CMDSwitcher<A>> = Omit< RelayerCMDs<A, C>, keyof RelayedChainInput | 'proof' >; export interface RelayerInfo { substrate: Record<string, RelayedChainConfig | null>; evm: Record<string, RelayedChainConfig | null>; } export type ChainNameIntoChainId = (name: string, basedOn: 'evm' | 'substrate') => InternalChainId | null; /** * Webb relayers manager * this will fetch/mange/provide this relayers and there capabilities * * */ export class WebbRelayerBuilder { /// storage for relayers capabilities private capabilities: Record<RelayerConfig['endpoint'], Capabilities> = {}; private _listUpdated = new Subject<void>(); public readonly listUpdated: Observable<void>; private constructor ( protected relayerConfigs: RelayerConfig[], private readonly chainNameAdapter: ChainNameIntoChainId, private appConfig: AppConfig ) { this.listUpdated = this._listUpdated.asObservable(); } /// Mapping the fetched relayers info to the Capabilities store private static infoIntoCapabilities ( _nfig: RelayerConfig, info: RelayerInfo, nameAdapter: ChainNameIntoChainId ): Capabilities { console.log('received info: ', info); return { hasIpService: true, supportedChains: { evm: info.evm ? Object.keys(info.evm) .filter( /** * account is deprecated but it's kept here for backward compatibility * */ (key) => (info.evm[key]?.account || info.evm[key]?.beneficiary) && nameAdapter(key, 'evm') != null ) .reduce((m, key) => { m.set(nameAdapter(key, 'evm'), info.evm[key]); return m; }, new Map()) : new Map(), substrate: info.substrate ? Object.keys(info.substrate) .filter((key) => info.substrate[key]?.beneficiary && nameAdapter(key, 'substrate') != null) .reduce((m, key) => { m.set(nameAdapter(key, 'substrate'), info.substrate[key]); return m; }, new Map()) : new Map() } }; } /// fetch relayers private async fetchCapabilitiesAndInsert (config: RelayerConfig) { this.capabilities[config.endpoint] = await this.fetchCapabilities(config.endpoint); return this.capabilities; } public async fetchCapabilities (endpoint: string): Promise<Capabilities> { const res = await fetch(`${endpoint}/api/v1/info`); const info: RelayerInfo = await res.json(); return WebbRelayerBuilder.infoIntoCapabilities( { endpoint }, info, this.chainNameAdapter ); } public async addRelayer (endpoint: string) { const c = await this.fetchCapabilitiesAndInsert({ endpoint }); this._listUpdated.next(); return c; } /** * init the builder * create new instance and fetch the relayers * */ static async initBuilder ( config: RelayerConfig[], chainNameAdapter: ChainNameIntoChainId, appConfig: AppConfig ): Promise<WebbRelayerBuilder> { const relayerBuilder = new WebbRelayerBuilder(config, chainNameAdapter, appConfig); // For all relayers in the relayerConfigs, fetch the info - but timeout after 5 seconds // This is done to prevent issues with relayers which are not operating properly await Promise.allSettled( config.map((p) => { return Promise.race([ relayerBuilder.fetchCapabilitiesAndInsert(p), new Promise((resolve) => { setTimeout(resolve.bind(null, null), 5000); }) ]); }) ); console.log(relayerBuilder); return relayerBuilder; } /* * get a list of the suitable relaryes for a given query * the list is randomized * */ getRelayer (query: RelayerQuery): WebbRelayer[] { const { baseOn, bridgeSupport, chainId, contractAddress, ipService, tornadoSupport } = query; const relayers = Object.keys(this.capabilities) .filter((key) => { const capabilities = this.capabilities[key]; if (ipService) { if (!capabilities.hasIpService) { return false; } } if (contractAddress && baseOn && chainId) { if (baseOn === 'evm') { return Boolean( capabilities.supportedChains[baseOn] .get(chainId) ?.contracts?.find( (contract) => contract.address === contractAddress.toLowerCase() && contract.eventsWatcher.enabled ) ); } } if (tornadoSupport && baseOn && chainId) { if (baseOn === 'evm') { const evmId = this.appConfig.chains[chainId].chainId; const mixersInfoForChain = new EvmChainMixersInfo(this.appConfig, evmId); const mixerInfo = mixersInfoForChain.getTornMixerInfoBySize( tornadoSupport.amount, tornadoSupport.tokenSymbol ); if (mixerInfo) { return Boolean( capabilities.supportedChains[baseOn] .get(chainId) ?.contracts?.find( (contract) => contract.address === mixerInfo.address.toLowerCase() && contract.eventsWatcher.enabled ) ); } else { return false; } } } if (bridgeSupport && baseOn && chainId) { if (baseOn === 'evm') { const bridgeAddress = getAnchorAddressForBridge( webbCurrencyIdFromString(bridgeSupport.tokenSymbol), chainId, bridgeSupport.amount, this.appConfig.bridgeByAsset ); if (bridgeAddress) { return Boolean( capabilities.supportedChains[baseOn] .get(chainId) ?.contracts?.find( (contract) => contract.address === bridgeAddress.toLowerCase() && contract.eventsWatcher.enabled ) ); } else { return false; } } } if (baseOn && chainId) { return Boolean(capabilities.supportedChains[baseOn].get(chainId)); } if (baseOn && !chainId) { console.log(capabilities.supportedChains, baseOn); return capabilities.supportedChains[baseOn].size > 0; } return true; }) .map((key) => { return new WebbRelayer(key, this.capabilities[key]); }); shuffleRelayers(relayers); return relayers; } } export enum RelayedWithdrawResult { /// the withdraw hasnt yet started PreFlight, /// the withdraw has been submitted to the relayers and no response yet OnFlight, // the withdraw is being processed Continue, /// the withdraw is done with success CleanExit, /// failed to create the withdraw Errored } type RelayerLeaves = { leaves: string[]; lastQueriedBlock: number; }; class RelayedWithdraw { /// status of the withdraw private status: RelayedWithdrawResult = RelayedWithdrawResult.PreFlight; /// watch for the current withdraw status readonly watcher: Observable<[RelayedWithdrawResult, string | undefined]>; private emitter: Subject<[RelayedWithdrawResult, string | undefined]> = new Subject(); constructor (private ws: WebSocket, private prefix: RelayerCMDKey) { this.watcher = this.emitter.asObservable(); ws.onmessage = ({ data }) => { const handledMessage = this.handleMessage(JSON.parse(data)); this.status = handledMessage[0]; this.emitter.next(handledMessage); if (this.status === RelayedWithdrawResult.CleanExit) { this.emitter.complete(); this.ws.close(); } }; ws.onerror = (e) => { console.log(e); }; } private handleMessage = (data: RelayerMessage): [RelayedWithdrawResult, string | undefined] => { if (data.error || data.withdraw?.errored) { return [RelayedWithdrawResult.Errored, data.error || data.withdraw?.errored?.reason]; } else if (data.network === 'invalidRelayerAddress') { return [RelayedWithdrawResult.Errored, 'Invalid relayer address']; } else if (data.withdraw?.finalized) { return [RelayedWithdrawResult.CleanExit, data.withdraw.finalized.txHash]; } else { return [RelayedWithdrawResult.Continue, undefined]; } }; generateWithdrawRequest<T extends RelayedChainInput, C extends CMDSwitcher<T['baseOn']>> ( chain: T, proof: RelayerCMDs<T['baseOn'], C>['proof'], args: WithdrawRelayerArgs<T['baseOn'], C> ) { return { [chain.baseOn]: { [this.prefix]: { contract: chain.contractAddress, proof, ...args } } }; } send (withdrawRequest: any) { if (this.status !== RelayedWithdrawResult.PreFlight) { throw Error('there is a withdraw process running'); } this.status = RelayedWithdrawResult.OnFlight; this.ws.send(JSON.stringify(withdrawRequest)); } await () { return this.watcher .pipe( filter(([next]) => { return next === RelayedWithdrawResult.CleanExit || next === RelayedWithdrawResult.Errored; }) ) .toPromise(); } get currentStatus () { return this.status; } } export class WebbRelayer { constructor (readonly endpoint: string, readonly capabilities: Capabilities) {} async initWithdraw<Target extends RelayerCMDKey> (target: Target) { const ws = new WebSocket(this.endpoint.replace('http', 'ws') + '/ws'); await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = reject; }); /// insure the socket is open /// maybe removed soon for (;;) { if (ws.readyState === 1) { break; } await new Promise((resolve) => { setTimeout(resolve, 300); }); } return new RelayedWithdraw(ws, target); } async getIp (): Promise<string> { const req = await fetch(`${this.endpoint}/api/v1/ip`); if (req.ok) { return req.json(); } else { throw new Error('network error'); } } // chainId should be formatted as a hex string async getLeaves (chainId: string, contractAddress: string): Promise<RelayerLeaves> { const url = `${this.endpoint}/api/v1/leaves/${chainId}/${contractAddress}`; logger.info(`fetching info from: ${url}`); const req = await fetch(url); if (req.ok) { const jsonResponse = await req.json(); const fetchedLeaves: string[] = jsonResponse.leaves; const lastQueriedBlock: string = jsonResponse.lastQueriedBlock; const lastQueriedBlockNumber: number = parseInt(lastQueriedBlock, 16); logger.info(`info fetched from relayer: ${fetchedLeaves} + ${lastQueriedBlockNumber}`); return { lastQueriedBlock: lastQueriedBlockNumber, leaves: fetchedLeaves }; } else { throw new Error('network error'); } } static intoActiveWebRelayer ( instance: WebbRelayer, query: { chain: InternalChainId; basedOn: 'evm' | 'substrate' }, getFees: (note: string) => Promise<{ totalFees: string; withdrawFeePercentage: number } | undefined> ): ActiveWebbRelayer { return new ActiveWebbRelayer(instance.endpoint, instance.capabilities, query, getFees); } } export class ActiveWebbRelayer extends WebbRelayer { constructor ( endpoint: string, capabilities: Capabilities, private query: { chain: InternalChainId; basedOn: 'evm' | 'substrate' }, private getFees: (note: string) => Promise<{ totalFees: string; withdrawFeePercentage: number } | undefined> ) { super(endpoint, capabilities); } private get config () { const list = this.capabilities.supportedChains[this.query.basedOn]; return list.get(this.query.chain); } get gasLimit (): number | undefined { return undefined; } get account (): string | undefined { return this.config?.account; } get beneficiary (): string | undefined { return this.config?.beneficiary; } fees = async (note: string) => { return this.getFees(note); }; }
nepoche/webb.js
packages/api-providers/src/contracts/utils/evm-note.ts
<filename>packages/api-providers/src/contracts/utils/evm-note.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 // @ts-ignore import snarkjs from 'tornado-snarkjs'; import { WebbError, WebbErrorCodes } from '../../webb-error/index.js'; import { bufferToFixed } from './buffer-to-fixed.js'; import { Deposit } from './make-deposit.js'; import { pedersenHash } from './pedersen-hash.js'; export class EvmNote { constructor ( private _currency: string, private _amount: number, private _chainId: number, private _preImage: Uint8Array ) {} static deserialize (noteString: string) { const noteRegex = /anchor-(?<currency>\w+)-(?<amount>[\d.]+)-(?<chainId>\d+)-0x(?<note>[0-9a-fA-F]{124})/g; try { const { amount, chainId, currency, note } = noteRegex.exec(noteString)?.groups as Record<string, any>; return new EvmNote(currency, Number(amount), Number(chainId), Buffer.from(note, 'hex')); } catch (e) { throw WebbError.from(WebbErrorCodes.NoteParsingFailure); } } serialize () { return this.toString(); } get currency () { return this._currency; } get amount () { return this._amount; } get chainId () { return this._chainId; } get preImage () { return this._preImage; } get preImageHex () { return bufferToFixed(this.preImage, 62); } toString () { return `anchor-${this.currency}-${this.amount}-${this.chainId}-${this.preImageHex}`; } intoDeposit (): Deposit { const commitment = pedersenHash(this.preImage); const nullifier = snarkjs.bigInt.leBuff2int(this.preImage.slice(0, 31)); const secret = snarkjs.bigInt.leBuff2int(this.preImage.slice(31, 62)); const nullifierHash = pedersenHash(nullifier.leInt2Buff(31)); return { commitment, nullifier, nullifierHash, preimage: this.preImage, secret }; } }
nepoche/webb.js
packages/api-providers/src/contracts/wrappers/webb-utils.ts
<gh_stars>0 // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 // @ts-ignore import * as snarkjs from 'snarkjs'; import { fetchKeyForEdges, fetchWasmForEdges } from '../../ipfs/evm/anchors.js'; import { AnchorWitnessInput } from './types.js'; type MaxEdges = 1 | 2 | 3 | 4 | 5; export const zeroAddress = '0x0000000000000000000000000000000000000000'; export const ZERO = 'ZERO'; const { groth16, zKey } = snarkjs; export const isZero = (value: string | number) => { if (value === zeroAddress) { return true; } return value === ZERO; }; export const generateWitness = async (input: AnchorWitnessInput, maxEdges: MaxEdges) => { try { const wasmBuf = await fetchWasmForEdges(maxEdges); const witnessCalculator = await require('../utils/witness-calculator')(wasmBuf); const buff = await witnessCalculator.calculateWTNSBin(input, 0); return buff; } catch (e) { console.log({ snarkError: e }); throw new Error('failed to generate witness'); } }; export const proofAndVerify = async (witness: any, maxEdges: MaxEdges) => { console.log(witness); const circuitKey = await fetchKeyForEdges(maxEdges); const res = await groth16.prove(circuitKey, witness); const vKey = await zKey.exportVerificationKey(circuitKey); const verificationResults = await groth16.verify(vKey, res.publicSignals, res.proof); if (verificationResults) { return res; } else { throw new Error('failed to create proof'); } };
nepoche/webb.js
packages/api-providers/src/abstracts/relayer/types.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { InternalChainId } from '../../chains/index.js'; export type RelayedChainConfig = { account: string; beneficiary?: string; contracts: Contract[]; }; export type Capabilities = { hasIpService: boolean; supportedChains: { substrate: Map<InternalChainId, RelayedChainConfig>; evm: Map<InternalChainId, RelayedChainConfig>; }; }; export interface Contract { contract: string; address: string; deployedAt: number; eventsWatcher: EventsWatcher; size: number; withdrawFeePercentage: number; linkedAnchors: LinkedAnchor[]; } export interface LinkedAnchor { chain: string; address: string; } export interface EventsWatcher { enabled: boolean; pollingInterval: number; } export type RelayerConfig = { endpoint: string; }; export interface Withdraw { finalized?: Finalized; errored?: Errored; connected?: string; connecting?: string; } export interface Finalized { txHash: string; } export interface Errored { reason: string; } export type RelayerMessage = { withdraw?: Withdraw; error?: string; network?: string; }; export type RelayerCMDBase = 'evm' | 'substrate'; export type MixerRelayTx = { chain: string; // Tree ID (Mixer tree id) id: number; proof: Array<number>; root: Array<number>; nullifierHash: Array<number>; // Ss558 Format recipient: string; // Ss558 Format relayer: string; fee: number; refund: number; }; type TornadoRelayTransaction = { chain: string; // The target contract. contract: string; // Proof bytes proof: string; // Fixed length Hex string fee: string; nullifierHash: string; recipient: string; // Fixed length Hex string refund: string; relayer: string; root: string; }; type AnchorRelayTransaction = Omit<TornadoRelayTransaction, 'root'> & { refreshCommitment: string; roots: Array<number>; }; export type RelayerSubstrateCommands = { mixerRelayTx: MixerRelayTx; }; export type RelayerEVMCommands = { tornadoRelayTx: TornadoRelayTransaction; anchorRelayTx: AnchorRelayTransaction; }; export type EVMCMDKeys = keyof RelayerEVMCommands; export type SubstrateCMDKeys = keyof RelayerSubstrateCommands; export type RelayerCMDKey = EVMCMDKeys | SubstrateCMDKeys;
nepoche/webb.js
packages/api-providers/src/types/index.ts
<reponame>nepoche/webb.js // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 export * from './abstracts.js'; export * from './anchor-config.interface.js'; export * from './bridge-config.interface.js'; export * from './chain-config.interface.js'; export * from './currency-config.interface.js'; export * from './mixer-config.interface.js'; export * from './wallet-config.interface.js';
nepoche/webb.js
packages/api-providers/src/enums/webb-currency-id.enum.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 // Do NOT change the ordering of this enum and always add to the end. Otherwise notes may break. export enum WebbCurrencyId { /// Production edgeware token EDG, /// Test edgeware token TEDG, /// Ether token ETH, /// Harmony token ONE, /// WEBB WEBB, SDN, WETH, MATIC, webbWETH, DEV, webbDEV, } export function webbCurrencyIdToString (c: WebbCurrencyId): string { switch (c) { case WebbCurrencyId.EDG: return 'EDG'; case WebbCurrencyId.TEDG: return 'TEDG'; case WebbCurrencyId.ETH: return 'ETH'; case WebbCurrencyId.ONE: return 'ONE'; case WebbCurrencyId.WEBB: return 'WEBB'; case WebbCurrencyId.SDN: return 'SDN'; case WebbCurrencyId.WETH: return 'WETH'; case WebbCurrencyId.MATIC: return 'MATIC'; case WebbCurrencyId.webbWETH: return 'webbWETH'; case WebbCurrencyId.DEV: return 'DEV'; case WebbCurrencyId.webbDEV: return 'webbDEV'; } } export function webbCurrencyIdFromString (c: string): WebbCurrencyId { switch (c) { case 'EDG': return WebbCurrencyId.EDG; case 'TEDG': return WebbCurrencyId.TEDG; case 'ETH': return WebbCurrencyId.ETH; case 'ONE': return WebbCurrencyId.ONE; case 'WEBB': return WebbCurrencyId.WEBB; case 'SDN': return WebbCurrencyId.SDN; case 'WETH': return WebbCurrencyId.WETH; case 'MATIC': return WebbCurrencyId.MATIC; case 'webbWETH': return WebbCurrencyId.webbWETH; case 'DEV': return WebbCurrencyId.DEV; case 'webbDEV': return WebbCurrencyId.webbDEV; default: throw new Error(`${c} isn't a valid WebbCurrencyId`); } }
nepoche/webb.js
packages/api-providers/src/chains/chain-utils.ts
// Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { WebbError, WebbErrorCodes } from '../webb-error/index.js'; import { ChainType, ChainTypeId, EVMChainId, InternalChainId, SubstrateChainId } from './chain-id.enum.js'; export const byteArrayToNum = (arr: number[]): number => { let n = 0; for (const i of arr) n = n * 256 + i; return n; }; /** * @param num the number to be converted * @param min the minimum bytes the array should hold (in the case of requiring empty bytes to match rust values) * @returns */ export const numToByteArray = (num: number, min: number): number[] => { let arr = []; while (num > 0) { arr.push(num % 256); num = Math.floor(num / 256); } arr.reverse(); // maintain minimum number of bytes while (arr.length < min) { arr = [0, ...arr]; } return arr; }; export const computeChainIdType = (chainType: ChainType, chainId: number | InternalChainId): number => { const chainTypeArray = numToByteArray(chainType, 2); const chainIdArray = numToByteArray(chainId, 4); const fullArray = [...chainTypeArray, ...chainIdArray]; return byteArrayToNum(fullArray); }; export const parseChainIdType = (chainIdType: number): ChainTypeId => { const byteArray = numToByteArray(chainIdType, 4); const chainType = byteArrayToNum(byteArray.slice(0, 2)); const chainId = byteArrayToNum(byteArray.slice(2)); return { chainId, chainType }; }; export const internalChainIdToChainId = (chainType: ChainType, internalId: InternalChainId) => { switch (chainType) { case ChainType.EVM: return internalChainIdIntoEVMId(internalId); case ChainType.Substrate: return internalChainIdIntoSubstrateId(internalId); default: throw WebbError.from(WebbErrorCodes.ChainIdTypeUnformatted); } }; export const chainTypeIdToInternalId = (chainTypeId: ChainTypeId): InternalChainId => { switch (chainTypeId.chainType) { case ChainType.EVM: return evmIdIntoInternalChainId(chainTypeId.chainId); case ChainType.Substrate: return substrateIdIntoInternalChainId(chainTypeId.chainId as SubstrateChainId); default: throw new Error('chainTypeId not handled in chainTypeIdToInternalId'); } }; export const evmIdIntoInternalChainId = (evmId: number | string): InternalChainId => { switch (Number(evmId) as EVMChainId) { case EVMChainId.EthereumMainNet: return InternalChainId.EthereumMainNet; case EVMChainId.Ropsten: return InternalChainId.Ropsten; case EVMChainId.Rinkeby: return InternalChainId.Rinkeby; case EVMChainId.Kovan: return InternalChainId.Kovan; case EVMChainId.Goerli: return InternalChainId.Goerli; case EVMChainId.Edgeware: return InternalChainId.Edgeware; case EVMChainId.Beresheet: return InternalChainId.EdgewareTestNet; case EVMChainId.HarmonyTestnet1: return InternalChainId.HarmonyTestnet1; case EVMChainId.HarmonyTestnet0: return InternalChainId.HarmonyTestnet0; case EVMChainId.HarmonyMainnet0: return InternalChainId.HarmonyMainnet0; case EVMChainId.Ganache: return InternalChainId.Ganache; case EVMChainId.Shiden: return InternalChainId.Shiden; case EVMChainId.OptimismTestnet: return InternalChainId.OptimismTestnet; case EVMChainId.ArbitrumTestnet: return InternalChainId.ArbitrumTestnet; case EVMChainId.PolygonTestnet: return InternalChainId.PolygonTestnet; case EVMChainId.HermesLocalnet: return InternalChainId.HermesLocalnet; case EVMChainId.AthenaLocalnet: return InternalChainId.AthenaLocalnet; } }; export const internalChainIdIntoEVMId = (chainId: InternalChainId | number | string): EVMChainId => { switch (Number(chainId) as InternalChainId) { case InternalChainId.Edgeware: return EVMChainId.Edgeware; case InternalChainId.EdgewareTestNet: return EVMChainId.Beresheet; case InternalChainId.EthereumMainNet: return EVMChainId.EthereumMainNet; case InternalChainId.Rinkeby: return EVMChainId.Rinkeby; case InternalChainId.Ropsten: return EVMChainId.Ropsten; case InternalChainId.Kovan: return EVMChainId.Kovan; case InternalChainId.Goerli: return EVMChainId.Goerli; case InternalChainId.HarmonyTestnet0: return EVMChainId.HarmonyTestnet0; case InternalChainId.HarmonyTestnet1: return EVMChainId.HarmonyTestnet1; case InternalChainId.HarmonyMainnet0: return EVMChainId.HarmonyMainnet0; case InternalChainId.Ganache: return EVMChainId.Ganache; case InternalChainId.Shiden: return EVMChainId.Shiden; case InternalChainId.OptimismTestnet: return EVMChainId.OptimismTestnet; case InternalChainId.ArbitrumTestnet: return EVMChainId.ArbitrumTestnet; case InternalChainId.PolygonTestnet: return EVMChainId.PolygonTestnet; case InternalChainId.HermesLocalnet: return EVMChainId.HermesLocalnet; case InternalChainId.AthenaLocalnet: return EVMChainId.AthenaLocalnet; default: throw Error(`unsupported evm id: ${chainId}`); } }; export const substrateIdIntoInternalChainId = (chainId: SubstrateChainId): InternalChainId => { switch (Number(chainId) as SubstrateChainId) { case SubstrateChainId.Edgeware: return InternalChainId.Edgeware; case SubstrateChainId.Webb: return InternalChainId.WebbDevelopment; default: throw Error(`Unsupported substrate id: ${chainId}`); } }; export const internalChainIdIntoSubstrateId = (chainId: InternalChainId | number | string): SubstrateChainId => { switch (Number(chainId) as InternalChainId) { case InternalChainId.Edgeware: return SubstrateChainId.Edgeware; case InternalChainId.WebbDevelopment: return SubstrateChainId.Webb; default: throw Error(`Internal Id ${chainId} is not a substrate id`); } };
nepoche/webb.js
packages/api-providers/src/web3/anchor-api.ts
<filename>packages/api-providers/src/web3/anchor-api.ts // Copyright 2022 @nepoche/ // SPDX-License-Identifier: Apache-2.0 import { AnchorBase, BridgeConfig, Currency, CurrencyRole, CurrencyType } from '@nepoche/api-providers/index.js'; import { AnchorApi } from '../abstracts/index.js'; import { ChainTypeId, chainTypeIdToInternalId, evmIdIntoInternalChainId } from '../chains/index.js'; import { WebbGovernedToken } from '../contracts/wrappers/index.js'; import { WebbWeb3Provider } from './webb-provider.js'; export class Web3AnchorApi extends AnchorApi<WebbWeb3Provider, BridgeConfig> { getTokenAddress (chainTypeId: ChainTypeId): string | null { const activeBridgeAsset = this.store.activeBridge?.asset; const internalChainId = chainTypeIdToInternalId(chainTypeId); return activeBridgeAsset ? this.config.currencies[activeBridgeAsset].addresses.get(internalChainId) ?? null : null; } private get config () { return this.inner.config; } async getCurrencies (): Promise<Currency[]> { const currentChainId = await this.inner.getChainId(); const internalChainId = evmIdIntoInternalChainId(currentChainId); const bridgeCurrenciesConfig = Object.values(this.config.currencies).filter((i) => { const isValid = i.role === CurrencyRole.Governable && i.type === CurrencyType.ERC20; const isSupported = Currency.fromCurrencyId(this.config.currencies, i.id).hasChain(internalChainId); return isSupported && isValid; }); return bridgeCurrenciesConfig.map((config) => { return Currency.fromCurrencyId(this.config.currencies, config.id); }); } private get activeBridgeAsset () { return this.store.activeBridge?.asset ?? null; } get currency (): Currency | null { return this.activeBridgeAsset ? Currency.fromCurrencyId(this.config.currencies, this.activeBridgeAsset) : null; } async getAnchors (): Promise<AnchorBase[]> { return ( this.store.activeBridge?.anchors.map((anchor) => ({ amount: anchor.amount, neighbours: anchor.anchorAddresses })) ?? [] ); } async getWrappableAssets (chainTypeId: ChainTypeId): Promise<Currency[]> { const bridge = this.activeBridge; const internalChainId = chainTypeIdToInternalId(chainTypeId); if (!bridge) { return []; } const wrappedTokenAddress = this.getTokenAddress(chainTypeId); 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[internalChainId].currencies.filter((currencyId) => { const wrappableTokenAddress = this.config.currencies[currencyId].addresses.get(internalChainId); return wrappableTokenAddress && tokenAddresses.includes(wrappableTokenAddress); }); if (await wrappedToken.isNativeAllowed()) { wrappableCurrencyIds.push(this.config.chains[internalChainId].nativeCurrencyId); } const wrappableCurrencies = wrappableCurrencyIds.map((currencyId) => { return Currency.fromCurrencyId(this.config.currencies, currencyId); }); return wrappableCurrencies; } }