Skip to content

Instantly share code, notes, and snippets.

@alexytiger
Last active September 2, 2019 04:09
Show Gist options
  • Save alexytiger/9661f4e9c5eab29a046d0ea8e071af7b to your computer and use it in GitHub Desktop.
Save alexytiger/9661f4e9c5eab29a046d0ea8e071af7b to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import { P2pBazaarAnchorModule } from '../p2p-bazaar.anchor.module';
import { Provider } from '../../core/services/tokens';
import { Observable, from, of, zip } from 'rxjs';
import { map, tap, switchMap } from 'rxjs/operators';
import { ethers, Contract, utils } from 'ethers';
import { PurchaseContractModel, ContractState} from '../models';
@Injectable({ providedIn: P2pBazaarAnchorModule })
export class PurchaseContractService {
private readonly abi = [
'function key() view returns(bytes32 key)',
'function title() view returns(string title)',
'function seller() view returns(address sellerAddress)',
'function buyer() view returns(address buyerAddress)',
'function price() view returns(uint weiPrice)',
'function ipfsHash() view returns(string ipfsHash)',
'function state() view returns(uint8 state)',
];
constructor(private provider: Provider ) {
}
public loadPurchaseContract(contractAddress: string): Observable<PurchaseContractModel> {
const contract: Contract = new ethers.Contract(contractAddress, this.abi, this.provider.getSigner());
return zip(
contract.key(),
contract.seller(),
contract.buyer(),
contract.price(),
contract.title(),
contract.ipfsHash(),
contract.state(),
)
.pipe(
map(([key, sellerAddress, buyerAddress, weiPrice, title, ipfsHash, state]) => {
const product: PurchaseContractModel = {
productKey: utils.parseBytes32String(key as ethers.utils.Arrayish),
contractAddress,
sellerAddress : sellerAddress as string,
buyerAddress: !!buyerAddress ? buyerAddress as string : null,
price: utils.formatEther(weiPrice as ethers.utils.BigNumberish), // $ETH
title: title as string,
ipfsHash: ipfsHash as string,
state: state as ContractState
};
return product;
} )
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment