refactor: Group profile function and eth function together (#67)

* refactor: Group profile function and eth function together

* refactor: group eth backend

* refactor: Move various eth call to eth backend

* refactor: move accounts call to account backend

* refactor: permission
This commit is contained in:
Anthony Laibe 2021-10-01 18:53:38 +02:00 committed by GitHub
parent 2bb5df3c5f
commit c7722cda00
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 400 additions and 378 deletions

View File

@ -41,9 +41,6 @@ proc callPrivateRPC*(methodName: string, payload = %* []): string =
# proc markTrustedPeer*(peer: string) =
# discard callPrivateRPC("markTrustedPeer".prefix(false), %* [peer])
# proc getBlockByNumber*(blockNumber: string): string =
# result = callPrivateRPC("eth_getBlockByNumber", %* [blockNumber, false])
# proc getTransfersByAddress*(address: string, toBlock: string, limit: string, fetchMore: bool = false): string =
# let toBlockParsed = if not fetchMore: newJNull() else: %toBlock
# result = callPrivateRPC("wallet_getTransfersByAddress", %* [address, toBlockParsed, limit, fetchMore])

View File

@ -2,14 +2,13 @@ import json, strutils, sequtils, tables, chronicles, times, sugar, algorithm
import statusgo_backend/chat as status_chat
import statusgo_backend/contacts as status_contacts
import statusgo_backend/chatCommands as status_chat_commands
import types/[message, status_update, activity_center_notification,
sticker, removed_message]
import types/[message, status_update, activity_center_notification, sticker, removed_message, profile]
import types/chat as chat_type
import utils as status_utils
import stickers
import ../eventemitter
import profile/profile
import contacts
import chat/[chat, utils]
import ens, accounts

View File

@ -1,8 +1,8 @@
import json, chronicles
import statusgo_backend/contacts as status_contacts
import statusgo_backend/accounts as status_accounts
import statusgo_backend/chat as status_chat
import profile/profile
import ./statusgo_backend/contacts as status_contacts
import ./statusgo_backend/accounts as status_accounts
import ./statusgo_backend/chat as status_chat
import ./types/profile
import ../eventemitter
const DELETE_CONTACT* = "__deleteThisContact__"

View File

@ -1,26 +1,24 @@
import sequtils
import strformat
import strutils
import profile/profile
import nimcrypto
import json
import json_serialization
import tables
import strformat
import statusgo_backend/core
import statusgo_backend/settings as status_settings
import ./types/[transaction, setting, rpc_response, network_type, network]
import utils
import statusgo_backend/wallet
import stew/byteutils
import unicode
import transactions
import algorithm
import web3/[ethtypes, conversions], stew/byteutils, stint
import eth/contracts
import eth/transactions as eth_transactions
import chronicles, libp2p/[multihash, multicodec, cid]
import ./wallet as status_wallet
import ./statusgo_backend/eth as eth
import ./statusgo_backend/wallet
import ./statusgo_backend/accounts as status_accounts
import ./statusgo_backend/settings as status_settings
import ./types/[transaction, setting, rpc_response, network_type, network, profile]
import ./utils
import ./transactions
import ./eth/contracts
const domain* = ".stateofus.eth"
@ -52,8 +50,7 @@ proc userNameOrAlias*(contact: Profile, removeSuffix: bool = false): string =
result = contact.alias
proc label*(username:string): string =
let name = username.toLower()
var node:array[32, byte] = keccak_256.digest(username).data
var node:array[32, byte] = keccak_256.digest(username.toLower()).data
result = "0x" & node.toHex()
proc namehash*(ensName:string): string =
@ -79,9 +76,9 @@ proc resolver*(usernameHash: string): string =
"from": "0x0000000000000000000000000000000000000000",
"data": fmt"{resolver_signature}{userNameHash}"
}, "latest"]
let response = callPrivateRPC("eth_call", payload)
let response = eth.call(payload)
# TODO: error handling
var resolverAddr = response.parseJson["result"].getStr
var resolverAddr = response.result
resolverAddr.removePrefix("0x000000000000000000000000")
result = "0x" & resolverAddr
@ -94,9 +91,9 @@ proc owner*(username: string): string =
"from": "0x0000000000000000000000000000000000000000",
"data": fmt"{owner_signature}{userNameHash}"
}, "latest"]
let response = callPrivateRPC("eth_call", payload)
let response = eth.call(payload)
# TODO: error handling
let ownerAddr = response.parseJson["result"].getStr;
let ownerAddr = response.result
if ownerAddr == "0x0000000000000000000000000000000000000000000000000000000000000000":
return ""
result = "0x" & ownerAddr.substr(26)
@ -111,9 +108,9 @@ proc pubkey*(username: string): string =
"from": "0x0000000000000000000000000000000000000000",
"data": fmt"{pubkey_signature}{userNameHash}"
}, "latest"]
let response = callPrivateRPC("eth_call", payload)
let response = eth.call(payload)
# TODO: error handling
var pubkey = response.parseJson["result"].getStr
var pubkey = response.result
if pubkey == "0x" or pubkey == "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000":
result = ""
else:
@ -130,9 +127,9 @@ proc address*(username: string): string =
"from": "0x0000000000000000000000000000000000000000",
"data": fmt"{address_signature}{userNameHash}"
}, "latest"]
let response = callPrivateRPC("eth_call", payload)
let response = eth.call(payload)
# TODO: error handling
let address = response.parseJson["result"].getStr;
let address = response.result
if address == "0x0000000000000000000000000000000000000000000000000000000000000000":
return ""
result = "0x" & address.substr(26)
@ -148,13 +145,14 @@ proc contenthash*(ensAddr: string): string =
"data": fmt"{contenthash_signature}{ensHash}"
}, "latest"]
let response = callPrivateRPC("eth_call", payload)
let bytesResponse = response.parseJson["result"].getStr;
let response = eth.call(payload)
let bytesResponse = response.result
if bytesResponse == "0x":
return ""
let size = fromHex(Stuint[256], bytesResponse[66..129]).truncate(int)
result = bytesResponse[130..129+size*2]
result = bytesResponse[130..129+size*2]
proc getPrice*(): Stuint[256] =
@ -166,13 +164,13 @@ proc getPrice*(): Stuint[256] =
"data": contract.methods["getPrice"].encodeAbi()
}, "latest"]
let responseStr = callPrivateRPC("eth_call", payload)
let response = Json.decode(responseStr, RpcResponse)
let response = eth.call(payload)
if not response.error.isNil:
raise newException(RpcException, "Error getting ens username price: " & response.error.message)
if response.result == "0x":
raise newException(RpcException, "Error getting ens username price: 0x")
result = fromHex(Stuint[256], response.result)
result = fromHex(Stuint[256], response.result)
proc releaseEstimateGas*(username: string, address: string, success: var bool): int =
let
@ -188,6 +186,7 @@ proc releaseEstimateGas*(username: string, address: string, success: var bool):
result = fromHex[int](response)
except RpcException as e:
error "Could not estimate gas for ens release", err=e.msg
error "Could not estimate gas for ens release", err=e.msg
proc release*(username: string, address: string, gas, gasPrice, password: string, success: var bool): string =
let
@ -204,6 +203,7 @@ proc release*(username: string, address: string, gas, gasPrice, password: strin
except RpcException as e:
error "Could not estimate gas for ens release", err=e.msg
proc getExpirationTime*(username: string, success: var bool): int =
let
label = fromHex(FixedBytes[32], label(username))
@ -216,7 +216,7 @@ proc getExpirationTime*(username: string, success: var bool): int =
tx.data = ensUsernamesContract.methods["getExpirationTime"].encodeAbi(expTime)
var response = ""
try:
response = eth_transactions.call(tx).result
response = eth.call(tx).result
success = true
except RpcException as e:
success = false
@ -277,6 +277,7 @@ proc setPubKeyEstimateGas*(username: string, address: string, pubKey: string, su
var hash = namehash(username)
hash.removePrefix("0x")
let
label = fromHex(FixedBytes[32], "0x" & hash)
x = fromHex(FixedBytes[32], "0x" & pubkey[4..67])
@ -321,7 +322,6 @@ proc statusRegistrarAddress*():string =
let network = status_settings.getCurrentNetwork().toNetwork()
result = $contracts.findContract(network.chainId, "ens-usernames").address
type
ENSType* {.pure.} = enum
IPFS,
@ -381,7 +381,7 @@ proc validateEnsName*(ens: string, isStatus: bool, usernames: seq[string]): stri
result = "available"
else:
let userPubKey = status_settings.getSetting[string](Setting.PublicKey, "0x0")
let userWallet = status_wallet.getWalletAccounts()[0].address
let userWallet = status_accounts.getWalletAccounts()[0].address
let ens_pubkey = pubkey(ens)
if ownerAddr != "":
if ens_pubkey == "" and ownerAddr == userWallet:

View File

@ -5,7 +5,12 @@ import
web3/ethtypes, stew/byteutils, nimcrypto, json_serialization, chronicles
import
../types/network, ../statusgo_backend/settings, ../statusgo_backend/coder, transactions, methods, ../utils
../types/network,
../statusgo_backend/settings,
../statusgo_backend/coder,
../statusgo_backend/eth,
./methods,
../utils
export
GetPackData, PackData, BuyToken, ApproveAndCall, Transfer, BalanceOf, Register, SetPubkey,

View File

@ -1,23 +0,0 @@
import
web3/ethtypes
import
transactions, ../types/[rpc_response, transaction]
proc sendTransaction*(tx: var TransactionData, password: string, success: var bool): string =
success = true
try:
let response = transactions.sendTransaction(tx, password)
result = response.result
except RpcException as e:
success = false
result = e.msg
proc estimateGas*(tx: var TransactionData, success: var bool): string =
success = true
try:
let response = transactions.estimateGas(tx)
result = response.result
except RpcException as e:
success = false
result = e.msg

View File

@ -5,7 +5,9 @@ import
nimcrypto, web3/[encoding, ethtypes]
import
../types/[rpc_response, transaction], ../statusgo_backend/coder, eth, transactions
../types/[rpc_response, transaction],
../statusgo_backend/coder,
../statusgo_backend/eth as eth
export sendTransaction
@ -42,7 +44,7 @@ proc estimateGas*(self: Method, tx: var TransactionData, methodDescriptor: objec
success = true
tx.data = self.encodeAbi(methodDescriptor)
try:
let response = transactions.estimateGas(tx)
let response = eth.estimateGas(tx)
result = response.result # gas estimate in hex
except RpcException as e:
success = false
@ -57,7 +59,7 @@ proc call*[T](self: Method, tx: var TransactionData, methodDescriptor: object, s
tx.data = self.encodeAbi(methodDescriptor)
let response: RpcResponse
try:
response = transactions.call(tx)
response = eth.call(tx)
except RpcException as e:
success = false
result = e.msg

View File

@ -7,15 +7,15 @@ import # std libs
from strutils import parseHexInt, parseInt
import # vendor libs
json_serialization, chronicles, libp2p/[multihash, multicodec, cid], stint,
json_serialization, chronicles, libp2p/[multicodec, cid], stint,
web3/[ethtypes, conversions]
from nimcrypto import fromHex
import # status-desktop libs
../types/[sticker, setting, rpc_response, network_type],
../statusgo_backend/[edn_helpers, settings],
../types/[sticker, setting, rpc_response, network_type],
../statusgo_backend/settings,
../statusgo_backend/eth as eth,
../utils,
./transactions as transactions,
./edn_helpers,
./contracts
# Retrieves number of sticker packs owned by user
@ -32,7 +32,7 @@ proc getBalance*(chainId: int, address: Address): int =
"data": contract.methods["balanceOf"].encodeAbi(balanceOf)
}, "latest"]
let response = transactions.eth_call(payload)
let response = eth.call(payload)
if not response.error.isNil:
raise newException(RpcException, "Error getting stickers balance: " & response.error.message)
@ -50,7 +50,7 @@ proc getPackCount*(chainId: int): int =
"data": contract.methods["packCount"].encodeAbi()
}, "latest"]
let response = transactions.eth_call(payload)
let response = eth.call(payload)
if not response.error.isNil:
raise newException(RpcException, "Error getting stickers balance: " & response.error.message)
@ -71,7 +71,7 @@ proc getPackData*(chainId: int, id: Stuint[256], running: var Atomic[bool]): Sti
"to": $contract.address,
"data": contractMethod.encodeAbi(getPackData)
}, "latest"]
let response = transactions.eth_call(payload)
let response = eth.call(payload)
if not response.error.isNil:
raise newException(RpcException, "Error getting sticker pack data: " & response.error.message)
@ -110,7 +110,7 @@ proc tokenOfOwnerByIndex*(chainId: int, address: Address, idx: Stuint[256]): int
"data": contract.methods["tokenOfOwnerByIndex"].encodeAbi(tokenOfOwnerByIndex)
}, "latest"]
let response = transactions.eth_call(payload)
let response = eth.call(payload)
if not response.error.isNil:
raise newException(RpcException, "Error getting owned tokens: " & response.error.message)
if response.result == "0x":
@ -126,7 +126,7 @@ proc getPackIdFromTokenId*(chainId: int, tokenId: Stuint[256]): int =
"data": contract.methods["tokenPackId"].encodeAbi(tokenPackId)
}, "latest"]
let response = transactions.eth_call(payload)
let response = eth.call(payload)
if not response.error.isNil:
raise newException(RpcException, "Error getting pack id from token id: " & response.error.message)
if response.result == "0x":

View File

@ -5,9 +5,10 @@ import
import
web3/[ethtypes, conversions], json_serialization
import
import
../statusgo_backend/[core, wallet, settings],
../statusgo_backend/tokens as statusgo_backend_tokens,
../statusgo_backend/eth as eth,
../types/[setting, network, rpc_response],
./contracts
from ../utils import parseAddress
@ -45,7 +46,7 @@ proc toggleAsset*(network: Network, symbol: string): seq[Erc20Contract] =
visibleTokens[$network.chainId] = %* visibleTokenList
let saved = saveSetting(Setting.VisibleTokens, $visibleTokens)
convertStringSeqToERC20ContractSeq(network, visibleTokenList)
convertStringSeqToERC20ContractSeq(network, visibleTokenList)
proc hideAsset*(network: Network, symbol: string) =
let visibleTokens = visibleTokensSNTDefault(network)
@ -67,22 +68,22 @@ proc getVisibleTokens*(network: Network): seq[Erc20Contract] =
proc getToken*(network: Network, tokenAddress: string): Erc20Contract =
allErc20ContractsByChainId(network.chainId).concat(statusgo_backend_tokens.getCustomTokens()).findByAddress(tokenAddress.parseAddress)
proc getTokenBalance*(network: Network, tokenAddress: string, account: string): string =
proc getTokenBalance*(network: Network, tokenAddress: string, account: string): string =
var postfixedAccount: string = account
postfixedAccount.removePrefix("0x")
let payload = %* [{
"to": tokenAddress, "from": account, "data": fmt"0x70a08231000000000000000000000000{postfixedAccount}"
}, "latest"]
let response = callPrivateRPC("eth_call", payload)
let balance = response.parseJson["result"].getStr
let response = eth.call(payload)
let balance = response.result
var decimals = 18
let address = parseAddress(tokenAddress)
let t = findErc20Contract(network.chainId, address)
let ct = statusgo_backend_tokens.getCustomTokens().findByAddress(address)
if t != nil:
if t != nil:
decimals = t.decimals
elif ct != nil:
elif ct != nil:
decimals = ct.decimals
result = $hex2Token(balance, decimals)
@ -99,9 +100,8 @@ proc getTokenString*(contract: Contract, methodName: string): string =
"to": $contract.address,
"data": contract.methods[methodName].encodeAbi()
}, "latest"]
let responseStr = callPrivateRPC("eth_call", payload)
let response = Json.decode(responseStr, RpcResponse)
let response = eth.call(payload)
if not response.error.isNil:
raise newException(RpcException, "Error getting token string - " & methodName & ": " & response.error.message)
if response.result == "0x":
@ -119,9 +119,8 @@ proc tokenDecimals*(contract: Contract): int =
"to": $contract.address,
"data": contract.methods["decimals"].encodeAbi()
}, "latest"]
let responseStr = callPrivateRPC("eth_call", payload)
let response = Json.decode(responseStr, RpcResponse)
let response = eth.call(payload)
if not response.error.isNil:
raise newException(RpcException, "Error getting token decimals: " & response.error.message)
if response.result == "0x":

