web: remove v1 web interface

Change-Id: Icaebf7f320f6460b65ee1cb62f854833c8f05cf1
This commit is contained in:
Leo 2021-07-19 16:20:19 +02:00
parent fb3d267a50
commit aa417344c1
46 changed files with 0 additions and 75698 deletions

View File

@ -154,26 +154,6 @@ k8s_resource("eth-devnet", port_forwards=[
port_forward(8545, name="Ganache RPC [:8545]")
])
# web frontend
docker_build(
ref = "web",
context = "./web",
dockerfile = "./web/Dockerfile",
ignore = ["./web/node_modules"],
live_update = [
sync("./web/src", "/home/node/app/src"),
sync("./web/public", "/home/node/app/public"),
sync("./web/contracts", "/home/node/app/contracts"),
],
)
k8s_yaml_with_ns("devnet/web.yaml")
k8s_resource("web", port_forwards=[
port_forward(3000, name="Experimental Web UI [:3000]")
])
# explorer web app
docker_build(

View File

@ -1 +0,0 @@
node_modules

View File

@ -1 +0,0 @@
GENERATE_SOURCEMAP = false

23
web/.gitignore vendored
View File

@ -1,23 +0,0 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -1,21 +0,0 @@
# syntax=docker/dockerfile:experimental
# Derivative of ethereum/Dockerfile, look there for an explanation on how it works.
FROM node:lts-alpine@sha256:2ae9624a39ce437e7f58931a5747fdc60224c6e40f8980db90728de58e22af7c
USER 1000
RUN mkdir -p /home/node/app
RUN mkdir -p /home/node/.npm
WORKDIR /home/node/app
ADD --chown=node:node package.json .
ADD --chown=node:node package-lock.json .
RUN --mount=type=cache,uid=1000,gid=1000,target=/home/node/.npm \
--mount=type=cache,uid=1000,gid=1000,target=node_modules \
npm install && \
cp -r node_modules node_modules_cache
RUN rmdir node_modules && mv node_modules_cache node_modules
ADD --chown=node:node . .

View File

@ -1,44 +0,0 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

20528
web/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,68 +0,0 @@
{
"name": "web",
"version": "0.1.0",
"private": true,
"dependencies": {
"@project-serum/sol-wallet-adapter": "^0.1.4",
"@solana/spl-token": "^0.0.11",
"@solana/web3.js": "^0.90.0",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"@types/bs58": "^4.0.1",
"@types/jest": "^24.0.0",
"@types/lodash.debounce": "^4.0.6",
"@types/node": "^12.12.67",
"@types/react": "^16.9.52",
"@types/react-dom": "^16.9.0",
"@types/react-router-dom": "^5.1.6",
"antd": "^4.7.0",
"bs58": "^4.0.1",
"buffer": "^5.6.0",
"buffer-layout": "^1.2.0",
"ethers": "^4.0.48",
"lodash.debounce": "^4.0.8",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "^3.4.3",
"typescript": "~3.7.2",
"web3": "^1.3.0"
},
"devDependencies": {
"@typechain/ethers-v4": "^1.0.0",
"npm": "^6.14.8",
"typechain": "^2.0.1",
"arweave-deploy": "^1.9.1",
"gh-pages": "^3.1.0",
"yarn": "^1.22.10"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"ethers": "typechain --target ethers-v4 --outDir src/contracts 'contracts/*.json'",
"deploy": "gh-pages -d build",
"deploy:ar": "arweave deploy-dir build --key-file ",
"rm-contracts": "rm -rf src/contracts && rm -rf contracts",
"import-contracts": "mkdir -p ./contracts && cp -r ../ethereum/build/contracts/* ./contracts/ && npm run ethers",
"refresh-contracts": "npm run rm-contracts && npm run import-contracts"
},
"eslintConfig": {
"extends": "react-app"
},
"homepage": ".",
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

View File

@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Wormhole Demonstration UI</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@ -1,15 +0,0 @@
{
"short_name": "Wormhole Bridge",
"name": "Solana token bridge",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -1,3 +0,0 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -1,5 +0,0 @@
@import '~antd/dist/antd.css';
.App{
height: 100%;
}

View File

@ -1,99 +0,0 @@
import React, {useEffect, useMemo, useState} from 'react';
import './App.css';
import * as solanaWeb3 from '@solana/web3.js';
import ClientContext from '../providers/ClientContext';
import Transfer from "../pages/Transfer";
import {Empty, Layout} from 'antd';
import {SolanaTokenProvider} from "../providers/SolanaTokenContext";
import {SlotProvider} from "../providers/SlotContext";
import { HashRouter, Link, Route, Switch} from 'react-router-dom';
import TransferSolana from "../pages/TransferSolana";
import WalletContext from '../providers/WalletContext';
import Wallet from "@project-serum/sol-wallet-adapter";
import {BridgeProvider} from "../providers/BridgeContext";
import Assistant from "../pages/Assistant";
import Message from "../pages/Message";
import {SOLANA_HOST} from "../config";
const {Header, Content, Footer} = Layout;
function App() {
let c = new solanaWeb3.Connection(SOLANA_HOST);
const wallet = useMemo(() => new Wallet("https://www.sollet.io", SOLANA_HOST), []);
const [connected, setConnected] = useState(false);
useEffect(() => {
wallet.on('connect', () => {
setConnected(true);
console.log('Connected to wallet ' + wallet.publicKey.toBase58());
});
wallet.on('disconnect', () => {
setConnected(false);
console.log('Disconnected from wallet');
});
return () => {
wallet.disconnect();
};
}, [wallet]);
return (
<div className="App">
<Layout style={{height: '100%'}}>
<HashRouter basename={"/"}>
<Header style={{position: 'fixed', zIndex: 1, width: '100%'}}>
<Link to="/" style={{paddingRight: 20}}>Message</Link>
<Link to="/assistant" style={{paddingRight: 20}}>Assistant</Link>
<Link to="/eth" style={{paddingRight: 20}}>Ethereum</Link>
<Link to="/solana">Solana</Link>
{
connected ? (<a style={{float: "right"}}>
Connected as {wallet.publicKey.toString()}
</a>) : (<a style={{float: "right"}} onClick={() => {
if (!connected) {
wallet.connect()
}
}
}>Connect</a>)
}
</Header>
<Content style={{padding: '0 50px', marginTop: 64}}>
<div style={{padding: 24}}>
{
connected?( <ClientContext.Provider value={c}>
<SlotProvider>
<WalletContext.Provider value={wallet}>
<BridgeProvider>
<SolanaTokenProvider>
<Switch>
<Route path="/assistant">
<Assistant/>
</Route>
<Route path="/solana">
<TransferSolana/>
</Route>
<Route path="/eth">
<Transfer/>
</Route>
<Route path="/">
<Message/>
</Route>
</Switch>
</SolanaTokenProvider>
</BridgeProvider>
</WalletContext.Provider>
</SlotProvider>
</ClientContext.Provider>):(
<Empty description={"Please connect your wallet"}/>
)
}
</div>
</Content>
<Footer style={{textAlign: 'center'}}>The Wormhole Project</Footer>
</HashRouter>
</Layout>
</div>
);
}
export default App;

View File

@ -1,45 +0,0 @@
import React, {useContext} from "react"
import {BalanceInfo, SolanaTokenContext} from "../providers/SolanaTokenContext";
import {Table} from "antd";
import {CHAIN_ID_SOLANA} from "../utils/bridge";
import {BigNumber} from "ethers/utils";
import {PublicKey} from "@solana/web3.js";
import {deriveERC20Address} from "../utils/helpers";
function SplBalances() {
let t = useContext(SolanaTokenContext);
const columns = [
{
title: 'Account',
key: 'account',
render: (n: any, v: BalanceInfo) => v.account.toString()
},
{
title: 'Mint',
dataIndex: 'mint',
key: 'mint',
},
{
title: 'Balance',
key: 'balance',
render: (n: any, v: BalanceInfo) => v.balance.div(new BigNumber(10).pow(v.decimals)).toString()
},
{
title: 'Wrapped',
key: 'wrapped',
render: (n: any, v: BalanceInfo) => {
return v.assetMeta.chain != CHAIN_ID_SOLANA ? `Wrapped (${v.assetMeta.chain == 2 ? "ETH" : "SOL"} - 0x${v.assetMeta.address.slice(12).toString("hex")})` : `Native (0x${deriveERC20Address(new PublicKey(v.mint))})`
}
},
];
return (<>
<h3>SPL Holdings on Solana</h3>
<Table dataSource={t.balances} columns={columns} pagination={false} scroll={{y: 400}}/>
</>
)
}
export default SplBalances

View File

@ -1,304 +0,0 @@
import React, {useContext, useEffect, useState} from "react";
import {Button, Empty, Form, Input, message, Modal, Select} from "antd";
import solanaWeb3, {Account, Connection, PublicKey, Transaction} from "@solana/web3.js";
import ClientContext from "../providers/ClientContext";
import {SlotContext} from "../providers/SlotContext";
import {SolanaTokenContext} from "../providers/SolanaTokenContext";
import {BridgeContext} from "../providers/BridgeContext";
import {WrappedAssetFactory} from "../contracts/WrappedAssetFactory";
import {WalletOutlined} from '@ant-design/icons';
import {BRIDGE_ADDRESS} from "../config";
import {WormholeFactory} from "../contracts/WormholeFactory";
import {ethers} from "ethers";
import debounce from "lodash.debounce"
import BN from "bignumber.js";
import {BigNumber} from "ethers/utils";
import {AssetMeta, SolanaBridge} from "../utils/bridge";
import {ChainID} from "../pages/Assistant";
import WalletContext from "../providers/WalletContext";
import Wallet from "@project-serum/sol-wallet-adapter";
const {confirm} = Modal;
const {Option} = Select;
interface TransferInitiatorParams {
onFromNetworkChanged?: (v: ChainID) => void
dataChanged?: (d: TransferInitiatorData) => void
}
export interface CoinInfo {
address: string,
name: string,
balance: BigNumber,
decimals: number,
allowance: BigNumber,
isWrapped: boolean,
chainID: number,
assetAddress: Buffer,
mint: string,
}
export interface TransferInitiatorData {
fromNetwork: ChainID,
fromCoinInfo: CoinInfo
toNetwork: ChainID,
toAddress: Buffer,
amount: BigNumber,
}
// @ts-ignore
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
export const defaultCoinInfo = {
address: "",
name: "",
balance: new BigNumber(0),
decimals: 0,
allowance: new BigNumber(0),
isWrapped: false,
chainID: 0,
assetAddress: new Buffer(0),
mint: ""
}
let debounceUpdater = debounce((e) => e(), 500)
async function createWrapped(c: Connection, b: SolanaBridge, wallet: Wallet, meta: AssetMeta, mint: PublicKey) {
try {
let tx = new Transaction();
// @ts-ignore
let [ix_account, newSigner] = await b.createWrappedAssetAndAccountInstructions(wallet.publicKey, mint, meta);
let recentHash = await c.getRecentBlockhash();
tx.recentBlockhash = recentHash.blockhash
tx.add(...ix_account)
tx.feePayer = wallet.publicKey;
tx.sign(newSigner);
let signed = await wallet.signTransaction(tx);
message.loading({content: "Waiting for transaction to be confirmed...", key: "tx", duration: 1000})
await c.sendRawTransaction(signed.serialize(), {preflightCommitment: "single"})
message.success({content: "Creation succeeded!", key: "tx"})
} catch (e) {
console.log(e)
message.error({content: "Creation failed", key: "tx"})
}
}
export default function TransferInitiator(params: TransferInitiatorParams) {
let c = useContext<solanaWeb3.Connection>(ClientContext);
let slot = useContext(SlotContext);
let b = useContext(SolanaTokenContext);
let bridge = useContext(BridgeContext);
let wallet = useContext(WalletContext);
let [fromNetwork, setFromNetwork] = useState(ChainID.ETH);
let [toNetwork, setToNetwork] = useState(ChainID.SOLANA);
let [fromAddress, setFromAddress] = useState("");
let [fromAddressValid, setFromAddressValid] = useState(false)
let [coinInfo, setCoinInfo] = useState<CoinInfo>(defaultCoinInfo);
let [toAddress, setToAddress] = useState("");
let [toAddressValid, setToAddressValid] = useState(false)
let [amount, setAmount] = useState(new BigNumber(0));
let [amountValid, setAmountValid] = useState(true);
let [wrappedMint, setWrappedMint] = useState("")
const updateBalance = async () => {
if (fromNetwork == ChainID.SOLANA) {
let acc = b.balances.find(value => value.account.toString() == fromAddress)
if (!acc) {
setFromAddressValid(false);
setCoinInfo(defaultCoinInfo);
return
}
setCoinInfo({
address: fromAddress,
name: "",
balance: acc.balance,
allowance: new BigNumber(0),
decimals: acc.assetMeta.decimals,
isWrapped: acc.assetMeta.chain != ChainID.SOLANA,
chainID: acc.assetMeta.chain,
assetAddress: acc.assetMeta.address,
// Solana specific
mint: acc.mint,
})
setFromAddressValid(true);
} else {
try {
let e = WrappedAssetFactory.connect(fromAddress, provider);
let addr = await signer.getAddress();
let balance = await e.balanceOf(addr);
let decimals = await e.decimals();
let symbol = await e.symbol();
let allowance = await e.allowance(addr, BRIDGE_ADDRESS);
let info = {
address: fromAddress,
name: symbol,
balance: balance,
allowance: allowance,
decimals: decimals,
isWrapped: false,
chainID: 2,
assetAddress: new Buffer(fromAddress.slice(2), "hex"),
mint: "",
}
let b = WormholeFactory.connect(BRIDGE_ADDRESS, provider);
let isWrapped = await b.isWrappedAsset(fromAddress)
if (isWrapped) {
info.chainID = await e.assetChain()
info.assetAddress = new Buffer((await e.assetAddress()).slice(2), "hex")
info.isWrapped = true
}
let wrappedMint = await bridge.getWrappedAssetMint({
chain: info.chainID,
address: info.assetAddress,
decimals: Math.min(decimals, 9),
});
console.log(decimals)
setWrappedMint(wrappedMint.toString())
setCoinInfo(info)
setFromAddressValid(true)
} catch (e) {
setCoinInfo(defaultCoinInfo);
setFromAddressValid(false)
}
}
}
useEffect(() => {
debounceUpdater(updateBalance)
}, [fromNetwork, fromAddress])
useEffect(() => {
if (toNetwork == ChainID.ETH) {
setToAddressValid(toAddress.length == 42 && toAddress.match(/0[xX][0-9a-fA-F]+/) != null)
} else {
setToAddressValid(toAddress != "")
}
}, [toNetwork, toAddress])
useEffect(() => {
setAmountValid(amount.lte(coinInfo.balance) && amount.gt(0))
}, [amount])
useEffect(() => {
if (params.dataChanged) {
params.dataChanged({
fromCoinInfo: coinInfo,
fromNetwork,
toNetwork,
toAddress: toAddressValid ? (toNetwork == ChainID.ETH ? new Buffer(toAddress.slice(2), "hex") : new PublicKey(toAddress).toBuffer()) : new Buffer(0),
amount: amount,
});
}
}, [fromNetwork, fromAddressValid, coinInfo, toNetwork, toAddress, toAddressValid, amount])
return (
<>
<Form layout={"vertical"}>
<Form.Item label="From" name="layout" validateStatus={fromAddressValid ? "success" : "error"}>
<Input.Group compact={true}>
<Select style={{width: '30%'}} defaultValue={ChainID.ETH} className="select-before"
value={fromNetwork}
onChange={(v: ChainID) => {
setFromNetwork(v);
setFromAddress("");
if (v === toNetwork) {
setToNetwork(v == ChainID.ETH ? ChainID.SOLANA : ChainID.ETH);
}
if (params.onFromNetworkChanged) params.onFromNetworkChanged(v);
}}>
<Option value={ChainID.ETH}>Ethereum</Option>
<Option value={ChainID.SOLANA}>Solana</Option>
</Select>
{fromNetwork == ChainID.ETH &&
<Input style={{width: '70%'}} placeholder="ERC20 address"
onChange={(e) => setFromAddress(e.target.value)}
suffix={coinInfo.name}/>}
{fromNetwork == ChainID.SOLANA &&
<>
<Select style={{width: '70%'}} placeholder="Pick a token account"
onChange={(e) => {
setFromAddress(e.toString())
}}>
{b.balances.map((v) => <Option
value={v.account.toString()}>{v.account.toString()}</Option>)}
</Select>
</>
}
</Input.Group>
</Form.Item>
<Form.Item label="Amount" name="layout"
validateStatus={amountValid ? "success" : "error"}>
<Input type={"number"} placeholder={"Amount"}
addonAfter={`Balance: ${new BN(coinInfo.balance.toString()).div(new BN(10).pow(coinInfo.decimals))}`}
onChange={(v) => {
if (v.target.value === "") {
setAmount(new BigNumber(0));
return
}
setAmount(new BigNumber(new BN(v.target.value).multipliedBy(new BN(Math.pow(10, coinInfo.decimals))).toFixed(0)))
}}/>
</Form.Item>
<Form.Item label="Recipient" name="layout" validateStatus={toAddressValid ? "success" : "error"}>
<Input.Group compact={true}>
<Select style={{width: '30%'}} defaultValue={ChainID.SOLANA} className="select-before"
value={toNetwork}
onChange={(v: ChainID) => {
setToNetwork(v)
if (v === fromNetwork) {
setFromNetwork(v == ChainID.ETH ? ChainID.SOLANA : ChainID.ETH);
}
setToAddress("");
}}>
<Option value={ChainID.ETH}>Ethereum</Option>
<Option value={ChainID.SOLANA}>Solana</Option>
</Select>
{toNetwork == ChainID.ETH &&
<Input style={{width: '70%'}} placeholder="Account address"
onChange={(e) => setToAddress(e.target.value)}/>}
{toNetwork == ChainID.SOLANA &&
<>
<Select style={{width: '60%'}} onChange={(e) => setToAddress(e.toString())}
placeholder="Pick a token account or create a new one"
notFoundContent={<Empty description="No accounts. Create a new one."/>}>
{b.balances.filter((v) => v.mint == wrappedMint).map((v) =>
<Option
value={v.account.toString()}>{v.account.toString()}</Option>)}
</Select>
<Button style={{width: '10%'}} disabled={!fromAddressValid} onClick={() => {
confirm({
title: 'Do you want to create a new token account?',
icon: <WalletOutlined/>,
content: (<>This will create a new token account for the
token: <code>{wrappedMint}</code></>),
onOk() {
createWrapped(c, bridge, wallet, {
chain: coinInfo.chainID,
address: coinInfo.assetAddress,
decimals: Math.min(coinInfo.decimals, 9)
}, new PublicKey(wrappedMint))
},
onCancel() {
},
})
}}>+</Button>
</>
}
</Input.Group>
</Form.Item>
</Form>
</>
);
}

View File

@ -1,199 +0,0 @@
import React, {useContext, useEffect, useState} from "react"
import {SolanaTokenContext} from "../providers/SolanaTokenContext";
import {Button, message, Table} from "antd";
import {Lockup} from "../utils/bridge";
import {BridgeContext} from "../providers/BridgeContext";
import {SlotContext} from "../providers/SlotContext";
import {ethers} from "ethers";
import {WormholeFactory} from "../contracts/WormholeFactory";
import {BRIDGE_ADDRESS} from "../config";
import {keccak256} from "ethers/utils";
import BN from 'bn.js';
import {PublicKey, Transaction} from "@solana/web3.js";
import ClientContext from "../providers/ClientContext";
import WalletContext from "../providers/WalletContext";
// @ts-ignore
if (window.ethereum === undefined) {
alert("Please install the MetaMask extension before using this experimental demo web UI");
}
// @ts-ignore
window.ethereum.enable();
// @ts-ignore
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
interface LockupWithStatus extends Lockup {
status: LockupStatus,
}
enum LockupStatus {
AWAITING_VAA,
UNCLAIMED_VAA,
COMPLETED
}
function TransferProposals() {
let s = useContext(SlotContext);
let t = useContext(SolanaTokenContext);
let tokens = useContext(SolanaTokenContext);
let b = useContext(BridgeContext);
let wallet = useContext(WalletContext);
let c = useContext(ClientContext);
let [lockups, setLockups] = useState<LockupWithStatus[]>([])
let [lastUpdate, setLastUpdate] = useState(0);
useEffect(() => {
if (s - lastUpdate <= 16) {
return
}
setLastUpdate(s);
let updateLockups = async () => {
let lockups: LockupWithStatus[] = [];
for (let account of tokens.balances) {
let accLockups = await b.fetchTransferProposals(account.account)
lockups.push(...accLockups.map(v => {
return {
status: LockupStatus.AWAITING_VAA,
...v
}
}))
}
let wormhole = WormholeFactory.connect(BRIDGE_ADDRESS, provider);
for (let lockup of lockups) {
if (lockup.vaaTime === undefined || lockup.vaaTime === 0) continue;
let signingData = lockup.vaa.slice(lockup.vaa[5] * 66 + 6)
for (let i = signingData.length; i > 0; i--) {
if (signingData[i] == 0xff) {
signingData = signingData.slice(0, i)
break
}
}
let hash = keccak256(signingData)
let submissionStatus = await wormhole.consumedVAAs(hash);
lockup.status = submissionStatus ? LockupStatus.COMPLETED : LockupStatus.UNCLAIMED_VAA;
}
setLockups(lockups);
}
updateLockups()
}, [s])
let executeVAA = async (v: LockupWithStatus) => {
let wh = WormholeFactory.connect(BRIDGE_ADDRESS, signer)
let vaa = new Buffer(v.vaa);
for (let i = vaa.length; i > 0; i--) {
if (vaa[i] == 0xff) {
vaa = vaa.slice(0, i)
break
}
}
let signatures = await b.fetchSignatureStatus(v.signatureAccount);
let sigData = Buffer.of(...signatures.reduce((previousValue, currentValue) => {
previousValue.push(currentValue.index)
previousValue.push(...currentValue.signature)
return previousValue
}, new Array<number>()))
vaa = Buffer.concat([vaa.slice(0, 5), Buffer.of(signatures.length), sigData, vaa.slice(6)])
message.loading({content: "Signing transaction...", key: "eth_tx", duration: 1000},)
let tx = await wh.submitVAA(vaa)
message.loading({content: "Waiting for transaction to be mined...", key: "eth_tx", duration: 1000})
await tx.wait(1)
message.success({content: "Execution of VAA succeeded", key: "eth_tx"})
}
let pokeProposal = async (proposalAddress: PublicKey) => {
message.loading({content: "Poking lockup ...", key: "poke"}, 1000)
let ix = await b.createPokeProposalInstruction(proposalAddress);
let recentHash = await c.getRecentBlockhash();
let tx = new Transaction();
tx.recentBlockhash = recentHash.blockhash
tx.add(ix)
tx.feePayer = wallet.publicKey;
let signed = await wallet.signTransaction(tx);
try {
await c.sendRawTransaction(signed.serialize())
message.success({content: "Poke succeeded", key: "poke"})
} catch (e) {
message.error({content: "Poke failed", key: "poke"})
}
}
let statusToPrompt = (v: LockupWithStatus) => {
switch (v.status) {
case LockupStatus.AWAITING_VAA:
return (<>Awaiting VAA (<a onClick={() => {
pokeProposal(v.lockupAddress)
}}>poke</a>)</>);
case LockupStatus.UNCLAIMED_VAA:
return (<Button onClick={() => {
executeVAA(v)
}}>Execute</Button>);
case LockupStatus.COMPLETED:
return ("Completed");
}
}
const columns = [
{
title: 'SourceAccount',
key: 'source',
render: (n: any, v: LockupWithStatus) => "SOL: " + v.sourceAddress.toString()
},
{
title: 'TargetAccount',
key: 'target',
render: (n: any, v: LockupWithStatus) => {
switch (v.toChain) {
case 1:
return "SOL: " + new PublicKey(v.targetAddress).toString()
case 2:
return "ETH: 0x" + new Buffer(v.targetAddress.slice(12)).toString("hex")
}
}
},
{
title: 'Asset',
key: 'assetAddress',
render: (n: any, v: LockupWithStatus) => {
switch (v.assetChain) {
case 1:
return "SOL: " + new PublicKey(v.assetAddress).toString()
case 2:
return "ETH: 0x" + new Buffer(v.assetAddress.slice(12)).toString("hex")
}
}
},
{
title: 'Amount',
key: 'amount',
render: (n: any, v: LockupWithStatus) => v.amount.div(new BN(10).pow(new BN(v.assetDecimals))).toString()
},
{
title: 'Status',
key: 'status',
render: (n: any, v: LockupWithStatus) => {
return (<>{statusToPrompt(v)}</>)
}
},
];
return (<>
<h3>Pending transfers to Ethereum</h3>
<Table dataSource={lockups} columns={columns}/>
</>
)
}
export default TransferProposals

View File

@ -1,18 +0,0 @@
import {PublicKey} from "@solana/web3.js";
const BRIDGE_ADDRESS = "0x254dffcd3277c0b1660f6d42efbb754edababc2b";
const WRAPPED_MASTER = "9A5e27995309a03f8B583feBdE7eF289FcCdC6Ae"
const SOLANA_BRIDGE_PROGRAM = new PublicKey("Bridge1p5gheXUvJ6jGWGeCsgPKgnE3YgdGKRVCMY9o");
const TOKEN_PROGRAM = new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
const SOLANA_HOST = "http://localhost:8899";
export {
BRIDGE_ADDRESS,
TOKEN_PROGRAM,
WRAPPED_MASTER,
SOLANA_BRIDGE_PROGRAM,
SOLANA_HOST
}

View File

@ -1,401 +0,0 @@
/* Generated by ts-generator ver. 0.0.8 */
/* tslint:disable */
import { Contract, ContractTransaction, EventFilter, Signer } from "ethers";
import { Listener, Provider } from "ethers/providers";
import { Arrayish, BigNumber, BigNumberish, Interface } from "ethers/utils";
import {
TransactionOverrides,
TypedEventDescription,
TypedFunctionDescription
} from ".";
interface Erc20Interface extends Interface {
functions: {
allowance: TypedFunctionDescription<{
encode([owner, spender]: [string, string]): string;
}>;
approve: TypedFunctionDescription<{
encode([spender, amount]: [string, BigNumberish]): string;
}>;
balanceOf: TypedFunctionDescription<{
encode([account]: [string]): string;
}>;
decimals: TypedFunctionDescription<{ encode([]: []): string }>;
decreaseAllowance: TypedFunctionDescription<{
encode([spender, subtractedValue]: [string, BigNumberish]): string;
}>;
increaseAllowance: TypedFunctionDescription<{
encode([spender, addedValue]: [string, BigNumberish]): string;
}>;
name: TypedFunctionDescription<{ encode([]: []): string }>;
symbol: TypedFunctionDescription<{ encode([]: []): string }>;
totalSupply: TypedFunctionDescription<{ encode([]: []): string }>;
transfer: TypedFunctionDescription<{
encode([recipient, amount]: [string, BigNumberish]): string;
}>;
transferFrom: TypedFunctionDescription<{
encode([sender, recipient, amount]: [
string,
string,
BigNumberish
]): string;
}>;
};
events: {
Approval: TypedEventDescription<{
encodeTopics([owner, spender, value]: [
string | null,
string | null,
null
]): string[];
}>;
Transfer: TypedEventDescription<{
encodeTopics([from, to, value]: [
string | null,
string | null,
null
]): string[];
}>;
};
}
export class Erc20 extends Contract {
connect(signerOrProvider: Signer | Provider | string): Erc20;
attach(addressOrName: string): Erc20;
deployed(): Promise<Erc20>;
on(event: EventFilter | string, listener: Listener): Erc20;
once(event: EventFilter | string, listener: Listener): Erc20;
addListener(eventName: EventFilter | string, listener: Listener): Erc20;
removeAllListeners(eventName: EventFilter | string): Erc20;
removeListener(eventName: any, listener: Listener): Erc20;
interface: Erc20Interface;
functions: {
allowance(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"allowance(address,address)"(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
approve(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"approve(address,uint256)"(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
balanceOf(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"balanceOf(address)"(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
decimals(overrides?: TransactionOverrides): Promise<number>;
"decimals()"(overrides?: TransactionOverrides): Promise<number>;
decreaseAllowance(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"decreaseAllowance(address,uint256)"(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
increaseAllowance(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"increaseAllowance(address,uint256)"(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
name(overrides?: TransactionOverrides): Promise<string>;
"name()"(overrides?: TransactionOverrides): Promise<string>;
symbol(overrides?: TransactionOverrides): Promise<string>;
"symbol()"(overrides?: TransactionOverrides): Promise<string>;
totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>;
"totalSupply()"(overrides?: TransactionOverrides): Promise<BigNumber>;
transfer(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"transfer(address,uint256)"(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
transferFrom(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"transferFrom(address,address,uint256)"(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
};
allowance(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"allowance(address,address)"(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
approve(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"approve(address,uint256)"(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
balanceOf(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"balanceOf(address)"(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
decimals(overrides?: TransactionOverrides): Promise<number>;
"decimals()"(overrides?: TransactionOverrides): Promise<number>;
decreaseAllowance(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"decreaseAllowance(address,uint256)"(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
increaseAllowance(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"increaseAllowance(address,uint256)"(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
name(overrides?: TransactionOverrides): Promise<string>;
"name()"(overrides?: TransactionOverrides): Promise<string>;
symbol(overrides?: TransactionOverrides): Promise<string>;
"symbol()"(overrides?: TransactionOverrides): Promise<string>;
totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>;
"totalSupply()"(overrides?: TransactionOverrides): Promise<BigNumber>;
transfer(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"transfer(address,uint256)"(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
transferFrom(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"transferFrom(address,address,uint256)"(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
filters: {
Approval(
owner: string | null,
spender: string | null,
value: null
): EventFilter;
Transfer(from: string | null, to: string | null, value: null): EventFilter;
};
estimate: {
allowance(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"allowance(address,address)"(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
approve(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"approve(address,uint256)"(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
balanceOf(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"balanceOf(address)"(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
decimals(overrides?: TransactionOverrides): Promise<BigNumber>;
"decimals()"(overrides?: TransactionOverrides): Promise<BigNumber>;
decreaseAllowance(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"decreaseAllowance(address,uint256)"(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
increaseAllowance(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"increaseAllowance(address,uint256)"(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
name(overrides?: TransactionOverrides): Promise<BigNumber>;
"name()"(overrides?: TransactionOverrides): Promise<BigNumber>;
symbol(overrides?: TransactionOverrides): Promise<BigNumber>;
"symbol()"(overrides?: TransactionOverrides): Promise<BigNumber>;
totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>;
"totalSupply()"(overrides?: TransactionOverrides): Promise<BigNumber>;
transfer(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"transfer(address,uint256)"(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
transferFrom(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"transferFrom(address,address,uint256)"(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
};
}

File diff suppressed because one or more lines are too long

View File

@ -1,469 +0,0 @@
/* Generated by ts-generator ver. 0.0.8 */
/* tslint:disable */
import { Contract, ContractTransaction, EventFilter, Signer } from "ethers";
import { Listener, Provider } from "ethers/providers";
import { Arrayish, BigNumber, BigNumberish, Interface } from "ethers/utils";
import {
TransactionOverrides,
TypedEventDescription,
TypedFunctionDescription
} from ".";
interface WormholeInterface extends Interface {
functions: {
consumedVAAs: TypedFunctionDescription<{ encode([]: [Arrayish]): string }>;
guardian_set_expirity: TypedFunctionDescription<{ encode([]: []): string }>;
guardian_set_index: TypedFunctionDescription<{ encode([]: []): string }>;
guardian_sets: TypedFunctionDescription<{
encode([]: [BigNumberish]): string;
}>;
isWrappedAsset: TypedFunctionDescription<{ encode([]: [string]): string }>;
wrappedAssetMaster: TypedFunctionDescription<{ encode([]: []): string }>;
wrappedAssets: TypedFunctionDescription<{ encode([]: [Arrayish]): string }>;
getGuardianSet: TypedFunctionDescription<{
encode([idx]: [BigNumberish]): string;
}>;
submitVAA: TypedFunctionDescription<{ encode([vaa]: [Arrayish]): string }>;
lockAssets: TypedFunctionDescription<{
encode([asset, amount, recipient, target_chain, nonce, refund_dust]: [
string,
BigNumberish,
Arrayish,
BigNumberish,
BigNumberish,
boolean
]): string;
}>;
lockETH: TypedFunctionDescription<{
encode([recipient, target_chain, nonce]: [
Arrayish,
BigNumberish,
BigNumberish
]): string;
}>;
};
events: {
LogGuardianSetChanged: TypedEventDescription<{
encodeTopics([oldGuardianIndex, newGuardianIndex]: [
null,
null
]): string[];
}>;
LogTokensLocked: TypedEventDescription<{
encodeTopics([
target_chain,
token_chain,
token_decimals,
token,
sender,
recipient,
amount,
nonce
]: [
null,
null,
null,
Arrayish | null,
Arrayish | null,
null,
null,
null
]): string[];
}>;
};
}
export class Wormhole extends Contract {
connect(signerOrProvider: Signer | Provider | string): Wormhole;
attach(addressOrName: string): Wormhole;
deployed(): Promise<Wormhole>;
on(event: EventFilter | string, listener: Listener): Wormhole;
once(event: EventFilter | string, listener: Listener): Wormhole;
addListener(eventName: EventFilter | string, listener: Listener): Wormhole;
removeAllListeners(eventName: EventFilter | string): Wormhole;
removeListener(eventName: any, listener: Listener): Wormhole;
interface: WormholeInterface;
functions: {
consumedVAAs(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<boolean>;
"consumedVAAs(bytes32)"(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<boolean>;
guardian_set_expirity(overrides?: TransactionOverrides): Promise<number>;
"guardian_set_expirity()"(
overrides?: TransactionOverrides
): Promise<number>;
guardian_set_index(overrides?: TransactionOverrides): Promise<number>;
"guardian_set_index()"(overrides?: TransactionOverrides): Promise<number>;
guardian_sets(
arg0: BigNumberish,
overrides?: TransactionOverrides
): Promise<number>;
"guardian_sets(uint32)"(
arg0: BigNumberish,
overrides?: TransactionOverrides
): Promise<number>;
isWrappedAsset(
arg0: string,
overrides?: TransactionOverrides
): Promise<boolean>;
"isWrappedAsset(address)"(
arg0: string,
overrides?: TransactionOverrides
): Promise<boolean>;
wrappedAssetMaster(overrides?: TransactionOverrides): Promise<string>;
"wrappedAssetMaster()"(overrides?: TransactionOverrides): Promise<string>;
wrappedAssets(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<string>;
"wrappedAssets(bytes32)"(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<string>;
getGuardianSet(
idx: BigNumberish,
overrides?: TransactionOverrides
): Promise<{
keys: string[];
expiration_time: number;
0: string[];
1: number;
}>;
"getGuardianSet(uint32)"(
idx: BigNumberish,
overrides?: TransactionOverrides
): Promise<{
keys: string[];
expiration_time: number;
0: string[];
1: number;
}>;
submitVAA(
vaa: Arrayish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"submitVAA(bytes)"(
vaa: Arrayish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
lockAssets(
asset: string,
amount: BigNumberish,
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
refund_dust: boolean,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"lockAssets(address,uint256,bytes32,uint8,uint32,bool)"(
asset: string,
amount: BigNumberish,
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
refund_dust: boolean,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
lockETH(
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"lockETH(bytes32,uint8,uint32)"(
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
};
consumedVAAs(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<boolean>;
"consumedVAAs(bytes32)"(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<boolean>;
guardian_set_expirity(overrides?: TransactionOverrides): Promise<number>;
"guardian_set_expirity()"(overrides?: TransactionOverrides): Promise<number>;
guardian_set_index(overrides?: TransactionOverrides): Promise<number>;
"guardian_set_index()"(overrides?: TransactionOverrides): Promise<number>;
guardian_sets(
arg0: BigNumberish,
overrides?: TransactionOverrides
): Promise<number>;
"guardian_sets(uint32)"(
arg0: BigNumberish,
overrides?: TransactionOverrides
): Promise<number>;
isWrappedAsset(
arg0: string,
overrides?: TransactionOverrides
): Promise<boolean>;
"isWrappedAsset(address)"(
arg0: string,
overrides?: TransactionOverrides
): Promise<boolean>;
wrappedAssetMaster(overrides?: TransactionOverrides): Promise<string>;
"wrappedAssetMaster()"(overrides?: TransactionOverrides): Promise<string>;
wrappedAssets(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<string>;
"wrappedAssets(bytes32)"(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<string>;
getGuardianSet(
idx: BigNumberish,
overrides?: TransactionOverrides
): Promise<{
keys: string[];
expiration_time: number;
0: string[];
1: number;
}>;
"getGuardianSet(uint32)"(
idx: BigNumberish,
overrides?: TransactionOverrides
): Promise<{
keys: string[];
expiration_time: number;
0: string[];
1: number;
}>;
submitVAA(
vaa: Arrayish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"submitVAA(bytes)"(
vaa: Arrayish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
lockAssets(
asset: string,
amount: BigNumberish,
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
refund_dust: boolean,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"lockAssets(address,uint256,bytes32,uint8,uint32,bool)"(
asset: string,
amount: BigNumberish,
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
refund_dust: boolean,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
lockETH(
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"lockETH(bytes32,uint8,uint32)"(
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
filters: {
LogGuardianSetChanged(
oldGuardianIndex: null,
newGuardianIndex: null
): EventFilter;
LogTokensLocked(
target_chain: null,
token_chain: null,
token_decimals: null,
token: Arrayish | null,
sender: Arrayish | null,
recipient: null,
amount: null,
nonce: null
): EventFilter;
};
estimate: {
consumedVAAs(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"consumedVAAs(bytes32)"(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
guardian_set_expirity(overrides?: TransactionOverrides): Promise<BigNumber>;
"guardian_set_expirity()"(
overrides?: TransactionOverrides
): Promise<BigNumber>;
guardian_set_index(overrides?: TransactionOverrides): Promise<BigNumber>;
"guardian_set_index()"(
overrides?: TransactionOverrides
): Promise<BigNumber>;
guardian_sets(
arg0: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"guardian_sets(uint32)"(
arg0: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
isWrappedAsset(
arg0: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"isWrappedAsset(address)"(
arg0: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
wrappedAssetMaster(overrides?: TransactionOverrides): Promise<BigNumber>;
"wrappedAssetMaster()"(
overrides?: TransactionOverrides
): Promise<BigNumber>;
wrappedAssets(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"wrappedAssets(bytes32)"(
arg0: Arrayish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
getGuardianSet(
idx: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"getGuardianSet(uint32)"(
idx: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
submitVAA(
vaa: Arrayish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"submitVAA(bytes)"(
vaa: Arrayish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
lockAssets(
asset: string,
amount: BigNumberish,
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
refund_dust: boolean,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"lockAssets(address,uint256,bytes32,uint8,uint32,bool)"(
asset: string,
amount: BigNumberish,
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
refund_dust: boolean,
overrides?: TransactionOverrides
): Promise<BigNumber>;
lockETH(
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"lockETH(bytes32,uint8,uint32)"(
recipient: Arrayish,
target_chain: BigNumberish,
nonce: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
};
}

File diff suppressed because one or more lines are too long

View File

@ -1,778 +0,0 @@
/* Generated by ts-generator ver. 0.0.8 */
/* tslint:disable */
import { Contract, ContractTransaction, EventFilter, Signer } from "ethers";
import { Listener, Provider } from "ethers/providers";
import { Arrayish, BigNumber, BigNumberish, Interface } from "ethers/utils";
import {
TransactionOverrides,
TypedEventDescription,
TypedFunctionDescription
} from ".";
interface WrappedAssetInterface extends Interface {
functions: {
assetAddress: TypedFunctionDescription<{ encode([]: []): string }>;
assetChain: TypedFunctionDescription<{ encode([]: []): string }>;
bridge: TypedFunctionDescription<{ encode([]: []): string }>;
initialized: TypedFunctionDescription<{ encode([]: []): string }>;
initialize: TypedFunctionDescription<{
encode([_assetChain, _assetAddress]: [BigNumberish, Arrayish]): string;
}>;
mint: TypedFunctionDescription<{
encode([account, amount]: [string, BigNumberish]): string;
}>;
burn: TypedFunctionDescription<{
encode([account, amount]: [string, BigNumberish]): string;
}>;
name: TypedFunctionDescription<{ encode([]: []): string }>;
symbol: TypedFunctionDescription<{ encode([]: []): string }>;
decimals: TypedFunctionDescription<{ encode([]: []): string }>;
totalSupply: TypedFunctionDescription<{ encode([]: []): string }>;
balanceOf: TypedFunctionDescription<{
encode([account]: [string]): string;
}>;
transfer: TypedFunctionDescription<{
encode([recipient, amount]: [string, BigNumberish]): string;
}>;
allowance: TypedFunctionDescription<{
encode([owner, spender]: [string, string]): string;
}>;
approve: TypedFunctionDescription<{
encode([spender, amount]: [string, BigNumberish]): string;
}>;
transferFrom: TypedFunctionDescription<{
encode([sender, recipient, amount]: [
string,
string,
BigNumberish
]): string;
}>;
increaseAllowance: TypedFunctionDescription<{
encode([spender, addedValue]: [string, BigNumberish]): string;
}>;
decreaseAllowance: TypedFunctionDescription<{
encode([spender, subtractedValue]: [string, BigNumberish]): string;
}>;
};
events: {
Approval: TypedEventDescription<{
encodeTopics([owner, spender, value]: [
string | null,
string | null,
null
]): string[];
}>;
Transfer: TypedEventDescription<{
encodeTopics([from, to, value]: [
string | null,
string | null,
null
]): string[];
}>;
};
}
export class WrappedAsset extends Contract {
connect(signerOrProvider: Signer | Provider | string): WrappedAsset;
attach(addressOrName: string): WrappedAsset;
deployed(): Promise<WrappedAsset>;
on(event: EventFilter | string, listener: Listener): WrappedAsset;
once(event: EventFilter | string, listener: Listener): WrappedAsset;
addListener(
eventName: EventFilter | string,
listener: Listener
): WrappedAsset;
removeAllListeners(eventName: EventFilter | string): WrappedAsset;
removeListener(eventName: any, listener: Listener): WrappedAsset;
interface: WrappedAssetInterface;
functions: {
assetAddress(overrides?: TransactionOverrides): Promise<string>;
"assetAddress()"(overrides?: TransactionOverrides): Promise<string>;
assetChain(overrides?: TransactionOverrides): Promise<number>;
"assetChain()"(overrides?: TransactionOverrides): Promise<number>;
bridge(overrides?: TransactionOverrides): Promise<string>;
"bridge()"(overrides?: TransactionOverrides): Promise<string>;
initialized(overrides?: TransactionOverrides): Promise<boolean>;
"initialized()"(overrides?: TransactionOverrides): Promise<boolean>;
initialize(
_assetChain: BigNumberish,
_assetAddress: Arrayish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"initialize(uint8,bytes32)"(
_assetChain: BigNumberish,
_assetAddress: Arrayish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
mint(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"mint(address,uint256)"(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
burn(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"burn(address,uint256)"(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* Returns the name of the token.
*/
name(overrides?: TransactionOverrides): Promise<string>;
/**
* Returns the name of the token.
*/
"name()"(overrides?: TransactionOverrides): Promise<string>;
/**
* Returns the symbol of the token, usually a shorter version of the name.
*/
symbol(overrides?: TransactionOverrides): Promise<string>;
/**
* Returns the symbol of the token, usually a shorter version of the name.
*/
"symbol()"(overrides?: TransactionOverrides): Promise<string>;
/**
* Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}.
*/
decimals(overrides?: TransactionOverrides): Promise<number>;
/**
* Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}.
*/
"decimals()"(overrides?: TransactionOverrides): Promise<number>;
/**
* See {IERC20-totalSupply}.
*/
totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* See {IERC20-totalSupply}.
*/
"totalSupply()"(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* See {IERC20-balanceOf}.
*/
balanceOf(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-balanceOf}.
*/
"balanceOf(address)"(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`.
*/
transfer(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`.
*/
"transfer(address,uint256)"(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* See {IERC20-allowance}.
*/
allowance(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-allowance}.
*/
"allowance(address,address)"(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-approve}. Requirements: - `spender` cannot be the zero address.
*/
approve(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* See {IERC20-approve}. Requirements: - `spender` cannot be the zero address.
*/
"approve(address,uint256)"(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`.
*/
transferFrom(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`.
*/
"transferFrom(address,address,uint256)"(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address.
*/
increaseAllowance(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address.
*/
"increaseAllowance(address,uint256)"(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`.
*/
decreaseAllowance(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`.
*/
"decreaseAllowance(address,uint256)"(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
};
assetAddress(overrides?: TransactionOverrides): Promise<string>;
"assetAddress()"(overrides?: TransactionOverrides): Promise<string>;
assetChain(overrides?: TransactionOverrides): Promise<number>;
"assetChain()"(overrides?: TransactionOverrides): Promise<number>;
bridge(overrides?: TransactionOverrides): Promise<string>;
"bridge()"(overrides?: TransactionOverrides): Promise<string>;
initialized(overrides?: TransactionOverrides): Promise<boolean>;
"initialized()"(overrides?: TransactionOverrides): Promise<boolean>;
initialize(
_assetChain: BigNumberish,
_assetAddress: Arrayish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"initialize(uint8,bytes32)"(
_assetChain: BigNumberish,
_assetAddress: Arrayish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
mint(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"mint(address,uint256)"(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
burn(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
"burn(address,uint256)"(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* Returns the name of the token.
*/
name(overrides?: TransactionOverrides): Promise<string>;
/**
* Returns the name of the token.
*/
"name()"(overrides?: TransactionOverrides): Promise<string>;
/**
* Returns the symbol of the token, usually a shorter version of the name.
*/
symbol(overrides?: TransactionOverrides): Promise<string>;
/**
* Returns the symbol of the token, usually a shorter version of the name.
*/
"symbol()"(overrides?: TransactionOverrides): Promise<string>;
/**
* Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}.
*/
decimals(overrides?: TransactionOverrides): Promise<number>;
/**
* Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}.
*/
"decimals()"(overrides?: TransactionOverrides): Promise<number>;
/**
* See {IERC20-totalSupply}.
*/
totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* See {IERC20-totalSupply}.
*/
"totalSupply()"(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* See {IERC20-balanceOf}.
*/
balanceOf(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-balanceOf}.
*/
"balanceOf(address)"(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`.
*/
transfer(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`.
*/
"transfer(address,uint256)"(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* See {IERC20-allowance}.
*/
allowance(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-allowance}.
*/
"allowance(address,address)"(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-approve}. Requirements: - `spender` cannot be the zero address.
*/
approve(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* See {IERC20-approve}. Requirements: - `spender` cannot be the zero address.
*/
"approve(address,uint256)"(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`.
*/
transferFrom(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`.
*/
"transferFrom(address,address,uint256)"(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address.
*/
increaseAllowance(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address.
*/
"increaseAllowance(address,uint256)"(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`.
*/
decreaseAllowance(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
/**
* Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`.
*/
"decreaseAllowance(address,uint256)"(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<ContractTransaction>;
filters: {
Approval(
owner: string | null,
spender: string | null,
value: null
): EventFilter;
Transfer(from: string | null, to: string | null, value: null): EventFilter;
};
estimate: {
assetAddress(overrides?: TransactionOverrides): Promise<BigNumber>;
"assetAddress()"(overrides?: TransactionOverrides): Promise<BigNumber>;
assetChain(overrides?: TransactionOverrides): Promise<BigNumber>;
"assetChain()"(overrides?: TransactionOverrides): Promise<BigNumber>;
bridge(overrides?: TransactionOverrides): Promise<BigNumber>;
"bridge()"(overrides?: TransactionOverrides): Promise<BigNumber>;
initialized(overrides?: TransactionOverrides): Promise<BigNumber>;
"initialized()"(overrides?: TransactionOverrides): Promise<BigNumber>;
initialize(
_assetChain: BigNumberish,
_assetAddress: Arrayish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"initialize(uint8,bytes32)"(
_assetChain: BigNumberish,
_assetAddress: Arrayish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
mint(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"mint(address,uint256)"(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
burn(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
"burn(address,uint256)"(
account: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* Returns the name of the token.
*/
name(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* Returns the name of the token.
*/
"name()"(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* Returns the symbol of the token, usually a shorter version of the name.
*/
symbol(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* Returns the symbol of the token, usually a shorter version of the name.
*/
"symbol()"(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}.
*/
decimals(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}.
*/
"decimals()"(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* See {IERC20-totalSupply}.
*/
totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* See {IERC20-totalSupply}.
*/
"totalSupply()"(overrides?: TransactionOverrides): Promise<BigNumber>;
/**
* See {IERC20-balanceOf}.
*/
balanceOf(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-balanceOf}.
*/
"balanceOf(address)"(
account: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`.
*/
transfer(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`.
*/
"transfer(address,uint256)"(
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-allowance}.
*/
allowance(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-allowance}.
*/
"allowance(address,address)"(
owner: string,
spender: string,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-approve}. Requirements: - `spender` cannot be the zero address.
*/
approve(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-approve}. Requirements: - `spender` cannot be the zero address.
*/
"approve(address,uint256)"(
spender: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`.
*/
transferFrom(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`.
*/
"transferFrom(address,address,uint256)"(
sender: string,
recipient: string,
amount: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address.
*/
increaseAllowance(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address.
*/
"increaseAllowance(address,uint256)"(
spender: string,
addedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`.
*/
decreaseAllowance(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
/**
* Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`.
*/
"decreaseAllowance(address,uint256)"(
spender: string,
subtractedValue: BigNumberish,
overrides?: TransactionOverrides
): Promise<BigNumber>;
};
}

File diff suppressed because one or more lines are too long

View File

@ -1,28 +0,0 @@
/* Generated by ts-generator ver. 0.0.8 */
/* tslint:disable */
import {
BigNumberish,
EventDescription,
FunctionDescription
} from "ethers/utils";
export interface TransactionOverrides {
gasLimit?: BigNumberish | Promise<BigNumberish>;
gasPrice?: BigNumberish | Promise<BigNumberish>;
nonce?: BigNumberish | Promise<BigNumberish>;
value?: BigNumberish | Promise<BigNumberish>;
from?: string | Promise<string>;
chainId?: number | Promise<number>;
}
export interface TypedEventDescription<
T extends Pick<EventDescription, "encodeTopics">
> extends EventDescription {
encodeTopics: T["encodeTopics"];
}
export interface TypedFunctionDescription<
T extends Pick<FunctionDescription, "encode">
> extends FunctionDescription {
encode: T["encode"];
}

View File

@ -1,7 +0,0 @@
body {
height: 100%;
}
#root{
height: 100%;
}

View File

@ -1,17 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App/App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

View File

@ -1,7 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -1,426 +0,0 @@
import React, {useContext, useState} from 'react';
import ClientContext from "../providers/ClientContext";
import * as solanaWeb3 from '@solana/web3.js';
import {PublicKey, Transaction} from '@solana/web3.js';
import {Button, message, Progress, Space, Spin, Steps} from "antd";
import {ethers} from "ethers";
import {Erc20Factory} from "../contracts/Erc20Factory";
import {Arrayish, BigNumber, BigNumberish} from "ethers/utils";
import {WormholeFactory} from "../contracts/WormholeFactory";
import {BRIDGE_ADDRESS, TOKEN_PROGRAM} from "../config";
import {SolanaTokenContext} from "../providers/SolanaTokenContext";
import {BridgeContext} from "../providers/BridgeContext";
import TransferInitiator, {defaultCoinInfo, TransferInitiatorData} from "../components/TransferInitiator";
import * as spl from "@solana/spl-token";
import BN from "bn.js"
import {SlotContext} from "../providers/SlotContext";
import WalletContext from "../providers/WalletContext";
// @ts-ignore
if (window.ethereum === undefined) {
alert("Please install the MetaMask extension before using this experimental demo web UI");
}
const {Step} = Steps;
// @ts-ignore
window.ethereum.enable();
// @ts-ignore
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
interface LoadingInfo {
loading: boolean,
message: string,
progress?: ProgressInfo,
}
interface ProgressInfo {
completion: number,
content: string
}
export enum ChainID {
SOLANA = 1,
ETH
}
async function approveAssets(asset: string,
amount: BigNumberish) {
let e = Erc20Factory.connect(asset, signer);
try {
message.loading({content: "Signing transaction...", key: "eth_tx", duration: 1000})
let res = await e.approve(BRIDGE_ADDRESS, amount)
message.loading({content: "Waiting for transaction to be mined...", key: "eth_tx", duration: 1000})
await res.wait(1);
message.success({content: "Approval on ETH succeeded!", key: "eth_tx"})
} catch (e) {
message.error({content: "Approval failed", key: "eth_tx"})
}
}
function Assistant() {
let c = useContext<solanaWeb3.Connection>(ClientContext);
let tokenAccounts = useContext(SolanaTokenContext);
let bridge = useContext(BridgeContext);
let wallet = useContext(WalletContext);
let slot = useContext(SlotContext);
let [fromNetwork, setFromNetwork] = useState(ChainID.ETH)
let [transferData, setTransferData] = useState<TransferInitiatorData>({
fromCoinInfo: defaultCoinInfo,
fromNetwork: 0,
toNetwork: 0,
toAddress: new Buffer(0),
amount: new BigNumber(0),
});
let [loading, setLoading] = useState<LoadingInfo>({
loading: false,
message: "",
progress: undefined
})
let [current, setCurrent] = useState(0);
let nextStep = (from: string) => {
setLoading({
...loading,
loading: false
})
if (from == "approve") {
lockAssets(transferData.fromCoinInfo.address, transferData.amount, transferData.toAddress, transferData.toNetwork)
} else if (from == "lock") {
// Await approvals or allow to submit guardian shit
if (fromNetwork == ChainID.ETH && transferData.toNetwork == ChainID.SOLANA) {
awaitCompletionEth()
} else if (fromNetwork == ChainID.SOLANA && transferData.toNetwork == ChainID.ETH) {
awaitCompletionSolana()
}
} else if (from == "vaa") {
postVAAOnEth()
}
setCurrent((v) => v + 1)
}
const lockAssets = async function (asset: string,
amount: BigNumberish,
recipient: Arrayish,
target_chain: BigNumberish) {
let wh = WormholeFactory.connect(BRIDGE_ADDRESS, signer);
try {
setLoading({
...loading,
loading: true,
message: "Allow transfer in Metamask...",
})
let res = await wh.lockAssets(asset, amount, recipient, target_chain, 10, false)
setLoading({
...loading,
loading: true,
message: "Waiting for transaction to be mined...",
})
await res.wait(1);
message.success({content: "Transfer on ETH succeeded!", key: "eth_tx"})
nextStep("lock");
} catch (e) {
message.error({content: "Transfer failed", key: "eth_tx"})
setCurrent(0);
setLoading({
...loading,
loading: false,
})
}
}
const approveAssets = async function (asset: string,
amount: BigNumberish) {
let e = Erc20Factory.connect(asset, signer);
try {
setLoading({
...loading,
loading: true,
message: "Allow approval in Metamask...",
})
let res = await e.approve(BRIDGE_ADDRESS, amount)
setLoading({
...loading,
loading: true,
message: "Waiting for transaction to be mined...",
})
await res.wait(1);
message.success({content: "Approval on ETH succeeded!", key: "eth_tx"})
nextStep("approve")
} catch (e) {
message.error({content: "Approval failed", key: "eth_tx"})
setCurrent(0);
setLoading({
loading: false,
...loading
})
}
}
const initiateTransfer = () => {
if (fromNetwork == ChainID.ETH && transferData.fromCoinInfo) {
nextStep("init")
if (transferData.fromCoinInfo?.allowance.lt(transferData.amount)) {
approveAssets(transferData.fromCoinInfo.address, transferData.amount)
} else {
lockAssets(transferData.fromCoinInfo.address, transferData.amount, transferData.toAddress, transferData.toNetwork)
}
} else if (fromNetwork == ChainID.SOLANA && transferData.fromCoinInfo) {
nextStep("init")
solanaTransfer();
}
}
let transferProposal: PublicKey;
let transferVAA = new Uint8Array(0);
const solanaTransfer = async () => {
setLoading({
...loading,
loading: true,
message: "Locking tokens on Solana...",
})
let {
ix: lock_ix,
transferKey
} = await bridge.createLockAssetInstruction(wallet.publicKey, new PublicKey(transferData.fromCoinInfo.address),
new PublicKey(transferData.fromCoinInfo.mint), new BN(transferData.amount.toString()),
transferData.toNetwork, transferData.toAddress,
{
chain: transferData.fromCoinInfo.chainID,
address: transferData.fromCoinInfo.assetAddress,
decimals: transferData.fromCoinInfo.decimals,
}, Math.random() * 100000);
let ix = spl.Token.createApproveInstruction(TOKEN_PROGRAM, new PublicKey(transferData.fromCoinInfo.address), await bridge.getConfigKey(), wallet.publicKey, [], transferData.amount.toNumber())
let bridge_account = await bridge.getConfigKey();
let fee_ix = solanaWeb3.SystemProgram.transfer({
fromPubkey: wallet.publicKey,
toPubkey: bridge_account,
lamports: await bridge.getTransferFee()
});
let recentHash = await c.getRecentBlockhash();
let tx = new Transaction();
tx.recentBlockhash = recentHash.blockhash
tx.add(ix)
tx.add(fee_ix)
tx.add(lock_ix)
tx.feePayer = wallet.publicKey;
let signed = await wallet.signTransaction(tx)
try {
await c.sendRawTransaction(signed.serialize())
message.success({content: "Transfer succeeded", key: "transfer"})
} catch (e) {
message.error({content: "Transfer failed", key: "transfer"})
}
transferProposal = transferKey
nextStep("lock")
}
const executeVAAOnETH = async (vaa: Uint8Array) => {
let wh = WormholeFactory.connect(BRIDGE_ADDRESS, signer)
setLoading({
...loading,
loading: true,
message: "Sign the claim...",
})
let tx = await wh.submitVAA(vaa)
setLoading({
...loading,
loading: true,
message: "Waiting for tokens unlock to be mined...",
})
await tx.wait(1)
message.success({content: "Execution of VAA succeeded", key: "eth_tx"})
nextStep("submit")
}
const awaitCompletionEth = () => {
let startBlock = provider.blockNumber;
let completed = false;
let blockHandler = (blockNumber: number) => {
if (blockNumber - startBlock < 15) {
setLoading({
loading: true,
message: "Awaiting ETH confirmations",
progress: {
completion: (blockNumber - startBlock) / 15 * 100,
content: `${blockNumber - startBlock}/${15}`
}
})
} else if (!completed) {
provider.removeListener("block", blockHandler)
setLoading({loading: true, message: "Awaiting completion on Solana"})
}
}
provider.on("block", blockHandler)
let accountChangeListener = c.onAccountChange(new PublicKey(transferData.toAddress), () => {
if (completed) return;
completed = true;
provider.removeListener("block", blockHandler)
c.removeAccountChangeListener(accountChangeListener);
nextStep("await")
}, "single")
}
const awaitCompletionSolana = () => {
let completed = false;
let startSlot = slot;
let slotUpdateListener = c.onSlotChange((slot) => {
if (completed) return;
if (slot.slot - startSlot < 32) {
setLoading({
loading: true,
message: "Awaiting confirmations",
progress: {
completion: (slot.slot - startSlot) / 32 * 100,
content: `${slot.slot - startSlot}/${32}`
}
})
} else {
setLoading({loading: true, message: "Awaiting guardian confirmation"})
}
})
let accountChangeListener = c.onAccountChange(transferProposal, async (a) => {
if (completed) return;
let lockup = bridge.parseLockup(transferProposal, a.data);
let vaa = lockup.vaa;
console.log(lockup)
for (let i = vaa.length; i > 0; i--) {
if (vaa[i] == 0xff) {
vaa = vaa.slice(0, i)
break
}
}
// Probably a poke
if (vaa.filter(v => v != 0).length == 0) {
return
}
completed = true;
c.removeAccountChangeListener(accountChangeListener);
c.removeSlotChangeListener(slotUpdateListener);
let signatures = await bridge.fetchSignatureStatus(lockup.signatureAccount);
let sigData = Buffer.of(...signatures.reduce((previousValue, currentValue) => {
previousValue.push(currentValue.index)
previousValue.push(...currentValue.signature)
return previousValue
}, new Array<number>()))
vaa = Buffer.concat([vaa.slice(0, 5), Buffer.of(signatures.length), sigData, vaa.slice(6)])
transferVAA = vaa
nextStep("vaa")
}, "single")
}
const postVAAOnEth = () => {
executeVAAOnETH(transferVAA);
}
const steps = [
{
title: 'Initiate Transfer',
content: (
<>
<TransferInitiator onFromNetworkChanged={setFromNetwork} dataChanged={(d) => {
setTransferData(d);
}}/>
<Button onClick={initiateTransfer}>Transfer</Button>
</>),
},
];
if (fromNetwork == ChainID.ETH) {
if (transferData.fromCoinInfo && transferData.fromCoinInfo.allowance.lt(transferData.amount)) {
steps.push({
title: 'Approval',
content: (<></>),
})
}
steps.push(...[
{
title: 'Transfer',
content: (<></>),
},
{
title: 'Wait for confirmations',
content: (<></>),
},
{
title: 'Done',
content: (<><Space align="center" style={{width: "100%", paddingTop: "128px", paddingBottom: "128px"}}
direction="vertical">
<Progress type="circle" percent={100} format={() => 'Done'}/>
<b>Your transfer has been completed</b>
</Space></>),
},
])
} else {
steps.push(...[
{
title: 'Transfer',
content: (<></>),
},
{
title: 'Wait for approval',
content: (<></>),
},
{
title: 'Claim tokens on ETH',
content: (<></>),
},
{
title: 'Done',
content: (<><Space align="center" style={{width: "100%", paddingTop: "128px", paddingBottom: "128px"}}
direction="vertical">
<Progress type="circle" percent={100} format={() => 'Done'}/>
<b>Your transfer has been completed</b>
</Space></>),
},
])
}
return (
<>
<Steps current={current}>
{steps.map(item => (
<Step key={item.title} title={item.title}/>
))}
</Steps>
<div className="steps-content"
style={{marginTop: "24px", marginBottom: "24px"}}>
{loading.loading ? loading.progress ? (
<Space align="center" style={{width: "100%", paddingTop: "128px", paddingBottom: "128px"}}
direction="vertical">
<ProgressIndicator {...loading.progress}/>
<b>{loading.message}</b>
</Space>) :
<Space align="center" style={{width: "100%", paddingTop: "128px", paddingBottom: "128px"}}
direction="vertical">
<Spin size={"large"}/>
<b>{loading.message}</b>
</Space> : steps[current].content}
</div>
</>
);
}
let ProgressIndicator = (params: { completion: number, content: string }) => {
return (<Progress type="circle" percent={params.completion} format={() => params.content}/>)
}
export default Assistant;

View File

@ -1,101 +0,0 @@
import React, { useState, useEffect } from 'react';
import { Form, Input, Button, List } from 'antd';
import { ethers } from "ethers";
import { BRIDGE_ADDRESS } from "../config";
import { ImplementationFactory } from '../contracts/ImplementationFactory';
// @ts-ignore
if (window.ethereum === undefined) {
alert("Please install the MetaMask extension before using this experimental demo web UI");
}
// @ts-ignore
window.ethereum.enable();
// @ts-ignore
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
function Message() {
const [form] = Form.useForm();
const [, forceUpdate] = useState({});
// map: { txHash: payloadString }
const [txHashToPayload, setTxHashToPayload] = useState<{ [txHash: string]: string }>({})
// To disable submit button at the beginning.
useEffect(() => {
forceUpdate({});
}, []);
const sendMessage = async ({ payload }: { payload: string }) => {
let nonceConst = Math.random() * 100000
let nonceBuffer = Buffer.alloc(4);
nonceBuffer.writeUInt32LE(nonceConst, 0)
let i = ImplementationFactory.connect(BRIDGE_ADDRESS, signer)
let res = await i.publishMessage(nonceBuffer, Buffer.from(payload, 'utf16le'), true)
await res.wait(1)
if (res.hash) {
setTxHashToPayload({ ...txHashToPayload, [res.hash]: payload })
}
form.resetFields(['payload'])
}
const rmTxHash = (txHash: string) => {
const { [txHash]: rm, ...others } = txHashToPayload
setTxHashToPayload(others)
return undefined // for typescript
}
return (
<>
<Form form={form} name="publish_message" layout="inline" onFinish={sendMessage}>
<Form.Item>
<h1><code>publishMessage</code></h1>
</Form.Item>
<Form.Item
name="payload"
rules={[{ required: true, message: 'Please enter a payload for the message.' }]}
>
<Input.TextArea placeholder="Payload to write to ETH" />
</Form.Item>
<Form.Item shouldUpdate>
{() => (
<Button
type="primary"
htmlType="submit"
disabled={
!form.isFieldsTouched(true) ||
!!form.getFieldsError().filter(({ errors }) => errors.length).length
}
>
Send to MetaMask
</Button>
)}
</Form.Item>
</Form>
{Object.keys(txHashToPayload).length >= 1 ? (
<List
dataSource={Object.keys(txHashToPayload)}
renderItem={item => (
<List.Item
actions={[<a onClick={() => rmTxHash(item)} >X</a>]}
>
<div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
<h4><code>{item}</code></h4>
<h4><code><pre>{txHashToPayload[item]}</pre></code></h4>
</div>
</List.Item>
)}
/>
) : null}
</>
);
}
export default Message;

View File

@ -1,297 +0,0 @@
import React, {useContext, useEffect, useState} from 'react';
import ClientContext from "../providers/ClientContext";
import * as solanaWeb3 from '@solana/web3.js';
import {Account, Connection, PublicKey, Transaction} from '@solana/web3.js';
import {Button, Card, Col, Divider, Form, Input, InputNumber, List, message, Row, Select} from "antd";
import {ethers} from "ethers";
import {Erc20Factory} from "../contracts/Erc20Factory";
import {Arrayish, BigNumber, BigNumberish} from "ethers/utils";
import {WormholeFactory} from "../contracts/WormholeFactory";
import {WrappedAssetFactory} from "../contracts/WrappedAssetFactory";
import {BRIDGE_ADDRESS} from "../config";
import {SolanaTokenContext} from "../providers/SolanaTokenContext";
import {BridgeContext} from "../providers/BridgeContext";
import {AssetMeta, SolanaBridge} from "../utils/bridge";
import {FormInstance} from "antd/lib/form";
import SplBalances from "../components/SplBalances";
import TransferProposals from "../components/TransferProposals";
import WalletContext from "../providers/WalletContext";
import Wallet from "@project-serum/sol-wallet-adapter";
// @ts-ignore
if (window.ethereum === undefined) {
alert("Please install the MetaMask extension before using this experimental demo web UI");
}
// @ts-ignore
window.ethereum.enable();
// @ts-ignore
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
async function lockAssets(asset: string,
amount: BigNumberish,
recipient: Arrayish,
target_chain: BigNumberish) {
let wh = WormholeFactory.connect(BRIDGE_ADDRESS, signer);
try {
message.loading({content: "Signing transaction...", key: "eth_tx", duration: 1000},)
let res = await wh.lockAssets(asset, amount, recipient, target_chain, 10, false)
message.loading({content: "Waiting for transaction to be mined...", key: "eth_tx", duration: 1000})
await res.wait(1);
message.success({content: "Transfer on ETH succeeded!", key: "eth_tx"})
} catch (e) {
console.log(e)
message.error({content: "Transfer failed", key: "eth_tx"})
}
}
async function approveAssets(asset: string,
amount: BigNumberish) {
let e = Erc20Factory.connect(asset, signer);
try {
message.loading({content: "Signing transaction...", key: "eth_tx", duration: 1000})
let res = await e.approve(BRIDGE_ADDRESS, amount)
message.loading({content: "Waiting for transaction to be mined...", key: "eth_tx", duration: 1000})
await res.wait(1);
message.success({content: "Approval on ETH succeeded!", key: "eth_tx"})
} catch (e) {
message.error({content: "Approval failed", key: "eth_tx"})
}
}
async function createWrapped(c: Connection, b: SolanaBridge, wallet: Wallet, meta: AssetMeta, mint: PublicKey) {
try {
let tx = new Transaction();
// @ts-ignore
let [ix_account, newSigner] = await b.createWrappedAssetAndAccountInstructions(key.publicKey, mint, meta);
let recentHash = await c.getRecentBlockhash();
tx.recentBlockhash = recentHash.blockhash
tx.add(...ix_account)
tx.sign(newSigner)
tx.feePayer = wallet.publicKey;
let signed = await wallet.signTransaction(tx);
message.loading({content: "Waiting for transaction to be confirmed...", key: "tx", duration: 1000})
await c.sendRawTransaction(signed.serialize())
message.success({content: "Creation succeeded!", key: "tx"})
} catch (e) {
console.log(e)
message.error({content: "Creation failed", key: "tx"})
}
}
function Transfer() {
let c = useContext<solanaWeb3.Connection>(ClientContext);
let tokenAccounts = useContext(SolanaTokenContext);
let bridge = useContext(BridgeContext);
let wallet = useContext(WalletContext);
let [coinInfo, setCoinInfo] = useState({
balance: new BigNumber(0),
decimals: 0,
allowance: new BigNumber(0),
isWrapped: false,
chainID: 0,
assetAddress: new Buffer("")
});
let [amount, setAmount] = useState(new BigNumber(0));
let [amountValid, setAmountValid] = useState(false);
let [address, setAddress] = useState("");
let [addressValid, setAddressValid] = useState(false)
let [solanaAccount, setSolanaAccount] = useState({
valid: false,
message: ""
})
let [wrappedMint, setWrappedMint] = useState("")
let [recipient, setRecipient] = useState("")
let [transacting, setTransacting] = useState(false);
let formRef = React.createRef<FormInstance>();
useEffect(() => {
let fetchBalance = async (token: string) => {
try {
let e = WrappedAssetFactory.connect(token, provider);
let addr = await signer.getAddress();
let balance = await e.balanceOf(addr);
let decimals = await e.decimals();
let allowance = await e.allowance(addr, BRIDGE_ADDRESS);
let info = {
balance: balance.div(new BigNumber(10).pow(decimals)),
allowance: allowance.div(new BigNumber(10).pow(decimals)),
decimals: decimals,
isWrapped: false,
chainID: 2,
assetAddress: new Buffer(token.slice(2), "hex")
}
let b = WormholeFactory.connect(BRIDGE_ADDRESS, provider);
let isWrapped = await b.isWrappedAsset(token)
if (isWrapped) {
info.chainID = await e.assetChain()
info.assetAddress = new Buffer((await e.assetAddress()).slice(2), "hex")
info.isWrapped = true
}
setCoinInfo(info)
setAddressValid(true)
} catch (e) {
setAddressValid(false)
}
}
fetchBalance(address)
}, [address, transacting])
useEffect(() => {
if (!addressValid) {
setWrappedMint("")
setSolanaAccount({
valid: false,
message: ""
})
return
}
let getWrappedInfo = async () => {
let wrappedMint = await bridge.getWrappedAssetMint({
chain: coinInfo.chainID,
address: coinInfo.assetAddress,
decimals: Math.min(coinInfo.decimals, 9)
});
setWrappedMint(wrappedMint.toString())
for (let account of tokenAccounts.balances) {
if (account.account.toString() == recipient) {
setSolanaAccount({
valid: true,
message: ""
})
return;
}
}
setSolanaAccount({
valid: false,
message: "Not a valid wrapped token account"
})
}
getWrappedInfo();
}, [address, addressValid, tokenAccounts, bridge])
useEffect(() => {
setAmountValid(amount.lte(coinInfo.balance))
}, [amount, coinInfo])
return (
<>
<Row gutter={12}>
<Col span={12}>
<Form onFinish={(values) => {
let recipient = new solanaWeb3.PublicKey(values["recipient"]).toBuffer()
let transferAmount = new BigNumber(values["amount"]).mul(new BigNumber(10).pow(coinInfo.decimals));
setTransacting(true)
if (coinInfo.allowance.gte(amount) || coinInfo.isWrapped) {
lockAssets(values["address"], transferAmount, recipient, values["target_chain"]).finally(() => {
setTransacting(false)
})
} else {
approveAssets(values["address"], transferAmount).finally(() => {
setTransacting(false)
})
}
}} style={{width: "100%"}} ref={formRef} layout={"vertical"}>
<Form.Item name="address" validateStatus={addressValid ? "success" : "error"} label={"Token:"}>
<Input addonAfter={`Balance: ${coinInfo.balance}`} name="address"
placeholder={"ERC20 address"}
onBlur={(v) => {
setAddress(v.target.value)
}}/>
</Form.Item>
<Form.Item name="amount" validateStatus={amountValid ? "success" : "error"} label={"Amount:"}>
<InputNumber name={"amount"} placeholder={"Amount"} type={"number"} min={0}
onChange={value => {
// @ts-ignore
setAmount(new BigNumber(value) || 0)
}}/>
</Form.Item>
<Form.Item name="target_chain"
label={"Target Chain:"}>
<Select placeholder="Target Chain">
<Select.Option value={1}>
Solana
</Select.Option>
</Select>
</Form.Item>
<Form.Item name="recipient" validateStatus={solanaAccount.valid ? "success" : "error"}
help={recipient === "" ? undefined : solanaAccount.message} label={"Recipient"}>
<Input name="recipient" placeholder={"Address of the recipient"}
onFocus={(v) => {
setRecipient(v.target.value)
}}/>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" style={{marginLeft: "auto"}}
disabled={transacting}>
{coinInfo.allowance.gte(amount) || coinInfo.isWrapped ? "Transfer" : "Approve"}
</Button>
</Form.Item>
</Form>
</Col>
<Col span={12}>
<Card>
<Row justify={"space-between"} align={"middle"}>
<Col>Token Accounts on Solana:</Col>
<Col><Button size={"small"}
disabled={wrappedMint === ""}
onClick={() => {
createWrapped(c, bridge, wallet, {
chain: coinInfo.chainID,
address: coinInfo.assetAddress,
decimals: Math.min(coinInfo.decimals, 9)
}, new PublicKey(wrappedMint))
}}>Create new</Button></Col>
</Row>
<Divider/>
<Row>
<Col span={24}>
<List>
{
tokenAccounts.balances
.filter(value => value.mint == wrappedMint)
.map(v => (
<List.Item
actions={[(<Button size={"small"} type={"dashed"} onClick={() => {
setRecipient(v.account.toString())
formRef.current?.setFieldsValue({
"recipient": v.account.toString()
})
}}>use</Button>)]}>
{v.account.toString()}
</List.Item>
))
}
</List>
</Col>
</Row>
</Card>
</Col>
</Row>
<Row>
<Col>
<SplBalances/>
</Col>
</Row>
<Row>
<Col>
<TransferProposals/>
</Col>
</Row>
</>
);
}
export default Transfer;

View File

@ -1,164 +0,0 @@
import React, {useContext, useEffect, useState} from 'react';
import ClientContext from "../providers/ClientContext";
import * as solanaWeb3 from '@solana/web3.js';
import {PublicKey, Transaction} from '@solana/web3.js';
import * as spl from '@solana/spl-token';
import {Button, Col, Form, Input, InputNumber, message, Row, Select} from "antd";
import {BigNumber} from "ethers/utils";
import SplBalances from "../components/SplBalances";
import {SlotContext} from "../providers/SlotContext";
import {SolanaTokenContext} from "../providers/SolanaTokenContext";
import {CHAIN_ID_SOLANA} from "../utils/bridge";
import {BridgeContext} from "../providers/BridgeContext";
import BN from 'bn.js';
import {TOKEN_PROGRAM} from "../config";
import WalletContext from "../providers/WalletContext";
function TransferSolana() {
let c = useContext<solanaWeb3.Connection>(ClientContext);
let slot = useContext(SlotContext);
let b = useContext(SolanaTokenContext);
let bridge = useContext(BridgeContext);
let wallet = useContext(WalletContext);
let [coinInfo, setCoinInfo] = useState({
balance: new BigNumber(0),
decimals: 0,
isWrapped: false,
chainID: 0,
wrappedAddress: new Buffer([]),
mint: ""
});
let [amount, setAmount] = useState(new BigNumber(0));
let [address, setAddress] = useState("");
let [addressValid, setAddressValid] = useState(false)
useEffect(() => {
async function getCoinInfo() {
let acc = b.balances.find(value => value.account.toString() == address)
if (!acc) {
setAmount(new BigNumber(0));
setAddressValid(false)
return
}
setCoinInfo({
balance: acc.balance,
decimals: acc.decimals,
isWrapped: acc.assetMeta.chain != CHAIN_ID_SOLANA,
chainID: acc.assetMeta.chain,
wrappedAddress: acc.assetMeta.address,
mint: acc.mint
})
setAddressValid(true)
}
getCoinInfo()
}, [address])
return (
<>
<Row gutter={12}>
<Col span={12}>
<p>Transfer from Solana:</p>
<Form onFinish={(values) => {
let recipient = new Buffer(values["recipient"].slice(2), "hex");
let transferAmount = new BN(values["amount"]).mul(new BN(10).pow(new BN(coinInfo.decimals)));
let fromAccount = new PublicKey(values["address"])
let send = async () => {
message.loading({content: "Transferring tokens...", key: "transfer"}, 1000)
let {ix: lock_ix} = await bridge.createLockAssetInstruction(wallet.publicKey, fromAccount, new PublicKey(coinInfo.mint), transferAmount, values["target_chain"], recipient,
{
chain: coinInfo.chainID,
address: coinInfo.wrappedAddress,
decimals: Math.min(coinInfo.decimals, 9)
}, Math.random() * 100000);
let ix = spl.Token.createApproveInstruction(TOKEN_PROGRAM, fromAccount, await bridge.getConfigKey(), wallet.publicKey, [], transferAmount.toNumber())
let bridge_account = await bridge.getConfigKey();
let fee_ix = solanaWeb3.SystemProgram.transfer({
fromPubkey: wallet.publicKey,
toPubkey: bridge_account,
lamports: await bridge.getTransferFee()
});
let recentHash = await c.getRecentBlockhash();
let tx = new Transaction();
tx.recentBlockhash = recentHash.blockhash
tx.add(ix)
tx.add(fee_ix)
tx.add(lock_ix)
tx.feePayer = wallet.publicKey;
let signed = await wallet.signTransaction(tx)
try {
await c.sendRawTransaction(signed.serialize())
message.success({content: "Transfer succeeded", key: "transfer"})
} catch (e) {
message.error({content: "Transfer failed", key: "transfer"})
}
}
send()
}} layout={"vertical"}>
<Form.Item name="address" validateStatus={addressValid ? "success" : "error"}
label={"Token Account:"}>
<Input
addonAfter={`Balance: ${coinInfo.balance.div(new BigNumber(Math.pow(10, coinInfo.decimals)))}`}
name="address"
placeholder={"Token account Pubkey"}
onBlur={(v) => {
setAddress(v.target.value)
}}/>
</Form.Item>
<Form.Item name="amount" rules={[{
required: true, validator: (rule, value, callback) => {
let big = new BigNumber(value).mul(new BigNumber(10).pow(coinInfo.decimals));
callback(big.lte(coinInfo.balance) ? undefined : "Amount exceeds balance")
}
}]} label={"Amount:"}>
<InputNumber name={"amount"} placeholder={"Amount"} type={"number"} onChange={value => {
// @ts-ignore
setAmount(value || 0)
}}/>
</Form.Item>
<Form.Item name="target_chain"
rules={[{required: true, message: "Please choose a target chain"}]}
label={"Target Chain:"}>
<Select placeholder="Target Chain">
<Select.Option value={2}>
Ethereum
</Select.Option>
</Select>
</Form.Item>
<Form.Item name="recipient" rules={[{
required: true,
validator: (rule, value, callback) => {
if (value.length !== 42 || value.indexOf("0x") != 0) {
callback("Invalid address")
} else {
callback()
}
}
}]} label={"Recipient:"}>
<Input name="recipient" placeholder={"Address of the recipient"}/>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Transfer
</Button>
</Form.Item>
</Form>
</Col>
</Row>
<Row>
<Col>
<SplBalances/>
</Col>
</Row>
</>
);
}
export default TransferSolana;

View File

@ -1,19 +0,0 @@
import React, {createContext, FunctionComponent, useContext} from "react"
import ClientContext from "../providers/ClientContext";
import solanaWeb3, {Connection, PublicKey} from "@solana/web3.js";
import {SolanaBridge} from "../utils/bridge";
import {SOLANA_BRIDGE_PROGRAM, TOKEN_PROGRAM} from "../config";
export const BridgeContext = createContext<SolanaBridge>(new SolanaBridge(new Connection(""),SOLANA_BRIDGE_PROGRAM, TOKEN_PROGRAM));
export const BridgeProvider: FunctionComponent = ({children}) => {
let c = useContext<solanaWeb3.Connection>(ClientContext);
let bridge = new SolanaBridge(c, SOLANA_BRIDGE_PROGRAM,TOKEN_PROGRAM)
return (
<BridgeContext.Provider value={bridge}>
{children}
</BridgeContext.Provider>
)
}

View File

@ -1,6 +0,0 @@
import React from 'react'
import * as solanaWeb3 from '@solana/web3.js';
import {SOLANA_HOST} from "../config";
const ClientContext = React.createContext<solanaWeb3.Connection>(new solanaWeb3.Connection(SOLANA_HOST));
export default ClientContext

View File

@ -1,22 +0,0 @@
import React, {createContext, FunctionComponent, useContext, useEffect, useState} from "react"
import ClientContext from "../providers/ClientContext";
import solanaWeb3 from "@solana/web3.js";
export const SlotContext = createContext(0)
export const SlotProvider: FunctionComponent = ({children}) => {
let c = useContext<solanaWeb3.Connection>(ClientContext);
let [slot, setSlot] = useState(0);
useEffect(() => {
c.onSlotChange(value => {
setSlot(value.slot);
});
})
return (
<SlotContext.Provider value={slot}>
{children}
</SlotContext.Provider>
)
}

View File

@ -1,83 +0,0 @@
import React, {createContext, FunctionComponent, useContext, useEffect, useState} from "react"
import ClientContext from "../providers/ClientContext";
import {AccountInfo, ParsedAccountData, PublicKey, RpcResponseAndContext} from "@solana/web3.js";
import {BigNumber} from "ethers/utils";
import {SlotContext} from "./SlotContext";
import {TOKEN_PROGRAM} from "../config";
import {BridgeContext} from "./BridgeContext";
import {message} from "antd";
import {AssetMeta} from "../utils/bridge";
import {Buffer} from "buffer";
import WalletContext from "./WalletContext";
export interface BalanceInfo {
mint: string,
account: PublicKey,
balance: BigNumber,
decimals: number,
assetMeta: AssetMeta
}
export interface TokenInfo {
balances: Array<BalanceInfo>
loading: boolean
}
export const SolanaTokenContext = createContext<TokenInfo>({
balances: [],
loading: false
})
export const SolanaTokenProvider: FunctionComponent = ({children}) => {
let wallet = useContext(WalletContext);
let c = useContext(ClientContext);
let b = useContext(BridgeContext);
let slot = useContext(SlotContext);
let [loading, setLoading] = useState(true)
let [balances, setBalances] = useState<Array<BalanceInfo>>([]);
let [lastUpdate, setLastUpdate] = useState(0);
useEffect(() => {
if (slot - lastUpdate <= 16) {
return
}
setLastUpdate(slot);
// @ts-ignore
setLoading(true)
let getAccounts = async () => {
let res: RpcResponseAndContext<Array<{ pubkey: PublicKey; account: AccountInfo<ParsedAccountData> }>> = await c.getParsedTokenAccountsByOwner(wallet.publicKey, {programId: TOKEN_PROGRAM}, "single")
let meta: AssetMeta[] = [];
for (let acc of res.value) {
let am = await b?.fetchAssetMeta(new PublicKey(acc.account.data.parsed.info.mint))
if (!am) {
throw new Error("could not derive asset meta")
}
am.decimals = acc.account.data.parsed.info.tokenAmount.decimals;
meta.push(am)
}
let balances: Array<BalanceInfo> = await res.value.map((v, i) => {
return {
mint: v.account.data.parsed.info.mint,
account: v.pubkey,
balance: new BigNumber(v.account.data.parsed.info.tokenAmount.amount),
decimals: v.account.data.parsed.info.tokenAmount.decimals,
assetMeta: meta[i],
}
})
setBalances(balances)
setLoading(false)
}
getAccounts();
},
[slot]
)
return (
<SolanaTokenContext.Provider value={{balances, loading}}>
{children}
</SolanaTokenContext.Provider>
)
}

View File

@ -1,6 +0,0 @@
import React from 'react'
import Wallet from '@project-serum/sol-wallet-adapter'
import {SOLANA_HOST} from "../config";
const WalletContext = React.createContext<Wallet>(new Wallet("https://www.sollet.io", SOLANA_HOST));
export default WalletContext

View File

@ -1 +0,0 @@
/// <reference types="react-scripts" />

View File

@ -1,149 +0,0 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
type Config = {
onSuccess?: (registration: ServiceWorkerRegistration) => void;
onUpdate?: (registration: ServiceWorkerRegistration) => void;
};
export function register(config?: Config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(
process.env.PUBLIC_URL,
window.location.href
);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl: string, config?: Config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl: string, config?: Config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' }
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}

14
web/src/sollet.d.ts vendored
View File

@ -1,14 +0,0 @@
declare module '@project-serum/sol-wallet-adapter' {
import EventEmitter = NodeJS.EventEmitter;
import {PublicKey, Transaction} from "@solana/web3.js";
export default class Wallet extends EventEmitter {
public publicKey: PublicKey;
constructor(url: string, network: string);
async connect();
async disconnect();
async signTransaction(tx: Transaction): Promise<Transaction>;
}
}

View File

@ -1,556 +0,0 @@
import * as solanaWeb3 from "@solana/web3.js";
import {PublicKey, TransactionInstruction} from "@solana/web3.js";
import BN from 'bn.js';
import assert from "assert";
import * as spl from '@solana/spl-token';
import {Token} from '@solana/spl-token';
// @ts-ignore
import * as BufferLayout from 'buffer-layout'
import {SOLANA_BRIDGE_PROGRAM, SOLANA_HOST, TOKEN_PROGRAM} from "../config";
import * as bs58 from "bs58";
export interface AssetMeta {
chain: number,
decimals: number,
address: Buffer
}
export interface Lockup {
lockupAddress: PublicKey,
amount: BN,
toChain: number,
sourceAddress: PublicKey,
targetAddress: Uint8Array,
assetAddress: Uint8Array,
assetChain: number,
assetDecimals: number,
nonce: number,
vaa: Uint8Array,
vaaTime: number,
pokeCounter: number,
signatureAccount: PublicKey,
initialized: boolean,
}
export interface Signature {
signature: number[],
index: number,
}
export const CHAIN_ID_SOLANA = 1;
class SolanaBridge {
connection: solanaWeb3.Connection;
programID: PublicKey;
tokenProgram: PublicKey;
constructor(connection: solanaWeb3.Connection, programID: PublicKey, tokenProgram: PublicKey) {
this.programID = programID;
this.tokenProgram = tokenProgram;
this.connection = connection;
}
async createLockAssetInstruction(
payer: PublicKey,
tokenAccount: PublicKey,
mint: PublicKey,
amount: BN,
targetChain: number,
targetAddress: Buffer,
asset: AssetMeta,
nonce: number,
): Promise<{ ix: TransactionInstruction, transferKey: PublicKey }> {
const dataLayout = BufferLayout.struct([
BufferLayout.u8('instruction'),
uint256('amount'),
BufferLayout.u8('targetChain'),
BufferLayout.blob(32, 'assetAddress'),
BufferLayout.u8('assetChain'),
BufferLayout.u8('assetDecimals'),
BufferLayout.blob(32, 'targetAddress'),
BufferLayout.seq(BufferLayout.u8(), 1),
BufferLayout.u32('nonce'),
]);
let nonceBuffer = Buffer.alloc(4);
nonceBuffer.writeUInt32LE(nonce, 0);
// @ts-ignore
let configKey = await this.getConfigKey();
let seeds: Array<Buffer> = [Buffer.from("transfer"), configKey.toBuffer(), new Buffer([asset.chain]),
padBuffer(asset.address, 32), new Buffer([targetChain]), padBuffer(targetAddress, 32), tokenAccount.toBuffer(),
nonceBuffer,
];
// @ts-ignore
let transferKey = (await solanaWeb3.PublicKey.findProgramAddress(seeds, this.programID))[0];
const data = Buffer.alloc(dataLayout.span);
dataLayout.encode(
{
instruction: 1, // TransferOut instruction
amount: padBuffer(new Buffer(amount.toArray()), 32),
targetChain: targetChain,
assetAddress: padBuffer(asset.address, 32),
assetChain: asset.chain,
assetDecimals: asset.decimals,
targetAddress: padBuffer(targetAddress, 32),
nonce: nonce,
},
data,
);
const keys = [
{pubkey: this.programID, isSigner: false, isWritable: false},
{pubkey: solanaWeb3.SystemProgram.programId, isSigner: false, isWritable: false},
{pubkey: this.tokenProgram, isSigner: false, isWritable: false},
{pubkey: solanaWeb3.SYSVAR_RENT_PUBKEY, isSigner: false, isWritable: false},
{pubkey: solanaWeb3.SYSVAR_CLOCK_PUBKEY, isSigner: false, isWritable: false},
{pubkey: solanaWeb3.SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false},
{pubkey: tokenAccount, isSigner: false, isWritable: true},
{pubkey: configKey, isSigner: false, isWritable: false},
{pubkey: transferKey, isSigner: false, isWritable: true},
{pubkey: mint, isSigner: false, isWritable: true},
{pubkey: payer, isSigner: true, isWritable: true},
];
if (asset.chain == CHAIN_ID_SOLANA) {
// @ts-ignore
let custodyKey = (await solanaWeb3.PublicKey.findProgramAddress([Buffer.from("custody"), configKey.toBuffer(), mint.toBuffer()], this.programID))[0];
keys.push({pubkey: custodyKey, isSigner: false, isWritable: true})
}
return {
ix: new TransactionInstruction({
keys,
programId: this.programID,
data,
}),
transferKey: transferKey,
};
}
createPokeProposalInstruction(
proposalAccount: PublicKey,
): TransactionInstruction {
const dataLayout = BufferLayout.struct([BufferLayout.u8('instruction'),]);
const data = Buffer.alloc(dataLayout.span);
dataLayout.encode(
{
instruction: 5, // PokeProposal instruction
},
data,
);
const keys = [
{pubkey: proposalAccount, isSigner: false, isWritable: true},
];
return new TransactionInstruction({
keys,
programId: this.programID,
data,
});
}
// fetchAssetMeta fetches the AssetMeta for an SPL token
async fetchAssetMeta(
mint: PublicKey,
): Promise<AssetMeta> {
// @ts-ignore
let configKey = await this.getConfigKey();
let seeds: Array<Buffer> = [Buffer.from("meta"), configKey.toBuffer(), mint.toBuffer()];
// @ts-ignore
let metaKey = (await solanaWeb3.PublicKey.findProgramAddress(seeds, this.programID))[0];
let metaInfo = await this.connection.getAccountInfo(metaKey);
if (metaInfo == null || metaInfo.lamports == 0) {
return {
address: mint.toBuffer(),
chain: CHAIN_ID_SOLANA,
decimals: 0,
}
} else {
const dataLayout = BufferLayout.struct([
BufferLayout.u8('assetChain'),
BufferLayout.blob(32, 'assetAddress'),
]);
let wrappedMeta = dataLayout.decode(metaInfo?.data);
return {
address: wrappedMeta.assetAddress,
chain: wrappedMeta.assetChain,
decimals: 0
}
}
}
// fetchSignatureStatus fetches the signatures for a VAA
async fetchSignatureStatus(
signatureStatus: PublicKey,
): Promise<Signature[]> {
let signatureInfo = await this.connection.getAccountInfo(signatureStatus, "single");
if (signatureInfo == null || signatureInfo.lamports == 0) {
throw new Error("not found")
} else {
const dataLayout = BufferLayout.struct([
BufferLayout.blob(20 * 65, 'signaturesRaw'),
]);
let rawSignatureInfo = dataLayout.decode(signatureInfo?.data);
let signatures: Signature[] = [];
for (let i = 0; i < 20; i++) {
let data = rawSignatureInfo.signaturesRaw.slice(65 * i, 65 * (i + 1));
let empty = true;
for (let v of data) {
if (v != 0) {
empty = false;
break
}
}
if (empty) continue;
signatures.push({
signature: data,
index: i,
})
}
return signatures;
}
}
parseLockup(address: PublicKey, data: Buffer): Lockup {
const dataLayout = BufferLayout.struct([
uint256('amount'),
BufferLayout.u8('toChain'),
BufferLayout.blob(32, 'sourceAddress'),
BufferLayout.blob(32, 'targetAddress'),
BufferLayout.blob(32, 'assetAddress'),
BufferLayout.u8('assetChain'),
BufferLayout.u8('assetDecimals'),
BufferLayout.seq(BufferLayout.u8(), 1), // 4 byte alignment because a u32 is following
BufferLayout.u32('nonce'),
BufferLayout.blob(1001, 'vaa'),
BufferLayout.seq(BufferLayout.u8(), 3), // 4 byte alignment because a u32 is following
BufferLayout.u32('vaaTime'),
BufferLayout.u32('lockupTime'),
BufferLayout.u8('pokeCounter'),
BufferLayout.blob(32, 'signatureAccount'),
BufferLayout.u8('initialized'),
]);
let parsedAccount = dataLayout.decode(data)
return {
lockupAddress: address,
amount: new BN(parsedAccount.amount, 2, "le"),
assetAddress: parsedAccount.assetAddress,
assetChain: parsedAccount.assetChain,
assetDecimals: parsedAccount.assetDecimals,
initialized: parsedAccount.initialized == 1,
nonce: parsedAccount.nonce,
sourceAddress: new PublicKey(parsedAccount.sourceAddress),
targetAddress: parsedAccount.targetAddress,
toChain: parsedAccount.toChain,
vaa: parsedAccount.vaa,
vaaTime: parsedAccount.vaaTime,
signatureAccount: new PublicKey(parsedAccount.signatureAccount),
pokeCounter: parsedAccount.pokeCounter
}
}
// fetchAssetMeta fetches the AssetMeta for an SPL token
async fetchTransferProposals(
tokenAccount: PublicKey,
): Promise<Lockup[]> {
let accountRes = await fetch(SOLANA_HOST, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"jsonrpc": "2.0",
"id": 1,
"method": "getProgramAccounts",
"params": [this.programID.toString(), {
"commitment": "single",
"filters": [{"dataSize": 1184}, {
"memcmp": {
"offset": 33,
"bytes": tokenAccount.toString()
}
}]
}]
}),
})
let raw_accounts = (await accountRes.json())["result"];
let accounts: Lockup[] = [];
for (let acc of raw_accounts) {
let pubkey = new PublicKey(acc.pubkey)
accounts.push(this.parseLockup(pubkey, bs58.decode(acc.account.data)))
}
return accounts
}
AccountLayout = BufferLayout.struct([publicKey('mint'), publicKey('owner'), uint64('amount'), BufferLayout.u32('option'), publicKey('delegate'), BufferLayout.u8('is_initialized'), BufferLayout.u8('is_native'), BufferLayout.u16('padding'), uint64('delegatedAmount')]);
async createWrappedAssetAndAccountInstructions(owner: PublicKey, mint: PublicKey, meta: AssetMeta): Promise<[TransactionInstruction[], solanaWeb3.Account]> {
const newAccount = new solanaWeb3.Account();
// @ts-ignore
const balanceNeeded = await Token.getMinBalanceRentForExemptAccount(this.connection);
let create_ix = solanaWeb3.SystemProgram.createAccount({
fromPubkey: owner,
newAccountPubkey: newAccount.publicKey,
lamports: balanceNeeded,
space: spl.AccountLayout.span,
programId: TOKEN_PROGRAM,
}); // create the new account
const keys = [{
pubkey: newAccount.publicKey,
isSigner: false,
isWritable: true
}, {
pubkey: mint,
isSigner: false,
isWritable: false
}, {
pubkey: owner,
isSigner: false,
isWritable: false
}, {
pubkey: solanaWeb3.SYSVAR_RENT_PUBKEY,
isSigner: false,
isWritable: false
}];
const dataLayout = BufferLayout.struct([BufferLayout.u8('instruction')]);
const data = Buffer.alloc(dataLayout.span);
dataLayout.encode({
instruction: 1 // InitializeAccount instruction
}, data);
let ix_init = {
keys,
programId: TOKEN_PROGRAM,
data
}
let ixs: TransactionInstruction[] = [];
let configKey = await this.getConfigKey();
let wrappedKey = await this.getWrappedAssetMint(meta);
let wrappedAcc = await this.connection.getAccountInfo(wrappedKey, "single");
if (!wrappedAcc) {
let metaKey = await this.getWrappedAssetMeta(wrappedKey);
const wa_keys = [{
pubkey: solanaWeb3.SystemProgram.programId,
isSigner: false,
isWritable: false
}, {
pubkey: TOKEN_PROGRAM,
isSigner: false,
isWritable: false
}, {
pubkey: solanaWeb3.SYSVAR_RENT_PUBKEY,
isSigner: false,
isWritable: false
}, {
pubkey: configKey,
isSigner: false,
isWritable: false
}, {
pubkey: owner,
isSigner: true,
isWritable: true
}, {
pubkey: wrappedKey,
isSigner: false,
isWritable: true
}, {
pubkey: metaKey,
isSigner: false,
isWritable: true
}];
const wrappedDataLayout = BufferLayout.struct([BufferLayout.u8('instruction'), BufferLayout.blob(32, "assetAddress"), BufferLayout.u8('chain'), BufferLayout.u8('decimals')]);
const wrappedData = Buffer.alloc(wrappedDataLayout.span);
wrappedDataLayout.encode({
instruction: 7, // CreateWrapped instruction
assetAddress: padBuffer(meta.address, 32),
chain: meta.chain,
decimals: meta.decimals
}, wrappedData);
let ix_wrapped = {
keys: wa_keys,
programId: SOLANA_BRIDGE_PROGRAM,
data: wrappedData
}
ixs.push(ix_wrapped);
}
ixs.push(create_ix, ix_init)
return [ixs, newAccount]
}
async getConfigKey(): Promise<PublicKey> {
// @ts-ignore
return (await solanaWeb3.PublicKey.findProgramAddress([Buffer.from("bridge")], this.programID))[0]
}
async getWrappedAssetMint(asset: AssetMeta): Promise<PublicKey> {
if (asset.chain === 1) {
return new PublicKey(asset.address)
}
let configKey = await this.getConfigKey();
let seeds: Array<Buffer> = [Buffer.from("wrapped"), configKey.toBuffer(), Buffer.of(asset.chain), Buffer.of(asset.decimals),
padBuffer(asset.address, 32)];
// @ts-ignore
return (await solanaWeb3.PublicKey.findProgramAddress(seeds, this.programID))[0];
}
async getWrappedAssetMeta(mint: PublicKey): Promise<PublicKey> {
let configKey = await this.getConfigKey();
let seeds: Array<Buffer> = [Buffer.from("meta"), configKey.toBuffer(), mint.toBuffer()];
// @ts-ignore
return (await solanaWeb3.PublicKey.findProgramAddress(seeds, this.programID))[0];
}
async getTransferFee(): Promise<number> {
// Reference processor.rs::Bridge::transfer_fee
return (await this.connection.getMinimumBalanceForRentExemption((40 + 1340) * 2)) + 18 * 10000 * 2
}
}
// Taken from https://github.com/solana-labs/solana-program-library
// Licensed under Apache 2.0
export class u64 extends BN {
/**
* Convert to Buffer representation
*/
toBuffer(): Buffer {
const a = super.toArray().reverse();
const b = Buffer.from(a);
if (b.length === 8) {
return b;
}
assert(b.length < 8, 'u64 too large');
const zeroPad = Buffer.alloc(8);
b.copy(zeroPad);
return zeroPad;
}
/**
* Construct a u64 from Buffer representation
*/
static fromBuffer(buffer: Buffer): u64 {
assert(buffer.length === 8, `Invalid buffer length: ${buffer.length}`);
return new BN(
// @ts-ignore
[...buffer]
.reverse()
.map(i => `00${i.toString(16)}`.slice(-2))
.join(''),
16,
);
}
}
function padBuffer(b: Buffer, len: number): Buffer {
const zeroPad = Buffer.alloc(len);
b.copy(zeroPad, len - b.length);
return zeroPad;
}
export class u256 extends BN {
/**
* Convert to Buffer representation
*/
toBuffer(): Buffer {
const a = super.toArray().reverse();
const b = Buffer.from(a);
if (b.length === 32) {
return b;
}
assert(b.length < 32, 'u256 too large');
const zeroPad = Buffer.alloc(32);
b.copy(zeroPad);
return zeroPad;
}
/**
* Construct a u256 from Buffer representation
*/
static fromBuffer(buffer: number[]): u256 {
assert(buffer.length === 32, `Invalid buffer length: ${buffer.length}`);
return new BN(
// @ts-ignore
[...buffer]
.reverse()
.map(i => `00${i.toString(16)}`.slice(-2))
.join(''),
16,
);
}
}
/**
* Layout for a public key
*/
export const publicKey = (property: string = 'publicKey'): Object => {
return BufferLayout.blob(32, property);
};
/**
* Layout for a 64bit unsigned value
*/
export const uint64 = (property: string = 'uint64'): Object => {
return BufferLayout.blob(8, property);
};
/**
* Layout for a 256-bit unsigned value
*/
export const uint256 = (property: string = 'uint256'): Object => {
return BufferLayout.blob(32, property);
};
/**
* Layout for a Rust String type
*/
export const rustString = (property: string = 'string') => {
const rsl = BufferLayout.struct(
[
BufferLayout.u32('length'),
BufferLayout.u32('lengthPadding'),
BufferLayout.blob(BufferLayout.offset(BufferLayout.u32(), -8), 'chars'),
],
property,
);
const _decode = rsl.decode.bind(rsl);
const _encode = rsl.encode.bind(rsl);
rsl.decode = (buffer: Buffer, offset: number) => {
const data = _decode(buffer, offset);
return data.chars.toString('utf8');
};
rsl.encode = (str: string, buffer: Buffer, offset: number) => {
const data = {
chars: Buffer.from(str, 'utf8'),
};
return _encode(data, buffer, offset);
};
return rsl;
};
export {SolanaBridge}

View File

@ -1,12 +0,0 @@
import {PublicKey} from "@solana/web3.js";
import {BRIDGE_ADDRESS, WRAPPED_MASTER} from "../config";
import {keccak256} from "ethers/utils";
// derive the ERC20 address of a Solana SPL asset wrapped on ETH.
export function deriveERC20Address(key: PublicKey) {
let hashData = "0xff" + BRIDGE_ADDRESS.slice(2);
hashData += keccak256(Buffer.concat([new Buffer([1]), key.toBuffer()])).slice(2) // asset_id
hashData += keccak256("0x3d602d80600a3d3981f3363d3d373d3d3d363d73" + WRAPPED_MASTER + "5af43d82803e903d91602b57fd5bf3").slice(2) // Bytecode
return keccak256(hashData).slice(26)
}

View File

@ -1,25 +0,0 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}