Best JavaScript code snippet using wpt
plugin.js
Source:plugin.js
1'use strict'2const debug = require('debug')('ilp-plugin-zcash-paychan')3const crypto = require('crypto')4const shared = require('ilp-plugin-shared')5const zcash = require('./zcash')6const Channel = require('./channel')7const EventEmitter2 = require('eventemitter2')8const InvalidFieldsError = shared.Errors.InvalidFieldsError9module.exports = class PluginZcashPaychan extends EventEmitter2 {10 constructor ({11 outgoingAmount,12 rpcUri,13 secret,14 timeout,15 network,16 peerPublicKey,17 zcashUri,18 maxInFlight,19 _store,20 }) {21 super()22 if (!rpcUri) {23 throw new InvalidFieldsError('missing opts.rpcUri')24 } else if (!secret) {25 throw new InvalidFieldsError('missing opts.secret')26 } else if (!peerPublicKey) {27 throw new InvalidFieldsError('missing opts.peerPublicKey')28 } else if (!zcashUri) {29 throw new InvalidFieldsError('missing opts.zcashUri')30 } else if (!_store) {31 throw new InvalidFieldsError('missing opts._store')32 }33 this._zcashUri = zcashUri34 this._peerPublicKey = peerPublicKey35 this._secret = secret36 this._network = network37 this._keypair = zcash.secretToKeypair(this._secret)38 this._address = zcash.publicKeyToAddress(this._keypair.getPublicKeyBuffer().toString('hex'))39 this._peerAddress = zcash.publicKeyToAddress(peerPublicKey)40 this._prefix = 'g.crypto.zcash.' + ((this._address > this._peerAddress)41 ? this._address + '~' + this._peerAddress42 : this._peerAddress + '~' + this._address) + '.'43 // TODO: make the balance right, and have it be configurable44 this._inFlight = new shared.Balance({ store: _store, maximum: maxInFlight })45 this._transfers = new shared.TransferLog({ store: _store })46 this._validator = new shared.Validator({ plugin: this })47 this.isAuthorized = () => true48 this._rpc = new shared.HttpRpc({49 rpcUri: rpcUri,50 plugin: this,51 // TODO: shared secret or something52 authToken: 'placeholder'53 })54 const channelParams = {55 // TODO: allow 2 different timeouts?56 timeout: timeout,57 uri: this._zcashUri,58 store: _store,59 network: this._network,60 secret: this._secret61 }62 // incoming channel submits and validates claims63 this._incomingChannel = new Channel(Object.assign({64 senderPublicKey: this._peerPublicKey65 }, channelParams))66 // outgoing channel generates claims and times out the channel67 this._outgoingChannel = new Channel(Object.assign({68 receiverPublicKey: this._peerPublicKey,69 amount: outgoingAmount70 }, channelParams))71 this.receive = this._rpc.receive.bind(this._rpc)72 this._rpc.addMethod('send_message', this._handleSendMessage)73 this._rpc.addMethod('send_transfer', this._handleSendTransfer)74 this._rpc.addMethod('fulfill_condition', this._handleFulfillCondition)75 this._rpc.addMethod('reject_incoming_transfer', this._handleRejectIncomingTransfer)76 this._rpc.addMethod('get_outgoing_txid', this._handleGetOutgoingTxId)77 }78 async _handleGetOutgoingTxId () {79 return this._outgoingTxId80 }81 async connect () {82 await this._inFlight.connect()83 await this._incomingChannel.connect()84 await this._outgoingChannel.connect()85 this._outgoingTxId = await this._outgoingChannel.createChannel()86 while (!this._incomingTxId) {87 await new Promise((resolve) => setTimeout(resolve, 5000))88 try {89 this._incomingTxId = await this._rpc.call('get_outgoing_txid', this._prefix, [])90 } catch (e) {91 debug('got rpc error:', e.message)92 debug('retrying...')93 }94 }95 await this._incomingChannel.loadTransaction({ txid: this._incomingTxId })96 await this._outgoingChannel.loadTransaction({})97 this._connected = true98 shared.Util.safeEmit(this, 'connect')99 }100 isConnected () {101 return !!this._connected102 }103 async disconnect () {104 await this._incomingChannel.claim()105 shared.Util.safeEmit(this, 'disconnect')106 }107 getAccount () {108 return this._prefix + this._address109 }110 getInfo () {111 return {112 prefix: this._prefix,113 currencyCode: 'ZEC',114 currencyScale: 8,115 connectors: [ this._prefix + this._peerPublicKey ]116 }117 }118 async sendMessage (_message) {119 const message = this._validator.normalizeOutgoingMessage(_message)120 await this._rpc.call('send_message', this._prefix, [ message ])121 shared.Util.safeEmit(this, 'outgoing_message', message)122 }123 async _handleSendMessage (_message) {124 const message = this._validator.normalizeIncomingMessage(_message)125 shared.Util.safeEmit(this, 'incoming_message', message)126 return true127 }128 async sendTransfer (_transfer) {129 const transfer = this._validator.normalizeOutgoingTransfer(_transfer)130 // TODO: wrap these into just one method131 const noRepeat = (this._transfers.cacheOutgoing(transfer) &&132 (await this._transfers.notInStore(transfer)))133 await this._rpc.call('send_transfer', this._prefix, [134 // TODO: util method for this?135 Object.assign({}, transfer, { noteToSelf: undefined })136 ])137 debug(transfer.id + ' acknowledged by peer')138 // TODO: is all this repeat stuff totally necessary?139 if (!noRepeat) return140 shared.Util.safeEmit(this, 'outgoing_prepare', transfer)141 this._setupTransferExpiry(transfer.id, transfer.expiresAt)142 }143 async _handleSendTransfer (_transfer) {144 const transfer = this._validator.normalizeIncomingTransfer(_transfer)145 // TODO: wrap these into just one method146 const noRepeat = (this._transfers.cacheIncoming(transfer) &&147 (await this._transfers.notInStore(transfer)))148 if (!noRepeat) return true149 await this._inFlight.add(transfer.amount)150 .catch((e) => {151 this._transfers.cancel(transfer.id)152 throw e153 })154 shared.Util.safeEmit(this, 'incoming_prepare', transfer)155 this._setupTransferExpiry(transfer.id, transfer.expiresAt)156 return true157 }158 async fulfillCondition (transferId, fulfillment) {159 // TODO: check out that method160 this._validator.validateFulfillment(fulfillment)161 // TODO: what even is this construct and why did I do it162 const error = this._transfers.assertAllowedChange(transferId, 'executed')163 if (error) {164 await error165 await this._rpc.call('fulfill_condition', this._prefix, [ transferId, fulfillment ])166 return167 }168 // TODO: what does this do and is it needed?169 this._transfers.assertIncoming(transferId)170 // TODO: make the error on this better when the transfer isn't found171 const transfer = this._transfers.get(transferId)172 shared.Util.safeEmit(this, 'incoming_fulfill', transfer, fulfillment)173 let claim174 try {175 claim = await this._rpc.call('fulfill_condition', this._prefix, [transferId, fulfillment])176 } catch (e) {177 console.error(e.stack)178 debug('failed to get claim from peer. keeping the in-flight balance up.')179 return180 }181 debug('got claim from peer:', claim)182 this._incomingChannel.processClaim({ transfer, claim })183 this._transfers.fulfill(transferId, fulfillment)184 console.log('fulfilled from store')185 }186 async _handleFulfillCondition (transferId, fulfillment) {187 this._validator.validateFulfillment(fulfillment)188 const error = this._transfers.assertAllowedChange(transferId, 'executed')189 if (error) {190 await error191 // TODO: return an error instead, so it gives better error?192 return true193 }194 this._transfers.assertOutgoing(transferId)195 const transfer = this._transfers.get(transferId)196 transfer.direction = 'outgoing' // the connector needs this for whatever reason197 console.log('fetched transfer for fulfill:', transfer)198 this._validateFulfillment(fulfillment, transfer.executionCondition)199 this._transfers.fulfill(transferId, fulfillment)200 console.log('fulfilled from store')201 shared.Util.safeEmit(this, 'outgoing_fulfill', transfer, fulfillment)202 console.log('creating claim')203 const sig = await this._outgoingChannel.createClaim(transfer)204 console.log('produced claim:', sig)205 return sig206 }207 _validateFulfillment (fulfillment, condition) {208 const hash = shared.Util.base64url(crypto209 .createHash('sha256')210 .update(Buffer.from(fulfillment, 'base64'))211 .digest())212 // TODO: validate the condition to make sure it's base64url213 if (hash !== condition) {214 throw new NotAcceptedError('fulfillment ' + fulfillment +215 ' does not match condition ' + condition)216 }217 }218 async rejectIncomingTransfer (transferId, reason) {219 const error = this._transfers.assertAllowedChange(transferId, 'cancelled')220 if (error) {221 await error222 await this._rpc.call('reject_incoming_transfer', this._prefix, [transferId, reason])223 return224 }225 debug('rejecting', transfer.id)226 this._transfers.assertIncoming(transferId)227 const transfer = this._transfers.get(transferId)228 this._transfers.cancel(transferId)229 shared.Util.safeEmit(this, 'incoming_reject', transfer)230 await this._inFlight.sub(transfer.amount)231 await this._rpc.call('reject_incoming_transfer', this._prefix, [ transferId, reason ])232 }233 async _handleRejectIncomingTransfer (transferId, reason) {234 const error = this._transfers.assertAllowedChange(transferId, 'cancelled')235 if (error) {236 await error237 return true238 }239 this._transfers.assertOutgoing(transferId)240 const transfer = this._transfers.get(transferId)241 this._transfers.cancel(transferId)242 shared.Util.safeEmit(this, 'outgoing_reject', transfer)243 return true244 }245 _setupTransferExpiry (transferId, expiresAt) {246 const expiry = Date.parse(expiresAt)247 const now = Date.now()248 setTimeout(249 this._expireTransfer.bind(this, transferId),250 (expiry - now))251 }252 async _expireTransfer (transferId) {253 debug('checking expiry on ' + transferId)254 // TODO: use a less confusing construct255 try {256 const error = this._transfers.assertAllowedChange(transferId, 'cancelled')257 if (error) {258 await error259 return260 }261 } catch (e) {262 debug(e.message)263 return264 }265 const cached = this._transfers._getCachedTransferWithInfo(transferId)266 this._transfers.cancel(transferId)267 if (cached.isIncoming) {268 this._inFlight.sub(cached.transfer.amount)269 }270 shared.Util.safeEmit(this, (cached.isIncoming ? 'incoming' : 'outgoing') + '_cancel',271 cached.transfer)272 }...
mocked-backend.service.ts
Source:mocked-backend.service.ts
1import { Injectable } from '@angular/core';2import { Observable, of } from 'rxjs';3import { Transfer } from '../../../../mock-data/transfer.model';4import { AccountAmountCurrency } from '../models/account-amount-currency';5import { TransferDto } from '../models/transfer';6import { HttpClient } from '@angular/common/http';7import { transactions } from '../../../../mock-data/transactions';8@Injectable({9 providedIn: 'root',10})11export class MockedBackendService {12 constructor(private httpClient: HttpClient) {}13 private _transfers: Transfer[] = [];14 get transfers(): Observable<Transfer[]> {15 return of(this._transfers);16 }17 private _account: AccountAmountCurrency = {18 amount: 1234.56,19 currencyCode: 'EUR',20 };21 getAccount(): Observable<AccountAmountCurrency> {22 return of(this._account);23 }24 getAllTransfers(): Observable<Transfer[]> {25 return of(this._transfers);26 }27 postTransfer(28 value: TransferDto29 ): Observable<{ transfer: Transfer; account: AccountAmountCurrency }> {30 const newTransfer: Transfer = {31 dates: {32 valueDate: new Date().getTime(),33 },34 categoryCode: '#fbbb1b',35 transaction: {36 type: 'Online Transfer',37 creditDebitIndicator: 'indicator',38 amountCurrency: {39 amount: -1 * value.amount.amount,40 currencyCode: value.amount.currencyCode,41 },42 },43 merchant: {44 name: value.toAccount,45 accountNumber: 'my account number',46 },47 };48 this._transfers = [...this._transfers, newTransfer];49 this._account = {50 ...this._account,51 amount: Number((this._account.amount - value.amount.amount).toFixed(2)),52 };53 return of({ transfer: newTransfer, account: this._account });54 }55 initDb(): Promise<void> {56 return this.httpClient57 .get<Transfer[]>('/api/transfers')58 .toPromise()59 .then((transfers) => {60 if (transfers) {61 this._transfers = transfers;62 }63 })64 .catch((err) => {65 this._transfers = transactions;66 });67 }...
WealthTransfer.js
Source:WealthTransfer.js
1const Transfer = require('./Transfer');2module.exports = class WealthTransfer {3 4 static DIRECTION_AUTHOR = 'directionAuthor';5 static DIRECTION_TARGET = 'directionTarget';6 7 constructor()8 {9 this._transfers = new Map();10 }11 addTransferDirection(direction)12 {13 if(!this._transfers.has(direction)) {14 this._transfers.set(direction, new Transfer());15 }16 return this.getTransferDirection(direction);17 }18 getTransferDirection(direction)19 {20 return this._transfers.get(direction);21 }22 serialize()23 {24 const transfers = {};25 this._transfers.forEach((transfer, direction) => {26 transfers[direction] = transfer.serialize();27 })28 return {29 direction: transfers,30 };31 }...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var options = {4};5wpt.runTest(url, options, function(err, data) {6 if (err) return console.error(err);7 wpt.getTestResults(data.data.testId, function(err, data) {8 if (err) return console.error(err);9 console.log(data.data.runs[1].firstView._transfers);10 });11});12var wpt = require('webpagetest');13var wpt = new WebPageTest('www.webpagetest.org');14var options = {15};16wpt.runTest(url, options, function(err, data) {17 if (err) return console.error(err);18 wpt.getTestResults(data.data.testId, function(err, data) {19 if (err) return console.error(err);20 console.log(data.data.runs[1].firstView._requests);21 });22});23var wpt = require('webpagetest');24var wpt = new WebPageTest('www.webpagetest.org');25var options = {26};27wpt.runTest(url, options, function(err, data) {28 if (err) return console.error(err);29 wpt.getTestResults(data.data.testId, function(err, data) {30 if (err) return console.error(err);31 console.log(data.data.runs[1].firstView._domains);32 });33});
Using AI Code Generation
1var wptools = require("wptools");2var path = require("path");3wptools._transfers("test", function(err, res) {4 if (err) {5 console.log(err);6 } else {7 console.log(res);8 }9});10var wptools = require("wptools");11var path = require("path");12wptools._transfer("test/test.txt", function(err, res) {13 if (err) {14 console.log(err);15 } else {16 console.log(res);17 }18});19var wptools = require("wptools");20var path = require("path");21wptools._upload("test/test.txt", "test/test2.txt", function(err, res) {22 if (err) {23 console.log(err);24 } else {25 console.log(res);26 }27});28var wptools = require("wptools");29var path = require("path");30wptools._delete("test/test.txt", function(err, res) {31 if (err) {32 console.log(err);33 } else {34 console.log(res);35 }36});37var wptools = require("wptools");38var path = require("path");39wptools._mkdir("test/test", function(err, res) {40 if (err) {41 console.log(err);42 } else {43 console.log(res);44 }45});46var wptools = require("wptools");47var path = require("path");48wptools._rmdir("test/test", function(err, res) {49 if (err) {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!