View File

@ -1,33 +0,0 @@
import
json, json_serialization, chronicles, web3/ethtypes
import
../statusgo_backend/core, ../types/[rpc_response, transaction], ../statusgo_backend/conversions
proc estimateGas*(tx: TransactionData): RpcResponse =
let response = core.callPrivateRPC("eth_estimateGas", %*[%tx])
result = Json.decode(response, RpcResponse)
if not result.error.isNil:
raise newException(RpcException, "Error getting gas estimate: " & result.error.message)
trace "Gas estimated succesfully", estimate=result.result
proc sendTransaction*(tx: TransactionData, password: string): RpcResponse =
let responseStr = core.sendTransaction($(%tx), password)
result = Json.decode(responseStr, RpcResponse)
if not result.error.isNil:
raise newException(RpcException, "Error sending transaction: " & result.error.message)
trace "Transaction sent succesfully", hash=result.result
proc call*(tx: TransactionData): RpcResponse =
let responseStr = core.callPrivateRPC("eth_call", %*[%tx, "latest"])
result = Json.decode(responseStr, RpcResponse)
if not result.error.isNil:
raise newException(RpcException, "Error calling method: " & result.error.message)
proc eth_call*(payload = %* []): RpcResponse =
let responseStr = core.callPrivateRPC("eth_call", payload)
result = Json.decode(responseStr, RpcResponse)
if not result.error.isNil:
raise newException(RpcException, "Error calling method: " & result.error.message)

View File

@ -1,16 +1,9 @@
import json
import strutils
import sets
import statusgo_backend/core
import chronicles
import ./statusgo_backend/permissions as status_permissions
import ./types/permission
import ../eventemitter
import sequtils
type
Permission* {.pure.} = enum
Web3 = "web3",
ContactCode = "contact-code"
Unknown = "unknown"
logScope:
topics = "permissions-model"
@ -19,13 +12,6 @@ type
PermissionsModel* = ref object
events*: EventEmitter
proc toPermission*(value: string): Permission =
result = Permission.Unknown
try:
result = parseEnum[Permission](value)
except:
warn "Unknown permission requested", value
proc newPermissionsModel*(events: EventEmitter): PermissionsModel =
result = PermissionsModel()
result.events = events
@ -33,73 +19,27 @@ proc newPermissionsModel*(events: EventEmitter): PermissionsModel =
proc init*(self: PermissionsModel) =
discard
type Dapp* = object
name*: string
permissions*: HashSet[Permission]
proc getDapps*(self: PermissionsModel): seq[Dapp] =
let response = callPrivateRPC("permissions_getDappPermissions")
result = @[]
for dapps in response.parseJson["result"].getElems():
var dapp = Dapp(
name: dapps["dapp"].getStr(),
permissions: initHashSet[Permission]()
)
for permission in dapps["permissions"].getElems():
dapp.permissions.incl(permission.getStr().toPermission())
result.add(dapp)
return status_permissions.getDapps()
proc getPermissions*(self: PermissionsModel, dapp: string): HashSet[Permission] =
let response = callPrivateRPC("permissions_getDappPermissions")
result = initHashSet[Permission]()
for dappPermission in response.parseJson["result"].getElems():
if dappPermission["dapp"].getStr() == dapp:
if not dappPermission.hasKey("permissions"): return
for permission in dappPermission["permissions"].getElems():
result.incl(permission.getStr().toPermission())
return status_permissions.getPermissions(dapp)
proc revoke*(self: PermissionsModel, permission: Permission) =
let response = callPrivateRPC("permissions_getDappPermissions")
var permissions = initHashSet[Permission]()
for dapps in response.parseJson["result"].getElems():
for currPerm in dapps["permissions"].getElems():
let p = currPerm.getStr().toPermission()
if p != permission:
permissions.incl(p)
discard callPrivateRPC("permissions_addDappPermissions", %*[{
"dapp": dapps["dapp"].getStr(),
"permissions": permissions.toSeq()
}])
status_permissions.revoke(permission)
proc hasPermission*(self: PermissionsModel, dapp: string, permission: Permission): bool =
result = self.getPermissions(dapp).contains(permission)
return self.getPermissions(dapp).contains(permission)
proc addPermission*(self: PermissionsModel, dapp: string, permission: Permission) =
var permissions = self.getPermissions(dapp)
permissions.incl(permission)
discard callPrivateRPC("permissions_addDappPermissions", %*[{
"dapp": dapp,
"permissions": permissions.toSeq()
}])
status_permissions.addPermission(dapp, permission)
proc revokePermission*(self: PermissionsModel, dapp: string, permission: Permission) =
var permissions = self.getPermissions(dapp)
permissions.excl(permission)
if permissions.len == 0:
discard callPrivateRPC("permissions_deleteDappPermissions", %*[dapp])
else:
discard callPrivateRPC("permissions_addDappPermissions", %*[{
"dapp": dapp,
"permissions": permissions.toSeq()
}])
status_permissions.revokePermission(dapp, permission)
proc clearPermissions*(self: PermissionsModel, dapp: string) =
discard callPrivateRPC("permissions_deleteDappPermissions", %*[dapp])
status_permissions.clearPermissions(dapp)
proc clearPermissions*(self: PermissionsModel) =
let response = callPrivateRPC("permissions_getDappPermissions")
for dapps in response.parseJson["result"].getElems():
discard callPrivateRPC("permissions_deleteDappPermissions", %*[dapps["dapp"].getStr()])
for dapps in status_permissions.getDapps():
status_permissions.clearPermissions(dapps.name)

View File

@ -1,6 +1,5 @@
import json
import ./types/[identity_image]
import profile/profile
import statusgo_backend/core as statusgo_backend_core
import statusgo_backend/accounts as status_accounts
import statusgo_backend/settings as status_settings

View File

