Skip to content

Instantly share code, notes, and snippets.

@alexytiger
Last active July 11, 2019 18:59
Show Gist options
  • Save alexytiger/75ebdba7a840b2c16baacfeaac1c286f to your computer and use it in GitHub Desktop.
Save alexytiger/75ebdba7a840b2c16baacfeaac1c286f to your computer and use it in GitHub Desktop.
import { FleaMarketContractToken } from './tokens/flea-market-contract-token';
import { Observable, from, of } from 'rxjs';
import { map, tap, switchMap } from 'rxjs/operators';
import { utils } from 'ethers';
@Injectable({ providedIn: P2pBazaarAnchorModule })
export class FleaMarketContractService {
constructor( private contractToken: FleaMarketContractToken ) {
}
public createPurchaseContract(product: any): Observable<string> {
const bytes32Key = utils.formatBytes32String(product.productKey);
const wei = utils.parseEther(product.etherValue);
// based on https://docs.ethers.io/ethers.js/html/cookbook-contracts.html
// Call the contract method, getting back the transaction tx
const token = this.contractToken.createPurchaseContract(bytes32Key, product.title, product.ipfsHash, {
value: wei
});
return from(token)
.pipe(
switchMap((tx: any) => {
// Wait for transaction to be mined
// Returned a Promise which would resolve to the TransactionReceipt once it is mined.
return from(tx.wait()).pipe(
// The receipt will have an "events" Array, which will have
// the emitted event from the Contract. The "logNewPurchaseContract(address contractAddress)
// call is the last event.
map(txReceipt => txReceipt.events.pop()),
// The 'contractAddress' is the first (and in this case only) parameter
// in the "logNewPurchaseContract(address contractAddress)" event
map(txEvent => txEvent.args['contractAddress'])
}))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment