From 0d4ead1b10003e20818694ba40ad37d542293893 Mon Sep 17 00:00:00 2001 From: BaldyAsh Date: Thu, 13 Dec 2018 20:52:58 +0300 Subject: [PATCH] added protocol and method --- .../ERC20/Web3+ERC20.swift | 34 +++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/web3swift/PrecompiledContracts/ERC20/Web3+ERC20.swift b/web3swift/PrecompiledContracts/ERC20/Web3+ERC20.swift index 82f1eaa6b..4030deae0 100644 --- a/web3swift/PrecompiledContracts/ERC20/Web3+ERC20.swift +++ b/web3swift/PrecompiledContracts/ERC20/Web3+ERC20.swift @@ -9,10 +9,19 @@ import BigInt import EthereumAddress import PromiseKit +protocol IERC20 { + func getBalance(account: EthereumAddress) throws -> BigUInt + func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) throws -> BigUInt + func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) throws -> WriteTransaction + func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) throws -> WriteTransaction + func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) throws -> WriteTransaction + func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction +} + // This namespace contains functions to work with ERC20 tokens. // variables are lazyly evaluated or global token information (name, ticker, total supply) // can be imperatively read and saved -public class ERC20 { +public class ERC20: IERC20 { @available(*, deprecated, renamed: "transactionOptions") public var options: Web3Options = .init() @@ -99,7 +108,7 @@ public class ERC20 { }.wait() } - func getBalance(account: EthereumAddress) throws -> BigUInt{ + public func getBalance(account: EthereumAddress) throws -> BigUInt { let contract = self.contract var transactionOptions = TransactionOptions() transactionOptions.callOnBlock = .latest @@ -185,5 +194,26 @@ public class ERC20 { return tx } + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) throws -> WriteTransaction { + let contract = self.contract + var basicOptions = TransactionOptions() + basicOptions.from = from + basicOptions.callOnBlock = .latest + + // get the decimals manually + let callResult = try contract.read("decimals", transactionOptions: basicOptions)!.call() + var decimals = BigUInt(0) + guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { + throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} + decimals = decTyped + + let intDecimals = Int(decimals) + guard let value = Web3.Utils.parseToBigUInt(amount, decimals: intDecimals) else { + throw Web3Error.inputError(desc: "Can not parse inputted amount") + } + + let tx = contract.write("approve", parameters: [spender, value] as [AnyObject], transactionOptions: basicOptions)! + return tx + } }