Skip to content

Commit

Permalink
Merge pull request #2 from BaldyAsh/erc20fix
Browse files Browse the repository at this point in the history
Fixed erc20 precompiled contract
  • Loading branch information
BaldyAsh authored Dec 14, 2018
2 parents 8c58d11 + 0d4ead1 commit dbfecb1
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions web3swift/PrecompiledContracts/ERC20/Web3+ERC20.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}

}

0 comments on commit dbfecb1

Please sign in to comment.