From f13c027918008328adf3709b9b17f2b0cd5848b1 Mon Sep 17 00:00:00 2001 From: Hwee-Boon Yar Date: Fri, 8 Jun 2018 15:54:56 +0800 Subject: [PATCH] Automatically add and show tokens for contracts that the wallet interacted with --- .../Coordinators/TokensCoordinator.swift | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/AlphaWallet/Tokens/Coordinators/TokensCoordinator.swift b/AlphaWallet/Tokens/Coordinators/TokensCoordinator.swift index 2f12c8e7d..99f96c77a 100644 --- a/AlphaWallet/Tokens/Coordinators/TokensCoordinator.swift +++ b/AlphaWallet/Tokens/Coordinators/TokensCoordinator.swift @@ -60,6 +60,7 @@ class TokensCoordinator: Coordinator { func start() { addFIFAToken() + autoDetectTokens() showTokens() } @@ -67,6 +68,51 @@ class TokensCoordinator: Coordinator { navigationController.viewControllers = [rootViewController] } + private func autoDetectTokens() { + guard let address = keystore.recentlyUsedWallet?.address else { return } + let web3 = Web3Swift(url: config.rpcURL) + GetContractInteractions(web3: web3).getContractList(address: address.eip55String, chainId: config.chainID) { contracts in + let detectedContracts = contracts.map { $0.lowercased() } + let alreadyAddedContracts = self.storage.enabledObject.map { $0.address.eip55String.lowercased() } + let contractsToAdd = detectedContracts - alreadyAddedContracts + for eachContract in contractsToAdd { + self.addToken(for: eachContract) + } + } + } + + private func addToken(for contract: String) { + fetchContractData(for: contract) { data in + switch data { + case .name, .symbol, .balance, .decimals: + break + case .stormBirdComplete(let name, let symbol, let balance): + if let address = Address(string: contract) { + let token = ERCToken( + contract: address, + name: name, + symbol: symbol, + decimals: 0, + isStormBird: true, + balance: balance + ) + self.storage.addCustom(token: token) + self.tokensViewController.fetch() + } + case .nonStormBirdComplete(let name, let symbol, let decimals): + let token = TokenObject( + contract: contract, + name: name, + symbol: symbol, + decimals: Int(decimals), + value: "0" + ) + self.storage.add(tokens: [token]) + self.tokensViewController.fetch() + } + } + } + func newTokenViewController() -> NewTokenViewController { let controller = NewTokenViewController() controller.delegate = self @@ -240,3 +286,9 @@ extension TokensCoordinator: NewTokenViewControllerDelegate { } } } + +func -(left: [T], right: [T]) -> [T] { + return left.filter { l in + !right.contains { $0 == l } + } +}