Skip to content

Commit

Permalink
Merge pull request #1 from MickWang/master
Browse files Browse the repository at this point in the history
add wasm vm support
  • Loading branch information
MickWang authored Jan 10, 2020
2 parents 31ce122 + e915a42 commit 53bafa8
Show file tree
Hide file tree
Showing 13 changed files with 129 additions and 44 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "cyano-wallet",
"version": "0.7.16",
"version": "0.7.19",
"private": true,
"scripts": {
"lint": "tslint -p .",
Expand All @@ -14,7 +14,7 @@
"@bugsnag/plugin-react": "^5.1.0",
"@ont-community/hdkey-secp256r1": "^1.0.1",
"@ont-community/ontology-ts-sdk-ledger": "^1.0.8",
"@ont-dev/ontology-dapi": "^0.4.9",
"@ont-dev/ontology-dapi": "^0.5.0",
"autoprefixer": "7.1.6",
"axios": "^0.18.0",
"babel-polyfill": "^6.26.0",
Expand All @@ -31,7 +31,7 @@
"lodash": "^4.17.10",
"long": "^4.0.0",
"object-assign": "4.1.1",
"ontology-ts-sdk": "^1.0.24",
"ontology-ts-sdk": "^1.1.0",
"ontology-ts-test": "^0.2.37",
"postcss-flexbugs-fixes": "3.2.0",
"promise": "8.0.1",
Expand Down
2 changes: 1 addition & 1 deletion public/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"name": "Cyano wallet",
"author": "Matus Zamborsky <[email protected]>",
"description": "Cyano wallet - an Ontology wallet",
"version": "0.7.16",
"version": "0.7.19",

"browser_action": {
"default_title": "Open the wallet"
Expand Down
2 changes: 1 addition & 1 deletion src/api/accountApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export function getAccount(wallet: string | Wallet) {

const defaultAddress = wallet.defaultAccountAddress;

if (defaultAddress != null) {
if (defaultAddress != null && defaultAddress !== '') {
const account = wallet.accounts.find((a) => a.address.toBase58() === defaultAddress);

if (account === undefined) {
Expand Down
4 changes: 3 additions & 1 deletion src/api/tokenApi.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
export type VmType = 'NEOVM' | 'WASMVM';

export interface OEP4Token {
name: string;
symbol: string;
decimals: number;
vmType: VmType;
}

export interface OEP4TokenAmount extends OEP4Token {
amount: string;
}
}
4 changes: 3 additions & 1 deletion src/background/api/smartContractApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,9 @@ function convertParam(parameter: Parameter): Param {
// will use ontology-ts-sdk to build script code and it treats ByteArray as hex string;
return new Param('', ParameterType.ByteArray, parameter.value);
} else if (parameter.type === 'String') {
return new Param('', ParameterType.String, parameter.value);
return new Param('', ParameterType.String, parameter.value)
} else if (parameter.type === 'Long') {
return new Param('', ParameterType.Long, parameter.value)
} else if (parameter.type === 'Array') {
return new Param('', ParameterType.Array, convertParams(parameter.value));
} else if (parameter.type === 'Map') {
Expand Down
118 changes: 93 additions & 25 deletions src/background/api/tokenApi.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,87 @@
import * as Long from 'long';
import { CONST, Crypto, Oep4, TransactionBuilder, utils } from 'ontology-ts-sdk';
import { CONST, Crypto, Oep4, Parameter, ParameterType, TransactionBuilder, utils } from 'ontology-ts-sdk';
import { decryptAccount, getAccount } from 'src/api/accountApi';
import { encodeAmount } from 'src/popup/utils/number';
import { TransferRequest } from 'src/redux/transactionRequests';
import { getWallet } from '../../api/authApi';
import { OEP4Token } from '../../api/tokenApi';
import { OEP4Token, VmType } from '../../api/tokenApi';
import { getClient } from '../network';
import { getStore } from '../redux';

import Address = Crypto.Address;
import Oep4TxBuilder = Oep4.Oep4TxBuilder;
import { isHexadecimal } from 'src/api/utils';

const gasPrice = '500';
const gasLimit = '20000';
export async function getOEP4Token(contract: string): Promise<OEP4Token> {
if (!isHexadecimal(contract)) {
throw new Error('Contract is not hexadecimal string');
}
contract = utils.reverseHex(contract);
// TODO 需要支持wasm vm的oep4;转账也要分NEO和wasm;

const builder = new Oep4TxBuilder(new Address(contract));
const contractAddr = utils.reverseHex(contract);
const builder = new Oep4TxBuilder(new Address(contractAddr));

const client = getClient();
const nameResponse = await client.sendRawTransaction(builder.queryName().serialize(), true);
const symbolResponse = await client.sendRawTransaction(builder.querySymbol().serialize(), true);
const decimalsResponse = await client.sendRawTransaction(builder.queryDecimals().serialize(), true);
// first get contract json to decide the vmType
const contractJson = await client.getContractJson(contract);
let vmType: VmType = 'NEOVM';
if (contractJson && contractJson.Error === 0) {
if (contractJson.Result && contractJson.Result.VmType === 3) {
vmType = 'WASMVM';
}
}
let nameResponse;
let symbolResponse;
let decimalsResponse;
if (vmType === 'WASMVM') {
const tx1 = TransactionBuilder.makeWasmVmInvokeTransaction(
'name',
[],
new Address(contractAddr),
gasPrice,
gasLimit,
);
nameResponse = await client.sendRawTransaction(tx1.serialize(), true);
const tx2 = TransactionBuilder.makeWasmVmInvokeTransaction(
'symbol',
[],
new Address(contractAddr),
gasPrice,
gasLimit,
);
symbolResponse = await client.sendRawTransaction(tx2.serialize(), true);
const tx3 = TransactionBuilder.makeWasmVmInvokeTransaction(
'decimals',
[],
new Address(contractAddr),
gasPrice,
gasLimit,
);
decimalsResponse = await client.sendRawTransaction(tx3.serialize(), true);
} else {
nameResponse = await client.sendRawTransaction(builder.queryName().serialize(), true);
symbolResponse = await client.sendRawTransaction(builder.querySymbol().serialize(), true);
decimalsResponse = await client.sendRawTransaction(builder.queryDecimals().serialize(), true);
}

return {
decimals: extractNumberResponse(decimalsResponse),
name: extractStringResponse(nameResponse),
symbol: extractStringResponse(symbolResponse),
vmType,
};
}

export async function getTokenBalanceOwn(contract: string) {
export async function getTokenBalanceOwn(contract: string, vmType: VmType) {
const state = getStore().getState();
const address = getAccount(state.wallet.wallet!).address;

return getTokenBalance(contract, address);
return getTokenBalance(contract, address, vmType);
}

export async function getTokenBalance(contract: string, address: Address) {
export async function getTokenBalance(contract: string, address: Address, vmType: VmType) {
const state = getStore().getState();

const token = state.settings.tokens.find((t) => t.contract === contract);
Expand All @@ -48,12 +90,23 @@ export async function getTokenBalance(contract: string, address: Address) {
}

contract = utils.reverseHex(contract);

const builder = new Oep4TxBuilder(new Address(contract));

const client = getClient();
const tx = builder.queryBalanceOf(address);
const response = await client.sendRawTransaction(tx.serialize(), true);
let response;
if (vmType === 'WASMVM') {
const params = [new Parameter('param1', ParameterType.Address, address)];
const tx = TransactionBuilder.makeWasmVmInvokeTransaction(
'balanceOf',
params,
new Address(contract),
gasPrice,
gasLimit,
);
response = await client.sendRawTransaction(tx.serialize(), true);
} else {
const builder = new Oep4TxBuilder(new Address(contract));
const tx = builder.queryBalanceOf(address);
response = await client.sendRawTransaction(tx.serialize(), true);
}

return Long.fromString(utils.reverseHex(response.Result.Result), true, 16).toString();
}
Expand All @@ -66,7 +119,6 @@ export async function transferToken(request: TransferRequest, password: string)
if (token === undefined) {
throw new Error('OEP-4 token not found.');
}

const contract = utils.reverseHex(token.contract);
const builder = new Oep4TxBuilder(new Address(contract));

Expand All @@ -75,15 +127,31 @@ export async function transferToken(request: TransferRequest, password: string)

const to = new Address(request.recipient);
const amount = String(request.amount);

const tx = builder.makeTransferTx(
from,
to,
encodeAmount(amount, token.decimals),
'500',
`${CONST.DEFAULT_GAS_LIMIT}`,
from,
);
let tx;
if (token.vmType === 'WASMVM') {
const params = [
new Parameter('from', ParameterType.Address, from),
new Parameter('to', ParameterType.Address, to),
new Parameter('amount', ParameterType.Long, encodeAmount(amount, token.decimals))
];
tx = TransactionBuilder.makeWasmVmInvokeTransaction(
'transfer',
params,
new Address(contract),
gasPrice,
`${CONST.DEFAULT_GAS_LIMIT}`,
from
);
} else {
tx = builder.makeTransferTx(
from,
to,
encodeAmount(amount, token.decimals),
'500',
`${CONST.DEFAULT_GAS_LIMIT}`,
from,
);
}

await TransactionBuilder.signTransactionAsync(tx, privateKey);

Expand Down
2 changes: 1 addition & 1 deletion src/background/balanceProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export async function refreshBalance(store: GlobalStore) {

for (const token of tokens) {
try {
const amount = await getTokenBalanceOwn(token.contract);
const amount = await getTokenBalanceOwn(token.contract, token.vmType);
tokenBalances.push({ contract: token.contract, amount });
} catch (e) {
// tslint:disable-next-line:no-console
Expand Down
1 change: 1 addition & 0 deletions src/background/redux/settingsReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export const settingsReducer: Reducer<SettingsState> = (state = defaultState, ac
name: action.name,
specification: action.specification,
symbol: action.symbol,
vmType: action.vmType
},
],
};
Expand Down
1 change: 1 addition & 0 deletions src/popup/pages/dashboard/dashboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ function prepareTokenAmounts(tokens: TokenState[] = [], items: TokenAmountState[
decimals: token.decimals,
name: token.name,
symbol: token.symbol,
vmType: token.vmType,
};
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/popup/pages/send/sendView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export const SendView: React.SFC<Props> = (props) => (
input={{ ...t.input, value: t.input.value }}
error={t.meta.touched && t.meta.invalid}
disabled={props.locked || get(formProps.values, 'asset') === undefined}
action={<Button type="button" onClick={() => props.handleMax(formProps)} content="MAX" />}
action={get(formProps.values, 'asset') === 'ONG' || get(formProps.values, 'asset') === 'ONT'? <Button type="button" onClick={() => props.handleMax(formProps)} content="MAX" /> : undefined}
/>
)}
/>
Expand Down
2 changes: 1 addition & 1 deletion src/popup/pages/tokenSettingsAdd/tokenSettingsAdd.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const enhancer = (Component: React.ComponentType<Props>) => (props: RouteCompone
const token = await manager.getOEP4Token(contract);

// todo: proper spec
await actions.addToken(contract, token.name, token.symbol, token.decimals, 'OEP-4');
await actions.addToken(contract, token.name, token.symbol, token.decimals, 'OEP-4', token.vmType);

await actions.finishLoading();

Expand Down
13 changes: 12 additions & 1 deletion src/redux/settings.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { VmType } from './../api/tokenApi';
/*
* Copyright (C) 2018 Matus Zamborsky
* This file is part of The Ontology Wallet&ID.
Expand All @@ -15,6 +16,7 @@
* You should have received a copy of the GNU Lesser General Public License
* along with The Ontology Wallet&ID. If not, see <http://www.gnu.org/licenses/>.
*/

export type NetValue = 'TEST' | 'MAIN' | 'PRIVATE';

// tslint:disable:object-literal-sort-keys
Expand All @@ -25,6 +27,7 @@ export interface TokenState {
symbol: string;
decimals: number;
specification: 'OEP-4';
vmType: VmType;
}

export interface TrustedSc {
Expand Down Expand Up @@ -70,13 +73,21 @@ export const setSettings = (
trustedScs,
});

export const addToken = (contract: string, name: string, symbol: string, decimals: number, specification: 'OEP-4') => ({
export const addToken = (
contract: string,
name: string,
symbol: string,
decimals: number,
specification: 'OEP-4',
vmType: VmType,
) => ({
type: ADD_TOKEN,
contract,
name,
symbol,
decimals,
specification,
vmType,
});

export const delToken = (contract: string) => ({ type: DEL_TOKEN, contract });
Expand Down
16 changes: 8 additions & 8 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -398,10 +398,10 @@
version "0.2.14"
resolved "https://registry.yarnpkg.com/@ont-community/window-post-message-proxy/-/window-post-message-proxy-0.2.14.tgz#e3b1fe1b1558d7aedbbc1d0053e35f21cd9dc05e"

"@ont-dev/ontology-dapi@^0.4.9":
version "0.4.9"
resolved "https://registry.yarnpkg.com/@ont-dev/ontology-dapi/-/ontology-dapi-0.4.9.tgz#3ddde4e037f8820cf85fc885d2d1efb685937df9"
integrity sha512-9FJYzrLv1VzbS8vQZxnAOWtYJRx6kwzuNeY1USXWo6bIWGNt9i9UVYxKPJkhyVQj/hRn4YQz0q7W0Fpm6mjnPQ==
"@ont-dev/ontology-dapi@^0.5.0":
version "0.5.0"
resolved "https://registry.yarnpkg.com/@ont-dev/ontology-dapi/-/ontology-dapi-0.5.0.tgz#12007ac71daa63da8822f763f7dfda44cab7328d"
integrity sha512-KgTzElwnwkLjfCW+cX3nWeB7sC+KhJye5ogJONRXr84mFpdgq+y28chcks80yopr5zSN28yAM/cIgIx6HocSJA==
dependencies:
"@ont-community/window-post-message-proxy" "^0.2.14"
base-x "^3.0.5"
Expand Down Expand Up @@ -6728,10 +6728,10 @@ ontology-ts-sdk@^0.9.4:
wif "^2.0.6"
ws "^4.1.0"

ontology-ts-sdk@^1.0.24:
version "1.0.24"
resolved "https://registry.yarnpkg.com/ontology-ts-sdk/-/ontology-ts-sdk-1.0.24.tgz#5fd403ef9aac3931d54a25e4a323c1e500c42fca"
integrity sha512-jk+B2QbbE3uYgBvCkdwcJodHJYkxfmb1Km6RsxK2yM6E6krp7h7y01WCvLuEk2bgWTayz/jIg7AizeUqeRVlyg==
ontology-ts-sdk@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/ontology-ts-sdk/-/ontology-ts-sdk-1.1.0.tgz#7156220ec723c8ad23f3ae2f5c92374b2a9da55c"
integrity sha512-DaJBG2Ugi83TbWfaWY75ijoKuBQ6+7QAveVMfuY0UxrrzxWw9hXqK7UayvGugIfkRWivWr0dyvpHAkL605e6HQ==
dependencies:
"@ont-community/hdkey-secp256r1" "^1.0.1"
"@ont-community/html5-websocket" "^2.0.2"
Expand Down

0 comments on commit 53bafa8

Please sign in to comment.