Skip to content

Commit

Permalink
Support WETH price fetching (#127)
Browse files Browse the repository at this point in the history
  • Loading branch information
kohlivarun5 authored Aug 14, 2021
1 parent 8d55345 commit 81a2423
Show file tree
Hide file tree
Showing 8 changed files with 145 additions and 32 deletions.
34 changes: 33 additions & 1 deletion NFTY/Model/Erc721Contract.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,21 @@ class Erc721Contract {
return TradeEvent(type:eventType,value:tx.value,blockNumber:tx.blockNumber)
}
}
.then (on:DispatchQueue.global(qos:.userInitiated)) { (event:TradeEvent?) -> Promise<TradeEvent?> in
switch(event?.value) {
case .none,.some(0):
return wethFetcher.valueOfTx(transactionHash: transactionHash)
.map(on:DispatchQueue.global(qos:.userInitiated)) { (txData:WETHFetcher.Info?) in
switch(txData) {
case .none: return nil
case .some(let tx):
return TradeEvent(type:eventType,value:tx.value,blockNumber:tx.blockNumber)
}
}
case .some:
return Promise.value(event)
}
}
}

func getTokenHistory(_ tokenId: UInt,fetcher:LogsFetcher) -> Promise<TradeEventStatus> {
Expand Down Expand Up @@ -177,7 +192,24 @@ class Erc721Contract {
case .some(let tx):
return TradeEvent(type:type ?? .bought,value:tx.value,blockNumber:tx.blockNumber)
}
}.done { response($0) }
}
.then (on:DispatchQueue.global(qos:.userInitiated)) { (event:TradeEvent) -> Promise<TradeEvent> in
switch(event.value) {
case 0:
return wethFetcher.valueOfTx(transactionHash: log.transactionHash)
.map(on:DispatchQueue.global(qos:.userInitiated)) { (txData:WETHFetcher.Info?) in
switch(txData) {
case .none:
return event
case .some(let tx):
return TradeEvent(type:type ?? .bought,value:tx.value,blockNumber:tx.blockNumber)
}
}
default:
return Promise.value(event)
}
}
.done { response($0) }
.catch { print($0) }
}
}
Expand Down
2 changes: 1 addition & 1 deletion NFTY/Model/OpenSeaApi.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ struct OpenSeaApi {
let assets = try jsonDecoder.decode(AssetOrders.self, from: data!)
// print(assets)

switch(assets.assets[safe:0]?.sell_orders?[safe:0]) {
switch(assets.assets.first?.sell_orders?.first) {
case .none:
seal.fulfill(BidAsk(bid:nil,ask:nil))
case .some(let order):
Expand Down
86 changes: 86 additions & 0 deletions NFTY/Model/TokenContracts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,77 @@ class TxFetcher {

var txFetcher = TxFetcher()

class WETHFetcher {

struct Info : Codable {
var value : BigUInt
var blockNumber : EthereumQuantity
}

private var cache = try! DiskStorage<EthereumData, Info>(
config: DiskConfig(name: "WETHFetcher.cache",expiry: .never),
transformer: TransformerFactory.forCodable(ofType: Info.self))

private func valueOfTx(transactionHash:EthereumData) -> Promise<Info?> {
print("getTransactionReceipt");
return web3.eth.getTransactionReceipt(transactionHash: transactionHash)
.map(on:DispatchQueue.global(qos:.userInitiated)) { (txData:EthereumTransactionReceiptObject?) -> Info? in
switch(txData) {
case .none:
return nil
case .some(let tx):
return tx.logs
.compactMap { log in
if (log.address.hex(eip55:false) != WETH_ADDRESS) {
return nil
}

if (!log.topics.contains(
try! EthereumData.string(
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")
)) {
return nil
}

return try! web3.eth.abi.decodeParameter(type:SolidityType.uint256,from:log.data.hex()) as! BigUInt

// Get data for the log
}
.first
.map { Info(value:$0,blockNumber: tx.blockNumber) }
}
}
}

func valueOfTx(transactionHash:EthereumData?) -> Promise<Info?> {
switch transactionHash {
case .none:
return Promise.value(nil)
case .some(let txHash):
return Promise { seal in
DispatchQueue.global(qos:.userInteractive).async {
switch (try? self.cache.object(forKey:txHash)) {
case .some(let p):
seal.fulfill(p)
case .none:
let p = self.valueOfTx(transactionHash: txHash)
p.done(on:DispatchQueue.global(qos:.userInteractive)) {
$0.flatMap { try? self.cache.setObject($0, forKey: txHash) }
seal.fulfill($0)
}
.catch {
print($0)
seal.fulfill(nil)
}
}
}
}
}
}
}

var wethFetcher = WETHFetcher()


var web3 = Web3(rpcURL: "https://mainnet.infura.io/v3/b4287cfd0a6b4849bd0ca79e144d3921")
var INIT_BLOCK = BigUInt(12850064 - (Date.from(year:2021,month:7,day:18)!.timeIntervalSinceNow / 15))
Expand Down Expand Up @@ -527,6 +598,21 @@ class AsciiPunksContract : ContractInterface {
return TradeEvent(type:eventType,value:tx.value,blockNumber:tx.blockNumber)
}
}
.then (on:DispatchQueue.global(qos:.userInitiated)) { (event:TradeEvent?) -> Promise<TradeEvent?> in
switch(event?.value) {
case .none,.some(0):
return wethFetcher.valueOfTx(transactionHash: transactionHash)
.map(on:DispatchQueue.global(qos:.userInitiated)) { (txData:WETHFetcher.Info?) in
switch(txData) {
case .none: return nil
case .some(let tx):
return TradeEvent(type:eventType,value:tx.value,blockNumber:tx.blockNumber)
}
}
case .some:
return Promise.value(event)
}
}
}

func getRecentTrades(onDone: @escaping () -> Void,_ response: @escaping (NFTWithPrice) -> Void) {
Expand Down
7 changes: 2 additions & 5 deletions NFTY/Model/TokenProtocols.swift
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,8 @@ class CompositeRecentTradesObject : ObservableObject {

/*

switch(sorted[safe:0]) {
case .some(let item):
sorted[0] = NFTItem(nft: item.nft, isNew: true)
case .none:
break
_ = sorted.first.map { item in
sorted[0] = NFTItem(nft: item.nft, isNew: true)
}

*/
Expand Down
2 changes: 1 addition & 1 deletion NFTY/ViewModel/WalletConnectModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ extension WalletConnect: ClientDelegate {
let sessionData = try! JSONEncoder().encode(session)
NSUbiquitousKeyValueStore.default.set(sessionData, forKey: CloudDefaultStorageKeys.walletConnect.rawValue)
delegate.didConnect(
account:session.walletInfo?.accounts[safe:0].flatMap {
account:session.walletInfo?.accounts.first.flatMap {
try? EthereumAddress(hex:$0,eip55: false)
})
}
Expand Down
1 change: 0 additions & 1 deletion NFTY/Views/CollectionView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ struct CollectionView: View {
return false;
}
})
// print(res[safe:0]);
return res;
}

Expand Down
9 changes: 3 additions & 6 deletions NFTY/Views/TokenPrice.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,12 @@ struct TokenPriceKnown : View {
BlockTimeLabel(blockNumber:blockNumber)
.font(.caption2)
.foregroundColor(subtleColor(self.color))
.padding([.top,.bottom],info.price == nil ? 2 : 0)
.padding([.leading,.trailing],2)
}
case (.none,.some(let blockNumber)):
BlockTimeLabel(blockNumber:blockNumber)
.font(.caption2)
.foregroundColor(subtleColor(self.color))
.padding([.top,.bottom],info.price == nil ? 2 : 0)
.padding([.leading,.trailing],2)
.padding([.top,.bottom],2)
case (.some(let wei),.none):
HStack {
UsdText(wei:wei,fontWeight:.semibold)
Expand Down Expand Up @@ -133,7 +130,7 @@ struct TokenPriceLazy : View {
data: status,
progress: {
Text(" ··· ")
.padding([.leading,.trailing])
.padding([.leading,.trailing],5)
}) {
TokenPriceStatus(status:$0,color:color)
}
Expand All @@ -152,7 +149,7 @@ struct TokenPrice: View {
case .lazy(let status):
TokenPriceLazy(status: status(),color:color)
}
}
}.padding([.leading,.trailing],5)
}
}