@ -1,29 +0,0 @@
import json
import ../types/[profile, account]
export profile
const contactAdded* = ":contact/added"
const contactBlocked* = ":contact/blocked"
const contactRequest* = ":contact/request-received"
proc isContact*(self: Profile): bool =
result = self.systemTags.contains(contactAdded)
proc isBlocked*(self: Profile): bool =
result = self.systemTags.contains(contactBlocked)
proc requestReceived*(self: Profile): bool =
result = self.systemTags.contains(contactRequest)
proc toProfileModel*(account: Account): Profile =
result = Profile(
id: "",
username: account.name,
identicon: account.identicon,
alias: account.name,
ensName: "",
ensVerified: false,
appearance: 0,
systemTags: @[]
)

View File

@ -1,6 +1,6 @@
import ens, wallet, permissions, utils
import ../eventemitter
import ./types/[setting]
import ./types/[setting, permission]
import utils
import statusgo_backend/accounts
import statusgo_backend/core

View File

@ -25,7 +25,7 @@ proc fromEvent*(T: type MessageSignal, event: JsonNode): MessageSignal =
if event["event"]{"contacts"} != nil:
for jsonContact in event["event"]["contacts"]:
signal.contacts.add(jsonContact.toProfileModel())
signal.contacts.add(jsonContact.toProfile())
var chatsWithMentions: seq[string] = @[]

View File

