From 258cdaad704b035524c1337bbb913c3ff8f4ec03 Mon Sep 17 00:00:00 2001 From: Toan Dang Date: Sat, 3 Feb 2024 17:08:08 +0700 Subject: [PATCH 01/11] update oa --- src/keyring/handler.ts | 120 ++++++++++++++++++++++++----------------- src/keyring/keyring.ts | 23 +++++--- 2 files changed, 87 insertions(+), 56 deletions(-) diff --git a/src/keyring/handler.ts b/src/keyring/handler.ts index a102ceb..b10ea6d 100644 --- a/src/keyring/handler.ts +++ b/src/keyring/handler.ts @@ -41,6 +41,7 @@ import { RequestSignOasisMsg, GetDefaultAddressOasisMsg } from './messages'; +import * as oasis from '@oasisprotocol/client'; import { KeyRingService } from './service'; import { Bech32Address } from '@owallet/cosmos'; import { Address } from '@owallet/crypto'; @@ -131,68 +132,68 @@ export const getHandler: (service: KeyRingService) => Handler = (service: KeyRin }; }; -const handleRestoreKeyRingMsg: (service: KeyRingService) => InternalHandler = service => { +const handleRestoreKeyRingMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (_env, _msg) => { return await service.restore(); }; }; -const handleDeleteKeyRingMsg: (service: KeyRingService) => InternalHandler = service => { +const handleDeleteKeyRingMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (_, msg) => { return await service.deleteKeyRing(msg.index, msg.password); }; }; -const handleUpdateNameKeyRingMsg: (service: KeyRingService) => InternalHandler = service => { +const handleUpdateNameKeyRingMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (_, msg) => { return await service.updateNameKeyRing(msg.index, msg.name, msg?.email); }; }; -const handleShowKeyRingMsg: (service: KeyRingService) => InternalHandler = service => { +const handleShowKeyRingMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (_, msg) => { return await service.showKeyRing(msg.index, msg.password); }; }; -const handleCreateMnemonicKeyMsg: (service: KeyRingService) => InternalHandler = service => { +const handleCreateMnemonicKeyMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (_, msg) => { return await service.createMnemonicKey(msg.kdf, msg.mnemonic, msg.password, msg.meta, msg.bip44HDPath); }; }; -const handleAddMnemonicKeyMsg: (service: KeyRingService) => InternalHandler = service => { +const handleAddMnemonicKeyMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (_, msg) => { return await service.addMnemonicKey(msg.kdf, msg.mnemonic, msg.meta, msg.bip44HDPath); }; }; -const handleCreatePrivateKeyMsg: (service: KeyRingService) => InternalHandler = service => { +const handleCreatePrivateKeyMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (_, msg) => { return await service.createPrivateKey(msg.kdf, msg.privateKey, msg.password, msg.meta); }; }; -const handleAddPrivateKeyMsg: (service: KeyRingService) => InternalHandler = service => { +const handleAddPrivateKeyMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (_, msg) => { return await service.addPrivateKey(msg.kdf, msg.privateKey, msg.meta); }; }; -const handleCreateLedgerKeyMsg: (service: KeyRingService) => InternalHandler = service => { +const handleCreateLedgerKeyMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (env, msg) => { return await service.createLedgerKey(env, msg.kdf, msg.password, msg.meta, msg.bip44HDPath); }; }; -const handleAddLedgerKeyMsg: (service: KeyRingService) => InternalHandler = service => { +const handleAddLedgerKeyMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (env, msg) => { const result = await service.addLedgerKey(env, msg.kdf, msg.meta, msg.bip44HDPath); return result; }; }; -const handleLockKeyRingMsg: (service: KeyRingService) => InternalHandler = service => { +const handleLockKeyRingMsg: (service: KeyRingService) => InternalHandler = (service) => { return () => { return { status: service.lock() @@ -200,7 +201,7 @@ const handleLockKeyRingMsg: (service: KeyRingService) => InternalHandler InternalHandler = service => { +const handleUnlockKeyRingMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (_, msg) => { return { status: await service.unlock(msg.password, msg.saving) @@ -208,11 +209,13 @@ const handleUnlockKeyRingMsg: (service: KeyRingService) => InternalHandler InternalHandler = service => { +const handleGetKeyMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (env, msg) => { await service.permissionService.checkOrGrantBasicAccessPermission(env, msg.chainId, msg.origin); const key = await service.getKey(msg.chainId); + console.log('🚀 ~ return ~ msg.chainId:', msg.chainId); + console.log('🚀 ~ return ~ key:', key); const networkType = getNetworkTypeByChainId(msg.chainId); @@ -221,12 +224,23 @@ const handleGetKeyMsg: (service: KeyRingService) => InternalHandler = const isInj = msg.chainId?.startsWith('injective'); const pubkeyLedger = service.getKeyRingLedgerPubKey(); const bech32Address = new Bech32Address(key.address); + // console.log('🚀 ~ return ~ bech32Address:', bech32Address); const { bech32PrefixAccAddr } = (await service.chainsService.getChainInfo(msg.chainId)).bech32Config; // hereee const bech32Convert = networkType === 'bitcoin' ? bech32Address.toBech32Btc(bech32PrefixAccAddr) : bech32Address.toBech32(bech32PrefixAccAddr); + + // if (msg.chainId === '0x5afe') { + // // const signerPublicKey = await service.load + // // const addressUint8Array = await oasis.staking.addressFromPublicKey(key.pubKey); + // const address = oasis.staking.addressToBech32(key.address); + // const bech32Convert = bech32Address.toBech32(Bech32Address.defaultBech32Config('oasis').bech32PrefixAccAddr); + // console.log('🚀 ~ return ~ bech32Convert:', bech32Convert); + // console.log('🚀 ~ return ~ address:', address); + // } + return { name: service.getKeyStoreMeta('name'), algo: 'secp256k1', @@ -244,7 +258,7 @@ const handleGetKeyMsg: (service: KeyRingService) => InternalHandler = }; }; -const handleRequestSignAminoMsg: (service: KeyRingService) => InternalHandler = service => { +const handleRequestSignAminoMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (env, msg) => { await service.permissionService.checkOrGrantBasicAccessPermission(env, msg.chainId, msg.origin); @@ -254,7 +268,7 @@ const handleRequestSignAminoMsg: (service: KeyRingService) => InternalHandler InternalHandler = service => { +) => InternalHandler = (service) => { return async (env, msg) => { await service.permissionService.checkOrGrantBasicAccessPermission(env, msg.chainId, msg.origin); @@ -262,7 +276,7 @@ const handleRequestVerifyADR36AminoSignDoc: ( }; }; -const handleRequestSignDirectMsg: (service: KeyRingService) => InternalHandler = service => { +const handleRequestSignDirectMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (env, msg) => { await service.permissionService.checkOrGrantBasicAccessPermission(env, msg.chainId, msg.origin); @@ -296,14 +310,14 @@ const handleRequestSignDirectMsg: (service: KeyRingService) => InternalHandler InternalHandler = service => { +) => InternalHandler = (service) => { return async (env, msg) => { const response = await service.requestSignEthereumTypedData(env, msg.chainId, msg.data?.[0]); return { result: JSON.stringify(response) }; }; }; -const handleRequestPublicKey: (service: KeyRingService) => InternalHandler = service => { +const handleRequestPublicKey: (service: KeyRingService) => InternalHandler = (service) => { return async (env, msg) => { const response = await service.requestPublicKey(env, msg.chainId); return { result: JSON.stringify(response) }; @@ -312,7 +326,7 @@ const handleRequestPublicKey: (service: KeyRingService) => InternalHandler InternalHandler = service => { +) => InternalHandler = (service) => { return async (env, msg) => { const response = await service.requestSignDecryptData(env, msg.chainId, msg.data); return { result: JSON.stringify(response) }; @@ -320,7 +334,7 @@ const handleRequestSignDecryptionData: ( }; const handleRequestSignEIP712CosmosTxMsg_v0: ( service: KeyRingService -) => InternalHandler = service => { +) => InternalHandler = (service) => { return async (env, msg) => { return await service.requestSignEIP712CosmosTx_v0_selected( env, @@ -335,14 +349,16 @@ const handleRequestSignEIP712CosmosTxMsg_v0: ( }; const handleRequestSignProxyDecryptionData: ( service: KeyRingService -) => InternalHandler = service => { +) => InternalHandler = (service) => { return async (env, msg) => { const response = await service.requestSignProxyDecryptionData(env, msg.chainId, msg.data); return { result: JSON.stringify(response) }; }; }; -const handleGetDefaultAddressMsg: (service: KeyRingService) => InternalHandler = service => { +const handleGetDefaultAddressMsg: (service: KeyRingService) => InternalHandler = ( + service +) => { return async (_, msg) => { const key = await service.getKey(msg.chainId); const ledgerCheck = service.getKeyRingType(); @@ -368,7 +384,7 @@ const handleGetDefaultAddressMsg: (service: KeyRingService) => InternalHandler InternalHandler = service => { +) => InternalHandler = (service) => { return async (env, msg) => { const response = await service.requestSignReEncryptData(env, msg.chainId, msg.data); @@ -376,14 +392,16 @@ const handleRequestSignProxyReEncryptionData: ( }; }; -const handleRequestSignBitcoinMsg: (service: KeyRingService) => InternalHandler = service => { +const handleRequestSignBitcoinMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (env, msg) => { const response = await service.requestSignBitcoin(env, msg.chainId, msg.data); return { rawTxHex: response }; }; }; -const handleRequestSignEthereumMsg: (service: KeyRingService) => InternalHandler = service => { +const handleRequestSignEthereumMsg: (service: KeyRingService) => InternalHandler = ( + service +) => { return async (env, msg) => { const response = await service.requestSignEthereum(env, msg.chainId, msg.data); @@ -391,9 +409,9 @@ const handleRequestSignEthereumMsg: (service: KeyRingService) => InternalHandler }; }; -const handleGetMultiKeyStoreInfoMsg: ( - service: KeyRingService -) => InternalHandler = service => { +const handleGetMultiKeyStoreInfoMsg: (service: KeyRingService) => InternalHandler = ( + service +) => { return () => { return { multiKeyStoreInfo: service.getMultiKeyStoreInfo() @@ -401,89 +419,91 @@ const handleGetMultiKeyStoreInfoMsg: ( }; }; -const handleChangeKeyRingMsg: (service: KeyRingService) => InternalHandler = service => { +const handleChangeKeyRingMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (_, msg) => { return await service.changeKeyStoreFromMultiKeyStore(msg.index); }; }; -const handleChangeChainMsg: (service: any) => InternalHandler = service => { +const handleChangeChainMsg: (service: any) => InternalHandler = (service) => { return async (_, msg) => { return await service.changeChain(msg.chainInfos); }; }; -const handleGetIsKeyStoreCoinTypeSetMsg: ( - service: KeyRingService -) => InternalHandler = service => { +const handleGetIsKeyStoreCoinTypeSetMsg: (service: KeyRingService) => InternalHandler = ( + service +) => { return (_, msg) => { return service.getKeyStoreBIP44Selectables(msg.chainId, msg.paths); }; }; -const handleSetKeyStoreCoinTypeMsg: (service: KeyRingService) => InternalHandler = service => { +const handleSetKeyStoreCoinTypeMsg: (service: KeyRingService) => InternalHandler = ( + service +) => { return async (_, msg) => { await service.setKeyStoreCoinType(msg.chainId, msg.coinType); return service.keyRingStatus; }; }; -const handleSetKeyStoreLedgerAddressMsg: ( - service: KeyRingService -) => InternalHandler = service => { +const handleSetKeyStoreLedgerAddressMsg: (service: KeyRingService) => InternalHandler = ( + service +) => { return async (env, msg) => { await service.setKeyStoreLedgerAddress(env, msg.bip44HDPath, msg.chainId); return service.keyRingStatus; }; }; -const handleCheckPasswordMsg: (service: KeyRingService) => InternalHandler = service => { +const handleCheckPasswordMsg: (service: KeyRingService) => InternalHandler = (service) => { return (_, msg) => { return service.checkPassword(msg.password); }; }; -const handleExportKeyRingDatasMsg: (service: KeyRingService) => InternalHandler = service => { +const handleExportKeyRingDatasMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (_, msg) => { return await service.exportKeyRingDatas(msg.password); }; }; -const handleRequestSignTronMsg: (service: KeyRingService) => InternalHandler = service => { +const handleRequestSignTronMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (env, msg) => { const response = await service.requestSignTron(env, msg.chainId, msg.data); return { ...response }; }; }; -const handleSendRawTransactionMsg: ( - service: KeyRingService -) => InternalHandler = service => { +const handleSendRawTransactionMsg: (service: KeyRingService) => InternalHandler = ( + service +) => { return async (env, msg) => { const response = await service.requestSendRawTransaction(env, msg.chainId, msg.data); return { ...response }; }; }; -const handleTriggerSmartContractMsg: ( - service: KeyRingService -) => InternalHandler = service => { +const handleTriggerSmartContractMsg: (service: KeyRingService) => InternalHandler = ( + service +) => { return async (env, msg) => { const response = await service.requestTriggerSmartContract(env, msg.chainId, msg.data); return { ...response }; }; }; -const handleRequestSignOasisMsg: (service: KeyRingService) => InternalHandler = service => { +const handleRequestSignOasisMsg: (service: KeyRingService) => InternalHandler = (service) => { return async (env, msg) => { const response = await service.requestSignOasis(env, msg.chainId, msg.data); return { ...response }; }; }; -const handleGetDefaultAddressOasisMsg: ( - service: KeyRingService -) => InternalHandler = service => { +const handleGetDefaultAddressOasisMsg: (service: KeyRingService) => InternalHandler = ( + service +) => { return async (_, msg) => { const address = await service.getDefaultOasisAddress(msg.chainId); const balance = await service.getDefaultOasisBalance(address, msg.chainId); diff --git a/src/keyring/keyring.ts b/src/keyring/keyring.ts index c9c32fd..8b3cd04 100644 --- a/src/keyring/keyring.ts +++ b/src/keyring/keyring.ts @@ -1,4 +1,5 @@ import { + ChainIdEnum, EmbedChainInfos, MIN_FEE_RATE, convertBip44ToHDPath, @@ -580,7 +581,7 @@ export class KeyRing { [ChainIdHelper.parse(chainId).identifier]: coinType }; - const keyStoreInMulti = this.multiKeyStore.find(keyStore => { + const keyStoreInMulti = this.multiKeyStore.find((keyStore) => { return ( KeyRing.getKeyStoreId(keyStore) === // eslint-disable-next-line @typescript-eslint/no-non-null-assertion @@ -609,7 +610,7 @@ export class KeyRing { const { publicKey, address } = (await this.ledgerKeeper.getPublicKey(env, hdPath, ledgerAppType)) || {}; const pubKey = publicKey ? Buffer.from(publicKey).toString('hex') : null; - const keyStoreInMulti = this.multiKeyStore.find(keyStore => { + const keyStoreInMulti = this.multiKeyStore.find((keyStore) => { return ( KeyRing.getKeyStoreId(keyStore) === // eslint-disable-next-line @typescript-eslint/no-non-null-assertion @@ -753,8 +754,18 @@ export class KeyRing { } return coinType === 60; })(); - + if (coinType === 474) { + const signerPublicKey = await this.loadPublicKeyOasis(); + const addressUint8Array = await oasis.staking.addressFromPublicKey(signerPublicKey); + return { + algo: 'ethsecp256k1', + pubKey: signerPublicKey, + address: addressUint8Array, + isNanoLedger: this.keyStore.type === 'ledger' + }; + } const pubKey = this.getPubKey(coinType); + const address = (() => { if (isEthermint) { return pubKey.getEthAddress(); @@ -1198,7 +1209,7 @@ export class KeyRing { const privKey = this.loadPrivKey(60); const privKeyBuffer = Buffer.from(privKey.toBytes()); const response = await Promise.all( - message[0].map(async data => { + message[0].map(async (data) => { const encryptedData = { ciphertext: Buffer.from(data.ciphertext, 'hex'), ephemPublicKey: Buffer.from(data.ephemPublicKey, 'hex'), @@ -1237,7 +1248,7 @@ export class KeyRing { throw new Error('Key Store is empty'); } - if (chainId === '0x5afe') { + if (chainId === ChainIdEnum.Oasis) { const pubKey = await this.loadPublicKeyOasis(); return pubKey; } @@ -1442,7 +1453,7 @@ export class KeyRing { throw new Error('Arrays are unimplemented in encodeData; use V4 extension'); } const parsedType = type.slice(0, type.lastIndexOf('[')); - const typeValuePairs = value.map(item => this.encodeField(types, name, parsedType, item, version)); + const typeValuePairs = value.map((item) => this.encodeField(types, name, parsedType, item, version)); return [ 'bytes32', keccak( From d8ef844698b8ba49beca359b7a9f64cf4c43888f Mon Sep 17 00:00:00 2001 From: Toan Dang Date: Sat, 3 Feb 2024 18:24:48 +0700 Subject: [PATCH 02/11] update oasis network --- src/chains/service.ts | 22 ++++++++++++---------- src/keyring/keyring.ts | 1 + 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/chains/service.ts b/src/chains/service.ts index 9a3f7bd..59ce7e9 100644 --- a/src/chains/service.ts +++ b/src/chains/service.ts @@ -33,7 +33,7 @@ export class ChainsService { return this.cachedChainInfos; } - const chainInfos = this.embedChainInfos.map(chainInfo => { + const chainInfos = this.embedChainInfos.map((chainInfo) => { return { ...chainInfo, embeded: true @@ -45,7 +45,7 @@ export class ChainsService { } const savedChainInfos: ChainInfoWithEmbed[] = ((await this.kvStore.get('chain-infos')) ?? []) - .filter(chainInfo => { + .filter((chainInfo) => { // Filter the overlaped chain info with the embeded chain infos. return !embedChainInfoIdentifierMap.get(ChainIdHelper.parse(chainInfo.chainId).identifier); }) @@ -60,7 +60,7 @@ export class ChainsService { // Set the updated property of the chain. result = await Promise.all( - result.map(async chainInfo => { + result.map(async (chainInfo) => { const updated: ChainInfo = await this.chainUpdaterKeeper.putUpdatedPropertyToChainInfo(chainInfo); return { @@ -87,7 +87,7 @@ export class ChainsService { } async getChainInfosWithoutEndpoints(): Promise { - return (await this.getChainInfos()).map(chainInfo => { + return (await this.getChainInfos()).map((chainInfo) => { const chainInfoMutable: Mutable< Optional > = { @@ -113,14 +113,14 @@ export class ChainsService { if (networkType) { if (networkType === 'evm') { // need to check if network type is evm, then we will convert chain id to number from hex - chainInfo = (await this.getChainInfos()).find(chainInfo => { + chainInfo = (await this.getChainInfos()).find((chainInfo) => { return ( ChainIdHelper.parse(Number(chainInfo.chainId)).identifier === ChainIdHelper.parse(Number(chainId)).identifier && chainInfo.networkType === networkType ); }); } else { - chainInfo = (await this.getChainInfos()).find(chainInfo => { + chainInfo = (await this.getChainInfos()).find((chainInfo) => { return ( ChainIdHelper.parse(chainInfo.chainId).identifier === ChainIdHelper.parse(chainId).identifier && chainInfo.networkType === networkType @@ -128,11 +128,13 @@ export class ChainsService { }); } } else { - chainInfo = (await this.getChainInfos()).find(chainInfo => { + chainInfo = (await this.getChainInfos()).find((chainInfo) => { return ChainIdHelper.parse(chainInfo.chainId).identifier === ChainIdHelper.parse(chainId).identifier; }); } - + chainInfo = (await this.getChainInfos()).find((chainInfo) => { + return ChainIdHelper.parse(chainInfo.chainId).identifier === ChainIdHelper.parse(chainId).identifier; + }); if (!chainInfo) { throw new Error(`There is no chain info for ${chainId}`); } @@ -150,7 +152,7 @@ export class ChainsService { async hasChainInfo(chainId: string): Promise { return ( - (await this.getChainInfos()).find(chainInfo => { + (await this.getChainInfos()).find((chainInfo) => { return ChainIdHelper.parse(chainInfo.chainId).identifier === ChainIdHelper.parse(chainId).identifier; }) != null ); @@ -210,7 +212,7 @@ export class ChainsService { const savedChainInfos = (await this.kvStore.get('chain-infos')) ?? []; - const resultChainInfo = savedChainInfos.filter(chainInfo => { + const resultChainInfo = savedChainInfos.filter((chainInfo) => { return ChainIdHelper.parse(chainInfo.chainId).identifier !== ChainIdHelper.parse(chainId).identifier; }); diff --git a/src/keyring/keyring.ts b/src/keyring/keyring.ts index 8b3cd04..997107b 100644 --- a/src/keyring/keyring.ts +++ b/src/keyring/keyring.ts @@ -754,6 +754,7 @@ export class KeyRing { } return coinType === 60; })(); + console.log('🚀 ~ isEthermint ~ isEthermint:', isEthermint); if (coinType === 474) { const signerPublicKey = await this.loadPublicKeyOasis(); const addressUint8Array = await oasis.staking.addressFromPublicKey(signerPublicKey); From 112523aeafdbc2aecf4abe4dd249b16eff3c2c2b Mon Sep 17 00:00:00 2001 From: Toan Dang Date: Mon, 5 Feb 2024 15:38:34 +0700 Subject: [PATCH 03/11] update sign oasis --- src/keyring/keyring.ts | 22 +++++++++++++++++++++- src/keyring/service.ts | 9 ++------- src/utils/helper.ts | 7 ++++--- src/utils/oasis-helper.ts | 1 + 4 files changed, 28 insertions(+), 11 deletions(-) diff --git a/src/keyring/keyring.ts b/src/keyring/keyring.ts index 997107b..b79c02c 100644 --- a/src/keyring/keyring.ts +++ b/src/keyring/keyring.ts @@ -69,9 +69,11 @@ import { uint2hex } from '../utils/oasis-helper'; import { OasisTransaction, signerFromPrivateKey } from '../utils/oasis-tx-builder'; +import { CoinPretty, Int } from '@owallet/unit'; // inject TronWeb class (globalThis as any).TronWeb = require('tronweb'); + export enum KeyRingStatus { NOTLOADED, EMPTY, @@ -822,13 +824,15 @@ export class KeyRing { const chainInfo = await this.chainsService.getChainInfo(chainId as string); - const nic = await getOasisNic(chainInfo.grpc); const accountSigner = await oasis.hdkey.HDKey.getAccountSigner(this.mnemonic, 0); + console.log('🚀 ~ signOasis ~ accountSigner:', accountSigner); const privateKey = uint2hex(accountSigner.secretKey); + console.log('🚀 ~ signOasis ~ privateKey:', privateKey); const bytes = hex2uint(privateKey!); const signer = signerFromPrivateKey(bytes); const bigIntAmount = BigInt(parseRoseStringToBigNumber(amount).toString()); console.log('bigIntAmount', bigIntAmount); + const nic = getOasisNic(chainInfo.grpc); const chainContext = await nic.consensusGetChainContext(); const tw = await OasisTransaction.buildTransfer(nic, signer, to.replaceAll(' ', ''), bigIntAmount); @@ -1031,6 +1035,22 @@ export class KeyRing { if (this.keyStore.type === 'ledger') { return this.processSignLedgerEvm(env, chainId, rpc, message); } else { + if (chainId === ChainIdEnum.OasisNative) { + console.log('🚀 ~ message:', message); + const data = message as any; + console.log('🚀 ~ data.value:', data.value); + + console.log('🚀 ~ Number(data.value):', Number(data.value)); + const chainInfo = await this.chainsService.getChainInfo(chainId as string); + console.log('🚀 ~ chainInfo.feeCurrencies:', chainInfo.feeCurrencies); + const amount = new CoinPretty(chainInfo.feeCurrencies[0], new Int(Number(data.value))).toDec().toString(); + + console.log('🚀 ~ amount:', amount); + const res = await this.signOasis(chainId, { amount: amount, to: (data as any).to }); + console.log('🚀 ~ res:', res); + return; + } + return this.processSignEvm(chainId, coinType, rpc, message); } } diff --git a/src/keyring/service.ts b/src/keyring/service.ts index b27adfb..1d8f3a8 100644 --- a/src/keyring/service.ts +++ b/src/keyring/service.ts @@ -443,8 +443,6 @@ export class KeyRingService { signed: newSignDoc, signature: encodeSecp256k1Signature(key.pubKey, signature) }; - } catch (e) { - console.log('e', e.message); } finally { this.interactionService.dispatchEvent(APP_PORT, 'request-sign-end', {}); } @@ -454,16 +452,13 @@ export class KeyRingService { const coinType = await this.chainsService.getChainCoinType(chainId); const rpc = await this.chainsService.getChainInfo(chainId); const rpcCustom = EVMOS_NETWORKS.includes(chainId) ? rpc.evmRpc : rpc.rest; - // TODO: add UI here so users can change gas, memo & fee - const newData = await this.estimateFeeAndWaitApprove(env, chainId, rpcCustom, data); // Need to check ledger here and ledger app type by chainId try { + // TODO: add UI here so users can change gas, memo & fee + const newData = await this.estimateFeeAndWaitApprove(env, chainId, rpcCustom, data); const rawTxHex = await this.keyRing.signAndBroadcastEthereum(env, chainId, coinType, rpcCustom, newData); - return rawTxHex; - } catch (error) { - console.log({ error }); } finally { this.interactionService.dispatchEvent(APP_PORT, 'request-sign-ethereum-end', {}); } diff --git a/src/utils/helper.ts b/src/utils/helper.ts index 996f42f..44c8e96 100644 --- a/src/utils/helper.ts +++ b/src/utils/helper.ts @@ -50,7 +50,7 @@ export const EIP712DomainTypeValidator = Joi.array() ) .unique() .min(1) - .custom(value => { + .custom((value) => { // Sort by name const domainFieldNames: Array = ['name', 'version', 'chainId', 'verifyingContract', 'salt']; @@ -165,7 +165,8 @@ export const handleAddressLedgerByChainId = ( * Return a nic client for the specified network, * or by default, for the currently selected network */ -export const getOasisNic = async url => { - const nic = await new oasis.client.NodeInternal(url); +//TODO: need handle duplicate from common +export const getOasisNic = (url) => { + const nic = new oasis.client.NodeInternal(url); return nic; }; diff --git a/src/utils/oasis-helper.ts b/src/utils/oasis-helper.ts index 6331f15..4060d39 100644 --- a/src/utils/oasis-helper.ts +++ b/src/utils/oasis-helper.ts @@ -12,6 +12,7 @@ export enum RuntimeTypes { Evm = 'evm', Oasis = 'oasis' } +//TODO: need handle duplicate export type ParaTimeConfig = { mainnet: ParaTimeNetwork; testnet: ParaTimeNetwork; From 9126db68abbe1b3274928de0f29aa63c30d714db Mon Sep 17 00:00:00 2001 From: Toan Dang Date: Mon, 5 Feb 2024 18:25:11 +0700 Subject: [PATCH 04/11] update sign --- src/keyring/keyring.ts | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/src/keyring/keyring.ts b/src/keyring/keyring.ts index b79c02c..5f804a8 100644 --- a/src/keyring/keyring.ts +++ b/src/keyring/keyring.ts @@ -822,26 +822,18 @@ export class KeyRing { const { amount, to } = data; - const chainInfo = await this.chainsService.getChainInfo(chainId as string); + // const chainInfo = await this.chainsService.getChainInfo(chainId as string); const accountSigner = await oasis.hdkey.HDKey.getAccountSigner(this.mnemonic, 0); - console.log('🚀 ~ signOasis ~ accountSigner:', accountSigner); const privateKey = uint2hex(accountSigner.secretKey); - console.log('🚀 ~ signOasis ~ privateKey:', privateKey); - const bytes = hex2uint(privateKey!); - const signer = signerFromPrivateKey(bytes); - const bigIntAmount = BigInt(parseRoseStringToBigNumber(amount).toString()); - console.log('bigIntAmount', bigIntAmount); - const nic = getOasisNic(chainInfo.grpc); - const chainContext = await nic.consensusGetChainContext(); - - const tw = await OasisTransaction.buildTransfer(nic, signer, to.replaceAll(' ', ''), bigIntAmount); - - await OasisTransaction.sign(chainContext, signer, tw); - const payload = await OasisTransaction.submit(nic, tw); - - return payload; + const bytes = hex2uint(privateKey!); + const txres = { + bytes, + amount, + to: to.replaceAll(' ', '') + }; + return txres; } public async loadBalanceOasis( @@ -1048,7 +1040,7 @@ export class KeyRing { console.log('🚀 ~ amount:', amount); const res = await this.signOasis(chainId, { amount: amount, to: (data as any).to }); console.log('🚀 ~ res:', res); - return; + return res; } return this.processSignEvm(chainId, coinType, rpc, message); From c7605f7ab345472b7edb194ec9708cb6bb61acec Mon Sep 17 00:00:00 2001 From: Toan Dang Date: Tue, 20 Feb 2024 16:28:48 +0700 Subject: [PATCH 05/11] handle message sign --- src/keyring/keyring.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/keyring/keyring.ts b/src/keyring/keyring.ts index 5f804a8..1bc7d3b 100644 --- a/src/keyring/keyring.ts +++ b/src/keyring/keyring.ts @@ -1028,18 +1028,14 @@ export class KeyRing { return this.processSignLedgerEvm(env, chainId, rpc, message); } else { if (chainId === ChainIdEnum.OasisNative) { - console.log('🚀 ~ message:', message); const data = message as any; - console.log('🚀 ~ data.value:', data.value); - console.log('🚀 ~ Number(data.value):', Number(data.value)); const chainInfo = await this.chainsService.getChainInfo(chainId as string); - console.log('🚀 ~ chainInfo.feeCurrencies:', chainInfo.feeCurrencies); + const amount = new CoinPretty(chainInfo.feeCurrencies[0], new Int(Number(data.value))).toDec().toString(); - console.log('🚀 ~ amount:', amount); const res = await this.signOasis(chainId, { amount: amount, to: (data as any).to }); - console.log('🚀 ~ res:', res); + return res; } From f9ab61ee8af28ceb82fd09eccf7049cdcc8d4fa4 Mon Sep 17 00:00:00 2001 From: Toan Dang Date: Wed, 21 Feb 2024 10:59:06 +0700 Subject: [PATCH 06/11] clear helper background --- src/keyring/keyring.ts | 4 +- src/utils/oasis-helper.ts | 128 ----------------------- src/utils/oasis-tx-builder.ts | 188 ---------------------------------- 3 files changed, 2 insertions(+), 318 deletions(-) delete mode 100644 src/utils/oasis-helper.ts delete mode 100644 src/utils/oasis-tx-builder.ts diff --git a/src/keyring/keyring.ts b/src/keyring/keyring.ts index 1bc7d3b..120bb82 100644 --- a/src/keyring/keyring.ts +++ b/src/keyring/keyring.ts @@ -67,8 +67,7 @@ import { parseRpcBalance, StringifiedBigInt, uint2hex -} from '../utils/oasis-helper'; -import { OasisTransaction, signerFromPrivateKey } from '../utils/oasis-tx-builder'; +} from '@owallet/common'; import { CoinPretty, Int } from '@owallet/unit'; // inject TronWeb class @@ -828,6 +827,7 @@ export class KeyRing { const privateKey = uint2hex(accountSigner.secretKey); const bytes = hex2uint(privateKey!); + const txres = { bytes, amount, diff --git a/src/utils/oasis-helper.ts b/src/utils/oasis-helper.ts deleted file mode 100644 index 4060d39..0000000 --- a/src/utils/oasis-helper.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { quantity, staking, types } from '@oasisprotocol/client'; -import BigNumber from 'bignumber.js'; -/** Redux can't serialize bigint fields, so we stringify them, and mark them. */ -export type StringifiedBigInt = string & PreserveAliasName; -// eslint-disable-next-line @typescript-eslint/ban-types -interface PreserveAliasName extends String {} -type ParaTimeNetwork = { - address: string | undefined; - runtimeId: string | undefined; -}; -export enum RuntimeTypes { - Evm = 'evm', - Oasis = 'oasis' -} -//TODO: need handle duplicate -export type ParaTimeConfig = { - mainnet: ParaTimeNetwork; - testnet: ParaTimeNetwork; - local: ParaTimeNetwork; - gasPrice: bigint; - feeGas: bigint; - decimals: number; - displayOrder: number; - type: RuntimeTypes; -}; - -// Hover to check if inferred variable type is StringifiedBigInt (not string) -export const testPreserveAliasName = '0' as StringifiedBigInt; - -export const uint2hex = (uint: Uint8Array) => Buffer.from(uint).toString('hex'); -export const hex2uint = (hex: string) => new Uint8Array(Buffer.from(hex, 'hex')); - -export const shortPublicKey = async (publicKey: Uint8Array) => { - return await staking.addressFromPublicKey(publicKey); -}; - -export const publicKeyToAddress = async (publicKey: Uint8Array) => { - const data = await staking.addressFromPublicKey(publicKey); - return staking.addressToBech32(data); -}; - -export const addressToPublicKey = async (addr: string) => { - return staking.addressFromBech32(addr); -}; - -export const uint2bigintString = (uint: Uint8Array): StringifiedBigInt => quantity.toBigInt(uint).toString(); -export const stringBigint2uint = (number: StringifiedBigInt) => quantity.fromBigInt(BigInt(number)); - -export function concat(...parts: Uint8Array[]) { - let length = 0; - for (const part of parts) { - length += part.length; - } - const result = new Uint8Array(length); - let pos = 0; - for (const part of parts) { - result.set(part, pos); - pos += part.length; - } - return result; -} - -export function parseRoseStringToBigNumber(value: string, decimals = 9): BigNumber { - const baseUnitBN = new BigNumber(value).shiftedBy(decimals); // * 10 ** decimals - if (baseUnitBN.isNaN()) { - throw new Error(`not a number in parseRoseStringToBigNumber(${value})`); - } - if (baseUnitBN.decimalPlaces()! > 0) { - console.error('lost precision in parseRoseStringToBigNumber(', value); - } - return baseUnitBN.decimalPlaces(0); -} - -export function parseRoseStringToBaseUnitString(value: string): StringifiedBigInt { - const baseUnitBN = parseRoseStringToBigNumber(value); - return BigInt(baseUnitBN.toFixed(0)).toString(); -} - -function getRoseString(roseBN: BigNumber, minimumFractionDigits: number, maximumFractionDigits: number) { - return roseBN.toFormat(Math.min(Math.max(roseBN.decimalPlaces()!, minimumFractionDigits), maximumFractionDigits)); -} - -export function isAmountGreaterThan(amount: string, value: string) { - return parseRoseStringToBigNumber(amount).isGreaterThan(parseRoseStringToBigNumber(value)); -} - -export function formatBaseUnitsAsRose( - amount: StringifiedBigInt, - { minimumFractionDigits = 0, maximumFractionDigits = Infinity } = {} -) { - const roseBN = new BigNumber(amount).shiftedBy(-9); // / 10 ** 9 - return getRoseString(roseBN, minimumFractionDigits, maximumFractionDigits); -} - -export function formatWeiAsWrose( - amount: StringifiedBigInt, - { minimumFractionDigits = 0, maximumFractionDigits = Infinity } = {} -) { - const roseBN = new BigNumber(amount).shiftedBy(-18); // / 10 ** 18 - return getRoseString(roseBN, minimumFractionDigits, maximumFractionDigits); -} - -export function parseRpcBalance(account: types.StakingAccount) { - const zero = stringBigint2uint('0'); - - return { - available: uint2bigintString(account.general?.balance || zero), - validator: { - escrow: uint2bigintString(account.escrow?.active?.balance || zero), - escrow_debonding: uint2bigintString(account.escrow?.debonding?.balance || zero) - } - }; -} - -export function formatCommissionPercent(commission: number): string { - return new BigNumber(commission).times(100).toFormat(); -} - -export function getFeeAmount(gasPrice: bigint, feeGas: bigint): string { - // A wild guess: the minimum gas price times the default loose - // overestimate of the gas. - return (gasPrice * feeGas).toString(); -} - -const defaultDepositFeeAmount = '0'; -export const getDefaultFeeAmount = (isDepositing: boolean, paraTimeConfig: ParaTimeConfig): string => { - return isDepositing ? defaultDepositFeeAmount : getFeeAmount(paraTimeConfig.feeGas, paraTimeConfig.gasPrice); -}; diff --git a/src/utils/oasis-tx-builder.ts b/src/utils/oasis-tx-builder.ts deleted file mode 100644 index 6e86746..0000000 --- a/src/utils/oasis-tx-builder.ts +++ /dev/null @@ -1,188 +0,0 @@ -import * as oasis from '@oasisprotocol/client'; -import * as oasisRT from '@oasisprotocol/client-rt'; -import { ContextSigner, Signer } from '@oasisprotocol/client/dist/signature'; -import { addressToPublicKey, shortPublicKey } from './oasis-helper'; - -type OasisClient = oasis.client.NodeInternal; -export class WalletError extends Error { - constructor(public readonly type: WalletErrors, message: string, public readonly originalError?: Error) { - super(message); - } -} - -export enum WalletErrors { - UnknownError = 'unknown', - UnknownGrpcError = 'unknown_grpc', - InvalidAddress = 'invalid_address', - InvalidPrivateKey = 'invalid_private_key', - InsufficientBalance = 'insufficient_balance', - CannotSendToSelf = 'cannot_send_to_self', - InvalidNonce = 'invalid_nonce', - DuplicateTransaction = 'duplicate_transaction', - NoOpenWallet = 'no_open_wallet', - USBTransportError = 'usb_transport_error', - USBTransportNotSupported = 'usb_transport_not_supported', - BluetoothTransportNotSupported = 'bluetooth_transport_not_supported', - LedgerUnknownError = 'unknown_ledger_error', - LedgerCannotOpenOasisApp = 'cannot_open_oasis_app', - LedgerOasisAppIsNotOpen = 'oasis_app_is_not_open', - LedgerNoDeviceSelected = 'no_device_selected', - LedgerTransactionRejected = 'transaction_rejected', - LedgerAppVersionNotSupported = 'ledger_version_not_supported', - LedgerDerivedDifferentAccount = 'ledger_derived_different_account', - IndexerAPIError = 'indexer_api_error', - DisconnectedError = 'disconnected_error', - ParaTimesUnknownError = 'para_times_unknown_error' -} - -export const signerFromPrivateKey = (privateKey: Uint8Array) => { - return oasis.signature.NaclSigner.fromSecret(privateKey, 'this key is not important'); -}; - -export const signerFromEthPrivateKey = (ethPrivateKey: Uint8Array) => { - return oasisRT.signatureSecp256k1.EllipticSigner.fromPrivate(ethPrivateKey, 'this key is not important'); -}; - -/** Transaction Wrapper */ -export type TW = oasis.consensus.TransactionWrapper; - -/** Runtime Transaction Wrapper */ -type RTW = oasisRT.wrapper.TransactionWrapper; - -export class OasisTransaction { - protected static genesis?: oasis.types.GenesisDocument; - - public static async buildReclaimEscrow( - nic: OasisClient, - signer: Signer, - account: string, - shares: bigint - ): Promise> { - const tw = oasis.staking.reclaimEscrowWrapper(); - const nonce = await OasisTransaction.getNonce(nic, signer); - tw.setNonce(nonce); - tw.setFeeAmount(oasis.quantity.fromBigInt(0n)); - tw.setBody({ - account: await addressToPublicKey(account), - shares: oasis.quantity.fromBigInt(shares) - }); - - const gas = await tw.estimateGas(nic, signer.public()); - tw.setFeeGas(gas); - - return tw; - } - - public static async buildAddEscrow( - nic: OasisClient, - signer: Signer, - account: string, - amount: bigint - ): Promise> { - const tw = oasis.staking.addEscrowWrapper(); - const nonce = await OasisTransaction.getNonce(nic, signer); - tw.setNonce(nonce); - tw.setFeeAmount(oasis.quantity.fromBigInt(0n)); - tw.setBody({ - account: await addressToPublicKey(account), - amount: oasis.quantity.fromBigInt(amount) - }); - - const gas = await tw.estimateGas(nic, signer.public()); - tw.setFeeGas(gas); - - return tw; - } - - public static async buildTransfer( - nic: OasisClient, - signer: Signer, - to: string, - amount: bigint - ): Promise> { - const tw = oasis.staking.transferWrapper(); - const nonce = await OasisTransaction.getNonce(nic, signer); - tw.setNonce(nonce); - tw.setFeeAmount(oasis.quantity.fromBigInt(0n)); - tw.setBody({ - to: await addressToPublicKey(to), - amount: oasis.quantity.fromBigInt(amount) - }); - - console.log('tw', tw); - - const gas = await tw.estimateGas(nic, signer.public()); - tw.setFeeGas(gas); - - return tw; - } - - public static async buildStakingAllowTransfer( - nic: OasisClient, - signer: Signer, - to: string, - amount: bigint - ): Promise> { - const tw = oasis.staking.allowWrapper(); - const nonce = await OasisTransaction.getNonce(nic, signer); - const beneficiary = await addressToPublicKey(to); - - tw.setNonce(nonce); - tw.setFeeAmount(oasis.quantity.fromBigInt(0n)); - tw.setBody({ - beneficiary, - negative: false, - amount_change: oasis.quantity.fromBigInt(amount) - }); - - const gas = await tw.estimateGas(nic, signer.public()); - tw.setFeeGas(gas); - - return tw; - } - - public static async signUsingLedger(chainContext: string, signer: ContextSigner, tw: TW): Promise { - await tw.sign(signer, chainContext); - - // @todo Upstream bug in oasis-app, the signature is larger than 64 bytes - tw.signedTransaction.signature.signature = tw.signedTransaction.signature.signature.slice(0, 64); - } - - public static async sign(chainContext: string, signer: Signer, tw: TW): Promise { - return tw.sign(new oasis.signature.BlindContextSigner(signer), chainContext); - } - - public static async signParaTime(chainContext: string, signer: Signer, tw: RTW): Promise { - return tw.sign([new oasis.signature.BlindContextSigner(signer)], chainContext); - } - - public static async submit(nic: OasisClient, tw: TW | RTW): Promise { - try { - await tw.submit(nic); - } catch (e: any) { - const grpcError = e?.cause?.metadata?.['grpc-message'] || e.message; - - if (!grpcError) { - throw new WalletError(WalletErrors.UnknownError, grpcError, e); - } - - switch (grpcError) { - case 'transaction: invalid nonce': - throw new WalletError(WalletErrors.InvalidNonce, 'Invalid nonce'); - case 'consensus: duplicate transaction': - throw new WalletError(WalletErrors.DuplicateTransaction, 'Duplicate transaction'); - default: - throw new WalletError(WalletErrors.UnknownGrpcError, grpcError, e); - } - } - } - - protected static async getNonce(nic: OasisClient, signer: Signer): Promise { - const nonce = await nic.consensusGetSignerNonce({ - account_address: await shortPublicKey(signer.public()), - height: 0 - }); - - return BigInt(nonce || 0); - } -} From e80446c7bff19bf64731dba00209e565e8787407 Mon Sep 17 00:00:00 2001 From: Toan Dang Date: Thu, 22 Feb 2024 18:09:40 +0700 Subject: [PATCH 07/11] refactor oasis --- src/keyring/handler.ts | 42 +++++++++++++++++++------------------- src/keyring/keyring.ts | 46 +++++++++++++++++++++--------------------- src/keyring/service.ts | 22 ++++++++++---------- 3 files changed, 55 insertions(+), 55 deletions(-) diff --git a/src/keyring/handler.ts b/src/keyring/handler.ts index b10ea6d..3a68287 100644 --- a/src/keyring/handler.ts +++ b/src/keyring/handler.ts @@ -92,8 +92,8 @@ export const getHandler: (service: KeyRingService) => Handler = (service: KeyRin return handleRequestSignTronMsg(service)(env, msg as RequestSignTronMsg); case RequestSignOasisMsg: return handleRequestSignOasisMsg(service)(env, msg as RequestSignOasisMsg); - case GetDefaultAddressOasisMsg: - return handleGetDefaultAddressOasisMsg(service)(env, msg as GetDefaultAddressOasisMsg); + // case GetDefaultAddressOasisMsg: + // return handleGetDefaultAddressOasisMsg(service)(env, msg as GetDefaultAddressOasisMsg); case RequestSignEthereumTypedDataMsg: return handleRequestSignEthereumTypedData(service)(env, msg as RequestSignEthereumTypedDataMsg); case RequestPublicKeyMsg: @@ -501,22 +501,22 @@ const handleRequestSignOasisMsg: (service: KeyRingService) => InternalHandler InternalHandler = ( - service -) => { - return async (_, msg) => { - const address = await service.getDefaultOasisAddress(msg.chainId); - const balance = await service.getDefaultOasisBalance(address, msg.chainId); - const ledgerCheck = service.getKeyRingType(); - - if (ledgerCheck === 'ledger') { - throw new Error('Ledger is currently not supported for Oasis.'); - } - return { - name: service.getKeyStoreMeta('name'), - type: Number(ledgerCheck), - address: address, - balance: balance - }; - }; -}; +// const handleGetDefaultAddressOasisMsg: (service: KeyRingService) => InternalHandler = ( +// service +// ) => { +// return async (_, msg) => { +// const address = await service.getDefaultOasisAddress(msg.chainId); +// const balance = await service.getDefaultOasisBalance(address, msg.chainId); +// const ledgerCheck = service.getKeyRingType(); + +// if (ledgerCheck === 'ledger') { +// throw new Error('Ledger is currently not supported for Oasis.'); +// } +// return { +// name: service.getKeyStoreMeta('name'), +// type: Number(ledgerCheck), +// address: address, +// balance: balance +// }; +// }; +// }; diff --git a/src/keyring/keyring.ts b/src/keyring/keyring.ts index 120bb82..75641a2 100644 --- a/src/keyring/keyring.ts +++ b/src/keyring/keyring.ts @@ -836,29 +836,29 @@ export class KeyRing { return txres; } - public async loadBalanceOasis( - address: string, - chainId: string - ): Promise<{ - available: StringifiedBigInt; - validator: { escrow: StringifiedBigInt; escrow_debonding: StringifiedBigInt }; - }> { - if (this.status !== KeyRingStatus.UNLOCKED || this.type === 'none' || !this.keyStore) { - throw new Error('Key ring is not unlocked'); - } - if (!this.mnemonic) { - throw new Error('Key store type is mnemonic and it is unlocked. But, mnemonic is not loaded unexpectedly'); - } - const chainInfo = await this.chainsService.getChainInfo(chainId as string); - - const nic = await getOasisNic(chainInfo.grpc); - - const publicKey = await addressToPublicKey(address); - const account = await nic.stakingAccount({ owner: publicKey, height: 0 }); - const grpcBalance = parseRpcBalance(account); - - return grpcBalance; - } + // public async loadBalanceOasis( + // address: string, + // chainId: string + // ): Promise<{ + // available: StringifiedBigInt; + // validator: { escrow: StringifiedBigInt; escrow_debonding: StringifiedBigInt }; + // }> { + // if (this.status !== KeyRingStatus.UNLOCKED || this.type === 'none' || !this.keyStore) { + // throw new Error('Key ring is not unlocked'); + // } + // if (!this.mnemonic) { + // throw new Error('Key store type is mnemonic and it is unlocked. But, mnemonic is not loaded unexpectedly'); + // } + // const chainInfo = await this.chainsService.getChainInfo(chainId as string); + + // const nic = await getOasisNic(chainInfo.grpc); + + // const publicKey = await addressToPublicKey(address); + // const account = await nic.stakingAccount({ owner: publicKey, height: 0 }); + // const grpcBalance = parseRpcBalance(account); + + // return grpcBalance; + // } private loadPrivKey(coinType: number): PrivKeySecp256k1 { if (this.status !== KeyRingStatus.UNLOCKED || this.type === 'none' || !this.keyStore) { diff --git a/src/keyring/service.ts b/src/keyring/service.ts index 1d8f3a8..942d86f 100644 --- a/src/keyring/service.ts +++ b/src/keyring/service.ts @@ -850,15 +850,15 @@ export class KeyRingService { } } - async getDefaultOasisAddress(chainId: string): Promise { - const signerPublicKey = await this.keyRing.loadPublicKeyOasis(); - const addressUint8Array = await oasis.staking.addressFromPublicKey(signerPublicKey); - const address = oasis.staking.addressToBech32(addressUint8Array); - return address; - } - - async getDefaultOasisBalance(address: string, chainId: string): Promise { - const balance = await this.keyRing.loadBalanceOasis(address, chainId); - return balance.available; - } + // async getDefaultOasisAddress(chainId: string): Promise { + // const signerPublicKey = await this.keyRing.loadPublicKeyOasis(); + // const addressUint8Array = await oasis.staking.addressFromPublicKey(signerPublicKey); + // const address = oasis.staking.addressToBech32(addressUint8Array); + // return address; + // } + + // async getDefaultOasisBalance(address: string, chainId: string): Promise { + // const balance = await this.keyRing.loadBalanceOasis(address, chainId); + // return balance.available; + // } } From b4d6c090ef2fcaa89259eb35cb0058379871dfbd Mon Sep 17 00:00:00 2001 From: Toan Dang Date: Fri, 23 Feb 2024 11:35:05 +0700 Subject: [PATCH 08/11] update oasis bg --- src/keyring/handler.ts | 9 --------- src/keyring/keyring.ts | 31 +++++++++++++++++++++++-------- 2 files changed, 23 insertions(+), 17 deletions(-) diff --git a/src/keyring/handler.ts b/src/keyring/handler.ts index 3a68287..03c91a8 100644 --- a/src/keyring/handler.ts +++ b/src/keyring/handler.ts @@ -232,15 +232,6 @@ const handleGetKeyMsg: (service: KeyRingService) => InternalHandler = ? bech32Address.toBech32Btc(bech32PrefixAccAddr) : bech32Address.toBech32(bech32PrefixAccAddr); - // if (msg.chainId === '0x5afe') { - // // const signerPublicKey = await service.load - // // const addressUint8Array = await oasis.staking.addressFromPublicKey(key.pubKey); - // const address = oasis.staking.addressToBech32(key.address); - // const bech32Convert = bech32Address.toBech32(Bech32Address.defaultBech32Config('oasis').bech32PrefixAccAddr); - // console.log('🚀 ~ return ~ bech32Convert:', bech32Convert); - // console.log('🚀 ~ return ~ address:', address); - // } - return { name: service.getKeyStoreMeta('name'), algo: 'secp256k1', diff --git a/src/keyring/keyring.ts b/src/keyring/keyring.ts index 75641a2..9d8b44d 100644 --- a/src/keyring/keyring.ts +++ b/src/keyring/keyring.ts @@ -2,7 +2,9 @@ import { ChainIdEnum, EmbedChainInfos, MIN_FEE_RATE, + OasisTransaction, convertBip44ToHDPath, + signerFromPrivateKey, splitPathStringToHDPath, typeBtcLedgerByAddress } from '@owallet/common'; @@ -821,19 +823,32 @@ export class KeyRing { const { amount, to } = data; - // const chainInfo = await this.chainsService.getChainInfo(chainId as string); - const accountSigner = await oasis.hdkey.HDKey.getAccountSigner(this.mnemonic, 0); const privateKey = uint2hex(accountSigner.secretKey); const bytes = hex2uint(privateKey!); - const txres = { - bytes, - amount, - to: to.replaceAll(' ', '') - }; - return txres; + if (this.kvStore.type() !== KVStoreType.mobile) { + return { + bytes, + amount, + to: to.replaceAll(' ', '') + }; + } + const chainInfo = await this.chainsService.getChainInfo(chainId as string); + const nic = await getOasisNic(chainInfo.grpc); + const signer = signerFromPrivateKey(bytes); + const bigIntAmount = BigInt(parseRoseStringToBigNumber(amount).toString()); + console.log('bigIntAmount', bigIntAmount); + const chainContext = await nic.consensusGetChainContext(); + + const tw = await OasisTransaction.buildTransfer(nic, signer, to.replaceAll(' ', ''), bigIntAmount); + + await OasisTransaction.sign(chainContext, signer, tw); + + const payload = await OasisTransaction.submit(nic, tw); + + return payload; } // public async loadBalanceOasis( From 28181240e2ddb4c44ae3f9b90bd4163e81674b3a Mon Sep 17 00:00:00 2001 From: Toan Dang Date: Fri, 23 Feb 2024 14:06:58 +0700 Subject: [PATCH 09/11] update keyring --- src/keyring/keyring.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/keyring/keyring.ts b/src/keyring/keyring.ts index 9d8b44d..3771be0 100644 --- a/src/keyring/keyring.ts +++ b/src/keyring/keyring.ts @@ -1042,7 +1042,7 @@ export class KeyRing { if (this.keyStore.type === 'ledger') { return this.processSignLedgerEvm(env, chainId, rpc, message); } else { - if (chainId === ChainIdEnum.OasisNative) { + if (chainId === ChainIdEnum.Oasis) { const data = message as any; const chainInfo = await this.chainsService.getChainInfo(chainId as string); From d617eb041112d294e7d0a6f75153bdf72f275172 Mon Sep 17 00:00:00 2001 From: Toan Dang Date: Mon, 26 Feb 2024 15:29:57 +0700 Subject: [PATCH 10/11] clean oasis --- src/keyring/handler.ts | 20 -------------------- src/keyring/service.ts | 12 ------------ 2 files changed, 32 deletions(-) diff --git a/src/keyring/handler.ts b/src/keyring/handler.ts index 03c91a8..4109152 100644 --- a/src/keyring/handler.ts +++ b/src/keyring/handler.ts @@ -491,23 +491,3 @@ const handleRequestSignOasisMsg: (service: KeyRingService) => InternalHandler InternalHandler = ( -// service -// ) => { -// return async (_, msg) => { -// const address = await service.getDefaultOasisAddress(msg.chainId); -// const balance = await service.getDefaultOasisBalance(address, msg.chainId); -// const ledgerCheck = service.getKeyRingType(); - -// if (ledgerCheck === 'ledger') { -// throw new Error('Ledger is currently not supported for Oasis.'); -// } -// return { -// name: service.getKeyStoreMeta('name'), -// type: Number(ledgerCheck), -// address: address, -// balance: balance -// }; -// }; -// }; diff --git a/src/keyring/service.ts b/src/keyring/service.ts index ea1db1f..ca1f0f2 100644 --- a/src/keyring/service.ts +++ b/src/keyring/service.ts @@ -853,16 +853,4 @@ export class KeyRingService { this.interactionService.dispatchEvent(APP_PORT, 'request-sign-oasis-end', {}); } } - - // async getDefaultOasisAddress(chainId: string): Promise { - // const signerPublicKey = await this.keyRing.loadPublicKeyOasis(); - // const addressUint8Array = await oasis.staking.addressFromPublicKey(signerPublicKey); - // const address = oasis.staking.addressToBech32(addressUint8Array); - // return address; - // } - - // async getDefaultOasisBalance(address: string, chainId: string): Promise { - // const balance = await this.keyRing.loadBalanceOasis(address, chainId); - // return balance.available; - // } } From 36ee5b48a4dd9ebf77a38ad5a0f48232431a3e44 Mon Sep 17 00:00:00 2001 From: Toan Dang Date: Mon, 26 Feb 2024 15:34:24 +0700 Subject: [PATCH 11/11] clean oasis bg --- src/keyring/handler.ts | 6 +----- src/keyring/keyring.ts | 27 +-------------------------- 2 files changed, 2 insertions(+), 31 deletions(-) diff --git a/src/keyring/handler.ts b/src/keyring/handler.ts index 4109152..f3f83cc 100644 --- a/src/keyring/handler.ts +++ b/src/keyring/handler.ts @@ -92,8 +92,6 @@ export const getHandler: (service: KeyRingService) => Handler = (service: KeyRin return handleRequestSignTronMsg(service)(env, msg as RequestSignTronMsg); case RequestSignOasisMsg: return handleRequestSignOasisMsg(service)(env, msg as RequestSignOasisMsg); - // case GetDefaultAddressOasisMsg: - // return handleGetDefaultAddressOasisMsg(service)(env, msg as GetDefaultAddressOasisMsg); case RequestSignEthereumTypedDataMsg: return handleRequestSignEthereumTypedData(service)(env, msg as RequestSignEthereumTypedDataMsg); case RequestPublicKeyMsg: @@ -214,8 +212,6 @@ const handleGetKeyMsg: (service: KeyRingService) => InternalHandler = await service.permissionService.checkOrGrantBasicAccessPermission(env, msg.chainId, msg.origin); const key = await service.getKey(msg.chainId); - console.log('🚀 ~ return ~ msg.chainId:', msg.chainId); - console.log('🚀 ~ return ~ key:', key); const networkType = getNetworkTypeByChainId(msg.chainId); @@ -224,7 +220,7 @@ const handleGetKeyMsg: (service: KeyRingService) => InternalHandler = const isInj = msg.chainId?.startsWith('injective'); const pubkeyLedger = service.getKeyRingLedgerPubKey(); const bech32Address = new Bech32Address(key.address); - // console.log('🚀 ~ return ~ bech32Address:', bech32Address); + const { bech32PrefixAccAddr } = (await service.chainsService.getChainInfo(msg.chainId)).bech32Config; // hereee const bech32Convert = diff --git a/src/keyring/keyring.ts b/src/keyring/keyring.ts index 3771be0..2e325ba 100644 --- a/src/keyring/keyring.ts +++ b/src/keyring/keyring.ts @@ -757,7 +757,7 @@ export class KeyRing { } return coinType === 60; })(); - console.log('🚀 ~ isEthermint ~ isEthermint:', isEthermint); + if (coinType === 474) { const signerPublicKey = await this.loadPublicKeyOasis(); const addressUint8Array = await oasis.staking.addressFromPublicKey(signerPublicKey); @@ -851,30 +851,6 @@ export class KeyRing { return payload; } - // public async loadBalanceOasis( - // address: string, - // chainId: string - // ): Promise<{ - // available: StringifiedBigInt; - // validator: { escrow: StringifiedBigInt; escrow_debonding: StringifiedBigInt }; - // }> { - // if (this.status !== KeyRingStatus.UNLOCKED || this.type === 'none' || !this.keyStore) { - // throw new Error('Key ring is not unlocked'); - // } - // if (!this.mnemonic) { - // throw new Error('Key store type is mnemonic and it is unlocked. But, mnemonic is not loaded unexpectedly'); - // } - // const chainInfo = await this.chainsService.getChainInfo(chainId as string); - - // const nic = await getOasisNic(chainInfo.grpc); - - // const publicKey = await addressToPublicKey(address); - // const account = await nic.stakingAccount({ owner: publicKey, height: 0 }); - // const grpcBalance = parseRpcBalance(account); - - // return grpcBalance; - // } - private loadPrivKey(coinType: number): PrivKeySecp256k1 { if (this.status !== KeyRingStatus.UNLOCKED || this.type === 'none' || !this.keyStore) { throw new Error('Key ring is not unlocked'); @@ -1033,7 +1009,6 @@ export class KeyRing { throw new Error('Key Store is empty'); } - // const cType = this.computeKeyStoreCoinType(chainId, coinType); const networkType = getNetworkTypeByChainId(chainId); if (networkType !== 'evm') { throw new Error('Invalid coin type passed in to Ethereum signing (expected 60)');