Expand Down
36 changes: 19 additions & 17 deletions NFTY/Views/WalletView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,22 @@ struct WalletView: View {
case .none:
ConnectWalletSheet()
case .some(let address):
VStack {
VStack(spacing:0) {
// https://stackoverflow.com/questions/59689342/swipe-between-two-pages-with-segmented-style-picker-in-swiftui
ZStack {
//Rectangle().fill(Color.clear)
switch(self.tokensPage) {
case .owned:
WalletTokensView(tokens: getOwnerTokens(address))
case .bids:
ActivityView(address:.maker(address),side:OpenSeaApi.Side.buy)
case .sales:
ActivityView(address:.maker(address),side:OpenSeaApi.Side.sell)
case .offers:
ActivityView(address:.owner(address),side:OpenSeaApi.Side.buy)
}
}

Picker(selection: Binding<Int>(
get: { self.tokensPage.rawValue },
set: { tag in
Expand All @@ -46,23 +61,10 @@ struct WalletView: View {
Text("Offers").tag(TokensPage.offers.rawValue)
}
.pickerStyle(SegmentedPickerStyle())
.colorMultiply(.orange)
.colorMultiply(.flatOrange)
.padding([.trailing,.leading],10)
.padding([.top,.bottom],5)

Spacer()
// https://stackoverflow.com/questions/59689342/swipe-between-two-pages-with-segmented-style-picker-in-swiftui
ZStack {
//Rectangle().fill(Color.clear)
switch(self.tokensPage) {
case .owned:
WalletTokensView(tokens: getOwnerTokens(address))
case .bids:
ActivityView(address:.maker(address),side:OpenSeaApi.Side.buy)
case .sales:
ActivityView(address:.maker(address),side:OpenSeaApi.Side.sell)
case .offers:
ActivityView(address:.owner(address),side:OpenSeaApi.Side.buy)
}
}
}

}
Expand Down

0 comments on commit 81a2423

Please sign in to comment.