@ -3,6 +3,7 @@ import json, os, nimcrypto, uuids, json_serialization, chronicles, strutils
from status_go import multiAccountGenerateAndDeriveAddresses, generateAlias, identicon, saveAccountAndLogin, login, openAccounts, getNodeConfig
import core
import ../utils as utils
from ../wallet/account as walletAccount import WalletAccount
import ../types/[account, fleet, rpc_response]
import accounts/constants
@ -14,7 +15,7 @@ proc getDefaultNodeConfig*(fleetConfig: FleetConfig, installationId: string): Js
let networkConfig = getNetworkConfig(constants.DEFAULT_NETWORK_NAME)
let upstreamUrl = networkConfig["config"]["UpstreamConfig"]["URL"]
let fleet = Fleet.PROD
var newDataDir = networkConfig["config"]["DataDir"].getStr
newDataDir.removeSuffix("_rpc")
result = constants.NODE_CONFIG.copy()
@ -43,10 +44,6 @@ proc getDefaultNodeConfig*(fleetConfig: FleetConfig, installationId: string): Js
proc hashPassword*(password: string): string =
result = "0x" & $keccak_256.digest(password)
proc getDefaultAccount*(): string =
var response = callPrivateRPC("eth_accounts")
result = parseJson(response)["result"][0].getStr()
proc generateAddresses*(n = 5): seq[GeneratedAccount] =
let multiAccountConfig = %* {
"n": n,
@ -57,6 +54,30 @@ proc generateAddresses*(n = 5): seq[GeneratedAccount] =
let generatedAccounts = $status_go.multiAccountGenerateAndDeriveAddresses($multiAccountConfig)
result = Json.decode(generatedAccounts, seq[GeneratedAccount])
proc getWalletAccounts*(): seq[WalletAccount] =
try:
var response = callPrivateRPC("accounts_getAccounts")
let accounts = parseJson(response)["result"]
var walletAccounts:seq[WalletAccount] = @[]
for account in accounts:
if (account["chat"].to(bool) == false): # Might need a better condition
walletAccounts.add(WalletAccount(
address: $account["address"].getStr,
path: $account["path"].getStr,
walletType: if (account.hasKey("type")): $account["type"].getStr else: "",
# Watch accoutns don't have a public key
publicKey: if (account.hasKey("public-key")): $account["public-key"].getStr else: "",
name: $account["name"].getStr,
iconColor: $account["color"].getStr,
wallet: account["wallet"].getBool,
chat: account["chat"].getBool,
))
result = walletAccounts
except:
let msg = getCurrentExceptionMsg()
error "Failed getting wallet accounts", msg
proc generateAlias*(publicKey: string): string =
result = $status_go.generateAlias(publicKey)

View File

@ -14,7 +14,7 @@ proc getContactByID*(id: string): Profile =
if responseResult == nil or responseResult.kind == JNull:
return nil
return toProfileModel(parseJSON($response)["result"])
return toProfile(parseJSON($response)["result"])
proc getContacts*(useCache: bool = true): (seq[Profile], bool) =
@ -32,7 +32,7 @@ proc getContacts*(useCache: bool = true): (seq[Profile], bool) =
contacts = @[]
return (contacts, false)
contacts = map(response["result"].getElems(), proc(x: JsonNode): Profile = x.toProfileModel())
contacts = map(response["result"].getElems(), proc(x: JsonNode): Profile = x.toProfile())
for contact in contacts:
contactsIndex[contact.id] = contact

View File

@ -45,10 +45,6 @@ proc markTrustedPeer*(peer: string) =
let response = callPrivateRPC("markTrustedPeer".prefix(false), %* [peer])
info "markTrustedPeer", topics="mailserver-interaction", rpc_method="waku_markTrustedPeer", peer, response
proc getBlockByNumber*(blockNumber: string): string =
result = callPrivateRPC("eth_getBlockByNumber", %* [blockNumber, false])
proc getTransfersByAddress*(address: string, toBlock: string, limit: string, fetchMore: bool = false): string =
let toBlockParsed = if not fetchMore: newJNull() else: %toBlock
result = callPrivateRPC("wallet_getTransfersByAddress", %* [address, toBlockParsed, limit, fetchMore])

View File

@ -0,0 +1,83 @@
import
json, json_serialization, chronicles, web3/ethtypes
import
./core,
./conversions,
../types/[rpc_response, transaction]
proc getBlockByNumber*(blockNumber: string): string =
result = core.callPrivateRPC("eth_getBlockByNumber", %* [blockNumber, false])
proc estimateGas*(tx: TransactionData): RpcResponse =
let response = core.callPrivateRPC("eth_estimateGas", %*[%tx])
result = Json.decode(response, RpcResponse)
if not result.error.isNil:
raise newException(RpcException, "Error getting gas estimate: " & result.error.message)
trace "Gas estimated succesfully", estimate=result.result
proc getDefaultAccount*(): string =
var response = core.callPrivateRPC("eth_accounts")
result = parseJson(response)["result"][0].getStr()
proc estimateGas*(tx: var TransactionData, success: var bool): string =
success = true
try:
let response = estimateGas(tx)
result = response.result
except RpcException as e:
success = false
result = e.msg
proc sendTransaction*(tx: TransactionData, password: string): RpcResponse =
let responseStr = core.sendTransaction($(%tx), password)
result = Json.decode(responseStr, RpcResponse)
if not result.error.isNil:
raise newException(RpcException, "Error sending transaction: " & result.error.message)
trace "Transaction sent succesfully", hash=result.result
proc sendTransaction*(tx: var TransactionData, password: string, success: var bool): string =
success = true
try:
let response = sendTransaction(tx, password)
result = response.result
except RpcException as e:
success = false
result = e.msg
proc getTransactionReceipt*(transactionHash: string): string =
result = core.callPrivateRPC("eth_getTransactionReceipt", %* [transactionHash])
proc getBalance*(address: string): string =
let payload = %* [address, "latest"]
let response = parseJson(core.callPrivateRPC("eth_getBalance", payload))
if response.hasKey("error"):
raise newException(RpcException, "Error getting balance: " & $response["error"])
else:
result = response["result"].str
proc maxPriorityFeePerGas*(): string =
let payload = %* []
result = callPrivateRPC("eth_maxPriorityFeePerGas", payload)
proc feeHistory*(n: int): string =
let payload = %* [n, "latest", nil]
result = callPrivateRPC("eth_feeHistory", payload)
proc getGasPrice*(): string =
let payload = %* []
result = callPrivateRPC("eth_gasPrice", payload)
proc call*(tx: TransactionData): RpcResponse =
let responseStr = core.callPrivateRPC("eth_call", %*[%tx, "latest"])
result = Json.decode(responseStr, RpcResponse)
if not result.error.isNil:
raise newException(RpcException, "Error calling method: " & result.error.message)
proc call*(payload = %* []): RpcResponse =
let responseStr = core.callPrivateRPC("eth_call", payload)
result = Json.decode(responseStr, RpcResponse)
if not result.error.isNil:
raise newException(RpcException, "Error calling method: " & result.error.message)

View File

@ -0,0 +1,67 @@
import json
import strutils
import sets
import chronicles
import sequtils
import ../types/permission
import ./core
proc getDapps*(): seq[Dapp] =
let response = core.callPrivateRPC("permissions_getDappPermissions")
result = @[]
for dapps in response.parseJson["result"].getElems():
var dapp = Dapp(
name: dapps["dapp"].getStr(),
permissions: initHashSet[Permission]()
)
for permission in dapps["permissions"].getElems():
dapp.permissions.incl(permission.getStr().toPermission())
result.add(dapp)
proc getPermissions*(dapp: string): HashSet[Permission] =
let response = core.callPrivateRPC("permissions_getDappPermissions")
result = initHashSet[Permission]()
for dappPermission in response.parseJson["result"].getElems():
if dappPermission["dapp"].getStr() == dapp:
if not dappPermission.hasKey("permissions"): return
for permission in dappPermission["permissions"].getElems():
result.incl(permission.getStr().toPermission())
proc revoke*(permission: Permission) =
let response = core.callPrivateRPC("permissions_getDappPermissions")
var permissions = initHashSet[Permission]()
for dapps in response.parseJson["result"].getElems():
for currPerm in dapps["permissions"].getElems():
let p = currPerm.getStr().toPermission()
if p != permission:
permissions.incl(p)
discard core.callPrivateRPC("permissions_addDappPermissions", %*[{
"dapp": dapps["dapp"].getStr(),
"permissions": permissions.toSeq()
}])
proc addPermission*(dapp: string, permission: Permission) =
var permissions = getPermissions(dapp)
permissions.incl(permission)
discard callPrivateRPC("permissions_addDappPermissions", %*[{
"dapp": dapp,
"permissions": permissions.toSeq()
}])
proc revokePermission*(dapp: string, permission: Permission) =
var permissions = getPermissions(dapp)
permissions.excl(permission)
if permissions.len == 0:
discard core.callPrivateRPC("permissions_deleteDappPermissions", %*[dapp])
else:
discard core.callPrivateRPC("permissions_addDappPermissions", %*[{
"dapp": dapp,
"permissions": permissions.toSeq()
}])
proc clearPermissions*(dapp: string) =
discard core.callPrivateRPC("permissions_deleteDappPermissions", %*[dapp])

View File

@ -4,32 +4,6 @@ from status_go import validateMnemonic#, startWallet
import ../wallet/account
import web3/conversions as web3_conversions, web3/ethtypes
proc getWalletAccounts*(): seq[WalletAccount] =
try:
var response = callPrivateRPC("accounts_getAccounts")
let accounts = parseJson(response)["result"]
var walletAccounts:seq[WalletAccount] = @[]
for account in accounts:
if (account["chat"].to(bool) == false): # Might need a better condition
walletAccounts.add(WalletAccount(
address: $account["address"].getStr,
path: $account["path"].getStr,
walletType: if (account.hasKey("type")): $account["type"].getStr else: "",
# Watch accoutns don't have a public key
publicKey: if (account.hasKey("public-key")): $account["public-key"].getStr else: "",
name: $account["name"].getStr,
iconColor: $account["color"].getStr,
wallet: account["wallet"].getBool,
chat: account["chat"].getBool,
))
result = walletAccounts
except:
let msg = getCurrentExceptionMsg()
error "Failed getting wallet accounts", msg
proc getTransactionReceipt*(transactionHash: string): string =
result = callPrivateRPC("eth_getTransactionReceipt", %* [transactionHash])
proc getTransfersByAddress*(address: string, toBlock: Uint256, limit: int, loadMore: bool = false): seq[Transaction] =
try:
@ -63,14 +37,6 @@ proc getTransfersByAddress*(address: string, toBlock: Uint256, limit: int, loadM
let msg = getCurrentExceptionMsg()
error "Failed getting wallet account transactions", msg
proc getBalance*(address: string): string =
let payload = %* [address, "latest"]
let response = parseJson(callPrivateRPC("eth_getBalance", payload))
if response.hasKey("error"):
raise newException(RpcException, "Error getting balance: " & $response["error"])
else:
result = response["result"].str
proc hex2Eth*(input: string): string =
var value = fromHex(Stuint[256], input)
result = utils.wei2Eth(value)
@ -146,22 +112,10 @@ proc fetchCryptoServices*(success: var bool): string =
error "Error getting crypto services: ", msg = e.msg
result = ""
proc maxPriorityFeePerGas*(): string =
let payload = %* []
result = callPrivateRPC("eth_maxPriorityFeePerGas", payload)
proc suggestFees*(): string =
let payload = %* []
result = callPrivateRPC("wallet_suggestFees", payload)
proc feeHistory*(n: int): string =
let payload = %* [n, "latest", nil]
result = callPrivateRPC("eth_feeHistory", payload)
proc getGasPrice*(): string =
let payload = %* []
result = callPrivateRPC("eth_gasPrice", payload)
proc addSavedAddress*(name, address: string): string =
let
payload = %* [{"name": name, "address": address}]

View File

@ -7,12 +7,11 @@ import # project deps
import # local deps
utils as status_utils,
statusgo_backend/settings as status_settings,
eth/contracts as status_contracts,
eth/stickers as status_stickers,
eth/contracts as eth_contracts,
eth/stickers as eth_stickers,
transactions,
statusgo_backend/wallet, ../eventemitter
import ./types/[sticker, transaction, rpc_response, network_type, network]
from utils as statusgo_backend_utils import eth2Wei, gwei2Wei, toUInt64, parseAddress
logScope:
topics = "stickers-model"
@ -29,9 +28,6 @@ type
sticker*: Sticker
save*: bool
# forward declaration
proc addStickerToRecent*(self: StickersModel, sticker: Sticker, save: bool = false)
proc newStickersModel*(events: EventEmitter): StickersModel =
result = StickersModel()
result.events = events
@ -40,6 +36,14 @@ proc newStickersModel*(events: EventEmitter): StickersModel =
result.installedStickerPacks = initTable[int, StickerPack]()
result.purchasedStickerPacks = @[]
proc addStickerToRecent*(self: StickersModel, sticker: Sticker, save: bool = false) =
self.recentStickers.insert(sticker, 0)
self.recentStickers = self.recentStickers.deduplicate()
if self.recentStickers.len > 24:
self.recentStickers = self.recentStickers[0..23] # take top 24 most recent
if save:
eth_stickers.saveRecentStickers(self.recentStickers)
proc init*(self: StickersModel) =
self.events.on("stickerSent") do(e: Args):
var evArgs = StickerArgs(e)
@ -47,9 +51,9 @@ proc init*(self: StickersModel) =
proc buildTransaction(packId: Uint256, address: Address, price: Uint256, approveAndCall: var ApproveAndCall[100], sntContract: var Erc20Contract, gas = "", gasPrice = "", isEIP1559Enabled = false, maxPriorityFeePerGas = "", maxFeePerGas = ""): TransactionData =
let network = status_settings.getCurrentNetwork().toNetwork()
sntContract = status_contracts.findErc20Contract(network.chainId, network.sntSymbol())
sntContract = eth_contracts.findErc20Contract(network.chainId, network.sntSymbol())
let
stickerMktContract = status_contracts.findContract(network.chainId, "sticker-market")
stickerMktContract = eth_contracts.findContract(network.chainId, "sticker-market")
buyToken = BuyToken(packId: packId, address: address, price: price)
buyTxAbiEncoded = stickerMktContract.methods["buyToken"].encodeAbi(buyToken)
approveAndCall = ApproveAndCall[100](to: stickerMktContract.address, value: price, data: DynamicBytes[100].fromHex(buyTxAbiEncoded))
@ -59,11 +63,11 @@ proc estimateGas*(packId: int, address: string, price: string, success: var bool
var
approveAndCall: ApproveAndCall[100]
network = status_settings.getCurrentNetwork().toNetwork()
sntContract = status_contracts.findErc20Contract(network.chainId, network.sntSymbol())
sntContract = eth_contracts.findErc20Contract(network.chainId, network.sntSymbol())
tx = buildTransaction(
packId.u256,
parseAddress(address),
eth2Wei(parseFloat(price), sntContract.decimals),
status_utils.parseAddress(address),
status_utils.eth2Wei(parseFloat(price), sntContract.decimals),
approveAndCall,
sntContract
)
@ -78,8 +82,8 @@ proc buyPack*(self: StickersModel, packId: int, address, price, gas, gasPrice: s
approveAndCall: ApproveAndCall[100]
tx = buildTransaction(
packId.u256,
parseAddress(address),
eth2Wei(parseFloat(price), 18), # SNT
status_utils.parseAddress(address),
status_utils.eth2Wei(parseFloat(price), 18), # SNT
approveAndCall,
sntContract,
gas,
@ -95,15 +99,15 @@ proc buyPack*(self: StickersModel, packId: int, address, price, gas, gasPrice: s
proc getStickerMarketAddress*(self: StickersModel): Address =
let network = status_settings.getCurrentNetwork().toNetwork()
result = status_contracts.findContract(network.chainId, "sticker-market").address
result = eth_contracts.findContract(network.chainId, "sticker-market").address
proc getPurchasedStickerPacks*(self: StickersModel, address: Address): seq[int] =
try:
let
network = status_settings.getCurrentNetwork().toNetwork()
balance = status_stickers.getBalance(network.chainId, address)
tokenIds = toSeq[0..<balance].mapIt(status_stickers.tokenOfOwnerByIndex(network.chainId, address, it.u256))
purchasedPackIds = tokenIds.mapIt(status_stickers.getPackIdFromTokenId(network.chainId, it.u256))
balance = eth_stickers.getBalance(network.chainId, address)
tokenIds = toSeq[0..<balance].mapIt(eth_stickers.tokenOfOwnerByIndex(network.chainId, address, it.u256))
purchasedPackIds = tokenIds.mapIt(eth_stickers.getPackIdFromTokenId(network.chainId, it.u256))
self.purchasedStickerPacks = self.purchasedStickerPacks.concat(purchasedPackIds)
result = self.purchasedStickerPacks
except RpcException:
@ -114,45 +118,37 @@ proc getInstalledStickerPacks*(self: StickersModel): Table[int, StickerPack] =
if self.installedStickerPacks != initTable[int, StickerPack]():
return self.installedStickerPacks
self.installedStickerPacks = status_stickers.getInstalledStickerPacks()
self.installedStickerPacks = eth_stickers.getInstalledStickerPacks()
result = self.installedStickerPacks
proc getAvailableStickerPacks*(running: var Atomic[bool]): Table[int, StickerPack] =
let network = status_settings.getCurrentNetwork().toNetwork()
return status_stickers.getAvailableStickerPacks(network.chainId, running)
return eth_stickers.getAvailableStickerPacks(network.chainId, running)
proc getRecentStickers*(self: StickersModel): seq[Sticker] =
result = status_stickers.getRecentStickers()
result = eth_stickers.getRecentStickers()
proc installStickerPack*(self: StickersModel, packId: int) =
if not self.availableStickerPacks.hasKey(packId):
return
let pack = self.availableStickerPacks[packId]
self.installedStickerPacks[packId] = pack
status_stickers.saveInstalledStickerPacks(self.installedStickerPacks)
eth_stickers.saveInstalledStickerPacks(self.installedStickerPacks)
proc removeRecentStickers*(self: StickersModel, packId: int) =
self.recentStickers.keepItIf(it.packId != packId)
status_stickers.saveRecentStickers(self.recentStickers)
eth_stickers.saveRecentStickers(self.recentStickers)
proc uninstallStickerPack*(self: StickersModel, packId: int) =
if not self.installedStickerPacks.hasKey(packId):
return
let pack = self.availableStickerPacks[packId]
self.installedStickerPacks.del(packId)
status_stickers.saveInstalledStickerPacks(self.installedStickerPacks)
proc addStickerToRecent*(self: StickersModel, sticker: Sticker, save: bool = false) =
self.recentStickers.insert(sticker, 0)
self.recentStickers = self.recentStickers.deduplicate()
if self.recentStickers.len > 24:
self.recentStickers = self.recentStickers[0..23] # take top 24 most recent
if save:
status_stickers.saveRecentStickers(self.recentStickers)
eth_stickers.saveInstalledStickerPacks(self.installedStickerPacks)
proc decodeContentHash*(value: string): string =
result = status_utils.decodeContentHash(value)
proc getPackIdFromTokenId*(tokenId: Stuint[256]): int =
let network = status_settings.getCurrentNetwork().toNetwork()
result = status_stickers.getPackIdFromTokenId(network.chainId, tokenId)
result = eth_stickers.getPackIdFromTokenId(network.chainId, tokenId)

View File

@ -1,12 +1,12 @@
{.used.}
import json_serialization
import json_serialization, json
import ../../eventemitter
import identity_image
include multi_accounts
import ./identity_image
import ./profile
include ./multi_accounts
export identity_image
type
@ -43,4 +43,16 @@ proc toAccount*(account: NodeAccount): Account =
result = Account(name: account.name, identityImage: account.identityImage, identicon: account.identicon, keyUid: account.keyUid)
type AccountArgs* = ref object of Args
account*: Account
account*: Account
proc toProfile*(account: Account): Profile =
result = Profile(
id: "",
username: account.name,
identicon: account.identicon,
alias: account.name,
ensName: "",
ensVerified: false,
appearance: 0,
systemTags: @[]
)

View File

@ -1,3 +1,3 @@
type
MailServer* = ref object
name*, endpoint*: string
name*, endpoint*: string

View File

@ -5,7 +5,7 @@ import json_serialization
import ../utils
import ../wallet/account
import ../statusgo_backend/accounts/constants as constants
import ../statusgo_backend/wallet as status_wallet
import ../statusgo_backend/accounts as status_accounts
import ../statusgo_backend/settings as status_settings
import ../statusgo_backend/tokens as status_tokens
import ../eth/contracts as status_contracts
@ -83,7 +83,7 @@ proc currentUserWalletContainsAddress(address: string): bool =
if (address.len == 0):
return false
let accounts = status_wallet.getWalletAccounts()
let accounts = status_accounts.getWalletAccounts()
for acc in accounts:
if (acc.address == address):
return true

View File

@ -0,0 +1,23 @@
import sets
import strutils
import chronicles
logScope:
topics = "permission-type"
type
Permission* {.pure.} = enum
Web3 = "web3",
ContactCode = "contact-code"
Unknown = "unknown"
type Dapp* = object
name*: string
permissions*: HashSet[Permission]
proc toPermission*(value: string): Permission =
result = Permission.Unknown
try:
result = parseEnum[Permission](value)
except:
warn "Unknown permission requested", value

View File

@ -5,6 +5,10 @@ import identity_image
export identity_image
const contactAdded* = ":contact/added"
const contactBlocked* = ":contact/blocked"
const contactRequest* = ":contact/request-received"
type Profile* = ref object
id*, alias*, username*, identicon*, address*, ensName*, localNickname*: string
ensVerified*: bool
@ -18,32 +22,41 @@ type Profile* = ref object
proc `$`*(self: Profile): string =
return fmt"Profile(id:{self.id}, username:{self.username}, systemTags: {self.systemTags}, ensName: {self.ensName})"
proc toProfileModel*(profile: JsonNode): Profile =
proc toProfile*(jsonNode: JsonNode): Profile =
var systemTags: seq[string] = @[]
if profile["systemTags"].kind != JNull:
systemTags = profile["systemTags"].to(seq[string])
if jsonNode["systemTags"].kind != JNull:
systemTags = jsonNode["systemTags"].to(seq[string])
result = Profile(
id: profile["id"].str,
username: profile["alias"].str,
identicon: profile["identicon"].str,
id: jsonNode["id"].str,
username: jsonNode["alias"].str,
identicon: jsonNode["identicon"].str,
identityImage: IdentityImage(),
address: profile["id"].str,
alias: profile["alias"].str,
address: jsonNode["id"].str,
alias: jsonNode["alias"].str,
ensName: "",
ensVerified: profile["ensVerified"].getBool,
ensVerified: jsonNode["ensVerified"].getBool,
appearance: 0,
systemTags: systemTags
)
if profile.hasKey("name"):
result.ensName = profile["name"].str
if jsonNode.hasKey("name"):
result.ensName = jsonNode["name"].str
if profile.hasKey("localNickname"):
result.localNickname = profile["localNickname"].str
if jsonNode.hasKey("localNickname"):
result.localNickname = jsonNode["localNickname"].str
if profile.hasKey("images") and profile["images"].kind != JNull:
if profile["images"].hasKey("thumbnail"):
result.identityImage.thumbnail = profile["images"]["thumbnail"]["uri"].str
if profile["images"].hasKey("large"):
result.identityImage.large = profile["images"]["large"]["uri"].str
if jsonNode.hasKey("images") and jsonNode["images"].kind != JNull:
if jsonNode["images"].hasKey("thumbnail"):
result.identityImage.thumbnail = jsonNode["images"]["thumbnail"]["uri"].str
if jsonNode["images"].hasKey("large"):
result.identityImage.large = jsonNode["images"]["large"]["uri"].str
proc isContact*(self: Profile): bool =
result = self.systemTags.contains(contactAdded)
proc isBlocked*(self: Profile): bool =
result = self.systemTags.contains(contactBlocked)
proc requestReceived*(self: Profile): bool =
result = self.systemTags.contains(contactRequest)

View File

@ -2,15 +2,14 @@ import json, strformat, strutils, chronicles, sequtils, sugar, httpclient, table
import json_serialization, stint, stew/byteutils, algorithm
from web3/ethtypes import Address, Quantity
from web3/conversions import `$`
from statusgo_backend/core import getBlockByNumber
import statusgo_backend/accounts as status_accounts
import statusgo_backend/tokens as statusgo_backend_tokens
import statusgo_backend/settings as status_settings
import statusgo_backend/wallet as status_wallet
import statusgo_backend/accounts/constants as constants
import eth/[eth, contracts]
import eth/tokens as status_tokens
from statusgo_backend/core import getBlockByNumber
import statusgo_backend/eth as eth
import eth/contracts
import eth/tokens as eth_tokens
from utils as statusgo_backend_utils import eth2Wei, gwei2Wei, wei2Gwei, first, toUInt64, parseAddress
import wallet/[balance_manager, collectibles]
import wallet/account as wallet_account
@ -90,7 +89,7 @@ proc estimateGas*(self: WalletModel, source, to, value, data: string, success: v
result = eth.estimateGas(tx, success)
proc getTransactionReceipt*(self: WalletModel, transactionHash: string): JsonNode =
result = status_wallet.getTransactionReceipt(transactionHash).parseJSON()["result"]
result = eth.getTransactionReceipt(transactionHash).parseJSON()["result"]
proc confirmTransactionStatus(self: WalletModel, pendingTransactions: JsonNode, blockNumber: int) =
for trx in pendingTransactions.getElems():
@ -228,7 +227,7 @@ proc newAccount*(self: WalletModel, walletType: string, derivationPath: string,
account
proc maxPriorityFeePerGas*(self: WalletModel):string =
let response = status_wallet.maxPriorityFeePerGas().parseJson()
let response = eth.maxPriorityFeePerGas().parseJson()
if response.hasKey("result"):
return $fromHex(Stuint[256], response["result"].getStr)
else:
@ -249,7 +248,7 @@ proc cmpUint256(x, y: Uint256): int =
else: -1
proc feeHistory*(self: WalletModel, n:int):seq[Uint256] =
let response = status_wallet.feeHistory(101).parseJson()
let response = eth.feeHistory(101).parseJson()
if response.hasKey("result"):
for it in response["result"]["baseFeePerGas"]:
result.add(fromHex(Stuint[256], it.getStr))
@ -260,8 +259,8 @@ proc feeHistory*(self: WalletModel, n:int):seq[Uint256] =
proc initAccounts*(self: WalletModel) =
let network = status_settings.getCurrentNetwork().toNetwork()
self.tokens = status_tokens.getVisibleTokens(network)
let accounts = status_wallet.getWalletAccounts()
self.tokens = eth_tokens.getVisibleTokens(network)
let accounts = status_accounts.getWalletAccounts()
for account in accounts:
var acc = WalletAccount(account)
self.populateAccount(acc, "")
@ -329,7 +328,7 @@ proc addAccountsFromSeed*(self: WalletModel, seed: string, password: string, acc
generatedAccount.derived = status_accounts.deriveAccounts(generatedAccount.id)
let
defaultAccount = status_accounts.getDefaultAccount()
defaultAccount = eth.getDefaultAccount()
isPasswordOk = status_accounts.verifyAccountPassword(defaultAccount, password, keystoreDir)
if not isPasswordOk:
raise newException(StatusGoException, "Error generating new account: invalid password")
@ -339,7 +338,7 @@ proc addAccountsFromSeed*(self: WalletModel, seed: string, password: string, acc
proc addAccountsFromPrivateKey*(self: WalletModel, privateKey: string, password: string, accountName: string, color: string, keystoreDir: string) =
let
generatedAccount = status_accounts.MultiAccountImportPrivateKey(privateKey)
defaultAccount = status_accounts.getDefaultAccount()
defaultAccount = eth.getDefaultAccount()
isPasswordOk = status_accounts.verifyAccountPassword(defaultAccount, password, keystoreDir)
if not isPasswordOk:
@ -374,7 +373,7 @@ proc deleteAccount*(self: WalletModel, address: string): string =
proc toggleAsset*(self: WalletModel, symbol: string) =
let network = status_settings.getCurrentNetwork().toNetwork()
self.tokens = status_tokens.toggleAsset(network, symbol)
self.tokens = eth_tokens.toggleAsset(network, symbol)
for account in self.accounts:
account.assetList = self.generateAccountConfiguredAssets(account.address)
updateBalance(account, self.getDefaultCurrency())
@ -382,8 +381,8 @@ proc toggleAsset*(self: WalletModel, symbol: string) =
proc hideAsset*(self: WalletModel, symbol: string) =
let network = status_settings.getCurrentNetwork().toNetwork()
status_tokens.hideAsset(network, symbol)
self.tokens = status_tokens.getVisibleTokens(network)
eth_tokens.hideAsset(network, symbol)
self.tokens = eth_tokens.getVisibleTokens(network)
for account in self.accounts:
account.assetList = self.generateAccountConfiguredAssets(account.address)
updateBalance(account, self.getDefaultCurrency())
@ -405,10 +404,7 @@ proc setInitialBlocksRange*(self: WalletModel): string =
result = status_wallet.setInitialBlocksRange()
proc getWalletAccounts*(self: WalletModel): seq[WalletAccount] =
result = status_wallet.getWalletAccounts()
proc getWalletAccounts*(): seq[WalletAccount] =
result = status_wallet.getWalletAccounts()
result = status_accounts.getWalletAccounts()
proc watchTransaction*(self: WalletModel, transactionHash: string): string =
result = status_wallet.watchTransaction(transactionHash)
@ -429,7 +425,7 @@ proc hex2Token*(self: WalletModel, input: string, decimals: int): string =
result = status_wallet.hex2Token(input, decimals)
proc getGasPrice*(self: WalletModel): string =
let response = status_wallet.getGasPrice().parseJson
let response = eth.getGasPrice().parseJson
if response.hasKey("result"):
return $fromHex(Stuint[256], response["result"].getStr)
else:

View File

@ -1,5 +1,6 @@
import strformat, strutils, stint, httpclient, json, chronicles, net
import ../statusgo_backend/wallet as status_wallet
import ../statusgo_backend/eth as eth
import ../statusgo_backend/settings as status_settings
import ../eth/tokens as status_tokens
import ../types/[rpc_response, network_type]
@ -37,7 +38,7 @@ proc getPrice(crypto: string, fiat: string): string =
client.close()
proc getEthBalance(address: string): string =
var balance = status_wallet.getBalance(address)
var balance = eth.getBalance(address)
result = status_wallet.hex2token(balance, 18)
proc getBalance*(symbol: string, accountAddress: string, tokenAddress: string, refreshCache: bool): string =

View File

@ -6,8 +6,8 @@ import # vendor libs
stint
import # status-desktop libs
../statusgo_backend/core as status,
../statusgo_backend/settings as status_settings,
../statusgo_backend/eth as eth,
../eth/contracts as contracts,
../stickers as status_stickers,
../utils as status_utils,
@ -31,8 +31,8 @@ proc getTokenUri(contract: Erc721Contract, tokenId: Stuint[256]): string =
"to": $contract.address,
"data": contract.methods["tokenURI"].encodeAbi(tokenUri)
}, "latest"]
response = callPrivateRPC("eth_call", payload)
var postfixedResult: string = parseJson($response)["result"].str
response = eth.call(payload)
var postfixedResult = response.result
postfixedResult.removeSuffix('0')
postfixedResult.removePrefix("0x")
postfixedResult = parseHexStr(postfixedResult)
@ -51,14 +51,15 @@ proc tokenOfOwnerByIndex(contract: Erc721Contract, address: Address, index: Stui
"to": $contract.address,
"data": contract.methods["tokenOfOwnerByIndex"].encodeAbi(tokenOfOwnerByIndex)
}, "latest"]
response = callPrivateRPC("eth_call", payload)
jsonResponse = parseJson($response)
if (not jsonResponse.hasKey("result")):
response = eth.call(payload)
if not response.error.isNil:
return -1
let res = jsonResponse["result"].getStr
if (res == "0x"):
if (response.result == "0x"):
return -1
result = fromHex[int](res)
result = fromHex[int](response.result)
proc balanceOf(contract: Erc721Contract, address: Address): int =
let
@ -67,14 +68,15 @@ proc balanceOf(contract: Erc721Contract, address: Address): int =
"to": $contract.address,
"data": contract.methods["balanceOf"].encodeAbi(balanceOf)
}, "latest"]
response = callPrivateRPC("eth_call", payload)
jsonResponse = parseJson($response)
if (not jsonResponse.hasKey("result")):
response = eth.call(payload)
if not response.error.isNil:
return 0
let res = jsonResponse["result"].getStr
if (res == "0x"):
if (response.result == "0x"):
return 0
result = fromHex[int](res)
result = fromHex[int](response.result)
proc tokensOfOwnerByIndex(contract: Erc721Contract, address: Address): seq[int] =
var index = 0

View File

@ -5,6 +5,7 @@ import statusgo_backend/accounts/constants as constants
import statusgo_backend/wallet as status_wallet
import statusgo_backend/network as status_network
import statusgo_backend/settings as status_settings
import statusgo_backend/eth as eth
import eth/contracts
import wallet2/balance_manager
import eth/tokens as tokens_backend
@ -60,7 +61,7 @@ proc initNetworks(self: Wallet2Model) =
self.networks = status_network.getNetworks()
proc initAccounts(self: Wallet2Model) =
let accounts = status_wallet.getWalletAccounts()
let accounts = status_accounts.getWalletAccounts()
for acc in accounts:
var assets: seq[Asset] = self.generateAccountConfiguredAssets(acc.address)
var walletAccount = newWalletAccount(acc.name, acc.address, acc.iconColor,
@ -164,7 +165,7 @@ proc addAccountsFromSeed*(self: Wallet2Model, seed: string, password: string, ac
generatedAccount.derived = status_accounts.deriveAccounts(generatedAccount.id)
let
defaultAccount = status_accounts.getDefaultAccount()
defaultAccount = eth.getDefaultAccount()
isPasswordOk = status_accounts.verifyAccountPassword(defaultAccount, password, keystoreDir)
if not isPasswordOk:
raise newException(StatusGoException, "Error generating new account: invalid password")
@ -174,7 +175,7 @@ proc addAccountsFromSeed*(self: Wallet2Model, seed: string, password: string, ac
proc addAccountsFromPrivateKey*(self: Wallet2Model, privateKey: string, password: string, accountName: string, color: string, keystoreDir: string) =
let
generatedAccount = status_accounts.MultiAccountImportPrivateKey(privateKey)
defaultAccount = status_accounts.getDefaultAccount()
defaultAccount = eth.getDefaultAccount()
isPasswordOk = status_accounts.verifyAccountPassword(defaultAccount, password, keystoreDir)
if not isPasswordOk:

View File

@ -1,5 +1,6 @@
import strformat, strutils, stint, httpclient, json, chronicles, net
import ../statusgo_backend/wallet as status_wallet
import ../statusgo_backend/eth as eth
import ../statusgo_backend/settings as status_settings
import ../eth/tokens as status_tokens
import ../types/[rpc_response, network_type]
@ -37,7 +38,7 @@ proc getPrice(crypto: string, fiat: string): string =
client.close()
proc getEthBalance(address: string): string =
var balance = status_wallet.getBalance(address)
var balance = eth.getBalance(address)
result = status_wallet.hex2token(balance, 18)
proc getBalance*(symbol: string, accountAddress: string, tokenAddress: string, refreshCache: bool): string =