From aa31496e5819b47468ca879b02d47d5212637ea6 Mon Sep 17 00:00:00 2001 From: justin <328965+justinbarry@users.noreply.github.com> Date: Fri, 27 May 2022 10:09:45 -0700 Subject: [PATCH] OPS - Run prettier on js codebase --- jest.config.js | 6 +- packages/fcl/src/config-utils.js | 2 +- .../src/current-user/exec-service/index.js | 31 +- .../strategies/utils/fetch-service.js | 2 +- packages/fcl/src/discovery/index.js | 4 +- packages/fcl/src/discovery/services.js | 26 +- packages/fcl/src/discovery/services.test.js | 101 +++--- packages/fcl/src/discovery/services/authn.js | 18 +- packages/protobuf/src/index.js | 2 +- packages/protobuf/src/index.test.js | 5 +- packages/protobuf/webpack.config.js | 20 +- packages/sdk/src/account/account.js | 3 +- packages/sdk/src/account/account.test.js | 3 +- packages/sdk/src/block/block.js | 3 +- .../sdk/src/build/build-arguments.test.js | 3 +- packages/sdk/src/build/build-at-block-id.js | 12 +- packages/sdk/src/build/build-get-account.js | 2 +- .../sdk/src/build/build-get-block-header.js | 2 +- packages/sdk/src/build/build-get-block.js | 2 +- .../sdk/src/build/build-get-collection.js | 2 +- ...d-get-events-at-block-height-range.test.js | 6 +- .../sdk/src/build/build-get-events.test.js | 3 +- .../sdk/src/build/build-get-latest-block.js | 3 +- .../src/build/build-get-latest-block.test.js | 3 +- .../src/build/build-get-transaction-status.js | 2 +- .../build-get-transaction-status.test.js | 5 +- .../sdk/src/build/build-get-transaction.js | 2 +- packages/sdk/src/build/build-invariant.js | 4 +- .../sdk/src/build/build-invariant.test.js | 3 +- packages/sdk/src/build/build-payer.test.js | 14 +- packages/sdk/src/build/build-ping.test.js | 2 +- packages/sdk/src/build/build-proposer.test.js | 14 +- packages/sdk/src/build/build-ref.js | 2 +- packages/sdk/src/build/build-ref.test.js | 2 +- packages/sdk/src/build/build-script.js | 5 +- packages/sdk/src/build/build-validator.js | 6 +- .../sdk/src/build/build-validator.test.js | 3 +- packages/sdk/src/contract.test.js | 20 +- packages/sdk/src/decode/decode.js | 5 +- packages/sdk/src/decode/decode.test.js | 30 +- packages/sdk/src/encode/encode.js | 47 +-- packages/sdk/src/encode/encode.test.js | 114 +++++-- packages/sdk/src/interaction/interaction.js | 85 ++--- .../sdk/src/interaction/interaction.test.js | 4 +- packages/sdk/src/resolve/resolve-accounts.js | 28 +- .../sdk/src/resolve/resolve-accounts.test.js | 114 ++++--- packages/sdk/src/resolve/resolve-arguments.js | 5 +- .../sdk/src/resolve/resolve-arguments.test.js | 68 ++-- packages/sdk/src/resolve/resolve-cadence.js | 11 +- .../sdk/src/resolve/resolve-cadence.test.js | 44 ++- .../resolve-final-normalization.test.js | 3 +- .../resolve-proposer-sequence-number.js | 45 +-- .../resolve-proposer-sequence-number.test.js | 3 +- .../sdk/src/resolve/resolve-ref-block-id.js | 22 +- .../src/resolve/resolve-ref-block-id.test.js | 5 +- .../sdk/src/resolve/resolve-signatures.js | 7 +- .../sdk/src/resolve/resolve-validators.js | 11 +- .../src/resolve/resolve-validators.test.js | 5 +- packages/sdk/src/resolve/resolve.js | 10 +- packages/sdk/src/resolve/voucher.js | 8 +- packages/sdk/src/response/response.test.js | 6 +- packages/sdk/src/send/send.js | 8 +- packages/sdk/src/utils/deprecate.js | 8 +- .../sdk/src/wallet-utils/encode-signable.js | 95 +++--- .../src/wallet-utils/encode-signable.test.js | 19 +- packages/transport-grpc/package.json | 86 ++--- .../transport-grpc/src/send-execute-script.js | 70 +++- .../src/send-execute-script.test.js | 115 ++++--- .../transport-grpc/src/send-get-account.js | 52 ++- .../src/send-get-account.test.js | 154 +++++---- .../src/send-get-block-header.js | 36 ++- .../src/send-get-block-header.test.js | 245 +++++++------- packages/transport-grpc/src/send-get-block.js | 31 +- .../transport-grpc/src/send-get-block.test.js | 301 ++++++++---------- .../transport-grpc/src/send-get-collection.js | 19 +- .../src/send-get-collection.test.js | 88 +++-- .../transport-grpc/src/send-get-events.js | 49 ++- .../src/send-get-events.test.js | 219 +++++++------ .../src/send-get-transaction-status.js | 28 +- .../src/send-get-transaction-status.test.js | 122 ++++--- .../src/send-get-transaction.js | 45 ++- .../src/send-get-transaction.test.js | 126 ++++---- packages/transport-grpc/src/send-grpc.js | 5 +- packages/transport-grpc/src/send-ping.js | 5 +- packages/transport-grpc/src/send-ping.test.js | 45 ++- .../transport-grpc/src/send-transaction.js | 26 +- packages/transport-grpc/src/unary.js | 5 +- packages/transport-http/package.json | 84 ++--- packages/transport-http/src/sdk-send-http.js | 2 +- .../transport-http/src/send-execute-script.js | 51 ++- .../src/send-execute-script.test.js | 151 ++++----- .../transport-http/src/send-get-account.js | 37 ++- .../src/send-get-account.test.js | 111 +++---- .../src/send-get-block-header.js | 20 +- .../src/send-get-block-header.test.js | 237 +++++++------- packages/transport-http/src/send-get-block.js | 29 +- .../transport-http/src/send-get-block.test.js | 263 ++++++++------- .../transport-http/src/send-get-collection.js | 12 +- .../src/send-get-collection.test.js | 47 ++- .../transport-http/src/send-get-events.js | 57 ++-- .../src/send-get-events.test.js | 161 +++++----- .../src/send-get-transaction.js | 28 +- .../src/send-get-transaction.test.js | 89 +++--- packages/transport-http/src/send-http.js | 7 +- packages/transport-http/src/send-ping.js | 7 +- packages/transport-http/src/send-ping.test.js | 37 +-- .../transport-http/src/send-transaction.js | 46 ++- packages/types/src/types.js | 286 +++++++++-------- packages/types/src/types.test.js | 36 ++- packages/util-actor/src/index.js | 32 +- packages/util-address/src/index.js | 4 +- packages/util-invariant/src/index.js | 2 +- packages/util-logger/src/util-logger.js | 29 +- packages/util-logger/src/util-logger.test.js | 4 +- .../src/util-node-http-modules.js | 2 +- packages/util-template/src/template.js | 2 +- packages/util-uid/src/util-uid.js | 9 +- 117 files changed, 2618 insertions(+), 2294 deletions(-) diff --git a/jest.config.js b/jest.config.js index 7770e7bfe..1c15fa8d0 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,5 +1,3 @@ module.exports = { - "projects": [ - "/packages/*" - ] -}; + projects: ["/packages/*"], +} diff --git a/packages/fcl/src/config-utils.js b/packages/fcl/src/config-utils.js index c19d564a4..b2828826e 100644 --- a/packages/fcl/src/config-utils.js +++ b/packages/fcl/src/config-utils.js @@ -48,6 +48,6 @@ export async function getDiscoveryService() { type: "authn", endpoint: discoveryWallet, method: discoveryWalletMethod, - discoveryAuthnInclude + discoveryAuthnInclude, } } diff --git a/packages/fcl/src/current-user/exec-service/index.js b/packages/fcl/src/current-user/exec-service/index.js index 666bb7283..475549ebb 100644 --- a/packages/fcl/src/current-user/exec-service/index.js +++ b/packages/fcl/src/current-user/exec-service/index.js @@ -31,33 +31,32 @@ export async function execService({service, msg = {}, opts = {}, config = {}}) { } try { - const res = await STRATEGIES[service.method]( - service, - msg, - opts, - fullConfig - ) + const res = await STRATEGIES[service.method](service, msg, opts, fullConfig) if (res.status === "REDIRECT") { invariant( service.type === res.data.type, "Cannot shift recursive service type in execService" ) return await execService({ - service: res.data, - msg, - opts, - config: fullConfig + service: res.data, + msg, + opts, + config: fullConfig, }) } else { return res } } catch (error) { - console.error("execService({service, msg = {}, opts = {}, config = {}})", error, { - service, - msg, - opts, - config - }) + console.error( + "execService({service, msg = {}, opts = {}, config = {}})", + error, + { + service, + msg, + opts, + config, + } + ) throw error } } diff --git a/packages/fcl/src/current-user/exec-service/strategies/utils/fetch-service.js b/packages/fcl/src/current-user/exec-service/strategies/utils/fetch-service.js index 5b13bb4b4..e8321f2ae 100644 --- a/packages/fcl/src/current-user/exec-service/strategies/utils/fetch-service.js +++ b/packages/fcl/src/current-user/exec-service/strategies/utils/fetch-service.js @@ -15,5 +15,5 @@ export function fetchService(service, opts = {}) { "Content-Type": "application/json", }, body: body, - }).then((d) => d.json()) + }).then(d => d.json()) } diff --git a/packages/fcl/src/discovery/index.js b/packages/fcl/src/discovery/index.js index 765c092e3..bb9dd6671 100644 --- a/packages/fcl/src/discovery/index.js +++ b/packages/fcl/src/discovery/index.js @@ -1,7 +1,7 @@ import authn from "./services/authn" const discovery = { - authn + authn, } -export {discovery} \ No newline at end of file +export {discovery} diff --git a/packages/fcl/src/discovery/services.js b/packages/fcl/src/discovery/services.js index 2720f539a..e475d3ebd 100644 --- a/packages/fcl/src/discovery/services.js +++ b/packages/fcl/src/discovery/services.js @@ -2,11 +2,17 @@ import {config} from "@onflow/config" import {invariant} from "@onflow/util-invariant" import {VERSION} from "../VERSION" -const asyncPipe = (...fns) => input => fns.reduce((chain, fn) => chain.then(fn), Promise.resolve(input)) +const asyncPipe = + (...fns) => + input => + fns.reduce((chain, fn) => chain.then(fn), Promise.resolve(input)) async function addServices(services = []) { const endpoint = await config.get("discovery.authn.endpoint") - invariant(Boolean(endpoint), `"discovery.authn.endpoint" in config must be defined.`) + invariant( + Boolean(endpoint), + `"discovery.authn.endpoint" in config must be defined.` + ) const include = await config.get("discovery.authn.include", []) const url = new URL(endpoint) @@ -18,10 +24,11 @@ async function addServices(services = []) { }, body: JSON.stringify({ fclVersion: VERSION, - include - }) - }).then(d => d.json()) - .then(json => [...services, ...json]) + include, + }), + }) + .then(d => d.json()) + .then(json => [...services, ...json]) } function addExtensions(services = []) { @@ -33,8 +40,5 @@ function filterServicesByType(services = [], type) { return services.filter(service => service.type === type) } -export const getServices = ({ type }) => asyncPipe( - addServices, - addExtensions, - s => filterServicesByType(s, type) -)([]) \ No newline at end of file +export const getServices = ({type}) => + asyncPipe(addServices, addExtensions, s => filterServicesByType(s, type))([]) diff --git a/packages/fcl/src/discovery/services.test.js b/packages/fcl/src/discovery/services.test.js index c9d0f6831..7860b164f 100644 --- a/packages/fcl/src/discovery/services.test.js +++ b/packages/fcl/src/discovery/services.test.js @@ -2,56 +2,56 @@ import {getServices} from "./services" import {config} from "@onflow/config" const serviceOne = { - "f_type": "Service", - "f_vsn": "1.0.0", - "type": "authn", - "method": "IFRAME/RPC", - "uid": "walletone#authn", - "endpoint": "https://test.test", - "provider": { - "address": "0x1", - "name": "Wallet One" - } + f_type: "Service", + f_vsn: "1.0.0", + type: "authn", + method: "IFRAME/RPC", + uid: "walletone#authn", + endpoint: "https://test.test", + provider: { + address: "0x1", + name: "Wallet One", + }, } const serviceTwo = { - "f_type": "Service", - "f_vsn": "1.0.0", - "type": "authz", - "method": "IFRAME/RPC", - "uid": "wallettwo#authn", - "endpoint": "https://test.test", - "provider": { - "address": "0x2", - "name": "Wallet Two" - } + f_type: "Service", + f_vsn: "1.0.0", + type: "authz", + method: "IFRAME/RPC", + uid: "wallettwo#authn", + endpoint: "https://test.test", + provider: { + address: "0x2", + name: "Wallet Two", + }, } const serviceThree = { - "f_type": "Service", - "f_vsn": "1.0.0", - "type": "authn", - "method": "IFRAME/RPC", - "uid": "walletthree#authn", - "endpoint": "https://test.test", - "provider": { - "address": "0x3", - "name": "Wallet Three" - } + f_type: "Service", + f_vsn: "1.0.0", + type: "authn", + method: "IFRAME/RPC", + uid: "walletthree#authn", + endpoint: "https://test.test", + provider: { + address: "0x3", + name: "Wallet Three", + }, } const serviceFour = { - "f_type": "Service", - "f_vsn": "1.0.0", - "type": "authn", - "method": "IFRAME/RPC", - "uid": "walletfour#authn", - "endpoint": "https://test.test", - "optIn": true, - "provider": { - "address": "0x4", - "name": "Wallet Four" - } + f_type: "Service", + f_vsn: "1.0.0", + type: "authn", + method: "IFRAME/RPC", + uid: "walletfour#authn", + endpoint: "https://test.test", + optIn: true, + provider: { + address: "0x4", + name: "Wallet Four", + }, } describe("getServices", () => { @@ -61,7 +61,10 @@ describe("getServices", () => { beforeEach(() => { windowSpy = jest.spyOn(window, "window", "get") configRef = config() - configRef.put("discovery.authn.endpoint", "https://fcl-discovery.onflow.org/api/testnet/authn") + configRef.put( + "discovery.authn.endpoint", + "https://fcl-discovery.onflow.org/api/testnet/authn" + ) }) afterEach(() => { @@ -73,16 +76,18 @@ describe("getServices", () => { const mockData = [serviceOne, serviceTwo] windowSpy.mockImplementation(() => ({ - fcl_extensions: [serviceThree] + fcl_extensions: [serviceThree], })) - global.fetch = jest.fn(() => Promise.resolve({ - json: () => Promise.resolve(mockData) - })) + global.fetch = jest.fn(() => + Promise.resolve({ + json: () => Promise.resolve(mockData), + }) + ) - const response = await getServices({ type: "authn" }) + const response = await getServices({type: "authn"}) const expectedResponse = [serviceThree, serviceOne] // returns extensions first expect(response.length).toEqual(2) expect(response).toEqual(expectedResponse) }) -}) \ No newline at end of file +}) diff --git a/packages/fcl/src/discovery/services/authn.js b/packages/fcl/src/discovery/services/authn.js index 8df28cdf1..611c486de 100644 --- a/packages/fcl/src/discovery/services/authn.js +++ b/packages/fcl/src/discovery/services/authn.js @@ -1,4 +1,11 @@ -import {spawn, subscriber, snapshoter, INIT, SUBSCRIBE, UNSUBSCRIBE} from "@onflow/util-actor" +import { + spawn, + subscriber, + snapshoter, + INIT, + SUBSCRIBE, + UNSUBSCRIBE, +} from "@onflow/util-actor" import {getServices} from "../services" const NAME = "authn" @@ -23,8 +30,11 @@ const warn = (fact, msg) => { const HANDLERS = { [INIT]: async ctx => { - warn(typeof window === "undefined", '"fcl.discovery" is only available in the browser.') - const services = await getServices({ type: NAME }) + warn( + typeof window === "undefined", + '"fcl.discovery" is only available in the browser.' + ) + const services = await getServices({type: NAME}) ctx.put(RESULTS, services) }, [SUBSCRIBE]: (ctx, letter) => { @@ -39,7 +49,7 @@ const spawnProviders = () => spawn(HANDLERS, NAME) const authn = { subscribe: cb => subscriber(NAME, spawnProviders, cb), - snapshot: () => snapshoter(NAME, spawnProviders) + snapshot: () => snapshoter(NAME, spawnProviders), } export default authn diff --git a/packages/protobuf/src/index.js b/packages/protobuf/src/index.js index 75d25d098..89c6123a4 100644 --- a/packages/protobuf/src/index.js +++ b/packages/protobuf/src/index.js @@ -17,4 +17,4 @@ export * from "./generated/flow/entities/transaction_pb_service.js" export * from "./generated/flow/entities/transaction_pb.js" export * from "./generated/flow/execution/execution_pb_service.js" -export * from "./generated/flow/execution/execution_pb.js" \ No newline at end of file +export * from "./generated/flow/execution/execution_pb.js" diff --git a/packages/protobuf/src/index.test.js b/packages/protobuf/src/index.test.js index 27a98a746..ebfe00bd1 100644 --- a/packages/protobuf/src/index.test.js +++ b/packages/protobuf/src/index.test.js @@ -1,4 +1,3 @@ test("placeholder", () => { - expect(1).toBe(1) - }) - \ No newline at end of file + expect(1).toBe(1) +}) diff --git a/packages/protobuf/webpack.config.js b/packages/protobuf/webpack.config.js index 2a313a733..0e7fd171d 100644 --- a/packages/protobuf/webpack.config.js +++ b/packages/protobuf/webpack.config.js @@ -1,13 +1,13 @@ -const path = require('path'); +const path = require("path") module.exports = { - entry: './src/index.js', - target: 'node', - devtool: 'source-map', + entry: "./src/index.js", + target: "node", + devtool: "source-map", output: { - path: path.resolve(__dirname, 'dist'), - filename: 'index.js', - library: '', - libraryTarget: 'commonjs-module' - } -} \ No newline at end of file + path: path.resolve(__dirname, "dist"), + filename: "index.js", + library: "", + libraryTarget: "commonjs-module", + }, +} diff --git a/packages/sdk/src/account/account.js b/packages/sdk/src/account/account.js index 9104f9266..0b3bedd18 100644 --- a/packages/sdk/src/account/account.js +++ b/packages/sdk/src/account/account.js @@ -15,7 +15,8 @@ export function account(address, {height, id} = {}, opts) { if (id) return send([getAccount(address), atBlockId(id)], opts).then(decode) // Get account by height - if (height) return send([getAccount(address), atBlockHeight(height)], opts).then(decode) + if (height) + return send([getAccount(address), atBlockHeight(height)], opts).then(decode) return send([getAccount(address)], opts).then(decode) } diff --git a/packages/sdk/src/account/account.test.js b/packages/sdk/src/account/account.test.js index 6aba23242..8c2e82ea0 100644 --- a/packages/sdk/src/account/account.test.js +++ b/packages/sdk/src/account/account.test.js @@ -1,4 +1,3 @@ test("placeholder", () => { - expect(0).toBe(0) + expect(0).toBe(0) }) - \ No newline at end of file diff --git a/packages/sdk/src/block/block.js b/packages/sdk/src/block/block.js index 056ea2340..232c08722 100644 --- a/packages/sdk/src/block/block.js +++ b/packages/sdk/src/block/block.js @@ -20,7 +20,8 @@ export function block({sealed = false, id, height} = {}, opts = {}) { if (id) return send([getBlock(), atBlockId(id)], opts).then(decode) // Get block by height - if (height) return send([getBlock(), atBlockHeight(height)], opts).then(decode) + if (height) + return send([getBlock(), atBlockHeight(height)], opts).then(decode) // Get latest block return send([getBlock(sealed)], opts).then(decode) diff --git a/packages/sdk/src/build/build-arguments.test.js b/packages/sdk/src/build/build-arguments.test.js index 6aba23242..8c2e82ea0 100644 --- a/packages/sdk/src/build/build-arguments.test.js +++ b/packages/sdk/src/build/build-arguments.test.js @@ -1,4 +1,3 @@ test("placeholder", () => { - expect(0).toBe(0) + expect(0).toBe(0) }) - \ No newline at end of file diff --git a/packages/sdk/src/build/build-at-block-id.js b/packages/sdk/src/build/build-at-block-id.js index 0498d1d41..2553bcee9 100644 --- a/packages/sdk/src/build/build-at-block-id.js +++ b/packages/sdk/src/build/build-at-block-id.js @@ -8,9 +8,15 @@ export function atBlockId(id) { return Ok(ix) }, validator((ix, {Ok, Bad}) => { - if (isGetAccount(ix)) return Bad(ix, "Unable to specify a block id with a Get Account interaction.") - if (typeof ix.block.isSealed === "boolean") return Bad(ix, "Unable to specify both block id and isSealed.") - if (ix.block.height) return Bad(ix, "Unable to specify both block id and block height.") + if (isGetAccount(ix)) + return Bad( + ix, + "Unable to specify a block id with a Get Account interaction." + ) + if (typeof ix.block.isSealed === "boolean") + return Bad(ix, "Unable to specify both block id and isSealed.") + if (ix.block.height) + return Bad(ix, "Unable to specify both block id and block height.") return Ok(ix) }), ]) diff --git a/packages/sdk/src/build/build-get-account.js b/packages/sdk/src/build/build-get-account.js index e41948f2f..a3649b958 100644 --- a/packages/sdk/src/build/build-get-account.js +++ b/packages/sdk/src/build/build-get-account.js @@ -7,6 +7,6 @@ export function getAccount(addr) { ix => { ix.account.addr = sansPrefix(addr) return Ok(ix) - } + }, ]) } diff --git a/packages/sdk/src/build/build-get-block-header.js b/packages/sdk/src/build/build-get-block-header.js index b8be57c1b..4a27a4406 100644 --- a/packages/sdk/src/build/build-get-block-header.js +++ b/packages/sdk/src/build/build-get-block-header.js @@ -6,6 +6,6 @@ export function getBlockHeader(isSealed = null) { ix => { ix.block.isSealed = isSealed return Ok(ix) - } + }, ]) } diff --git a/packages/sdk/src/build/build-get-block.js b/packages/sdk/src/build/build-get-block.js index ef7f7c938..553e8d31c 100644 --- a/packages/sdk/src/build/build-get-block.js +++ b/packages/sdk/src/build/build-get-block.js @@ -6,6 +6,6 @@ export function getBlock(isSealed = null) { ix => { ix.block.isSealed = isSealed return Ok(ix) - } + }, ]) } diff --git a/packages/sdk/src/build/build-get-collection.js b/packages/sdk/src/build/build-get-collection.js index 3f8528da5..c64bd9094 100644 --- a/packages/sdk/src/build/build-get-collection.js +++ b/packages/sdk/src/build/build-get-collection.js @@ -6,6 +6,6 @@ export function getCollection(id = null) { ix => { ix.collection.id = id return ix - } + }, ]) } diff --git a/packages/sdk/src/build/build-get-events-at-block-height-range.test.js b/packages/sdk/src/build/build-get-events-at-block-height-range.test.js index 28a1b3795..9889ca07a 100644 --- a/packages/sdk/src/build/build-get-events-at-block-height-range.test.js +++ b/packages/sdk/src/build/build-get-events-at-block-height-range.test.js @@ -7,7 +7,11 @@ describe("Build Get Events At Block Height Range", () => { const start = 123 const end = 456 - let ix = await getEventsAtBlockHeightRange(eventName, start, end)(interaction()) + let ix = await getEventsAtBlockHeightRange( + eventName, + start, + end + )(interaction()) expect(isGetEvents(ix)).toBe(true) expect(ix.events.eventType).toBe(eventName) diff --git a/packages/sdk/src/build/build-get-events.test.js b/packages/sdk/src/build/build-get-events.test.js index 6aba23242..8c2e82ea0 100644 --- a/packages/sdk/src/build/build-get-events.test.js +++ b/packages/sdk/src/build/build-get-events.test.js @@ -1,4 +1,3 @@ test("placeholder", () => { - expect(0).toBe(0) + expect(0).toBe(0) }) - \ No newline at end of file diff --git a/packages/sdk/src/build/build-get-latest-block.js b/packages/sdk/src/build/build-get-latest-block.js index 3aedfff95..0c79908de 100644 --- a/packages/sdk/src/build/build-get-latest-block.js +++ b/packages/sdk/src/build/build-get-latest-block.js @@ -1,7 +1,6 @@ import {pipe, Ok, makeGetLatestBlock} from "../interaction/interaction.js" export function getLatestBlock(isSealed = false) { - console.warn( ` %cFCL/SDK Deprecation Notice @@ -20,6 +19,6 @@ export function getLatestBlock(isSealed = false) { ix => { ix.block.isSealed = isSealed return Ok(ix) - } + }, ]) } diff --git a/packages/sdk/src/build/build-get-latest-block.test.js b/packages/sdk/src/build/build-get-latest-block.test.js index 6aba23242..8c2e82ea0 100644 --- a/packages/sdk/src/build/build-get-latest-block.test.js +++ b/packages/sdk/src/build/build-get-latest-block.test.js @@ -1,4 +1,3 @@ test("placeholder", () => { - expect(0).toBe(0) + expect(0).toBe(0) }) - \ No newline at end of file diff --git a/packages/sdk/src/build/build-get-transaction-status.js b/packages/sdk/src/build/build-get-transaction-status.js index 8431e6b8c..7d9870fca 100644 --- a/packages/sdk/src/build/build-get-transaction-status.js +++ b/packages/sdk/src/build/build-get-transaction-status.js @@ -6,6 +6,6 @@ export function getTransactionStatus(transactionId) { ix => { ix.transaction.id = transactionId return Ok(ix) - } + }, ]) } diff --git a/packages/sdk/src/build/build-get-transaction-status.test.js b/packages/sdk/src/build/build-get-transaction-status.test.js index 113e6f832..4de877cc6 100644 --- a/packages/sdk/src/build/build-get-transaction-status.test.js +++ b/packages/sdk/src/build/build-get-transaction-status.test.js @@ -1,4 +1,7 @@ -import {interaction, isGetTransactionStatus} from "../interaction/interaction.js" +import { + interaction, + isGetTransactionStatus, +} from "../interaction/interaction.js" import {getTransactionStatus} from "./build-get-transaction-status.js" describe("Build Get Transaction Status", () => { diff --git a/packages/sdk/src/build/build-get-transaction.js b/packages/sdk/src/build/build-get-transaction.js index 920e71cc5..cdd1c80cf 100644 --- a/packages/sdk/src/build/build-get-transaction.js +++ b/packages/sdk/src/build/build-get-transaction.js @@ -6,6 +6,6 @@ export function getTransaction(transactionId) { ix => { ix.transaction.id = transactionId return Ok(ix) - } + }, ]) } diff --git a/packages/sdk/src/build/build-invariant.js b/packages/sdk/src/build/build-invariant.js index 4766036ba..fddb25e45 100644 --- a/packages/sdk/src/build/build-invariant.js +++ b/packages/sdk/src/build/build-invariant.js @@ -1,9 +1,9 @@ -import { Ok, Bad } from "../interaction/interaction.js" +import {Ok, Bad} from "../interaction/interaction.js" export function invariant(...args) { if (args.length > 1) { const [predicate, message] = args - return invariant((ix, { Ok, Bad }) => { + return invariant((ix, {Ok, Bad}) => { return predicate ? Ok(ix) : Bad(ix, message) }) } diff --git a/packages/sdk/src/build/build-invariant.test.js b/packages/sdk/src/build/build-invariant.test.js index 6aba23242..8c2e82ea0 100644 --- a/packages/sdk/src/build/build-invariant.test.js +++ b/packages/sdk/src/build/build-invariant.test.js @@ -1,4 +1,3 @@ test("placeholder", () => { - expect(0).toBe(0) + expect(0).toBe(0) }) - \ No newline at end of file diff --git a/packages/sdk/src/build/build-payer.test.js b/packages/sdk/src/build/build-payer.test.js index 0465adc4e..4fff58f81 100644 --- a/packages/sdk/src/build/build-payer.test.js +++ b/packages/sdk/src/build/build-payer.test.js @@ -3,18 +3,18 @@ import {payer} from "./build-payer.js" describe("Build Payer", () => { test("Build Payer", async () => { - const authz = { addr: "0xabc123" } + const authz = {addr: "0xabc123"} let ix = await (await payer(authz))(interaction()) const payerAccount = ix.accounts[ix.payer] - + expect(payerAccount.addr).toEqual(authz.addr) - expect(payerAccount.role).toEqual({ - authorizer: false, - param: false, - payer: true, - proposer: false + expect(payerAccount.role).toEqual({ + authorizer: false, + param: false, + payer: true, + proposer: false, }) }) }) diff --git a/packages/sdk/src/build/build-ping.test.js b/packages/sdk/src/build/build-ping.test.js index 3991c56b8..6404d5b70 100644 --- a/packages/sdk/src/build/build-ping.test.js +++ b/packages/sdk/src/build/build-ping.test.js @@ -4,7 +4,7 @@ import {ping} from "./build-ping.js" describe("Build Ping", () => { test("Build Ping", async () => { let ix = await ping()(interaction()) - + expect(isPing(ix)).toBe(true) }) }) diff --git a/packages/sdk/src/build/build-proposer.test.js b/packages/sdk/src/build/build-proposer.test.js index 1c781d0d5..47370fcdf 100644 --- a/packages/sdk/src/build/build-proposer.test.js +++ b/packages/sdk/src/build/build-proposer.test.js @@ -3,18 +3,18 @@ import {proposer} from "./build-proposer.js" describe("Build Proposer", () => { test("Build Proposer", async () => { - const authz = { addr: "0xabc123" } + const authz = {addr: "0xabc123"} let ix = await (await proposer(authz))(interaction()) const proposerAccount = ix.accounts[ix.proposer] - + expect(proposerAccount.addr).toEqual(authz.addr) - expect(proposerAccount.role).toEqual({ - authorizer: false, - param: false, - payer: false, - proposer: true + expect(proposerAccount.role).toEqual({ + authorizer: false, + param: false, + payer: false, + proposer: true, }) }) }) diff --git a/packages/sdk/src/build/build-ref.js b/packages/sdk/src/build/build-ref.js index cc5b12f0d..7d60242c3 100644 --- a/packages/sdk/src/build/build-ref.js +++ b/packages/sdk/src/build/build-ref.js @@ -5,6 +5,6 @@ export function ref(refBlock) { ix => { ix.message.refBlock = refBlock return Ok(ix) - } + }, ]) } diff --git a/packages/sdk/src/build/build-ref.test.js b/packages/sdk/src/build/build-ref.test.js index 2792be7c3..516b35893 100644 --- a/packages/sdk/src/build/build-ref.test.js +++ b/packages/sdk/src/build/build-ref.test.js @@ -6,7 +6,7 @@ describe("Build Ref", () => { const refBlockId = "abc123" let ix = await ref(refBlockId)(interaction()) - + expect(ix.message.refBlock).toEqual(refBlockId) }) }) diff --git a/packages/sdk/src/build/build-script.js b/packages/sdk/src/build/build-script.js index 9f4510ec8..45c3ca954 100644 --- a/packages/sdk/src/build/build-script.js +++ b/packages/sdk/src/build/build-script.js @@ -2,8 +2,5 @@ import {pipe, Ok, put, makeScript} from "../interaction/interaction.js" import {template} from "@onflow/util-template" export function script(...args) { - return pipe([ - makeScript, - put("ix.cadence", template(...args)) - ]) + return pipe([makeScript, put("ix.cadence", template(...args))]) } diff --git a/packages/sdk/src/build/build-validator.js b/packages/sdk/src/build/build-validator.js index a978661c6..708a9602e 100644 --- a/packages/sdk/src/build/build-validator.js +++ b/packages/sdk/src/build/build-validator.js @@ -1,7 +1,7 @@ import {update} from "../interaction/interaction.js" export function validator(cb) { - return update('ix.validators', validators => - Array.isArray(validators) ? validators.push(cb) : [cb] - ) + return update("ix.validators", validators => + Array.isArray(validators) ? validators.push(cb) : [cb] + ) } diff --git a/packages/sdk/src/build/build-validator.test.js b/packages/sdk/src/build/build-validator.test.js index 6aba23242..8c2e82ea0 100644 --- a/packages/sdk/src/build/build-validator.test.js +++ b/packages/sdk/src/build/build-validator.test.js @@ -1,4 +1,3 @@ test("placeholder", () => { - expect(0).toBe(0) + expect(0).toBe(0) }) - \ No newline at end of file diff --git a/packages/sdk/src/contract.test.js b/packages/sdk/src/contract.test.js index 6881d0ba5..866d0c02f 100644 --- a/packages/sdk/src/contract.test.js +++ b/packages/sdk/src/contract.test.js @@ -5,15 +5,17 @@ import * as interaction from "./interaction/interaction.js" import * as send from "./send/send.js" import * as template from "@onflow/util-template" -const interfaceContract = (label, wat) => ([template]) => { - const keys = template.replace(/\s+/g, "|").split("|").filter(Boolean) - - describe(label, () => { - for (let key of keys) - test(`${label}.${key}`, () => - expect(wat[key]).toStrictEqual(expect.any(Function))) - }) -} +const interfaceContract = + (label, wat) => + ([template]) => { + const keys = template.replace(/\s+/g, "|").split("|").filter(Boolean) + + describe(label, () => { + for (let key of keys) + test(`${label}.${key}`, () => + expect(wat[key]).toStrictEqual(expect.any(Function))) + }) + } interfaceContract("export", root)` build resolve send diff --git a/packages/sdk/src/decode/decode.js b/packages/sdk/src/decode/decode.js index d3d4d3943..0e12b651e 100644 --- a/packages/sdk/src/decode/decode.js +++ b/packages/sdk/src/decode/decode.js @@ -64,9 +64,8 @@ const decodeArray = async (array, decoders, stack) => const decodeDictionary = async (dictionary, decoders, stack) => await dictionary.reduce(async (acc, v) => { acc = await acc - acc[ - await recurseDecode(v.key, decoders, [...stack, v.key]) - ] = await recurseDecode(v.value, decoders, [...stack, v.key]) + acc[await recurseDecode(v.key, decoders, [...stack, v.key])] = + await recurseDecode(v.value, decoders, [...stack, v.key]) return acc }, Promise.resolve({})) diff --git a/packages/sdk/src/decode/decode.test.js b/packages/sdk/src/decode/decode.test.js index b5a86e8ce..df53fc346 100644 --- a/packages/sdk/src/decode/decode.test.js +++ b/packages/sdk/src/decode/decode.test.js @@ -704,7 +704,8 @@ const genVoidSpec = () => { // Int const genInt = () => { - const minInt256 = -57896044618658097711785492504343953926634992332820282019728792003956564819978 + const minInt256 = + -57896044618658097711785492504343953926634992332820282019728792003956564819978 const maxUInt256 = 115792089237316195423570985008687907853269984665640564039457584007913129639945 const ranInt = ~~(Math.random() * (maxUInt256 - minInt256) + minInt256) return { @@ -766,9 +767,8 @@ const genDictionary = (depth = 0) => { const dictionaryLength = ~~(Math.random() * 10) const arr = Array.from({length: dictionaryLength}).reduce( acc => { - const {payload: valPayload, decoded: val} = OPTIONS[ - ~~(Math.random() * OPTIONS.length) - ]() + const {payload: valPayload, decoded: val} = + OPTIONS[~~(Math.random() * OPTIONS.length)]() const {payload: keyPayload, decoded: ranStringKey} = genString() acc.dict.push({ key: keyPayload, @@ -819,9 +819,8 @@ const genResource = (depth = 0) => { const fieldsLength = ~~(Math.random() * 10) const res = Array.from({length: fieldsLength}).reduce( acc => { - const {payload: valPayload, decoded: val} = OPTIONS[ - ~~(Math.random() * OPTIONS.length) - ]() + const {payload: valPayload, decoded: val} = + OPTIONS[~~(Math.random() * OPTIONS.length)]() const {decoded: ranStringName} = genString() acc.fields.push({ name: ranStringName, @@ -872,9 +871,8 @@ const genStruct = (depth = 0) => { const fieldsLength = ~~(Math.random() * 10) const res = Array.from({length: fieldsLength}).reduce( acc => { - const {payload: valPayload, decoded: val} = OPTIONS[ - ~~(Math.random() * OPTIONS.length) - ]() + const {payload: valPayload, decoded: val} = + OPTIONS[~~(Math.random() * OPTIONS.length)]() const {decoded: ranStringName} = genString() acc.fields.push({ name: ranStringName, @@ -925,9 +923,8 @@ const genEvent = (depth = 0) => { const fieldsLength = ~~(Math.random() * 10) const res = Array.from({length: fieldsLength}).reduce( acc => { - const {payload: valPayload, decoded: val} = OPTIONS[ - ~~(Math.random() * OPTIONS.length) - ]() + const {payload: valPayload, decoded: val} = + OPTIONS[~~(Math.random() * OPTIONS.length)]() const {decoded: ranStringName} = genString() acc.fields.push({ name: ranStringName, @@ -978,9 +975,8 @@ const genEnum = (depth = 0) => { const fieldsLength = ~~(Math.random() * 10) const res = Array.from({length: fieldsLength}).reduce( acc => { - const {payload: valPayload, decoded: val} = OPTIONS[ - ~~(Math.random() * OPTIONS.length) - ]() + const {payload: valPayload, decoded: val} = + OPTIONS[~~(Math.random() * OPTIONS.length)]() const {decoded: ranStringName} = genString() acc.fields.push({ name: ranStringName, @@ -1206,7 +1202,7 @@ describe("custom decoder tests", () => { }, } - const Jeff = function(resource) { + const Jeff = function (resource) { if (!(this instanceof Jeff)) return new Jeff(resource) this.firstName = resource.firstName this.lastName = resource.lastName diff --git a/packages/sdk/src/encode/encode.js b/packages/sdk/src/encode/encode.js index fbf7eb88f..388487ced 100644 --- a/packages/sdk/src/encode/encode.js +++ b/packages/sdk/src/encode/encode.js @@ -1,10 +1,13 @@ -import { SHA3 } from "sha3" -import { encode, Buffer } from "@onflow/rlp" -import { sansPrefix } from "@onflow/util-address" +import {SHA3} from "sha3" +import {encode, Buffer} from "@onflow/rlp" +import {sansPrefix} from "@onflow/util-address" -export const encodeTransactionPayload = tx => prependTransactionDomainTag(rlpEncode(preparePayload(tx))) -export const encodeTransactionEnvelope = tx => prependTransactionDomainTag(rlpEncode(prepareEnvelope(tx))) -export const encodeTxIdFromVoucher = voucher => sha3_256(rlpEncode(prepareVoucher(voucher))) +export const encodeTransactionPayload = tx => + prependTransactionDomainTag(rlpEncode(preparePayload(tx))) +export const encodeTransactionEnvelope = tx => + prependTransactionDomainTag(rlpEncode(prepareEnvelope(tx))) +export const encodeTxIdFromVoucher = voucher => + sha3_256(rlpEncode(prepareVoucher(voucher))) const rightPaddedHexBuffer = (value, pad) => Buffer.from(value.padEnd(pad * 2, 0), "hex") @@ -12,7 +15,10 @@ const rightPaddedHexBuffer = (value, pad) => const leftPaddedHexBuffer = (value, pad) => Buffer.from(value.padStart(pad * 2, 0), "hex") -const TRANSACTION_DOMAIN_TAG = rightPaddedHexBuffer(Buffer.from("FLOW-V0.0-transaction").toString("hex"), 32).toString("hex") +const TRANSACTION_DOMAIN_TAG = rightPaddedHexBuffer( + Buffer.from("FLOW-V0.0-transaction").toString("hex"), + 32 +).toString("hex") const prependTransactionDomainTag = tx => TRANSACTION_DOMAIN_TAG + tx const addressBuffer = addr => leftPaddedHexBuffer(addr, 8) @@ -103,16 +109,19 @@ const prepareVoucher = voucher => { const signers = collectSigners(voucher) const prepareSigs = sigs => { - return sigs.map(({ address, keyId, sig }) => { - return { signerIndex: signers.get(address), keyId, sig } - }).sort((a, b) => { - if (a.signerIndex > b.signerIndex) return 1 - if (a.signerIndex < b.signerIndex) return -1 - if (a.keyId > b.keyId) return 1 - if (a.keyId < b.keyId) return -1 - }).map(sig => { - return [sig.signerIndex, sig.keyId, signatureBuffer(sig.sig)] - }) + return sigs + .map(({address, keyId, sig}) => { + return {signerIndex: signers.get(address), keyId, sig} + }) + .sort((a, b) => { + if (a.signerIndex > b.signerIndex) return 1 + if (a.signerIndex < b.signerIndex) return -1 + if (a.keyId > b.keyId) return 1 + if (a.keyId < b.keyId) return -1 + }) + .map(sig => { + return [sig.signerIndex, sig.keyId, signatureBuffer(sig.sig)] + }) } return [ @@ -125,7 +134,9 @@ const prepareVoucher = voucher => { voucher.proposalKey.keyId, voucher.proposalKey.sequenceNum, addressBuffer(sansPrefix(voucher.payer)), - voucher.authorizers.map(authorizer => addressBuffer(sansPrefix(authorizer))), + voucher.authorizers.map(authorizer => + addressBuffer(sansPrefix(authorizer)) + ), ], prepareSigs(voucher.payloadSigs), prepareSigs(voucher.envelopeSigs), diff --git a/packages/sdk/src/encode/encode.test.js b/packages/sdk/src/encode/encode.test.js index 09a69654f..69bcfe4eb 100644 --- a/packages/sdk/src/encode/encode.test.js +++ b/packages/sdk/src/encode/encode.test.js @@ -1,6 +1,10 @@ const merge = require("deepmerge") -import {encodeTransactionPayload, encodeTransactionEnvelope, encodeTxIdFromVoucher} from "./encode.js" +import { + encodeTransactionPayload, + encodeTransactionEnvelope, + encodeTxIdFromVoucher, +} from "./encode.js" import * as root from "./encode.js" it("export contract interface", () => { @@ -124,43 +128,43 @@ describe("encode transaction", () => { "empty cadence", buildTx({cadence: ""}), "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f84280c0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c9880000000000000001", - "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f869f84280c0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c9880000000000000001e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162" + "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f869f84280c0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c9880000000000000001e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", ], [ "null refBlock", buildTx({refBlock: null}), "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a000000000000000000000000000000000000000000000000000000000000000002a880000000000000001040a880000000000000001c9880000000000000001", - "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f899f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a000000000000000000000000000000000000000000000000000000000000000002a880000000000000001040a880000000000000001c9880000000000000001e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162" + "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f899f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a000000000000000000000000000000000000000000000000000000000000000002a880000000000000001040a880000000000000001c9880000000000000001e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", ], [ "zero computeLimit", buildTx({computeLimit: 0}), "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b80880000000000000001040a880000000000000001c9880000000000000001", - "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f899f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b80880000000000000001040a880000000000000001c9880000000000000001e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162" + "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f899f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b80880000000000000001040a880000000000000001c9880000000000000001e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", ], [ "zero proposalKey.key", buildTx({proposalKey: {keyId: 0}}), "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001800a880000000000000001c9880000000000000001", - "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f899f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001800a880000000000000001c9880000000000000001e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162" + "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f899f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001800a880000000000000001c9880000000000000001e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", ], [ "zero proposalKey.sequenceNum", buildTx({proposalKey: {sequenceNum: 0}}), "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a8800000000000000010480880000000000000001c9880000000000000001", - "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f899f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a8800000000000000010480880000000000000001c9880000000000000001e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162" + "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f899f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a8800000000000000010480880000000000000001c9880000000000000001e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", ], [ "empty authorizers", buildTx({authorizers: []}), "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f869b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c0", - "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f890f869b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c0e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162" + "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f890f869b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c0e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", ], [ "multiple authorizers", buildTx({authorizers: ["01", "02"]}), "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f87bb07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001d2880000000000000001880000000000000002", - "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f8a2f87bb07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001d2880000000000000001880000000000000002e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162" + "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f8a2f87bb07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001d2880000000000000001880000000000000002e4e38004a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", ], ] @@ -174,12 +178,12 @@ describe("encode transaction", () => { [ "empty payloadSigs", buildTx({payloadSigs: []}), - "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f875f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c9880000000000000001c0" + "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f875f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c9880000000000000001c0", ], [ "zero payloadSigs.0.key", buildTx({payloadSigs: [{keyId: 0}]}), - "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f899f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c9880000000000000001e4e38080a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162" + "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f899f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c9880000000000000001e4e38080a0f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", ], [ "out-of-order payloadSigs -- by signer", @@ -191,7 +195,7 @@ describe("encode transaction", () => { {address: "02", keyId: 0, sig: "b"}, ], }), - "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f893f884b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001db880000000000000001880000000000000002880000000000000003ccc3808080c3018080c3028080" + "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f893f884b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001db880000000000000001880000000000000002880000000000000003ccc3808080c3018080c3028080", ], [ "out-of-order payloadSigs -- by key ID", @@ -203,7 +207,7 @@ describe("encode transaction", () => { {address: "01", keyId: 1, sig: "b"}, ], }), - "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f881f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c9880000000000000001ccc3808080c3800180c3800280" + "464c4f572d56302e302d7472616e73616374696f6e0000000000000000000000f881f872b07472616e73616374696f6e207b2065786563757465207b206c6f67282248656c6c6f2c20576f726c64212229207d207dc0a0f0e4c2f76c58916ec258f246851bea091d14d4247a2fc3e18694461b1816e13b2a880000000000000001040a880000000000000001c9880000000000000001ccc3808080c3800180c3800280", ], ] @@ -289,8 +293,14 @@ describe("encode txId from voucher", () => { ["non-string refBlock", buildVoucher({refBlock: 42})], ["non-number computeLimit", buildVoucher({computeLimit: "foo"})], ["non-object proposalKey", buildVoucher({proposalKey: "foo"})], - ["non-string proposalKey.address", buildVoucher({proposalKey: {address: 42}})], - ["non-number proposalKey.keyId", buildVoucher({proposalKey: {keyId: "foo"}})], + [ + "non-string proposalKey.address", + buildVoucher({proposalKey: {address: 42}}), + ], + [ + "non-number proposalKey.keyId", + buildVoucher({proposalKey: {keyId: "foo"}}), + ], [ "non-number proposalKey.sequenceNum", buildVoucher({proposalKey: {sequenceNum: "foo"}}), @@ -301,7 +311,10 @@ describe("encode txId from voucher", () => { const invalidPayloadSigsCases = [ ["null payloadSigs", buildVoucher({payloadSigs: null})], - ["null payloadSigs.0.address", buildVoucher({payloadSigs: [{address: null}]})], + [ + "null payloadSigs.0.address", + buildVoucher({payloadSigs: [{address: null}]}), + ], ["null payloadSigs.0.keyId", buildVoucher({payloadSigs: [{keyId: null}]})], ["null payloadSigs.0.sig", buildVoucher({payloadSigs: [{sig: null}]})], @@ -319,8 +332,14 @@ describe("encode txId from voucher", () => { const invalidEnvelopeSigsCases = [ ["null envelopeSigs", buildVoucher({envelopeSigs: null})], - ["null envelopeSigs.0.address", buildVoucher({envelopeSigs: [{address: null}]})], - ["null envelopeSigs.0.keyId", buildVoucher({envelopeSigs: [{keyId: null}]})], + [ + "null envelopeSigs.0.address", + buildVoucher({envelopeSigs: [{address: null}]}), + ], + [ + "null envelopeSigs.0.keyId", + buildVoucher({envelopeSigs: [{keyId: null}]}), + ], ["null envelopeSigs.0.sig", buildVoucher({envelopeSigs: [{sig: null}]})], ["non-array envelopeSigs", buildVoucher({envelopeSigs: {}})], @@ -332,7 +351,10 @@ describe("encode txId from voucher", () => { "non-number envelopeSigs.0.keyId", buildVoucher({envelopeSigs: [{keyId: "foo"}]}), ], - ["non-string envelopeSigs.0.sig", buildVoucher({envelopeSigs: [{sig: 42}]})], + [ + "non-string envelopeSigs.0.sig", + buildVoucher({envelopeSigs: [{sig: 42}]}), + ], ] // Test case format: @@ -345,12 +367,20 @@ describe("encode txId from voucher", () => { [ "complete tx", buildVoucher({}), - "118d6462f1c4182501d56f04a0cd23cf685283194bb316dceeb215b353120b2b" + "118d6462f1c4182501d56f04a0cd23cf685283194bb316dceeb215b353120b2b", ], [ "complete tx with envelope sig", - buildVoucher({envelopeSigs: [{ address: "01", keyId: 4, sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162"}]}), - "363172029cc6bfc5df3f99e84393e82b6c11e2a920c0e8c3229d077ae8bc31f7" + buildVoucher({ + envelopeSigs: [ + { + address: "01", + keyId: 4, + sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", + }, + ], + }), + "363172029cc6bfc5df3f99e84393e82b6c11e2a920c0e8c3229d077ae8bc31f7", ], [ "empty cadence", @@ -385,31 +415,55 @@ describe("encode txId from voucher", () => { [ "empty payloadSigs", buildVoucher({payloadSigs: []}), - "c56b673a57fb94d546b9c30ac637d20021d04faf046e2cd5ea32591b7175794e" + "c56b673a57fb94d546b9c30ac637d20021d04faf046e2cd5ea32591b7175794e", ], [ "out-of-order payloadSigs -- by signer", buildVoucher({ authorizers: ["01", "02", "03"], payloadSigs: [ - {address: "03", keyId: 0, sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162"}, - {address: "01", keyId: 0, sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162"}, - {address: "02", keyId: 0, sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162"}, + { + address: "03", + keyId: 0, + sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", + }, + { + address: "01", + keyId: 0, + sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", + }, + { + address: "02", + keyId: 0, + sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", + }, ], }), - "b67576744b0d051ba81e4d6635a47b9c8973b3adc7410bcd213880d5094b264a" + "b67576744b0d051ba81e4d6635a47b9c8973b3adc7410bcd213880d5094b264a", ], [ "out-of-order payloadSigs -- by key ID", buildVoucher({ authorizers: ["01"], payloadSigs: [ - {address: "01", keyId: 2, sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162"}, - {address: "01", keyId: 0, sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162"}, - {address: "01", keyId: 1, sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162"}, + { + address: "01", + keyId: 2, + sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", + }, + { + address: "01", + keyId: 0, + sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", + }, + { + address: "01", + keyId: 1, + sig: "f7225388c1d69d57e6251c9fda50cbbf9e05131e5adb81e5aa0422402f048162", + }, ], }), - "183a74ecc0782fbffc364cac0c404ee01144ae258841b806a6274259bfc7ef8b" + "183a74ecc0782fbffc364cac0c404ee01144ae258841b806a6274259bfc7ef8b", ], ] diff --git a/packages/sdk/src/interaction/interaction.js b/packages/sdk/src/interaction/interaction.js index f8676e820..4ba2eb69d 100644 --- a/packages/sdk/src/interaction/interaction.js +++ b/packages/sdk/src/interaction/interaction.js @@ -138,42 +138,45 @@ const makeIx = wat => ix => { return Ok(ix) } -export const prepAccount = (acct, opts = {}) => ix => { - invariant( - typeof acct === "function" || typeof acct === "object", - "prepAccount must be passed an authorization function or an account object" - ) - invariant(opts.role != null, "Account must have a role") - - const ACCOUNT = JSON.parse(ACCT) - const role = opts.role - const tempId = uuid() - - if (acct.authorization && isFn(acct.authorization)) acct = {resolve: acct.authorization} - if (!acct.authorization && isFn(acct)) acct = {resolve: acct} - - ix.accounts[tempId] = { - ...ACCOUNT, - tempId, - ...acct, - role: { - ...ACCOUNT.role, - ...(typeof acct.role === "object" ? acct.role : {}), - [role]: true, - }, +export const prepAccount = + (acct, opts = {}) => + ix => { + invariant( + typeof acct === "function" || typeof acct === "object", + "prepAccount must be passed an authorization function or an account object" + ) + invariant(opts.role != null, "Account must have a role") + + const ACCOUNT = JSON.parse(ACCT) + const role = opts.role + const tempId = uuid() + + if (acct.authorization && isFn(acct.authorization)) + acct = {resolve: acct.authorization} + if (!acct.authorization && isFn(acct)) acct = {resolve: acct} + + ix.accounts[tempId] = { + ...ACCOUNT, + tempId, + ...acct, + role: { + ...ACCOUNT.role, + ...(typeof acct.role === "object" ? acct.role : {}), + [role]: true, + }, + } + + if (role === AUTHORIZER) { + ix.authorizations.push(tempId) + } else if (role === PAYER) { + ix.payer.push(tempId) + } else { + ix[role] = tempId + } + + return ix } - if (role === AUTHORIZER) { - ix.authorizations.push(tempId) - } else if (role === PAYER) { - ix.payer.push(tempId) - } else { - ix[role] = tempId - } - - return ix -} - export const makeArgument = arg => ix => { let tempId = uuid() ix.message.arguments.push(tempId) @@ -184,7 +187,9 @@ export const makeArgument = arg => ix => { ix.arguments[tempId].asArgument = arg.asArgument ix.arguments[tempId].xform = arg.xform ix.arguments[tempId].resolve = arg.resolve - ix.arguments[tempId].resolveArgument = isFn(arg.resolveArgument) ? arg.resolveArgument.bind(arg) : arg.resolveArgument + ix.arguments[tempId].resolveArgument = isFn(arg.resolveArgument) + ? arg.resolveArgument.bind(arg) + : arg.resolveArgument return Ok(ix) } @@ -264,10 +269,12 @@ export const put = (key, value) => ix => { return Ok(ix) } -export const update = (key, fn = identity) => ix => { - ix.assigns[key] = fn(ix.assigns[key], ix) - return Ok(ix) -} +export const update = + (key, fn = identity) => + ix => { + ix.assigns[key] = fn(ix.assigns[key], ix) + return Ok(ix) + } export const destroy = key => ix => { delete ix.assigns[key] diff --git a/packages/sdk/src/interaction/interaction.test.js b/packages/sdk/src/interaction/interaction.test.js index 5bb404e8a..ebfe00bd1 100644 --- a/packages/sdk/src/interaction/interaction.test.js +++ b/packages/sdk/src/interaction/interaction.test.js @@ -1,3 +1,3 @@ test("placeholder", () => { - expect(1).toBe(1) -}) \ No newline at end of file + expect(1).toBe(1) +}) diff --git a/packages/sdk/src/resolve/resolve-accounts.js b/packages/sdk/src/resolve/resolve-accounts.js index eb917385d..690e7259d 100644 --- a/packages/sdk/src/resolve/resolve-accounts.js +++ b/packages/sdk/src/resolve/resolve-accounts.js @@ -49,31 +49,35 @@ async function collectAccounts(ix, accounts, last, depth = 3) { if (ix.accounts[ax.tempId].role.payer) { if (Array.isArray(ix.payer)) { - ix.payer = Array.from(new Set([...ix.payer, ax.tempId].map(d => - d === old.tempId ? ax.tempId : d - ))) + ix.payer = Array.from( + new Set( + [...ix.payer, ax.tempId].map(d => + d === old.tempId ? ax.tempId : d + ) + ) + ) } else { - ix.payer = Array.from(new Set([ix.payer, ax.tempId].map(d => - d === old.tempId ? ax.tempId : d - ))) + ix.payer = Array.from( + new Set( + [ix.payer, ax.tempId].map(d => (d === old.tempId ? ax.tempId : d)) + ) + ) } if (ix.payer.length > 1) { // remove payer dups based on addr and keyId const dupList = [] const payerAccts = [] ix.payer = ix.payer.reduce((g, tempId) => { - const { addr, keyId } = ix.accounts[tempId]; - const key = `${addr}-${keyId}`; + const {addr, keyId} = ix.accounts[tempId] + const key = `${addr}-${keyId}` payerAccts.push(addr) - if (dupList.includes(key)) return g; + if (dupList.includes(key)) return g dupList.push(key) return [...g, tempId] }, []) const multiAccts = Array.from(new Set(payerAccts)) if (multiAccts.length > 1) { - throw new Error( - "Payer can not be different accounts" - ) + throw new Error("Payer can not be different accounts") } } } diff --git a/packages/sdk/src/resolve/resolve-accounts.test.js b/packages/sdk/src/resolve/resolve-accounts.test.js index 7d2b21cb9..99dbd2bd1 100644 --- a/packages/sdk/src/resolve/resolve-accounts.test.js +++ b/packages/sdk/src/resolve/resolve-accounts.test.js @@ -8,7 +8,7 @@ import { limit, authorizations, } from "../sdk.js" -import { buildPreSignable } from "./resolve-accounts" +import {buildPreSignable} from "./resolve-accounts" test("Voucher in PreSignable", async () => { const authz = { @@ -56,7 +56,7 @@ test("Voucher in PreSignable multiple payer keys", async () => { const authz = { addr: "0x01", tempId: "0x01-1", - signingFunction: () => ({ signature: "123" }), + signingFunction: () => ({signature: "123"}), keyId: 1, sequenceNum: 123, } @@ -64,23 +64,34 @@ test("Voucher in PreSignable multiple payer keys", async () => { const authzPayer = { addr: "0x02", address: "0x02", - resolve: (account, preSignable) => [{ - ...account, - tempId: "0x02-0", - addr: "0x02", - keyId: 0, - sequenceNum: 123, - signingFunction: (signable) => ({ signature: "123", addr: "0x02", keyId: 0 }), - resolve: null, - }, { - ...account, - tempId: "0x02-1", - addr: "0x02", - keyId: 1, - sequenceNum: 123, - signingFunction: (signable) => ({ signature: "333", addr: "0x02", keyId: 1 }), - resolve: null, - }] + resolve: (account, preSignable) => [ + { + ...account, + tempId: "0x02-0", + addr: "0x02", + keyId: 0, + sequenceNum: 123, + signingFunction: signable => ({ + signature: "123", + addr: "0x02", + keyId: 0, + }), + resolve: null, + }, + { + ...account, + tempId: "0x02-1", + addr: "0x02", + keyId: 1, + sequenceNum: 123, + signingFunction: signable => ({ + signature: "333", + addr: "0x02", + keyId: 1, + }), + resolve: null, + }, + ], } const built = await build([ @@ -90,7 +101,7 @@ test("Voucher in PreSignable multiple payer keys", async () => { authorizations([authz]), payer(authzPayer), ref("123"), - ]); + ]) const ix = await resolve(built) expect(ix.payer).toEqual(["0x02-0", "0x02-1"]) @@ -102,27 +113,25 @@ test("Voucher in PreSignable multiple payer keys", async () => { refBlock: "123", computeLimit: 156, arguments: [], - proposalKey: { address: "0x01", keyId: 1, sequenceNum: 123 }, + proposalKey: {address: "0x01", keyId: 1, sequenceNum: 123}, payer: "0x02", authorizers: ["0x01"], payloadSigs: [ - { address: "0x01", keyId: 1, sig: "123" }, - { address: "0x01", keyId: 1, sig: "123" }, + {address: "0x01", keyId: 1, sig: "123"}, + {address: "0x01", keyId: 1, sig: "123"}, ], envelopeSigs: [ - { address: "0x02", keyId: 0, sig: "123" }, - { address: "0x02", keyId: 1, sig: "333" } + {address: "0x02", keyId: 0, sig: "123"}, + {address: "0x02", keyId: 1, sig: "333"}, ], }) }) - - test("Voucher in PreSignable multiple payer keys different accounts", async () => { const authz = { addr: "0x01", tempId: "0x01-1", - signingFunction: () => ({ signature: "123" }), + signingFunction: () => ({signature: "123"}), keyId: 1, sequenceNum: 123, } @@ -130,23 +139,34 @@ test("Voucher in PreSignable multiple payer keys different accounts", async () = const authzPayer = { addr: "0x02", address: "0x02", - resolve: (account, preSignable) => [{ - ...account, - tempId: "0x02-0", - addr: "0x02", - keyId: 0, - sequenceNum: 123, - signingFunction: (signable) => ({ signature: "123", addr: "0x02", keyId: 0 }), - resolve: null, - }, { - ...account, - tempId: "0x01-1", - addr: "0x01", - keyId: 1, - sequenceNum: 123, - signingFunction: (signable) => ({ signature: "333", addr: "0x02", keyId: 1 }), - resolve: null, - }] + resolve: (account, preSignable) => [ + { + ...account, + tempId: "0x02-0", + addr: "0x02", + keyId: 0, + sequenceNum: 123, + signingFunction: signable => ({ + signature: "123", + addr: "0x02", + keyId: 0, + }), + resolve: null, + }, + { + ...account, + tempId: "0x01-1", + addr: "0x01", + keyId: 1, + sequenceNum: 123, + signingFunction: signable => ({ + signature: "333", + addr: "0x02", + keyId: 1, + }), + resolve: null, + }, + ], } const built = await build([ @@ -156,7 +176,7 @@ test("Voucher in PreSignable multiple payer keys different accounts", async () = authorizations([authz]), payer(authzPayer), ref("123"), - ]); + ]) await expect(resolve(built)).rejects.toThrow() -}) \ No newline at end of file +}) diff --git a/packages/sdk/src/resolve/resolve-arguments.js b/packages/sdk/src/resolve/resolve-arguments.js index 41933eb7c..04db4a7d1 100644 --- a/packages/sdk/src/resolve/resolve-arguments.js +++ b/packages/sdk/src/resolve/resolve-arguments.js @@ -15,7 +15,10 @@ function cast(arg) { } async function handleArgResolution(arg, depth = 3) { - invariant(depth > 0, `Argument Resolve Recursion Limit Exceeded for Arg: ${arg.tempId}`) + invariant( + depth > 0, + `Argument Resolve Recursion Limit Exceeded for Arg: ${arg.tempId}` + ) if (isFn(arg.resolveArgument)) { const resolvedArg = await arg.resolveArgument() diff --git a/packages/sdk/src/resolve/resolve-arguments.test.js b/packages/sdk/src/resolve/resolve-arguments.test.js index cb18a5c28..79ec830c4 100644 --- a/packages/sdk/src/resolve/resolve-arguments.test.js +++ b/packages/sdk/src/resolve/resolve-arguments.test.js @@ -1,12 +1,10 @@ -import { - resolveArguments -} from "../sdk.js" +import {resolveArguments} from "../sdk.js" describe("resolveArguments", () => { const argID = "28948a11n4" const argObj = { type: "Address", - value: "0xf8d6e0586b0a20c7" + value: "0xf8d6e0586b0a20c7", } const tag = "SCRIPT" const kind = "ARGUMENT" @@ -25,10 +23,10 @@ describe("resolveArguments", () => { value: argObj.value, xform: { label: "Address", - asArgument: () => argObj - } - } - } + asArgument: () => argObj, + }, + }, + }, } const res = await resolveArguments(ix) @@ -45,17 +43,17 @@ describe("resolveArguments", () => { resolve: jest.fn(), resolveArgument: jest.fn().mockResolvedValue({ xform: { - asArgument: () => argObj - } + asArgument: () => argObj, + }, }), tempId, value: null, xform: { label: "Address", - asArgument: () => argObj - } - } - } + asArgument: () => argObj, + }, + }, + }, } const res = await resolveArguments(ix) @@ -65,11 +63,10 @@ describe("resolveArguments", () => { }) test("should resolve nested asynchronous arguments", async () => { - const resolveTwo = jest.fn().mockResolvedValue({ xform: { - asArgument: () => argObj - } + asArgument: () => argObj, + }, }) const ix = { @@ -81,18 +78,18 @@ describe("resolveArguments", () => { resolve: undefined, resolveArgument: jest.fn().mockResolvedValue({ xform: { - asArgument: () => argObj + asArgument: () => argObj, }, - resolveArgument: resolveTwo + resolveArgument: resolveTwo, }), tempId, value: null, xform: { label: "Address", - asArgument: () => argObj - } - } - } + asArgument: () => argObj, + }, + }, + }, } const res = await resolveArguments(ix) @@ -112,34 +109,31 @@ describe("resolveArguments", () => { resolveArgument: jest.fn().mockResolvedValue({ tempId: "1", xform: { - asArgument: () => argObj + asArgument: () => argObj, }, resolveArgument: jest.fn().mockResolvedValue({ tempId: "2", xform: { - asArgument: () => argObj + asArgument: () => argObj, }, resolveArgument: jest.fn().mockResolvedValue({ tempId: "3", xform: { - asArgument: () => argObj - } - }) - }) + asArgument: () => argObj, + }, + }), + }), }), tempId, value: null, xform: { label: "Address", - asArgument: () => argObj - } - } - } + asArgument: () => argObj, + }, + }, + }, } - await expect(resolveArguments(ix)) - .rejects - .toThrow(); + await expect(resolveArguments(ix)).rejects.toThrow() }) }) - \ No newline at end of file diff --git a/packages/sdk/src/resolve/resolve-cadence.js b/packages/sdk/src/resolve/resolve-cadence.js index bb1713456..2d7412592 100644 --- a/packages/sdk/src/resolve/resolve-cadence.js +++ b/packages/sdk/src/resolve/resolve-cadence.js @@ -17,13 +17,10 @@ export async function resolveCadence(ix) { ix.message.cadence = await config() .where(/^0x/) .then(d => - Object.entries(d).reduce( - (cadence, [key, value]) => { - const regex = new RegExp("(\\b" + key + "\\b)", 'g') - return cadence.replace(regex, value) - }, - cadence - ) + Object.entries(d).reduce((cadence, [key, value]) => { + const regex = new RegExp("(\\b" + key + "\\b)", "g") + return cadence.replace(regex, value) + }, cadence) ) } diff --git a/packages/sdk/src/resolve/resolve-cadence.test.js b/packages/sdk/src/resolve/resolve-cadence.test.js index d8a25e897..8320d6fee 100644 --- a/packages/sdk/src/resolve/resolve-cadence.test.js +++ b/packages/sdk/src/resolve/resolve-cadence.test.js @@ -4,35 +4,35 @@ import {config} from "@onflow/config" const log = msg => ix => (console.log(msg, ix), ix) -describe('resolveCadence', () => { +describe("resolveCadence", () => { test("cadence is a string", async () => { const CADENCE = "CADENCE_STRING" - + const ix = await pipe([ makeScript, put("ix.cadence", CADENCE), resolveCadence, ])(interaction()) - + expect(ix.message.cadence).toBe(CADENCE) }) - + test("cadence is a function", async () => { - const CADENCE = async function() { + const CADENCE = async function () { return "CADENCE_ASYNC_FUNCTION" } - + const ix = await pipe([ makeScript, put("ix.cadence", CADENCE), resolveCadence, ])(interaction()) - + expect(ix.message.cadence).toBe(await CADENCE()) }) - + test("replaces all addresses from config", async () => { - const CADENCE = async function() { + const CADENCE = async function () { return ` import MyContract from 0xMY_CONTRACT_ADDRESS @@ -41,8 +41,8 @@ describe('resolveCadence', () => { } ` } - - const RESULT = async function() { + + const RESULT = async function () { return ` import MyContract from 0x123abc @@ -51,20 +51,20 @@ describe('resolveCadence', () => { } ` } - + config.put("0xMY_CONTRACT_ADDRESS", "0x123abc") - + const ix = await pipe([ makeScript, put("ix.cadence", CADENCE), resolveCadence, ])(interaction()) - + expect(ix.message.cadence).toEqual(await RESULT()) }) test("similar config names do not replace each other", async () => { - const CADENCE = async function() { + const CADENCE = async function () { return ` import FooBar from 0xFoo import FooBar from 0xFooBar @@ -83,8 +83,8 @@ describe('resolveCadence', () => { pub fun otherThree(): Address {return 0xFooBar} ` } - - const RESULT = async function() { + + const RESULT = async function () { return ` import FooBar from 0x123 import FooBar from 0x456 @@ -103,17 +103,15 @@ describe('resolveCadence', () => { pub fun otherThree(): Address {return 0x456} ` } - - config - .put('0xFoo', '0x123') - .put('0xFooBar', '0x456') - + + config.put("0xFoo", "0x123").put("0xFooBar", "0x456") + const ix = await pipe([ makeScript, put("ix.cadence", CADENCE), resolveCadence, ])(interaction()) - + expect(ix.message.cadence).toEqual(await RESULT()) }) }) diff --git a/packages/sdk/src/resolve/resolve-final-normalization.test.js b/packages/sdk/src/resolve/resolve-final-normalization.test.js index 6aba23242..8c2e82ea0 100644 --- a/packages/sdk/src/resolve/resolve-final-normalization.test.js +++ b/packages/sdk/src/resolve/resolve-final-normalization.test.js @@ -1,4 +1,3 @@ test("placeholder", () => { - expect(0).toBe(0) + expect(0).toBe(0) }) - \ No newline at end of file diff --git a/packages/sdk/src/resolve/resolve-proposer-sequence-number.js b/packages/sdk/src/resolve/resolve-proposer-sequence-number.js index 7107500db..f66bc0adb 100644 --- a/packages/sdk/src/resolve/resolve-proposer-sequence-number.js +++ b/packages/sdk/src/resolve/resolve-proposer-sequence-number.js @@ -9,30 +9,31 @@ import {invariant} from "@onflow/util-invariant" import {Buffer} from "@onflow/rlp" import {send as defaultSend} from "@onflow/transport-http" -export const resolveProposerSequenceNumber = ({ node }) => async (ix) => { - if (!(isTransaction(ix))) return Ok(ix) - if (ix.accounts[ix.proposer].sequenceNum) return Ok(ix) +export const resolveProposerSequenceNumber = + ({node}) => + async ix => { + if (!isTransaction(ix)) return Ok(ix) + if (ix.accounts[ix.proposer].sequenceNum) return Ok(ix) - const sendFn = await config.first( - ["sdk.transport", "sdk.send"], - defaultSend - ) + const sendFn = await config.first( + ["sdk.transport", "sdk.send"], + defaultSend + ) - invariant( - sendFn, - `Required value for sdk.transport is not defined in config. See: ${"https://github.com/onflow/fcl-js/blob/master/packages/sdk/CHANGELOG.md#0057-alpha1----2022-01-21"}` - ) + invariant( + sendFn, + `Required value for sdk.transport is not defined in config. See: ${"https://github.com/onflow/fcl-js/blob/master/packages/sdk/CHANGELOG.md#0057-alpha1----2022-01-21"}` + ) - const response = await sendFn( - await build([ - getAccount(ix.accounts[ix.proposer].addr) - ]), - {config, response: responseModule, Buffer, ix: ixModule}, - {node} - ) - const decoded = await decodeResponse(response) + const response = await sendFn( + await build([getAccount(ix.accounts[ix.proposer].addr)]), + {config, response: responseModule, Buffer, ix: ixModule}, + {node} + ) + const decoded = await decodeResponse(response) - ix.accounts[ix.proposer].sequenceNum = decoded.keys[ix.accounts[ix.proposer].keyId].sequenceNumber + ix.accounts[ix.proposer].sequenceNum = + decoded.keys[ix.accounts[ix.proposer].keyId].sequenceNumber - return Ok(ix) -} + return Ok(ix) + } diff --git a/packages/sdk/src/resolve/resolve-proposer-sequence-number.test.js b/packages/sdk/src/resolve/resolve-proposer-sequence-number.test.js index 6aba23242..8c2e82ea0 100644 --- a/packages/sdk/src/resolve/resolve-proposer-sequence-number.test.js +++ b/packages/sdk/src/resolve/resolve-proposer-sequence-number.test.js @@ -1,4 +1,3 @@ test("placeholder", () => { - expect(0).toBe(0) + expect(0).toBe(0) }) - \ No newline at end of file diff --git a/packages/sdk/src/resolve/resolve-ref-block-id.js b/packages/sdk/src/resolve/resolve-ref-block-id.js index e4cb5a54e..5e7af37c8 100644 --- a/packages/sdk/src/resolve/resolve-ref-block-id.js +++ b/packages/sdk/src/resolve/resolve-ref-block-id.js @@ -1,4 +1,9 @@ -import {isTransaction, Ok, interaction, pipe} from "../interaction/interaction.js" +import { + isTransaction, + Ok, + interaction, + pipe, +} from "../interaction/interaction.js" import * as ixModule from "../interaction/interaction.js" import {response} from "../response/response.js" import {config} from "@onflow/config" @@ -8,25 +13,18 @@ import {invariant} from "@onflow/util-invariant" import {Buffer} from "@onflow/rlp" import {send as defaultSend} from "@onflow/transport-http" -async function getRefId (opts) { +async function getRefId(opts) { const node = await config().get("accessNode.api") - const sendFn = await config.first( - ["sdk.transport", "sdk.send"], - defaultSend - ) + const sendFn = await config.first(["sdk.transport", "sdk.send"], defaultSend) invariant( - sendFn, + sendFn, `Required value for sdk.transport is not defined in config. See: ${"https://github.com/onflow/fcl-js/blob/master/packages/sdk/CHANGELOG.md#0057-alpha1----2022-01-21"}` ) var ix ix = await pipe(interaction(), [getBlock()]) - ix = await sendFn( - ix, - {config, response, Buffer, ix: ixModule}, - {node} - ) + ix = await sendFn(ix, {config, response, Buffer, ix: ixModule}, {node}) ix = await decodeResponse(ix) return ix.id } diff --git a/packages/sdk/src/resolve/resolve-ref-block-id.test.js b/packages/sdk/src/resolve/resolve-ref-block-id.test.js index 27a98a746..ebfe00bd1 100644 --- a/packages/sdk/src/resolve/resolve-ref-block-id.test.js +++ b/packages/sdk/src/resolve/resolve-ref-block-id.test.js @@ -1,4 +1,3 @@ test("placeholder", () => { - expect(1).toBe(1) - }) - \ No newline at end of file + expect(1).toBe(1) +}) diff --git a/packages/sdk/src/resolve/resolve-signatures.js b/packages/sdk/src/resolve/resolve-signatures.js index 93a1fea52..f6d37836c 100644 --- a/packages/sdk/src/resolve/resolve-signatures.js +++ b/packages/sdk/src/resolve/resolve-signatures.js @@ -68,9 +68,10 @@ export function buildSignable(acct, message, ix) { } function prepForEncoding(ix) { - const payerAddress = sansPrefix((Array.isArray(ix.payer) - ? ix.accounts[ix.payer[0]] - : ix.accounts[ix.payer]).addr); + const payerAddress = sansPrefix( + (Array.isArray(ix.payer) ? ix.accounts[ix.payer[0]] : ix.accounts[ix.payer]) + .addr + ) return { cadence: ix.message.cadence, refBlock: ix.message.refBlock || null, diff --git a/packages/sdk/src/resolve/resolve-validators.js b/packages/sdk/src/resolve/resolve-validators.js index 207c83ad4..1974aff54 100644 --- a/packages/sdk/src/resolve/resolve-validators.js +++ b/packages/sdk/src/resolve/resolve-validators.js @@ -1,6 +1,9 @@ -import { get, pipe, Ok, Bad } from "../interaction/interaction.js" +import {get, pipe, Ok, Bad} from "../interaction/interaction.js" export async function resolveValidators(ix) { - const validators = get(ix, 'ix.validators', []) - return pipe(ix, validators.map(cb => ix => cb(ix, { Ok, Bad }))) -} + const validators = get(ix, "ix.validators", []) + return pipe( + ix, + validators.map(cb => ix => cb(ix, {Ok, Bad})) + ) +} diff --git a/packages/sdk/src/resolve/resolve-validators.test.js b/packages/sdk/src/resolve/resolve-validators.test.js index 30cedf980..8c2e82ea0 100644 --- a/packages/sdk/src/resolve/resolve-validators.test.js +++ b/packages/sdk/src/resolve/resolve-validators.test.js @@ -1,4 +1,3 @@ test("placeholder", () => { - expect(0).toBe(0) - }) - \ No newline at end of file + expect(0).toBe(0) +}) diff --git a/packages/sdk/src/resolve/resolve.js b/packages/sdk/src/resolve/resolve.js index 534234cb3..ee06d70bf 100644 --- a/packages/sdk/src/resolve/resolve.js +++ b/packages/sdk/src/resolve/resolve.js @@ -68,7 +68,10 @@ export const resolve = pipe([ async function execFetchRef(ix) { if (isTransaction(ix) && ix.message.refBlock == null) { const node = await config().get("accessNode.api") - const sendFn = await config.first(["sdk.transport", "sdk.send"], defaultSend) + const sendFn = await config.first( + ["sdk.transport", "sdk.send"], + defaultSend + ) invariant( sendFn, @@ -92,7 +95,10 @@ async function execFetchSequenceNumber(ix) { invariant(acct, `Transactions require a proposer`) if (acct.sequenceNum == null) { const node = await config().get("accessNode.api") - const sendFn = await config.first(["sdk.transport", "sdk.send"], defaultSend) + const sendFn = await config.first( + ["sdk.transport", "sdk.send"], + defaultSend + ) invariant( sendFn, diff --git a/packages/sdk/src/resolve/voucher.js b/packages/sdk/src/resolve/voucher.js index 04c39a055..0a07cbfaf 100644 --- a/packages/sdk/src/resolve/voucher.js +++ b/packages/sdk/src/resolve/voucher.js @@ -6,7 +6,7 @@ export function findInsideSigners(ix) { let inside = new Set(ix.authorizations) inside.add(ix.proposer) if (Array.isArray(ix.payer)) { - ix.payer.forEach(p => inside.delete(p)); + ix.payer.forEach(p => inside.delete(p)) } else { inside.delete(ix.payer) } @@ -36,7 +36,7 @@ export const createSignableVoucher = ix => { sig: ix.accounts[id].signature, })) - const buildOutsideSigners = () => + const buildOutsideSigners = () => findOutsideSigners(ix).map(id => ({ address: withPrefix(ix.accounts[id].addr), keyId: ix.accounts[id].keyId, @@ -53,7 +53,9 @@ export const createSignableVoucher = ix => { keyId: ix.accounts[ix.proposer].keyId, sequenceNum: ix.accounts[ix.proposer].sequenceNum, }, - payer: withPrefix(ix.accounts[Array.isArray(ix.payer) ? ix.payer[0] : ix.payer].addr), + payer: withPrefix( + ix.accounts[Array.isArray(ix.payer) ? ix.payer[0] : ix.payer].addr + ), authorizers: buildAuthorizers(), payloadSigs: buildInsideSigners(), envelopeSigs: buildOutsideSigners(), diff --git a/packages/sdk/src/response/response.test.js b/packages/sdk/src/response/response.test.js index 4201152a6..226ca304c 100644 --- a/packages/sdk/src/response/response.test.js +++ b/packages/sdk/src/response/response.test.js @@ -1,7 +1,7 @@ import {response} from "./response.js" test("Response - Snapshot", async () => { - const resp = response() + const resp = response() - expect(resp).toMatchSnapshot() -}) \ No newline at end of file + expect(resp).toMatchSnapshot() +}) diff --git a/packages/sdk/src/send/send.js b/packages/sdk/src/send/send.js index 191ce665f..05ee44e29 100644 --- a/packages/sdk/src/send/send.js +++ b/packages/sdk/src/send/send.js @@ -14,7 +14,7 @@ export const send = async (args = [], opts = {}) => { ) invariant( - sendFn, + sendFn, `Required value for sdk.transport is not defined in config. See: ${"https://github.com/onflow/fcl-js/blob/master/packages/sdk/CHANGELOG.md#0057-alpha1----2022-01-21"}` ) @@ -26,5 +26,9 @@ export const send = async (args = [], opts = {}) => { opts.node = opts.node || (await config().get("accessNode.api")) if (Array.isArray(args)) args = pipe(interaction(), args) - return sendFn(await resolveFn(args), {config, response, ix: ixModule, Buffer}, opts) + return sendFn( + await resolveFn(args), + {config, response, ix: ixModule, Buffer}, + opts + ) } diff --git a/packages/sdk/src/utils/deprecate.js b/packages/sdk/src/utils/deprecate.js index 30f2ec396..6d8e174c7 100644 --- a/packages/sdk/src/utils/deprecate.js +++ b/packages/sdk/src/utils/deprecate.js @@ -39,7 +39,7 @@ export const deprecate = { const getByValue = (map, searchValue) => { for (let [key, value] of map.entries()) { - if (value === searchValue) return key; + if (value === searchValue) return key } } @@ -56,10 +56,10 @@ export const applyRenamings = (originalObject, deprecationsMap) => { title: "FCL/SDK Deprecation Notice", message: `"${property}" will be deprecated in a future version. Please use "${deprecationsMap.get(property)}" instead.`, - level: logger.LEVELS.warn + level: logger.LEVELS.warn, }) } return Reflect.get(obj, property) - } + }, }) -} \ No newline at end of file +} diff --git a/packages/sdk/src/wallet-utils/encode-signable.js b/packages/sdk/src/wallet-utils/encode-signable.js index 384161c4d..006d2ed4d 100644 --- a/packages/sdk/src/wallet-utils/encode-signable.js +++ b/packages/sdk/src/wallet-utils/encode-signable.js @@ -1,62 +1,65 @@ import {withPrefix, sansPrefix} from "@onflow/util-address" import { - encodeTransactionPayload, - encodeTransactionEnvelope, + encodeTransactionPayload, + encodeTransactionEnvelope, } from "../encode/encode.js" -const findPayloadSigners = (voucher) => { - // Payload Signers Are: (authorizers + proposer) - payer - let payload = new Set(voucher.authorizers) - payload.add(voucher.proposalKey.address) - payload.delete(voucher.payer) - return Array.from(payload).map(withPrefix) +const findPayloadSigners = voucher => { + // Payload Signers Are: (authorizers + proposer) - payer + let payload = new Set(voucher.authorizers) + payload.add(voucher.proposalKey.address) + payload.delete(voucher.payer) + return Array.from(payload).map(withPrefix) } -const findEnvelopeSigners = (voucher) => { - // Envelope Signers Are: (payer) - let envelope = new Set([voucher.payer]) - return Array.from(envelope).map(withPrefix) +const findEnvelopeSigners = voucher => { + // Envelope Signers Are: (payer) + let envelope = new Set([voucher.payer]) + return Array.from(envelope).map(withPrefix) } export class UnableToDetermineMessageEncodingTypeForSignerAddress extends Error { - constructor(signerAddress) { - const msg = ` + constructor(signerAddress) { + const msg = ` Encode Message From Signable Error: Unable to determine message encoding for signer addresss: ${signerAddress}. Please ensure the address: ${signerAddress} is intended to sign the given transaction as specified by the transaction signable. `.trim() - super(msg) - this.name = "Unable To Determine Message Encoding For Signer Addresss" - } + super(msg) + this.name = "Unable To Determine Message Encoding For Signer Addresss" + } } export const encodeMessageFromSignable = (signable, signerAddress) => { - let payloadSigners = findPayloadSigners(signable.voucher) - let envelopeSigners = findEnvelopeSigners(signable.voucher) - - const isPayloadSigner = payloadSigners.includes(withPrefix(signerAddress)) - const isEnvelopeSigner = envelopeSigners.includes(withPrefix(signerAddress)) - - if (!isPayloadSigner && !isEnvelopeSigner) { - throw new UnableToDetermineMessageEncodingTypeForSignerAddress(signerAddress) - } - - const message = { - cadence: signable.voucher.cadence, - refBlock: signable.voucher.refBlock, - computeLimit: signable.voucher.computeLimit, - arguments: signable.voucher.arguments, - proposalKey: { - ...signable.voucher.proposalKey, - address: sansPrefix(signable.voucher.proposalKey.address) - }, - payer: sansPrefix(signable.voucher.payer), - authorizers: signable.voucher.authorizers.map(sansPrefix), - payloadSigs: signable.voucher.payloadSigs.map(ps => ({ - ...ps, - address: sansPrefix(ps.address) - })) - } - - return isPayloadSigner ? encodeTransactionPayload(message) : encodeTransactionEnvelope(message) -} + let payloadSigners = findPayloadSigners(signable.voucher) + let envelopeSigners = findEnvelopeSigners(signable.voucher) + + const isPayloadSigner = payloadSigners.includes(withPrefix(signerAddress)) + const isEnvelopeSigner = envelopeSigners.includes(withPrefix(signerAddress)) + + if (!isPayloadSigner && !isEnvelopeSigner) { + throw new UnableToDetermineMessageEncodingTypeForSignerAddress( + signerAddress + ) + } + const message = { + cadence: signable.voucher.cadence, + refBlock: signable.voucher.refBlock, + computeLimit: signable.voucher.computeLimit, + arguments: signable.voucher.arguments, + proposalKey: { + ...signable.voucher.proposalKey, + address: sansPrefix(signable.voucher.proposalKey.address), + }, + payer: sansPrefix(signable.voucher.payer), + authorizers: signable.voucher.authorizers.map(sansPrefix), + payloadSigs: signable.voucher.payloadSigs.map(ps => ({ + ...ps, + address: sansPrefix(ps.address), + })), + } + + return isPayloadSigner + ? encodeTransactionPayload(message) + : encodeTransactionEnvelope(message) +} diff --git a/packages/sdk/src/wallet-utils/encode-signable.test.js b/packages/sdk/src/wallet-utils/encode-signable.test.js index 1701300cd..bbf8298a9 100644 --- a/packages/sdk/src/wallet-utils/encode-signable.test.js +++ b/packages/sdk/src/wallet-utils/encode-signable.test.js @@ -1,4 +1,7 @@ -import {encodeMessageFromSignable, UnableToDetermineMessageEncodingTypeForSignerAddress} from "./encode-signable.js" +import { + encodeMessageFromSignable, + UnableToDetermineMessageEncodingTypeForSignerAddress, +} from "./encode-signable.js" import { encodeTransactionPayload as encodeInsideMessage, encodeTransactionEnvelope as encodeOutsideMessage, @@ -12,9 +15,7 @@ const MESSAGE = { proposalKey: {address: "02", keyId: 1, sequenceNum: 123}, payer: "01", authorizers: ["02"], - payloadSigs: [ - {address: "02", keyId: 1, sig: "123"}, - ], + payloadSigs: [{address: "02", keyId: 1, sig: "123"}], } const encodedPayerMessage = encodeOutsideMessage(MESSAGE) @@ -28,9 +29,7 @@ const VOUCHER = { proposalKey: {address: "0x02", keyId: 1, sequenceNum: 123}, payer: "0x01", authorizers: ["0x02"], - payloadSigs: [ - {address: "0x02", keyId: 1, sig: "123"}, - ], + payloadSigs: [{address: "0x02", keyId: 1, sig: "123"}], } const PAYER_SIGNABLE = { @@ -68,9 +67,11 @@ describe("encode signable", () => { test("encode signable for address NOT included in signable", () => { const runTest = () => { - return encodeMessageFromSignable(NON_PAYER_SIGNABLE, "0x09") + return encodeMessageFromSignable(NON_PAYER_SIGNABLE, "0x09") } - expect(runTest).toThrow(UnableToDetermineMessageEncodingTypeForSignerAddress) + expect(runTest).toThrow( + UnableToDetermineMessageEncodingTypeForSignerAddress + ) }) }) diff --git a/packages/transport-grpc/package.json b/packages/transport-grpc/package.json index d21cc75fc..190f84ad0 100644 --- a/packages/transport-grpc/package.json +++ b/packages/transport-grpc/package.json @@ -1,46 +1,46 @@ { - "name": "@onflow/transport-grpc", - "version": "1.0.1", - "description": "Flow SDK GRPC Transport Module", - "license": "Apache-2.0", - "author": "Dapper Labs ", - "homepage": "https://onflow.org", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/onflow/flow-js-sdk.git" - }, - "bugs": { - "url": "https://github.com/onflow/flow-js-sdk/issues" - }, - "jest": { - "transform": { - ".js": "jest-esm-transformer" - } - }, - "devDependencies": { - "jest": "^27.0.6", - "jest-esm-transformer": "1.0.0", - "microbundle": "^0.13.3" - }, - "source": "src/sdk-send-grpc.js", - "main": "dist/sdk-send-grpc.js", - "module": "dist/sdk-send-grpc.module.js", - "unpkg": "dist/sdk-send-grpc.umd.js", - "scripts": { - "alpha": "npm publish --tag alpha", - "prepublishOnly": "npm test && npm run build", - "test": "jest", - "build": "microbundle --no-compress", - "test:watch": "jest --watch", - "start": "microbundle watch --no-compress" - }, - "dependencies": { - "@improbable-eng/grpc-web": "^0.14.0", - "@improbable-eng/grpc-web-node-http-transport": "^0.14.0", - "@onflow/protobuf": "^1.0.0", - "@onflow/rlp": "^1.0.1", - "@onflow/util-address": "^1.0.1", - "@onflow/util-invariant": "^1.0.1", - "@onflow/util-template": "^1.0.1" + "name": "@onflow/transport-grpc", + "version": "1.0.1", + "description": "Flow SDK GRPC Transport Module", + "license": "Apache-2.0", + "author": "Dapper Labs ", + "homepage": "https://onflow.org", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/onflow/flow-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/onflow/flow-js-sdk/issues" + }, + "jest": { + "transform": { + ".js": "jest-esm-transformer" } + }, + "devDependencies": { + "jest": "^27.0.6", + "jest-esm-transformer": "1.0.0", + "microbundle": "^0.13.3" + }, + "source": "src/sdk-send-grpc.js", + "main": "dist/sdk-send-grpc.js", + "module": "dist/sdk-send-grpc.module.js", + "unpkg": "dist/sdk-send-grpc.umd.js", + "scripts": { + "alpha": "npm publish --tag alpha", + "prepublishOnly": "npm test && npm run build", + "test": "jest", + "build": "microbundle --no-compress", + "test:watch": "jest --watch", + "start": "microbundle watch --no-compress" + }, + "dependencies": { + "@improbable-eng/grpc-web": "^0.14.0", + "@improbable-eng/grpc-web-node-http-transport": "^0.14.0", + "@onflow/protobuf": "^1.0.0", + "@onflow/rlp": "^1.0.1", + "@onflow/util-address": "^1.0.1", + "@onflow/util-invariant": "^1.0.1", + "@onflow/util-template": "^1.0.1" + } } diff --git a/packages/transport-grpc/src/send-execute-script.js b/packages/transport-grpc/src/send-execute-script.js index fc5ddd37c..7008a09cf 100644 --- a/packages/transport-grpc/src/send-execute-script.js +++ b/packages/transport-grpc/src/send-execute-script.js @@ -1,8 +1,14 @@ import {invariant} from "@onflow/util-invariant" -import {ExecuteScriptAtLatestBlockRequest, ExecuteScriptAtBlockIDRequest, ExecuteScriptAtBlockHeightRequest, AccessAPI} from "@onflow/protobuf" +import { + ExecuteScriptAtLatestBlockRequest, + ExecuteScriptAtBlockIDRequest, + ExecuteScriptAtBlockHeightRequest, + AccessAPI, +} from "@onflow/protobuf" import {unary as defaultUnary} from "./unary" -const argumentBuffer = (arg, context) => context.Buffer.from(JSON.stringify(arg), "utf8") +const argumentBuffer = (arg, context) => + context.Buffer.from(JSON.stringify(arg), "utf8") const hexBuffer = (hex, context) => context.Buffer.from(hex, "hex") async function sendExecuteScriptAtBlockIDRequest(ix, context, opts) { @@ -13,10 +19,17 @@ async function sendExecuteScriptAtBlockIDRequest(ix, context, opts) { req.setBlockId(hexBuffer(ix.block.id, context)) const code = context.Buffer.from(ix.message.cadence, "utf8") - ix.message.arguments.forEach(arg => req.addArguments(argumentBuffer(ix.arguments[arg].asArgument, context))) + ix.message.arguments.forEach(arg => + req.addArguments(argumentBuffer(ix.arguments[arg].asArgument, context)) + ) req.setScript(code) - const res = await unary(opts.node, AccessAPI.ExecuteScriptAtBlockID, req, context) + const res = await unary( + opts.node, + AccessAPI.ExecuteScriptAtBlockID, + req, + context + ) return constructResponse(ix, context, res) } @@ -29,11 +42,18 @@ async function sendExecuteScriptAtBlockHeightRequest(ix, context, opts) { req.setBlockHeight(Number(ix.block.height)) const code = context.Buffer.from(ix.message.cadence, "utf8") - ix.message.arguments.forEach(arg => req.addArguments(argumentBuffer(ix.arguments[arg].asArgument, context))) + ix.message.arguments.forEach(arg => + req.addArguments(argumentBuffer(ix.arguments[arg].asArgument, context)) + ) req.setScript(code) - const res = await unary(opts.node, AccessAPI.ExecuteScriptAtBlockHeight, req, context) - + const res = await unary( + opts.node, + AccessAPI.ExecuteScriptAtBlockHeight, + req, + context + ) + return constructResponse(ix, context, res) } @@ -41,29 +61,47 @@ async function sendExecuteScriptAtLatestBlockRequest(ix, context, opts) { const unary = opts.unary || defaultUnary const req = new ExecuteScriptAtLatestBlockRequest() - + const code = context.Buffer.from(ix.message.cadence, "utf8") - ix.message.arguments.forEach(arg => req.addArguments(argumentBuffer(ix.arguments[arg].asArgument, context))) + ix.message.arguments.forEach(arg => + req.addArguments(argumentBuffer(ix.arguments[arg].asArgument, context)) + ) req.setScript(code) - const res = await unary(opts.node, AccessAPI.ExecuteScriptAtLatestBlock, req, context) + const res = await unary( + opts.node, + AccessAPI.ExecuteScriptAtLatestBlock, + req, + context + ) return constructResponse(ix, context, res) } -function constructResponse(ix, context, res) { +function constructResponse(ix, context, res) { let ret = context.response() ret.tag = ix.tag - ret.encodedData = JSON.parse(context.Buffer.from(res.getValue_asU8()).toString("utf8")) + ret.encodedData = JSON.parse( + context.Buffer.from(res.getValue_asU8()).toString("utf8") + ) return ret } export async function sendExecuteScript(ix, context = {}, opts = {}) { - invariant(opts.node, `SDK Send Execute Script Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Execute Script Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Execute Script Error: context.Buffer must be defined.`) - + invariant( + opts.node, + `SDK Send Execute Script Error: opts.node must be defined.` + ) + invariant( + context.response, + `SDK Send Execute Script Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Execute Script Error: context.Buffer must be defined.` + ) + ix = await ix if (ix.block.id) { diff --git a/packages/transport-grpc/src/send-execute-script.test.js b/packages/transport-grpc/src/send-execute-script.test.js index 9c6831777..fc66f3335 100644 --- a/packages/transport-grpc/src/send-execute-script.test.js +++ b/packages/transport-grpc/src/send-execute-script.test.js @@ -8,39 +8,35 @@ import {resolve} from "../../sdk/src/resolve/resolve.js" import {response as responseADT} from "../../sdk/src/response/response.js" import {Buffer} from "@onflow/rlp" -const jsonToUInt8Array = (json) => { - var str = JSON.stringify(json, null, 0); - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; +const jsonToUInt8Array = json => { + var str = JSON.stringify(json, null, 0) + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} describe("Send Execute Script", () => { test("ExecuteScriptAtLatestBlock", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const returnedJSONCDC = {type: "Int", value: 123} unaryMock.mockReturnValue({ - getValue_asU8: () => jsonToUInt8Array(returnedJSONCDC) - }); + getValue_asU8: () => jsonToUInt8Array(returnedJSONCDC), + }) let response = await sendExecuteScript( - await resolve( - await build([ - script`pub fun main(): Int { return 123 }` - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([script`pub fun main(): Int { return 123 }`])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -62,29 +58,29 @@ describe("Send Execute Script", () => { }) test("ExecuteScriptAtBlockID", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const returnedJSONCDC = {type: "Int", value: 123} unaryMock.mockReturnValue({ - getValue_asU8: () => jsonToUInt8Array(returnedJSONCDC) - }); + getValue_asU8: () => jsonToUInt8Array(returnedJSONCDC), + }) const response = await sendExecuteScript( - await resolve( - await build([ - script`pub fun main(): Int { return 123 }`, - atBlockId("abc123") - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve( + await build([ + script`pub fun main(): Int { return 123 }`, + atBlockId("abc123"), + ]) + ), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -108,29 +104,29 @@ describe("Send Execute Script", () => { }) test("ExecuteScriptAtBlockHeight", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const returnedJSONCDC = {type: "Int", value: 123} unaryMock.mockReturnValue({ - getValue_asU8: () => jsonToUInt8Array(returnedJSONCDC) - }); + getValue_asU8: () => jsonToUInt8Array(returnedJSONCDC), + }) const response = await sendExecuteScript( - await resolve( - await build([ - script`pub fun main(): Int { return 123 }`, - atBlockHeight(123) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve( + await build([ + script`pub fun main(): Int { return 123 }`, + atBlockHeight(123), + ]) + ), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -152,5 +148,4 @@ describe("Send Execute Script", () => { expect(response.encodedData).toEqual(returnedJSONCDC) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-grpc/src/send-get-account.js b/packages/transport-grpc/src/send-get-account.js index b63f13baa..b00273ac7 100644 --- a/packages/transport-grpc/src/send-get-account.js +++ b/packages/transport-grpc/src/send-get-account.js @@ -1,5 +1,9 @@ import {invariant} from "@onflow/util-invariant" -import {GetAccountAtLatestBlockRequest, GetAccountAtBlockHeightRequest, AccessAPI} from "@onflow/protobuf" +import { + GetAccountAtLatestBlockRequest, + GetAccountAtBlockHeightRequest, + AccessAPI, +} from "@onflow/protobuf" import {sansPrefix, withPrefix} from "@onflow/util-address" import {unary as defaultUnary} from "./unary" @@ -30,7 +34,12 @@ async function sendGetAccountAtBlockHeightRequest(ix, context, opts) { req.setBlockHeight(Number(ix.block.height)) req.setAddress(addressBuffer(sansPrefix(ix.account.addr), context)) - const res = await unary(opts.node, AccessAPI.GetAccountAtBlockHeight, req, context) + const res = await unary( + opts.node, + AccessAPI.GetAccountAtBlockHeight, + req, + context + ) return constructResponse(ix, context, res) } @@ -41,7 +50,12 @@ async function sendGetAccountAtLatestBlockRequest(ix, context, opts) { const req = new GetAccountAtLatestBlockRequest() req.setAddress(addressBuffer(sansPrefix(ix.account.addr), context)) - const res = await unary(opts.node, AccessAPI.GetAccountAtLatestBlock, req, context) + const res = await unary( + opts.node, + AccessAPI.GetAccountAtLatestBlock, + req, + context + ) return constructResponse(ix, context, res) } @@ -52,16 +66,25 @@ function constructResponse(ix, context, res) { const account = res.getAccount() - let contractsMap; - const contracts = (contractsMap = account.getContractsMap()) ? contractsMap.getEntryList().reduce((acc, contract) => ({ - ...acc, - [contract[0]]: context.Buffer.from(contract[1] || new UInt8Array()).toString("utf8") - }), {}) : {} + let contractsMap + const contracts = (contractsMap = account.getContractsMap()) + ? contractsMap.getEntryList().reduce( + (acc, contract) => ({ + ...acc, + [contract[0]]: context.Buffer.from( + contract[1] || new UInt8Array() + ).toString("utf8"), + }), + {} + ) + : {} ret.account = { address: withPrefix(u8ToHex(account.getAddress_asU8(), context)), balance: account.getBalance(), - code: context.Buffer.from(account.getCode_asU8() || new UInt8Array()).toString("utf8"), + code: context.Buffer.from( + account.getCode_asU8() || new UInt8Array() + ).toString("utf8"), contracts, keys: account.getKeysList().map(publicKey => ({ index: publicKey.getIndex(), @@ -79,11 +102,16 @@ function constructResponse(ix, context, res) { return ret } - export async function sendGetAccount(ix, context = {}, opts = {}) { invariant(opts.node, `SDK Send Get Account Error: opts.node must be defined.`) - invariant(context.response, `SDK Get Account Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Get Account Error: context.Buffer must be defined.`) + invariant( + context.response, + `SDK Get Account Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Get Account Error: context.Buffer must be defined.` + ) ix = await ix diff --git a/packages/transport-grpc/src/send-get-account.test.js b/packages/transport-grpc/src/send-get-account.test.js index a55138371..4541d424f 100644 --- a/packages/transport-grpc/src/send-get-account.test.js +++ b/packages/transport-grpc/src/send-get-account.test.js @@ -7,66 +7,63 @@ import {resolve} from "../../sdk/src/resolve/resolve.js" import {response as responseADT} from "../../sdk/src/response/response.js" import {Buffer} from "@onflow/rlp" -const jsonToUInt8Array = (json) => { - var str = JSON.stringify(json, null, 0); - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; - -const hexStrToUInt8Array = (hex) => { - return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); -}; - -const strToUInt8Array = (str) => { - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; +const jsonToUInt8Array = json => { + var str = JSON.stringify(json, null, 0) + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} + +const hexStrToUInt8Array = hex => { + return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))) +} + +const strToUInt8Array = str => { + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} describe("Send Get Account", () => { test("GetAccountAtBlockHeightRequest", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const returnedAccount = { - address: "0x1654653399040a61", - code: "contract", - keys: [], - balance: 10, - contracts: {} + address: "0x1654653399040a61", + code: "contract", + keys: [], + balance: 10, + contracts: {}, } unaryMock.mockReturnValue({ - getAccount: () => ({ - getAddress_asU8: () => hexStrToUInt8Array("1654653399040a61"), - getCode_asU8: () => strToUInt8Array("contract"), - getKeysList: () => [], - getBalance: () => 10, - getContractsMap: () => ({ - getEntryList: () => [] - }), - }) - }); + getAccount: () => ({ + getAddress_asU8: () => hexStrToUInt8Array("1654653399040a61"), + getCode_asU8: () => strToUInt8Array("contract"), + getKeysList: () => [], + getBalance: () => 10, + getContractsMap: () => ({ + getEntryList: () => [], + }), + }), + }) const response = await sendGetAccount( - await resolve( - await build([ - getAccount("0x1654653399040a61"), - atBlockHeight(123) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve( + await build([getAccount("0x1654653399040a61"), atBlockHeight(123)]) + ), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -90,42 +87,38 @@ describe("Send Get Account", () => { }) test("GetAccountAtLatestBlockRequest", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const returnedAccount = { - address: "0x1654653399040a61", - code: "contract", - keys: [], - balance: 10, - contracts: {} + address: "0x1654653399040a61", + code: "contract", + keys: [], + balance: 10, + contracts: {}, } unaryMock.mockReturnValue({ - getAccount: () => ({ - getAddress_asU8: () => hexStrToUInt8Array("1654653399040a61"), - getCode_asU8: () => strToUInt8Array("contract"), - getKeysList: () => [], - getBalance: () => 10, - getContractsMap: () => ({ - getEntryList: () => [] - }), - }) - }); + getAccount: () => ({ + getAddress_asU8: () => hexStrToUInt8Array("1654653399040a61"), + getCode_asU8: () => strToUInt8Array("contract"), + getKeysList: () => [], + getBalance: () => 10, + getContractsMap: () => ({ + getEntryList: () => [], + }), + }), + }) const response = await sendGetAccount( - await resolve( - await build([ - getAccount("0x1654653399040a61") - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getAccount("0x1654653399040a61")])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -145,5 +138,4 @@ describe("Send Get Account", () => { expect(response.account).toEqual(returnedAccount) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-grpc/src/send-get-block-header.js b/packages/transport-grpc/src/send-get-block-header.js index 1b4609c08..964907284 100644 --- a/packages/transport-grpc/src/send-get-block-header.js +++ b/packages/transport-grpc/src/send-get-block-header.js @@ -1,5 +1,10 @@ import {invariant} from "@onflow/util-invariant" -import {GetLatestBlockHeaderRequest, GetBlockHeaderByIDRequest, GetBlockHeaderByHeightRequest, AccessAPI} from "@onflow/protobuf" +import { + GetLatestBlockHeaderRequest, + GetBlockHeaderByIDRequest, + GetBlockHeaderByHeightRequest, + AccessAPI, +} from "@onflow/protobuf" import {unary as defaultUnary} from "./unary" const u8ToHex = (u8, context) => context.Buffer.from(u8).toString("hex") @@ -22,7 +27,12 @@ async function sendGetBlockHeaderByHeightRequest(ix, context, opts) { const req = new GetBlockHeaderByHeightRequest() req.setHeight(Number(ix.block.height)) - const res = await unary(opts.node, AccessAPI.GetBlockHeaderByHeight, req, context) + const res = await unary( + opts.node, + AccessAPI.GetBlockHeaderByHeight, + req, + context + ) return constructResponse(ix, context, res) } @@ -36,7 +46,12 @@ async function sendGetLatestBlockHeaderRequest(ix, context, opts) { req.setIsSealed(ix.block.isSealed) } - const res = await unary(opts.node, AccessAPI.GetLatestBlockHeader, req, context) + const res = await unary( + opts.node, + AccessAPI.GetLatestBlockHeader, + req, + context + ) return constructResponse(ix, context, res) } @@ -57,9 +72,18 @@ function constructResponse(ix, context, res) { } export async function sendGetBlockHeader(ix, context = {}, opts = {}) { - invariant(opts.node, `SDK Send Get Block Header Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Block Header Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Get Block Header Error: context.Buffer must be defined.`) + invariant( + opts.node, + `SDK Send Get Block Header Error: opts.node must be defined.` + ) + invariant( + context.response, + `SDK Send Get Block Header Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Get Block Header Error: context.Buffer must be defined.` + ) ix = await ix diff --git a/packages/transport-grpc/src/send-get-block-header.test.js b/packages/transport-grpc/src/send-get-block-header.test.js index 329dd04ad..303548a6f 100644 --- a/packages/transport-grpc/src/send-get-block-header.test.js +++ b/packages/transport-grpc/src/send-get-block-header.test.js @@ -8,66 +8,61 @@ import {resolve} from "../../sdk/src/resolve/resolve.js" import {response as responseADT} from "../../sdk/src/response/response.js" import {Buffer} from "@onflow/rlp" -const jsonToUInt8Array = (json) => { - var str = JSON.stringify(json, null, 0); - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; - -const hexStrToUInt8Array = (hex) => { - return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); -}; - -const strToUInt8Array = (str) => { - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; +const jsonToUInt8Array = json => { + var str = JSON.stringify(json, null, 0) + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} + +const hexStrToUInt8Array = hex => { + return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))) +} + +const strToUInt8Array = str => { + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} describe("Send Get Block Header", () => { test("GetBlockHeaderByID", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const dateNow = new Date(Date.now()) const returnedBlockHeader = { - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), } unaryMock.mockReturnValue({ - getBlock: () => ({ - getId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getHeight: () => 123, - getTimestamp: () => ({ - toDate: () => dateNow - }) - }) - }); + getBlock: () => ({ + getId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getHeight: () => 123, + getTimestamp: () => ({ + toDate: () => dateNow, + }), + }), + }) const response = await sendGetBlockHeader( - await resolve( - await build([ - getBlockHeader(), - atBlockId("a1b2c3") - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getBlockHeader(), atBlockId("a1b2c3")])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -89,43 +84,38 @@ describe("Send Get Block Header", () => { }) test("GetBlockHeaderByHeight", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const dateNow = new Date(Date.now()) const returnedBlockHeader = { - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), } unaryMock.mockReturnValue({ - getBlock: () => ({ - getId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getHeight: () => 123, - getTimestamp: () => ({ - toDate: () => dateNow - }) - }) - }); + getBlock: () => ({ + getId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getHeight: () => 123, + getTimestamp: () => ({ + toDate: () => dateNow, + }), + }), + }) const response = await sendGetBlockHeader( - await resolve( - await build([ - getBlockHeader(), - atBlockHeight(123) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getBlockHeader(), atBlockHeight(123)])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -147,42 +137,38 @@ describe("Send Get Block Header", () => { }) test("GetLatestBlockHeader - isSealed = false", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const dateNow = new Date(Date.now()) const returnedBlockHeader = { - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), } unaryMock.mockReturnValue({ - getBlock: () => ({ - getId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getHeight: () => 123, - getTimestamp: () => ({ - toDate: () => dateNow - }) - }) - }); + getBlock: () => ({ + getId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getHeight: () => 123, + getTimestamp: () => ({ + toDate: () => dateNow, + }), + }), + }) const response = await sendGetBlockHeader( - await resolve( - await build([ - getBlockHeader() - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getBlockHeader()])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -204,42 +190,38 @@ describe("Send Get Block Header", () => { }) test("GetLatestBlockHeader - isSealed = true", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const dateNow = new Date(Date.now()) const returnedBlockHeader = { - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), } unaryMock.mockReturnValue({ - getBlock: () => ({ - getId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getHeight: () => 123, - getTimestamp: () => ({ - toDate: () => dateNow - }) - }) - }); + getBlock: () => ({ + getId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getHeight: () => 123, + getTimestamp: () => ({ + toDate: () => dateNow, + }), + }), + }) const response = await sendGetBlockHeader( - await resolve( - await build([ - getBlockHeader(true) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getBlockHeader(true)])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -259,5 +241,4 @@ describe("Send Get Block Header", () => { expect(response.blockHeader).toEqual(returnedBlockHeader) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-grpc/src/send-get-block.js b/packages/transport-grpc/src/send-get-block.js index 2fc5f42fa..7546f33e1 100644 --- a/packages/transport-grpc/src/send-get-block.js +++ b/packages/transport-grpc/src/send-get-block.js @@ -1,5 +1,10 @@ import {invariant} from "@onflow/util-invariant" -import {GetBlockByIDRequest, GetBlockByHeightRequest, GetLatestBlockRequest, AccessAPI} from "@onflow/protobuf" +import { + GetBlockByIDRequest, + GetBlockByHeightRequest, + GetLatestBlockRequest, + AccessAPI, +} from "@onflow/protobuf" import {unary as defaultUnary} from "./unary" const u8ToHex = (u8, context) => context.Buffer.from(u8).toString("hex") @@ -21,7 +26,7 @@ async function sendGetBlockByHeightRequest(ix, context, opts) { const req = new GetBlockByHeightRequest() req.setHeight(Number(ix.block.height)) - + const res = await unary(opts.node, AccessAPI.GetBlockByHeight, req, context) return constructResponse(ix, context, res) @@ -55,12 +60,18 @@ function constructResponse(ix, context, res) { height: block.getHeight(), timestamp: block.getTimestamp().toDate().toISOString(), collectionGuarantees: collectionGuarantees.map(collectionGuarantee => ({ - collectionId: u8ToHex(collectionGuarantee.getCollectionId_asU8(), context), + collectionId: u8ToHex( + collectionGuarantee.getCollectionId_asU8(), + context + ), })), blockSeals: blockSeals.map(blockSeal => ({ blockId: u8ToHex(blockSeal.getBlockId_asU8(), context), - executionReceiptId: u8ToHex(blockSeal.getExecutionReceiptId_asU8(), context), - })) + executionReceiptId: u8ToHex( + blockSeal.getExecutionReceiptId_asU8(), + context + ), + })), } return ret @@ -68,8 +79,14 @@ function constructResponse(ix, context, res) { export async function sendGetBlock(ix, context = {}, opts = {}) { invariant(opts.node, `SDK Send Get Block Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Block Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Get Block Error: context.Buffer must be defined.`) + invariant( + context.response, + `SDK Send Get Block Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Get Block Error: context.Buffer must be defined.` + ) ix = await ix diff --git a/packages/transport-grpc/src/send-get-block.test.js b/packages/transport-grpc/src/send-get-block.test.js index 251c2aa5b..ef4532646 100644 --- a/packages/transport-grpc/src/send-get-block.test.js +++ b/packages/transport-grpc/src/send-get-block.test.js @@ -8,73 +8,68 @@ import {resolve} from "../../sdk/src/resolve/resolve.js" import {response as responseADT} from "../../sdk/src/response/response.js" import {Buffer} from "@onflow/rlp" -const jsonToUInt8Array = (json) => { - var str = JSON.stringify(json, null, 0); - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; - -const hexStrToUInt8Array = (hex) => { - return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); -}; - -const strToUInt8Array = (str) => { - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; +const jsonToUInt8Array = json => { + var str = JSON.stringify(json, null, 0) + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} + +const hexStrToUInt8Array = hex => { + return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))) +} + +const strToUInt8Array = str => { + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} describe("Send Get Block", () => { test("GetBlockByID", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const dateNow = new Date(Date.now()) const returnedBlock = { - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), - collectionGuarantees: [], - blockSeals: [] + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), + collectionGuarantees: [], + blockSeals: [], } unaryMock.mockReturnValue({ - getBlock: () => ({ - getId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getHeight: () => 123, - getTimestamp: () => ({ - toDate: () => ({ - toISOString: () => dateNow.toISOString() - }) - }), - getCollectionGuaranteesList: () => [], - getBlockSealsList: () => [], - getSignaturesList: () => [] - }) - }); + getBlock: () => ({ + getId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getHeight: () => 123, + getTimestamp: () => ({ + toDate: () => ({ + toISOString: () => dateNow.toISOString(), + }), + }), + getCollectionGuaranteesList: () => [], + getBlockSealsList: () => [], + getSignaturesList: () => [], + }), + }) const response = await sendGetBlock( - await resolve( - await build([ - getBlock(), - atBlockId("a1b2c3") - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getBlock(), atBlockId("a1b2c3")])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -96,50 +91,45 @@ describe("Send Get Block", () => { }) test("GetBlockByHeight", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const dateNow = new Date(Date.now()) const returnedBlock = { - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), - collectionGuarantees: [], - blockSeals: [] + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), + collectionGuarantees: [], + blockSeals: [], } unaryMock.mockReturnValue({ - getBlock: () => ({ - getId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getHeight: () => 123, - getTimestamp: () => ({ - toDate: () => ({ - toISOString: () => dateNow.toISOString() - }) - }), - getCollectionGuaranteesList: () => [], - getBlockSealsList: () => [], - getSignaturesList: () => [] - }) - }); + getBlock: () => ({ + getId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getHeight: () => 123, + getTimestamp: () => ({ + toDate: () => ({ + toISOString: () => dateNow.toISOString(), + }), + }), + getCollectionGuaranteesList: () => [], + getBlockSealsList: () => [], + getSignaturesList: () => [], + }), + }) const response = await sendGetBlock( - await resolve( - await build([ - getBlock(), - atBlockHeight(123) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getBlock(), atBlockHeight(123)])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -161,49 +151,45 @@ describe("Send Get Block", () => { }) test("GetLatestBlock - isSealed = false", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const dateNow = new Date(Date.now()) const returnedBlock = { - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), - collectionGuarantees: [], - blockSeals: [] + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), + collectionGuarantees: [], + blockSeals: [], } unaryMock.mockReturnValue({ - getBlock: () => ({ - getId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getHeight: () => 123, - getTimestamp: () => ({ - toDate: () => ({ - toISOString: () => dateNow.toISOString() - }) - }), - getCollectionGuaranteesList: () => [], - getBlockSealsList: () => [], - getSignaturesList: () => [] - }) - }); + getBlock: () => ({ + getId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getHeight: () => 123, + getTimestamp: () => ({ + toDate: () => ({ + toISOString: () => dateNow.toISOString(), + }), + }), + getCollectionGuaranteesList: () => [], + getBlockSealsList: () => [], + getSignaturesList: () => [], + }), + }) const response = await sendGetBlock( - await resolve( - await build([ - getBlock() - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getBlock()])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -225,49 +211,45 @@ describe("Send Get Block", () => { }) test("GetLatestBlock - isSealed = true", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const dateNow = new Date(Date.now()) const returnedBlock = { - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), - collectionGuarantees: [], - blockSeals: [] + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), + collectionGuarantees: [], + blockSeals: [], } unaryMock.mockReturnValue({ - getBlock: () => ({ - getId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getHeight: () => 123, - getTimestamp: () => ({ - toDate: () => ({ - toISOString: () => dateNow.toISOString() - }) - }), - getCollectionGuaranteesList: () => [], - getBlockSealsList: () => [], - getSignaturesList: () => [] - }) - }); + getBlock: () => ({ + getId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getParentId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getHeight: () => 123, + getTimestamp: () => ({ + toDate: () => ({ + toISOString: () => dateNow.toISOString(), + }), + }), + getCollectionGuaranteesList: () => [], + getBlockSealsList: () => [], + getSignaturesList: () => [], + }), + }) const response = await sendGetBlock( - await resolve( - await build([ - getBlock(true) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getBlock(true)])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -287,5 +269,4 @@ describe("Send Get Block", () => { expect(response.block).toEqual(returnedBlock) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-grpc/src/send-get-collection.js b/packages/transport-grpc/src/send-get-collection.js index 68787388d..b0e6aa0ad 100644 --- a/packages/transport-grpc/src/send-get-collection.js +++ b/packages/transport-grpc/src/send-get-collection.js @@ -6,9 +6,18 @@ const u8ToHex = (u8, context) => context.Buffer.from(u8).toString("hex") const hexBuffer = (hex, context) => context.Buffer.from(hex, "hex") export async function sendGetCollection(ix, context = {}, opts = {}) { - invariant(opts.node, `SDK Send Get Collection Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Collection Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Get Collection Error: context.Buffer must be defined.`) + invariant( + opts.node, + `SDK Send Get Collection Error: opts.node must be defined.` + ) + invariant( + context.response, + `SDK Send Get Collection Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Get Collection Error: context.Buffer must be defined.` + ) const unary = opts.unary || defaultUnary @@ -25,7 +34,9 @@ export async function sendGetCollection(ix, context = {}, opts = {}) { ret.tag = ix.tag ret.collection = { id: u8ToHex(collection.getId_asU8(), context), - transactionIds: (collection.getTransactionIdsList()).map(x => u8ToHex(x, context)) + transactionIds: collection + .getTransactionIdsList() + .map(x => u8ToHex(x, context)), } return ret diff --git a/packages/transport-grpc/src/send-get-collection.test.js b/packages/transport-grpc/src/send-get-collection.test.js index e608da48c..0268a731d 100644 --- a/packages/transport-grpc/src/send-get-collection.test.js +++ b/packages/transport-grpc/src/send-get-collection.test.js @@ -6,60 +6,53 @@ import {resolve} from "../../sdk/src/resolve/resolve.js" import {response as responseADT} from "../../sdk/src/response/response.js" import {Buffer} from "@onflow/rlp" -const jsonToUInt8Array = (json) => { - var str = JSON.stringify(json, null, 0); - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; - -const hexStrToUInt8Array = (hex) => { - return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); -}; - -const strToUInt8Array = (str) => { - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; - +const jsonToUInt8Array = json => { + var str = JSON.stringify(json, null, 0) + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} + +const hexStrToUInt8Array = hex => { + return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))) +} + +const strToUInt8Array = str => { + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} describe("Send Get Collection", () => { test("GetCollection", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const returnedCollection = { - id: "a1b2c3", - transactionIds: ["a1b2c3"] + id: "a1b2c3", + transactionIds: ["a1b2c3"], } unaryMock.mockReturnValue({ - getCollection: () => ({ - getId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getTransactionIdsList: () => ([ - hexStrToUInt8Array("a1b2c3") - ]), - }) - }); + getCollection: () => ({ + getId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getTransactionIdsList: () => [hexStrToUInt8Array("a1b2c3")], + }), + }) const response = await sendGetCollection( - await resolve( - await build([ - getCollection("a1b2c3"), - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getCollection("a1b2c3")])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -78,7 +71,8 @@ describe("Send Get Collection", () => { expect(unaryMockCollectionId).not.toBeUndefined() expect(response.collection.id).toBe(returnedCollection.id) - expect(response.collection.transactionIds[0]).toBe(returnedCollection.transactionIds[0]) + expect(response.collection.transactionIds[0]).toBe( + returnedCollection.transactionIds[0] + ) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-grpc/src/send-get-events.js b/packages/transport-grpc/src/send-get-events.js index f8b5fd062..66c6667fd 100644 --- a/packages/transport-grpc/src/send-get-events.js +++ b/packages/transport-grpc/src/send-get-events.js @@ -1,5 +1,9 @@ import {invariant} from "@onflow/util-invariant" -import {GetEventsForHeightRangeRequest, GetEventsForBlockIDsRequest, AccessAPI} from "@onflow/protobuf" +import { + GetEventsForHeightRangeRequest, + GetEventsForBlockIDsRequest, + AccessAPI, +} from "@onflow/protobuf" import {unary as defaultUnary} from "./unary" const u8ToHex = (u8, context) => context.Buffer.from(u8).toString("hex") @@ -14,7 +18,12 @@ async function sendGetEventsForHeightRangeRequest(ix, context, opts) { req.setStartHeight(Number(ix.events.start)) req.setEndHeight(Number(ix.events.end)) - const res = await unary(opts.node, AccessAPI.GetEventsForHeightRange, req, context) + const res = await unary( + opts.node, + AccessAPI.GetEventsForHeightRange, + req, + context + ) return constructResponse(ix, context, res) } @@ -25,11 +34,14 @@ async function sendGetEventsForBlockIDsRequest(ix, context, opts) { const req = new GetEventsForBlockIDsRequest() req.setType(ix.events.eventType) - ix.events.blockIds.forEach(id => - req.addBlockIds(hexBuffer(id, context)) - ) + ix.events.blockIds.forEach(id => req.addBlockIds(hexBuffer(id, context))) - const res = await unary(opts.node, AccessAPI.GetEventsForBlockIDs, req, context) + const res = await unary( + opts.node, + AccessAPI.GetEventsForBlockIDs, + req, + context + ) return constructResponse(ix, context, res) } @@ -53,7 +65,9 @@ function constructResponse(ix, context, res) { transactionId: u8ToHex(event.getTransactionId_asU8(), context), transactionIndex: event.getTransactionIndex(), eventIndex: event.getEventIndex(), - payload: JSON.parse(context.Buffer.from(event.getPayload_asU8()).toString("utf8")), + payload: JSON.parse( + context.Buffer.from(event.getPayload_asU8()).toString("utf8") + ), }) }) return blocks @@ -62,21 +76,28 @@ function constructResponse(ix, context, res) { return ret } -export async function sendGetEvents(ix, context = {}, opts = {}) { +export async function sendGetEvents(ix, context = {}, opts = {}) { invariant(opts.node, `SDK Send Get Events Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Events Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Get Events Error: context.Buffer must be defined.`) + invariant( + context.response, + `SDK Send Get Events Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Get Events Error: context.Buffer must be defined.` + ) ix = await ix - const interactionContainsBlockHeightRange = ix.events.start !== null - const interactionContainsBlockIDsList = Array.isArray(ix.events.blockIds) && ix.events.blockIds.length > 0 - + const interactionContainsBlockHeightRange = ix.events.start !== null + const interactionContainsBlockIDsList = + Array.isArray(ix.events.blockIds) && ix.events.blockIds.length > 0 + invariant( interactionContainsBlockHeightRange || interactionContainsBlockIDsList, "SendGetEventsError: Unable to determine which get events request to send. Either a block height range, or block IDs must be specified." ) - + if (interactionContainsBlockHeightRange) { return await sendGetEventsForHeightRangeRequest(ix, context, opts) } else { diff --git a/packages/transport-grpc/src/send-get-events.test.js b/packages/transport-grpc/src/send-get-events.test.js index c305f34ba..06577626a 100644 --- a/packages/transport-grpc/src/send-get-events.test.js +++ b/packages/transport-grpc/src/send-get-events.test.js @@ -8,83 +8,80 @@ import {resolve} from "../../sdk/src/resolve/resolve.js" import {response as responseADT} from "../../sdk/src/response/response.js" import {Buffer} from "@onflow/rlp" -const jsonToUInt8Array = (json) => { - var str = JSON.stringify(json, null, 0); - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; - -const hexStrToUInt8Array = (hex) => { - return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); -}; - -const strToUInt8Array = (str) => { - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; +const jsonToUInt8Array = json => { + var str = JSON.stringify(json, null, 0) + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} + +const hexStrToUInt8Array = hex => { + return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))) +} + +const strToUInt8Array = str => { + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} describe("Send Get Events", () => { test("GetEventsForBlockIDs", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const dateNow = new Date(Date.now()) const returnedEvents = [ - { - blockId: "a1b2c3", - blockHeight: 123, - blockTimestamp: dateNow.toISOString(), - type: "MyEvent", - transactionId: "a1b2c3", - transactionIndex: 123, - eventIndex: 456, - payload: {type: "String", value: "Hello, Flow"} - } - ] + { + blockId: "a1b2c3", + blockHeight: 123, + blockTimestamp: dateNow.toISOString(), + type: "MyEvent", + transactionId: "a1b2c3", + transactionIndex: 123, + eventIndex: 456, + payload: {type: "String", value: "Hello, Flow"}, + }, + ] unaryMock.mockReturnValue({ - getResultsList: () => [ + getResultsList: () => [ + { + getBlockId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getBlockHeight: () => 123, + getBlockTimestamp: () => ({ + toDate: () => ({ + toISOString: () => dateNow.toISOString(), + }), + }), + getEventsList: () => [ { - getBlockId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getBlockHeight: () => 123, - getBlockTimestamp: () => ({ - toDate: () => ({ - toISOString: () => dateNow.toISOString(), - }) - }), - getEventsList: () => ([ - { - getType: () => "MyEvent", - getTransactionId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getTransactionIndex: () => 123, - getEventIndex: () => 456, - getPayload_asU8: () => jsonToUInt8Array({type: "String", value: "Hello, Flow"}), - } - ]) - } - ] - }); + getType: () => "MyEvent", + getTransactionId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getTransactionIndex: () => 123, + getEventIndex: () => 456, + getPayload_asU8: () => + jsonToUInt8Array({type: "String", value: "Hello, Flow"}), + }, + ], + }, + ], + }) const response = await sendGetEvents( - await resolve( - await build([ - getEventsAtBlockIds("MyEvent", ["a1b2c3"]), - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getEventsAtBlockIds("MyEvent", ["a1b2c3"])])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -109,60 +106,59 @@ describe("Send Get Events", () => { }) test("GetEventsForHeightRange", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const dateNow = new Date(Date.now()) const returnedEvents = [ - { - blockId: "a1b2c3", - blockHeight: 123, - blockTimestamp: dateNow.toISOString(), - type: "MyEvent", - transactionId: "a1b2c3", - transactionIndex: 123, - eventIndex: 456, - payload: {type: "String", value: "Hello, Flow"} - } - ] + { + blockId: "a1b2c3", + blockHeight: 123, + blockTimestamp: dateNow.toISOString(), + type: "MyEvent", + transactionId: "a1b2c3", + transactionIndex: 123, + eventIndex: 456, + payload: {type: "String", value: "Hello, Flow"}, + }, + ] unaryMock.mockReturnValue({ - getResultsList: () => [ + getResultsList: () => [ + { + getBlockId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getBlockHeight: () => 123, + getBlockTimestamp: () => ({ + toDate: () => ({ + toISOString: () => dateNow.toISOString(), + }), + }), + getEventsList: () => [ { - getBlockId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getBlockHeight: () => 123, - getBlockTimestamp: () => ({ - toDate: () => ({ - toISOString: () => dateNow.toISOString(), - }) - }), - getEventsList: () => ([ - { - getType: () => "MyEvent", - getTransactionId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getTransactionIndex: () => 123, - getEventIndex: () => 456, - getPayload_asU8: () => jsonToUInt8Array({type: "String", value: "Hello, Flow"}), - } - ]) - } - ] - }); + getType: () => "MyEvent", + getTransactionId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getTransactionIndex: () => 123, + getEventIndex: () => 456, + getPayload_asU8: () => + jsonToUInt8Array({type: "String", value: "Hello, Flow"}), + }, + ], + }, + ], + }) const response = await sendGetEvents( - await resolve( - await build([ - getEventsAtBlockHeightRange("MyEvent", 123, 456), - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve( + await build([getEventsAtBlockHeightRange("MyEvent", 123, 456)]) + ), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -186,5 +182,4 @@ describe("Send Get Events", () => { expect(response.events[0]).toStrictEqual(returnedEvents[0]) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-grpc/src/send-get-transaction-status.js b/packages/transport-grpc/src/send-get-transaction-status.js index d79022442..e71e81b52 100644 --- a/packages/transport-grpc/src/send-get-transaction-status.js +++ b/packages/transport-grpc/src/send-get-transaction-status.js @@ -8,16 +8,25 @@ const STATUS_MAP = { 2: "FINALIZED", 3: "EXECUTED", 4: "SEALED", - 5: "EXPIRED" + 5: "EXPIRED", } const u8ToHex = (u8, context) => context.Buffer.from(u8).toString("hex") const hexBuffer = (hex, context) => context.Buffer.from(hex, "hex") export async function sendGetTransactionStatus(ix, context = {}, opts = {}) { - invariant(opts.node, `SDK Send Get Transaction Status Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Transaction Status Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Get Transaction Status Error: context.Buffer must be defined.`) + invariant( + opts.node, + `SDK Send Get Transaction Status Error: opts.node must be defined.` + ) + invariant( + context.response, + `SDK Send Get Transaction Status Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Get Transaction Status Error: context.Buffer must be defined.` + ) const unary = opts.unary || defaultUnary @@ -26,7 +35,12 @@ export async function sendGetTransactionStatus(ix, context = {}, opts = {}) { const req = new GetTransactionRequest() req.setId(hexBuffer(ix.transaction.id, context)) - const res = await unary(opts.node, AccessAPI.GetTransactionResult, req, context) + const res = await unary( + opts.node, + AccessAPI.GetTransactionResult, + req, + context + ) let events = res.getEventsList() @@ -43,7 +57,9 @@ export async function sendGetTransactionStatus(ix, context = {}, opts = {}) { transactionId: u8ToHex(event.getTransactionId_asU8(), context), transactionIndex: event.getTransactionIndex(), eventIndex: event.getEventIndex(), - payload: JSON.parse(context.Buffer.from(event.getPayload_asU8()).toString("utf8")), + payload: JSON.parse( + context.Buffer.from(event.getPayload_asU8()).toString("utf8") + ), })), } diff --git a/packages/transport-grpc/src/send-get-transaction-status.test.js b/packages/transport-grpc/src/send-get-transaction-status.test.js index 85c85b352..9648429fd 100644 --- a/packages/transport-grpc/src/send-get-transaction-status.test.js +++ b/packages/transport-grpc/src/send-get-transaction-status.test.js @@ -6,77 +6,74 @@ import {resolve} from "../../sdk/src/resolve/resolve.js" import {response as responseADT} from "../../sdk/src/response/response.js" import {Buffer} from "@onflow/rlp" -const jsonToUInt8Array = (json) => { - var str = JSON.stringify(json, null, 0); - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; - -const hexStrToUInt8Array = (hex) => { - return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); -}; - -const strToUInt8Array = (str) => { - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; +const jsonToUInt8Array = json => { + var str = JSON.stringify(json, null, 0) + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} + +const hexStrToUInt8Array = hex => { + return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))) +} + +const strToUInt8Array = str => { + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} describe("Get Transaction Status", () => { test("GetTransactionResult", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const returnedTransactionStatus = { - blockId: null, - status: 2, - statusString: "FINALIZED", - statusCode: 0, - errorMessage: "No Error", - events: [ - { - type: "MyEvent", - transactionId: "a1b2c3", - transactionIndex: 123, - eventIndex: 456, - payload: {type: "String", value: "Hello, Flow"} - } - ] + blockId: null, + status: 2, + statusString: "FINALIZED", + statusCode: 0, + errorMessage: "No Error", + events: [ + { + type: "MyEvent", + transactionId: "a1b2c3", + transactionIndex: 123, + eventIndex: 456, + payload: {type: "String", value: "Hello, Flow"}, + }, + ], } unaryMock.mockReturnValue({ - getStatus: () => 2, - getStatusCode: () => 0, - getErrorMessage: () => "No Error", - getEventsList: () => ([ - { - getType: () => "MyEvent", - getTransactionId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getTransactionIndex: () => 123, - getEventIndex: () => 456, - getPayload_asU8: () => jsonToUInt8Array({type: "String", value: "Hello, Flow"}), - } - ]) - }); - - const response = await sendGetTransactionStatus( - await resolve( - await build([ - getTransactionStatus("MyTxID"), - ]) - ), + getStatus: () => 2, + getStatusCode: () => 0, + getErrorMessage: () => "No Error", + getEventsList: () => [ { - response: responseADT, - Buffer, + getType: () => "MyEvent", + getTransactionId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getTransactionIndex: () => 123, + getEventIndex: () => 456, + getPayload_asU8: () => + jsonToUInt8Array({type: "String", value: "Hello, Flow"}), }, - { - unary: unaryMock, - node: "localhost:3000" - } + ], + }) + + const response = await sendGetTransactionStatus( + await resolve(await build([getTransactionStatus("MyTxID")])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -96,5 +93,4 @@ describe("Get Transaction Status", () => { expect(response.transactionStatus).toStrictEqual(returnedTransactionStatus) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-grpc/src/send-get-transaction.js b/packages/transport-grpc/src/send-get-transaction.js index e686b1c66..73e334c98 100644 --- a/packages/transport-grpc/src/send-get-transaction.js +++ b/packages/transport-grpc/src/send-get-transaction.js @@ -6,10 +6,19 @@ const u8ToHex = (u8, context) => context.Buffer.from(u8).toString("hex") const hexBuffer = (hex, context) => context.Buffer.from(hex, "hex") export async function sendGetTransaction(ix, context = {}, opts = {}) { - invariant(opts.node, `SDK Send Get Transaction Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Transaction Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Get Transaction Error: context.Buffer must be defined.`) - + invariant( + opts.node, + `SDK Send Get Transaction Error: opts.node must be defined.` + ) + invariant( + context.response, + `SDK Send Get Transaction Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Get Transaction Error: context.Buffer must be defined.` + ) + const unary = opts.unary || defaultUnary ix = await ix @@ -25,26 +34,32 @@ export async function sendGetTransaction(ix, context = {}, opts = {}) { const unwrapKey = key => ({ address: u8ToHex(key.getAddress_asU8(), context), keyId: key.getKeyId(), - sequenceNumber: key.getSequenceNumber() + sequenceNumber: key.getSequenceNumber(), }) const unwrapSignature = sig => ({ address: u8ToHex(sig.getAddress_asU8(), context), keyId: sig.getKeyId(), - signature: u8ToHex(sig.getSignature_asU8(), context) + signature: u8ToHex(sig.getSignature_asU8(), context), }) let transaction = res.getTransaction() ret.transaction = { - script: context.Buffer.from(transaction.getScript_asU8()).toString("utf8"), - args: (transaction.getArgumentsList()).map(arg => JSON.parse(context.Buffer.from(arg).toString("utf8"))), - referenceBlockId: u8ToHex(transaction.getReferenceBlockId_asU8(), context), - gasLimit: transaction.getGasLimit(), - proposalKey: unwrapKey(transaction.getProposalKey()), - payer: u8ToHex(transaction.getPayer_asU8(), context), - authorizers: (transaction.getAuthorizersList()).map(x => u8ToHex(x, context)), - payloadSignatures: (transaction.getPayloadSignaturesList()).map(unwrapSignature), - envelopeSignatures: (transaction.getEnvelopeSignaturesList()).map(unwrapSignature) + script: context.Buffer.from(transaction.getScript_asU8()).toString("utf8"), + args: transaction + .getArgumentsList() + .map(arg => JSON.parse(context.Buffer.from(arg).toString("utf8"))), + referenceBlockId: u8ToHex(transaction.getReferenceBlockId_asU8(), context), + gasLimit: transaction.getGasLimit(), + proposalKey: unwrapKey(transaction.getProposalKey()), + payer: u8ToHex(transaction.getPayer_asU8(), context), + authorizers: transaction.getAuthorizersList().map(x => u8ToHex(x, context)), + payloadSignatures: transaction + .getPayloadSignaturesList() + .map(unwrapSignature), + envelopeSignatures: transaction + .getEnvelopeSignaturesList() + .map(unwrapSignature), } return ret diff --git a/packages/transport-grpc/src/send-get-transaction.test.js b/packages/transport-grpc/src/send-get-transaction.test.js index 8b911a173..81ecf2747 100644 --- a/packages/transport-grpc/src/send-get-transaction.test.js +++ b/packages/transport-grpc/src/send-get-transaction.test.js @@ -6,80 +6,75 @@ import {resolve} from "../../sdk/src/resolve/resolve.js" import {response as responseADT} from "../../sdk/src/response/response.js" import {Buffer} from "@onflow/rlp" -const jsonToUInt8Array = (json) => { - var str = JSON.stringify(json, null, 0); - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; - -const hexStrToUInt8Array = (hex) => { - return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))); -}; - -const strToUInt8Array = (str) => { - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; - +const jsonToUInt8Array = json => { + var str = JSON.stringify(json, null, 0) + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} + +const hexStrToUInt8Array = hex => { + return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16))) +} + +const strToUInt8Array = str => { + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} describe("Get Transaction", () => { test("GetTransactionResult", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() const returnedTransaction = { - script: "Cadence Code", - args: [], - referenceBlockId: "a1b2c3", - gasLimit: 123, - proposalKey: { - address: "1654653399040a61", - keyId: 1, - sequenceNumber: 1 - }, - payer: "1654653399040a61", - authorizers: [], - payloadSignatures: [], - envelopeSignatures: [] + script: "Cadence Code", + args: [], + referenceBlockId: "a1b2c3", + gasLimit: 123, + proposalKey: { + address: "1654653399040a61", + keyId: 1, + sequenceNumber: 1, + }, + payer: "1654653399040a61", + authorizers: [], + payloadSignatures: [], + envelopeSignatures: [], } unaryMock.mockReturnValue({ - getTransaction: () => ({ - getScript_asU8: () => strToUInt8Array("Cadence Code"), - getArgumentsList: () => ([]), - getReferenceBlockId_asU8: () => hexStrToUInt8Array("a1b2c3"), - getGasLimit: () => 123, - getProposalKey: () => ({ - getAddress_asU8: () => hexStrToUInt8Array("1654653399040a61"), - getKeyId: () => 1, - getSequenceNumber: () => 1, - }), - getPayer_asU8: () => hexStrToUInt8Array("1654653399040a61"), - getAuthorizersList: () => ([]), - getPayloadSignaturesList: () => ([]), - getEnvelopeSignaturesList: () => ([]) - }) - }); + getTransaction: () => ({ + getScript_asU8: () => strToUInt8Array("Cadence Code"), + getArgumentsList: () => [], + getReferenceBlockId_asU8: () => hexStrToUInt8Array("a1b2c3"), + getGasLimit: () => 123, + getProposalKey: () => ({ + getAddress_asU8: () => hexStrToUInt8Array("1654653399040a61"), + getKeyId: () => 1, + getSequenceNumber: () => 1, + }), + getPayer_asU8: () => hexStrToUInt8Array("1654653399040a61"), + getAuthorizersList: () => [], + getPayloadSignaturesList: () => [], + getEnvelopeSignaturesList: () => [], + }), + }) const response = await sendGetTransaction( - await resolve( - await build([ - getTransaction("MyTxID"), - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([getTransaction("MyTxID")])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -99,5 +94,4 @@ describe("Get Transaction", () => { expect(response.transaction).toStrictEqual(returnedTransaction) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-grpc/src/send-grpc.js b/packages/transport-grpc/src/send-grpc.js index cb705b87b..404a137a3 100644 --- a/packages/transport-grpc/src/send-grpc.js +++ b/packages/transport-grpc/src/send-grpc.js @@ -11,7 +11,10 @@ import {sendGetCollection} from "./send-get-collection.js" import {sendPing} from "./send-ping.js" export const send = async (ix, context = {}, opts = {}) => { - invariant(opts.node, `SDK Send Error: Either opts.node or "accessNode.api" in config must be defined.`) + invariant( + opts.node, + `SDK Send Error: Either opts.node or "accessNode.api" in config must be defined.` + ) invariant(context.ix, `SDK Send Error: context.ix must be defined.`) ix = await ix diff --git a/packages/transport-grpc/src/send-ping.js b/packages/transport-grpc/src/send-ping.js index 0e51e3e46..7b16c9f60 100644 --- a/packages/transport-grpc/src/send-ping.js +++ b/packages/transport-grpc/src/send-ping.js @@ -4,7 +4,10 @@ import {unary as defaultUnary} from "./unary" export async function sendPing(ix, context = {}, opts = {}) { invariant(opts.node, `SDK Send Ping Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Ping Error: context.response must be defined.`) + invariant( + context.response, + `SDK Send Ping Error: context.response must be defined.` + ) const unary = opts.unary || defaultUnary diff --git a/packages/transport-grpc/src/send-ping.test.js b/packages/transport-grpc/src/send-ping.test.js index 9fad6713d..bd58abde0 100644 --- a/packages/transport-grpc/src/send-ping.test.js +++ b/packages/transport-grpc/src/send-ping.test.js @@ -6,35 +6,31 @@ import {resolve} from "../../sdk/src/resolve/resolve.js" import {response as responseADT} from "../../sdk/src/response/response.js" import {Buffer} from "@onflow/rlp" -const jsonToUInt8Array = (json) => { - var str = JSON.stringify(json, null, 0); - var ret = new Uint8Array(str.length); - for (var i = 0; i < str.length; i++) { - ret[i] = str.charCodeAt(i); - } - return ret -}; +const jsonToUInt8Array = json => { + var str = JSON.stringify(json, null, 0) + var ret = new Uint8Array(str.length) + for (var i = 0; i < str.length; i++) { + ret[i] = str.charCodeAt(i) + } + return ret +} describe("Ping", () => { test("Ping", async () => { - const unaryMock = jest.fn(); + const unaryMock = jest.fn() - unaryMock.mockReturnValue({}); + unaryMock.mockReturnValue({}) await sendPing( - await resolve( - await build([ - ping(), - ]) - ), - { - response: responseADT, - Buffer, - }, - { - unary: unaryMock, - node: "localhost:3000" - } + await resolve(await build([ping()])), + { + response: responseADT, + Buffer, + }, + { + unary: unaryMock, + node: "localhost:3000", + } ) expect(unaryMock.mock.calls.length).toEqual(1) @@ -51,5 +47,4 @@ describe("Ping", () => { expect(unaryMockRequest).not.toBeUndefined() }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-grpc/src/send-transaction.js b/packages/transport-grpc/src/send-transaction.js index 9d78d8a1e..439b28198 100644 --- a/packages/transport-grpc/src/send-transaction.js +++ b/packages/transport-grpc/src/send-transaction.js @@ -9,12 +9,19 @@ const paddedHexBuffer = (hex, pad, context) => const scriptBuffer = (script, context) => context.Buffer.from(script, "utf8") const hexBuffer = (hex, context) => context.Buffer.from(hex, "hex") const addressBuffer = (addr, context) => paddedHexBuffer(addr, 8, context) -const argumentBuffer = (arg, context) => context.Buffer.from(JSON.stringify(arg), "utf8") +const argumentBuffer = (arg, context) => + context.Buffer.from(JSON.stringify(arg), "utf8") export async function sendTransaction(ix, context = {}, opts = {}) { invariant(opts.node, `SDK Send Transaction Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Transaction Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Transaction Error: context.Buffer must be defined.`) + invariant( + context.response, + `SDK Send Transaction Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Transaction Error: context.Buffer must be defined.` + ) const unary = opts.unary || defaultUnary @@ -26,7 +33,14 @@ export async function sendTransaction(ix, context = {}, opts = {}) { tx.setReferenceBlockId( ix.message.refBlock ? hexBuffer(ix.message.refBlock, context) : null ) - tx.setPayer(addressBuffer(sansPrefix(ix.accounts[Array.isArray(ix.payer) ? ix.payer[0] : ix.payer].addr), context)) + tx.setPayer( + addressBuffer( + sansPrefix( + ix.accounts[Array.isArray(ix.payer) ? ix.payer[0] : ix.payer].addr + ), + context + ) + ) ix.message.arguments.forEach(arg => tx.addArguments(argumentBuffer(ix.arguments[arg].asArgument, context)) @@ -36,7 +50,9 @@ export async function sendTransaction(ix, context = {}, opts = {}) { .reduce((prev, current) => { return prev.find(item => item === current) ? prev : [...prev, current] }, []) - .forEach(addr => tx.addAuthorizers(addressBuffer(sansPrefix(addr), context))) + .forEach(addr => + tx.addAuthorizers(addressBuffer(sansPrefix(addr), context)) + ) const proposalKey = new Transaction.ProposalKey() proposalKey.setAddress( diff --git a/packages/transport-grpc/src/unary.js b/packages/transport-grpc/src/unary.js index b811a64b0..111cfa8c0 100644 --- a/packages/transport-grpc/src/unary.js +++ b/packages/transport-grpc/src/unary.js @@ -5,7 +5,10 @@ import {NodeHttpTransport} from "@improbable-eng/grpc-web-node-http-transport" grpc.setDefaultTransport(NodeHttpTransport()) export async function unary(host, method, request, context) { - invariant(context.config, `SDK GRPC Unary Error: context.config must be defined.`) + invariant( + context.config, + `SDK GRPC Unary Error: context.config must be defined.` + ) const metadataFromConfig = await context.config().get("grpc.metadata", {}) return new Promise((resolve, reject) => { grpc.unary(method, { diff --git a/packages/transport-http/package.json b/packages/transport-http/package.json index efa314b4d..e7101162b 100644 --- a/packages/transport-http/package.json +++ b/packages/transport-http/package.json @@ -1,45 +1,45 @@ { - "name": "@onflow/transport-http", - "version": "1.2.0", - "description": "Flow SDK HTTP Transport Module", - "license": "Apache-2.0", - "author": "Dapper Labs ", - "homepage": "https://onflow.org", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/onflow/flow-js-sdk.git" - }, - "bugs": { - "url": "https://github.com/onflow/flow-js-sdk/issues" - }, - "jest": { - "transform": { - ".js": "jest-esm-transformer" - } - }, - "devDependencies": { - "@onflow/rlp": "^1.0.1", - "@onflow/types": "^1.0.1", - "jest": "^27.0.6", - "jest-esm-transformer": "1.0.0", - "microbundle": "^0.13.3" - }, - "source": "src/sdk-send-http.js", - "main": "dist/sdk-send-http.js", - "module": "dist/sdk-send-http.module.js", - "unpkg": "dist/sdk-send-http.umd.js", - "scripts": { - "alpha": "npm publish --tag alpha", - "prepublishOnly": "npm test && npm run build", - "test": "jest", - "build": "microbundle --no-compress", - "test:watch": "jest --watch", - "start": "microbundle watch --no-compress" - }, - "dependencies": { - "@onflow/util-address": "^1.0.1", - "@onflow/util-invariant": "^1.0.1", - "@onflow/util-template": "^1.0.1", - "@onflow/util-node-http-modules": "^1.0.2" + "name": "@onflow/transport-http", + "version": "1.2.0", + "description": "Flow SDK HTTP Transport Module", + "license": "Apache-2.0", + "author": "Dapper Labs ", + "homepage": "https://onflow.org", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/onflow/flow-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/onflow/flow-js-sdk/issues" + }, + "jest": { + "transform": { + ".js": "jest-esm-transformer" } + }, + "devDependencies": { + "@onflow/rlp": "^1.0.1", + "@onflow/types": "^1.0.1", + "jest": "^27.0.6", + "jest-esm-transformer": "1.0.0", + "microbundle": "^0.13.3" + }, + "source": "src/sdk-send-http.js", + "main": "dist/sdk-send-http.js", + "module": "dist/sdk-send-http.module.js", + "unpkg": "dist/sdk-send-http.umd.js", + "scripts": { + "alpha": "npm publish --tag alpha", + "prepublishOnly": "npm test && npm run build", + "test": "jest", + "build": "microbundle --no-compress", + "test:watch": "jest --watch", + "start": "microbundle watch --no-compress" + }, + "dependencies": { + "@onflow/util-address": "^1.0.1", + "@onflow/util-invariant": "^1.0.1", + "@onflow/util-template": "^1.0.1", + "@onflow/util-node-http-modules": "^1.0.2" + } } diff --git a/packages/transport-http/src/sdk-send-http.js b/packages/transport-http/src/sdk-send-http.js index ab90a4a73..ab7f94861 100644 --- a/packages/transport-http/src/sdk-send-http.js +++ b/packages/transport-http/src/sdk-send-http.js @@ -8,4 +8,4 @@ export {sendGetTransaction} from "./send-get-transaction.js" export {sendGetTransactionStatus} from "./send-get-transaction-status.js" export {sendPing} from "./send-ping.js" export {sendTransaction} from "./send-transaction.js" -export {send} from "./send-http.js" \ No newline at end of file +export {send} from "./send-http.js" diff --git a/packages/transport-http/src/send-execute-script.js b/packages/transport-http/src/send-execute-script.js index e09ab01df..ca9094627 100644 --- a/packages/transport-http/src/send-execute-script.js +++ b/packages/transport-http/src/send-execute-script.js @@ -10,9 +10,13 @@ async function sendExecuteScriptAtBlockIDRequest(ix, context, opts) { path: `/v1/scripts?block_id=${ix.block.id}`, method: "POST", body: { - "script": context.Buffer.from(ix.message.cadence).toString("base64"), - "arguments": ix.message.arguments.map(arg => context.Buffer.from(JSON.stringify(ix.arguments[arg].asArgument)).toString("base64")) - } + script: context.Buffer.from(ix.message.cadence).toString("base64"), + arguments: ix.message.arguments.map(arg => + context.Buffer.from( + JSON.stringify(ix.arguments[arg].asArgument) + ).toString("base64") + ), + }, }) return constructResponse(ix, context, res) @@ -26,11 +30,15 @@ async function sendExecuteScriptAtBlockHeightRequest(ix, context, opts) { path: `/v1/scripts?block_height=${ix.block.height}`, method: "POST", body: { - "script": context.Buffer.from(ix.message.cadence).toString("base64"), - "arguments": ix.message.arguments.map(arg => context.Buffer.from(JSON.stringify(ix.arguments[arg].asArgument)).toString("base64")) - } + script: context.Buffer.from(ix.message.cadence).toString("base64"), + arguments: ix.message.arguments.map(arg => + context.Buffer.from( + JSON.stringify(ix.arguments[arg].asArgument) + ).toString("base64") + ), + }, }) - + return constructResponse(ix, context, res) } @@ -42,27 +50,40 @@ async function sendExecuteScriptAtLatestBlockRequest(ix, context, opts) { path: `/v1/scripts?block_height=sealed`, method: "POST", body: { - "script": context.Buffer.from(ix.message.cadence).toString("base64"), - "arguments": ix.message.arguments.map(arg => context.Buffer.from(JSON.stringify(ix.arguments[arg].asArgument)).toString("base64")) - } + script: context.Buffer.from(ix.message.cadence).toString("base64"), + arguments: ix.message.arguments.map(arg => + context.Buffer.from( + JSON.stringify(ix.arguments[arg].asArgument) + ).toString("base64") + ), + }, }) return constructResponse(ix, context, res) } -function constructResponse(ix, context, res) { +function constructResponse(ix, context, res) { let ret = context.response() ret.tag = ix.tag - + ret.encodedData = JSON.parse(context.Buffer.from(res, "base64").toString()) return ret } export async function sendExecuteScript(ix, context = {}, opts = {}) { - invariant(opts.node, `SDK Send Execute Script Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Execute Script Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Execute Script Error: context.Buffer must be defined.`) + invariant( + opts.node, + `SDK Send Execute Script Error: opts.node must be defined.` + ) + invariant( + context.response, + `SDK Send Execute Script Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Execute Script Error: context.Buffer must be defined.` + ) ix = await ix diff --git a/packages/transport-http/src/send-execute-script.test.js b/packages/transport-http/src/send-execute-script.test.js index ae0bb7de8..14d8c9665 100644 --- a/packages/transport-http/src/send-execute-script.test.js +++ b/packages/transport-http/src/send-execute-script.test.js @@ -1,7 +1,7 @@ import {sendExecuteScript} from "./send-execute-script.js" import {build} from "../../sdk/src/build/build.js" import {script} from "../../sdk/src/build/build-script.js" -import { args, arg } from "../../sdk/src/build/build-arguments.js" +import {args, arg} from "../../sdk/src/build/build-arguments.js" import {atBlockId} from "../../sdk/src/build/build-at-block-id.js" import {atBlockHeight} from "../../sdk/src/build/build-at-block-height.js" import {resolve} from "../../sdk/src/resolve/resolve.js" @@ -11,31 +11,28 @@ import {Buffer} from "@onflow/rlp" describe("Send Execute Script", () => { test("ExecuteScriptAtLatestBlock", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() - const returnedJSONCDC = Buffer.from(JSON.stringify({type: "Int", value: 123})).toString("base64") + const returnedJSONCDC = Buffer.from( + JSON.stringify({type: "Int", value: 123}) + ).toString("base64") - httpRequestMock.mockReturnValue( - returnedJSONCDC - ) + httpRequestMock.mockReturnValue(returnedJSONCDC) const cadence = "pub fun main(a: Int): Int { return a }" let response = await sendExecuteScript( - await resolve( - await build([ - script(cadence), - args([ arg( 123, types.Int ) ]) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve( + await build([script(cadence), args([arg(123, types.Int)])]) + ), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -47,40 +44,40 @@ describe("Send Execute Script", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/scripts?block_height=sealed", - method: "POST", - body: { script: "cHViIGZ1biBtYWluKGE6IEludCk6IEludCB7IHJldHVybiBhIH0=", arguments: ["eyJ0eXBlIjoiSW50IiwidmFsdWUiOiIxMjMifQ=="] } + hostname: "localhost", + path: "/v1/scripts?block_height=sealed", + method: "POST", + body: { + script: "cHViIGZ1biBtYWluKGE6IEludCk6IEludCB7IHJldHVybiBhIH0=", + arguments: ["eyJ0eXBlIjoiSW50IiwidmFsdWUiOiIxMjMifQ=="], + }, }) - expect(response.encodedData).toEqual(JSON.parse(Buffer.from(returnedJSONCDC, "base64").toString())) + expect(response.encodedData).toEqual( + JSON.parse(Buffer.from(returnedJSONCDC, "base64").toString()) + ) }) test("ExecuteScriptAtBlockID", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() - const returnedJSONCDC = Buffer.from(JSON.stringify({type: "Int", value: 123})).toString("base64") + const returnedJSONCDC = Buffer.from( + JSON.stringify({type: "Int", value: 123}) + ).toString("base64") - httpRequestMock.mockReturnValue( - returnedJSONCDC - ) + httpRequestMock.mockReturnValue(returnedJSONCDC) const cadence = "pub fun main(): Int { return 123 }" let response = await sendExecuteScript( - await resolve( - await build([ - script(cadence), - atBlockId(123) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([script(cadence), atBlockId(123)])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -92,40 +89,40 @@ describe("Send Execute Script", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/scripts?block_id=123", - method: "POST", - body: { script: "cHViIGZ1biBtYWluKCk6IEludCB7IHJldHVybiAxMjMgfQ==", arguments: [] } + hostname: "localhost", + path: "/v1/scripts?block_id=123", + method: "POST", + body: { + script: "cHViIGZ1biBtYWluKCk6IEludCB7IHJldHVybiAxMjMgfQ==", + arguments: [], + }, }) - expect(response.encodedData).toEqual(JSON.parse(Buffer.from(returnedJSONCDC, "base64").toString())) + expect(response.encodedData).toEqual( + JSON.parse(Buffer.from(returnedJSONCDC, "base64").toString()) + ) }) test("ExecuteScriptAtBlockHeight", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() - const returnedJSONCDC = Buffer.from(JSON.stringify({type: "Int", value: 123})).toString("base64") + const returnedJSONCDC = Buffer.from( + JSON.stringify({type: "Int", value: 123}) + ).toString("base64") - httpRequestMock.mockReturnValue( - returnedJSONCDC - ) + httpRequestMock.mockReturnValue(returnedJSONCDC) const cadence = "pub fun main(): Int { return 123 }" let response = await sendExecuteScript( - await resolve( - await build([ - script(cadence), - atBlockHeight(123) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([script(cadence), atBlockHeight(123)])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -137,12 +134,16 @@ describe("Send Execute Script", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/scripts?block_height=123", - method: "POST", - body: { script: "cHViIGZ1biBtYWluKCk6IEludCB7IHJldHVybiAxMjMgfQ==", arguments: [] } + hostname: "localhost", + path: "/v1/scripts?block_height=123", + method: "POST", + body: { + script: "cHViIGZ1biBtYWluKCk6IEludCB7IHJldHVybiAxMjMgfQ==", + arguments: [], + }, }) - expect(response.encodedData).toEqual(JSON.parse(Buffer.from(returnedJSONCDC, "base64").toString())) + expect(response.encodedData).toEqual( + JSON.parse(Buffer.from(returnedJSONCDC, "base64").toString()) + ) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-http/src/send-get-account.js b/packages/transport-http/src/send-get-account.js index f309a7441..552785356 100644 --- a/packages/transport-http/src/send-get-account.js +++ b/packages/transport-http/src/send-get-account.js @@ -2,17 +2,17 @@ import {invariant} from "@onflow/util-invariant" import {httpRequest as defaultHttpRequest} from "./http-request.js" const HashAlgorithmIDs = { - "SHA2_256": 1, - "SHA2_384": 2, - "SHA3_256": 3, - "SHA3_384": 4, - "KMAC128_BLS_BLS12_381": 5 + SHA2_256: 1, + SHA2_384: 2, + SHA3_256: 3, + SHA3_384: 4, + KMAC128_BLS_BLS12_381: 5, } const SignatureAlgorithmIDs = { - "ECDSA_P256": 1, - "ECDSA_secp256k1": 2, - "BLS_BLS12_381": 3 + ECDSA_P256: 1, + ECDSA_secp256k1: 2, + BLS_BLS12_381: 3, } async function sendGetAccountAtBlockHeightRequest(ix, context, opts) { @@ -22,7 +22,7 @@ async function sendGetAccountAtBlockHeightRequest(ix, context, opts) { hostname: opts.node, path: `/v1/accounts/${ix.account.addr}?block_height=${ix.block.height}&expand=contracts,keys`, method: "GET", - body: null + body: null, }) return constructResponse(ix, context, res) @@ -31,15 +31,13 @@ async function sendGetAccountAtBlockHeightRequest(ix, context, opts) { async function sendGetAccountAtLatestBlockRequest(ix, context, opts) { const httpRequest = opts.httpRequest || defaultHttpRequest - const height = ix.block?.isSealed - ? "sealed" - : "final" + const height = ix.block?.isSealed ? "sealed" : "final" const res = await httpRequest({ hostname: opts.node, path: `/v1/accounts/${ix.account.addr}?block_height=${height}&expand=contracts,keys`, method: "GET", - body: null + body: null, }) return constructResponse(ix, context, res) @@ -73,17 +71,22 @@ function constructResponse(ix, context, res) { sequenceNumber: Number(key.sequence_number), weight: Number(key.weight), revoked: key.revoked, - })) + })), } return ret } - export async function sendGetAccount(ix, context = {}, opts = {}) { invariant(opts.node, `SDK Send Get Account Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Account Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Get Account Error: context.Buffer must be defined.`) + invariant( + context.response, + `SDK Send Get Account Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Get Account Error: context.Buffer must be defined.` + ) ix = await ix diff --git a/packages/transport-http/src/send-get-account.test.js b/packages/transport-http/src/send-get-account.test.js index ea1efe41c..7c9c5c7b7 100644 --- a/packages/transport-http/src/send-get-account.test.js +++ b/packages/transport-http/src/send-get-account.test.js @@ -8,33 +8,30 @@ import {Buffer} from "@onflow/rlp" describe("Send Get Account", () => { test("GetAccountAtBlockHeightRequest", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const returnedAccount = { - address: "0x1654653399040a61", - keys: [], - balance: "10", - contracts: {}, - code: null + address: "0x1654653399040a61", + keys: [], + balance: "10", + contracts: {}, + code: null, } httpRequestMock.mockReturnValue(returnedAccount) const response = await sendGetAccount( - await resolve( - await build([ - getAccount("0x1654653399040a61"), - atBlockHeight(123) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve( + await build([getAccount("0x1654653399040a61"), atBlockHeight(123)]) + ), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -46,48 +43,43 @@ describe("Send Get Account", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/accounts/1654653399040a61?block_height=123&expand=contracts,keys", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/accounts/1654653399040a61?block_height=123&expand=contracts,keys", + method: "GET", + body: null, }) expect(response.account).toEqual({ - address: "0x1654653399040a61", - keys: [], - balance: 10, - contracts: {}, - code: "" + address: "0x1654653399040a61", + keys: [], + balance: 10, + contracts: {}, + code: "", }) - }) test("GetAccountAtLatestBlockRequest", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const returnedAccount = { - address: "0x1654653399040a61", - keys: [], - balance: "10", - contracts: {}, - code: null + address: "0x1654653399040a61", + keys: [], + balance: "10", + contracts: {}, + code: null, } httpRequestMock.mockReturnValue(returnedAccount) const response = await sendGetAccount( - await resolve( - await build([ - getAccount("0x1654653399040a61"), - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getAccount("0x1654653399040a61")])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -99,18 +91,17 @@ describe("Send Get Account", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/accounts/1654653399040a61?block_height=final&expand=contracts,keys", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/accounts/1654653399040a61?block_height=final&expand=contracts,keys", + method: "GET", + body: null, }) expect(response.account).toEqual({ - address: "0x1654653399040a61", - keys: [], - balance: 10, - contracts: {}, - code: "" + address: "0x1654653399040a61", + keys: [], + balance: 10, + contracts: {}, + code: "", }) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-http/src/send-get-block-header.js b/packages/transport-http/src/send-get-block-header.js index 6f13405c6..ea24952fe 100644 --- a/packages/transport-http/src/send-get-block-header.js +++ b/packages/transport-http/src/send-get-block-header.js @@ -8,7 +8,7 @@ async function sendGetBlockHeaderByIDRequest(ix, context, opts) { hostname: opts.node, path: `/v1/blocks/${ix.block.id}`, method: "GET", - body: null + body: null, }) return constructResponse(ix, context, res) @@ -21,7 +21,7 @@ async function sendGetBlockHeaderByHeightRequest(ix, context, opts) { hostname: opts.node, path: `/v1/blocks?height=${ix.block.height}`, method: "GET", - body: null + body: null, }) return constructResponse(ix, context, res) @@ -30,15 +30,13 @@ async function sendGetBlockHeaderByHeightRequest(ix, context, opts) { async function sendGetLatestBlockHeaderRequest(ix, context, opts) { const httpRequest = opts.httpRequest || defaultHttpRequest - const height = ix.block?.isSealed - ? "sealed" - : "finalized" + const height = ix.block?.isSealed ? "sealed" : "finalized" const res = await httpRequest({ hostname: opts.node, path: `/v1/blocks?height=${height}`, method: "GET", - body: null + body: null, }) return constructResponse(ix, context, res) @@ -60,8 +58,14 @@ function constructResponse(ix, context, res) { } export async function sendGetBlockHeader(ix, context = {}, opts = {}) { - invariant(opts.node, `SDK Send Get Block Header Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Block Header Error: context.response must be defined.`) + invariant( + opts.node, + `SDK Send Get Block Header Error: opts.node must be defined.` + ) + invariant( + context.response, + `SDK Send Get Block Header Error: context.response must be defined.` + ) ix = await ix diff --git a/packages/transport-http/src/send-get-block-header.test.js b/packages/transport-http/src/send-get-block-header.test.js index c21e64bca..90d4becdd 100644 --- a/packages/transport-http/src/send-get-block-header.test.js +++ b/packages/transport-http/src/send-get-block-header.test.js @@ -9,36 +9,33 @@ import {Buffer} from "@onflow/rlp" describe("Send Get Block Header", () => { test("GetBlockHeaderByID", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const dateNow = new Date(Date.now()) - const returnedBlockHeader = [{ + const returnedBlockHeader = [ + { header: { - id: "a1b2c3", - parent_id: "a1b2c3", - height: "123", - timestamp: dateNow.toISOString(), - } - }] + id: "a1b2c3", + parent_id: "a1b2c3", + height: "123", + timestamp: dateNow.toISOString(), + }, + }, + ] - httpRequestMock.mockReturnValue(returnedBlockHeader); + httpRequestMock.mockReturnValue(returnedBlockHeader) const response = await sendGetBlockHeader( - await resolve( - await build([ - getBlockHeader(), - atBlockId("a1b2c3") - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getBlockHeader(), atBlockId("a1b2c3")])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -50,51 +47,48 @@ describe("Send Get Block Header", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/blocks/a1b2c3", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/blocks/a1b2c3", + method: "GET", + body: null, }) expect(response.blockHeader).toEqual({ - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), }) }) test("GetBlockHeaderByHeight", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const dateNow = new Date(Date.now()) - const returnedBlockHeader = [{ + const returnedBlockHeader = [ + { header: { - id: "a1b2c3", - parent_id: "a1b2c3", - height: "123", - timestamp: dateNow.toISOString(), - } - }] + id: "a1b2c3", + parent_id: "a1b2c3", + height: "123", + timestamp: dateNow.toISOString(), + }, + }, + ] - httpRequestMock.mockReturnValue(returnedBlockHeader); + httpRequestMock.mockReturnValue(returnedBlockHeader) const response = await sendGetBlockHeader( - await resolve( - await build([ - getBlockHeader(), - atBlockHeight(123) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getBlockHeader(), atBlockHeight(123)])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -106,50 +100,48 @@ describe("Send Get Block Header", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/blocks?height=123", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/blocks?height=123", + method: "GET", + body: null, }) expect(response.blockHeader).toEqual({ - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), }) }) test("GetLatestBlockHeader - isSealed = false", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const dateNow = new Date(Date.now()) - const returnedBlockHeader = [{ + const returnedBlockHeader = [ + { header: { - id: "a1b2c3", - parent_id: "a1b2c3", - height: "123", - timestamp: dateNow.toISOString(), - } - }] + id: "a1b2c3", + parent_id: "a1b2c3", + height: "123", + timestamp: dateNow.toISOString(), + }, + }, + ] - httpRequestMock.mockReturnValue(returnedBlockHeader); + httpRequestMock.mockReturnValue(returnedBlockHeader) const response = await sendGetBlockHeader( - await resolve( - await build([ - getBlockHeader() - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getBlockHeader()])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -161,50 +153,48 @@ describe("Send Get Block Header", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/blocks?height=finalized", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/blocks?height=finalized", + method: "GET", + body: null, }) expect(response.blockHeader).toEqual({ - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), }) }) test("GetLatestBlockHeader - isSealed = true", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const dateNow = new Date(Date.now()) - const returnedBlockHeader = [{ + const returnedBlockHeader = [ + { header: { - id: "a1b2c3", - parent_id: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), - } - }] + id: "a1b2c3", + parent_id: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), + }, + }, + ] - httpRequestMock.mockReturnValue(returnedBlockHeader); + httpRequestMock.mockReturnValue(returnedBlockHeader) const response = await sendGetBlockHeader( - await resolve( - await build([ - getBlockHeader(true) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getBlockHeader(true)])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -216,18 +206,17 @@ describe("Send Get Block Header", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/blocks?height=sealed", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/blocks?height=sealed", + method: "GET", + body: null, }) expect(response.blockHeader).toEqual({ - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), }) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-http/src/send-get-block.js b/packages/transport-http/src/send-get-block.js index 978e572b4..ac931a604 100644 --- a/packages/transport-http/src/send-get-block.js +++ b/packages/transport-http/src/send-get-block.js @@ -8,7 +8,7 @@ async function sendGetBlockByIDRequest(ix, context, opts) { hostname: opts.node, path: `/v1/blocks/${ix.block.id}?expand=payload`, method: "GET", - body: null + body: null, }) return constructResponse(ix, context, res) @@ -21,7 +21,7 @@ async function sendGetBlockByHeightRequest(ix, context, opts) { hostname: opts.node, path: `/v1/blocks?height=${ix.block.height}&expand=payload`, method: "GET", - body: null + body: null, }) return constructResponse(ix, context, res) @@ -30,15 +30,13 @@ async function sendGetBlockByHeightRequest(ix, context, opts) { async function sendGetBlockRequest(ix, context, opts) { const httpRequest = opts.httpRequest || defaultHttpRequest - const height = ix.block?.isSealed - ? "sealed" - : "final" + const height = ix.block?.isSealed ? "sealed" : "final" const res = await httpRequest({ hostname: opts.node, path: `/v1/blocks?height=${height}&expand=payload`, method: "GET", - body: null + body: null, }) return constructResponse(ix, context, res) @@ -54,14 +52,16 @@ function constructResponse(ix, context, res) { parentId: block.header.parent_id, height: Number(block.header.height), timestamp: block.header.timestamp, - collectionGuarantees: block.payload.collection_guarantees.map(collectionGuarantee => ({ - collectionId: collectionGuarantee.collection_id, - signerIds: collectionGuarantee.signer_ids, - })), - blockSeals: block.payload.block_seals.map(blockSeal => ({ + collectionGuarantees: block.payload.collection_guarantees.map( + collectionGuarantee => ({ + collectionId: collectionGuarantee.collection_id, + signerIds: collectionGuarantee.signer_ids, + }) + ), + blockSeals: block.payload.block_seals.map(blockSeal => ({ blockId: blockSeal.block_id, executionReceiptId: blockSeal.result_id, - })) + })), } return ret @@ -69,7 +69,10 @@ function constructResponse(ix, context, res) { export async function sendGetBlock(ix, context = {}, opts = {}) { invariant(opts.node, `SDK Send Get Block Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Block Error: context.response must be defined.`) + invariant( + context.response, + `SDK Send Get Block Error: context.response must be defined.` + ) ix = await ix diff --git a/packages/transport-http/src/send-get-block.test.js b/packages/transport-http/src/send-get-block.test.js index a0f38e669..5c26d693f 100644 --- a/packages/transport-http/src/send-get-block.test.js +++ b/packages/transport-http/src/send-get-block.test.js @@ -9,40 +9,37 @@ import {Buffer} from "@onflow/rlp" describe("Send Get Block", () => { test("GetBlockByID", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const dateNow = new Date(Date.now()) - const returnedBlock = [{ + const returnedBlock = [ + { header: { - id: "a1b2c3", - parent_id: "a1b2c3", - height: "123", - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parent_id: "a1b2c3", + height: "123", + timestamp: dateNow.toISOString(), }, payload: { - collection_guarantees: [], - block_seals: [], - } - }] + collection_guarantees: [], + block_seals: [], + }, + }, + ] httpRequestMock.mockReturnValue(returnedBlock) const response = await sendGetBlock( - await resolve( - await build([ - getBlock(), - atBlockId("a1b2c3") - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getBlock(), atBlockId("a1b2c3")])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -54,57 +51,54 @@ describe("Send Get Block", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/blocks/a1b2c3?expand=payload", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/blocks/a1b2c3?expand=payload", + method: "GET", + body: null, }) expect(response.block).toEqual({ - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), - collectionGuarantees: [], - blockSeals: [] + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), + collectionGuarantees: [], + blockSeals: [], }) }) test("GetBlockByHeight", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const dateNow = new Date(Date.now()) - const returnedBlock = [{ + const returnedBlock = [ + { header: { - id: "a1b2c3", - parent_id: "a1b2c3", - height: "123", - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parent_id: "a1b2c3", + height: "123", + timestamp: dateNow.toISOString(), }, payload: { - collection_guarantees: [], - block_seals: [], - } - }] + collection_guarantees: [], + block_seals: [], + }, + }, + ] - httpRequestMock.mockReturnValue(returnedBlock); + httpRequestMock.mockReturnValue(returnedBlock) const response = await sendGetBlock( - await resolve( - await build([ - getBlock(), - atBlockHeight(123) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getBlock(), atBlockHeight(123)])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -116,56 +110,54 @@ describe("Send Get Block", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/blocks?height=123&expand=payload", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/blocks?height=123&expand=payload", + method: "GET", + body: null, }) expect(response.block).toEqual({ - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), - collectionGuarantees: [], - blockSeals: [] + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), + collectionGuarantees: [], + blockSeals: [], }) }) test("GetLatestBlock - isSealed = false", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const dateNow = new Date(Date.now()) - const returnedBlock = [{ + const returnedBlock = [ + { header: { - id: "a1b2c3", - parent_id: "a1b2c3", - height: "123", - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parent_id: "a1b2c3", + height: "123", + timestamp: dateNow.toISOString(), }, payload: { - collection_guarantees: [], - block_seals: [], - } - }] + collection_guarantees: [], + block_seals: [], + }, + }, + ] httpRequestMock.mockReturnValue(returnedBlock) const response = await sendGetBlock( - await resolve( - await build([ - getBlock() - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getBlock()])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -177,56 +169,54 @@ describe("Send Get Block", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/blocks?height=final&expand=payload", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/blocks?height=final&expand=payload", + method: "GET", + body: null, }) expect(response.block).toEqual({ - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), - collectionGuarantees: [], - blockSeals: [] + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), + collectionGuarantees: [], + blockSeals: [], }) }) test("GetLatestBlock - isSealed = true", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const dateNow = new Date(Date.now()) - const returnedBlock = [{ + const returnedBlock = [ + { header: { - id: "a1b2c3", - parent_id: "a1b2c3", - height: "123", - timestamp: dateNow.toISOString(), + id: "a1b2c3", + parent_id: "a1b2c3", + height: "123", + timestamp: dateNow.toISOString(), }, payload: { - collection_guarantees: [], - block_seals: [], - } - }] + collection_guarantees: [], + block_seals: [], + }, + }, + ] httpRequestMock.mockReturnValue(returnedBlock) const response = await sendGetBlock( - await resolve( - await build([ - getBlock(true) - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getBlock(true)])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -238,20 +228,19 @@ describe("Send Get Block", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/blocks?height=sealed&expand=payload", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/blocks?height=sealed&expand=payload", + method: "GET", + body: null, }) expect(response.block).toEqual({ - id: "a1b2c3", - parentId: "a1b2c3", - height: 123, - timestamp: dateNow.toISOString(), - collectionGuarantees: [], - blockSeals: [] + id: "a1b2c3", + parentId: "a1b2c3", + height: 123, + timestamp: dateNow.toISOString(), + collectionGuarantees: [], + blockSeals: [], }) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-http/src/send-get-collection.js b/packages/transport-http/src/send-get-collection.js index be7fa5254..b0c54aedb 100644 --- a/packages/transport-http/src/send-get-collection.js +++ b/packages/transport-http/src/send-get-collection.js @@ -2,8 +2,14 @@ import {invariant} from "@onflow/util-invariant" import {httpRequest as defaultHttpRequest} from "./http-request.js" export async function sendGetCollection(ix, context = {}, opts = {}) { - invariant(opts.node, `SDK Send Get Collection Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Collection Error: context.response must be defined.`) + invariant( + opts.node, + `SDK Send Get Collection Error: opts.node must be defined.` + ) + invariant( + context.response, + `SDK Send Get Collection Error: context.response must be defined.` + ) const httpRequest = opts.httpRequest || defaultHttpRequest @@ -11,7 +17,7 @@ export async function sendGetCollection(ix, context = {}, opts = {}) { hostname: opts.node, path: `/v1/collections/${ix.collection.id}?expand=transactions`, method: "GET", - body: null + body: null, }) const ret = context.response() diff --git a/packages/transport-http/src/send-get-collection.test.js b/packages/transport-http/src/send-get-collection.test.js index 30aa078a6..17da63dd9 100644 --- a/packages/transport-http/src/send-get-collection.test.js +++ b/packages/transport-http/src/send-get-collection.test.js @@ -7,31 +7,29 @@ import {Buffer} from "@onflow/rlp" describe("Send Get Collection", () => { test("GetCollection", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const returnedCollection = { - id: "a1b2c3", - transactions: [{ - id: "a1b2c3" - }] + id: "a1b2c3", + transactions: [ + { + id: "a1b2c3", + }, + ], } - httpRequestMock.mockReturnValue(returnedCollection); + httpRequestMock.mockReturnValue(returnedCollection) const response = await sendGetCollection( - await resolve( - await build([ - getCollection("a1b2c3"), - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getCollection("a1b2c3")])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -43,14 +41,13 @@ describe("Send Get Collection", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/collections/a1b2c3?expand=transactions", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/collections/a1b2c3?expand=transactions", + method: "GET", + body: null, }) expect(response.collection.id).toBe(returnedCollection.id) expect(response.collection.transactionIds[0]).toBe("a1b2c3") }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-http/src/send-get-events.js b/packages/transport-http/src/send-get-events.js index 604c892d8..037b22e48 100644 --- a/packages/transport-http/src/send-get-events.js +++ b/packages/transport-http/src/send-get-events.js @@ -8,7 +8,7 @@ async function sendGetEventsForHeightRangeRequest(ix, context, opts) { hostname: opts.node, path: `/v1/events?type=${ix.events.eventType}&start_height=${ix.events.start}&end_height=${ix.events.end}`, method: "GET", - body: null + body: null, }) return constructResponse(ix, context, res) @@ -19,9 +19,11 @@ async function sendGetEventsForBlockIDsRequest(ix, context, opts) { const res = await httpRequest({ hostname: opts.node, - path: `/v1/events?type=${ix.events.eventType}&block_ids=${ix.events.blockIds.join(",")}`, + path: `/v1/events?type=${ + ix.events.eventType + }&block_ids=${ix.events.blockIds.join(",")}`, method: "GET", - body: null + body: null, }) return constructResponse(ix, context, res) @@ -32,37 +34,50 @@ function constructResponse(ix, context, res) { ret.tag = ix.tag ret.events = [] - res.forEach(block => block.events ? - block.events.forEach(event => ret.events.push({ - blockId: block.block_id, - blockHeight: Number(block.block_height), - blockTimestamp: block.block_timestamp, - type: event.type, - transactionId: event.transaction_id, - transactionIndex: Number(event.transaction_index), - eventIndex: Number(event.event_index), - payload: JSON.parse(context.Buffer.from(event.payload, "base64").toString()) - })) : null + res.forEach(block => + block.events + ? block.events.forEach(event => + ret.events.push({ + blockId: block.block_id, + blockHeight: Number(block.block_height), + blockTimestamp: block.block_timestamp, + type: event.type, + transactionId: event.transaction_id, + transactionIndex: Number(event.transaction_index), + eventIndex: Number(event.event_index), + payload: JSON.parse( + context.Buffer.from(event.payload, "base64").toString() + ), + }) + ) + : null ) return ret } -export async function sendGetEvents(ix, context = {}, opts = {}) { +export async function sendGetEvents(ix, context = {}, opts = {}) { invariant(opts.node, `SDK Send Get Events Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Events Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Get Events Error: context.Buffer must be defined.`) + invariant( + context.response, + `SDK Send Get Events Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Get Events Error: context.Buffer must be defined.` + ) ix = await ix - const interactionContainsBlockHeightRange = ix.events.start !== null - const interactionContainsBlockIDsList = Array.isArray(ix.events.blockIds) && ix.events.blockIds.length > 0 - + const interactionContainsBlockHeightRange = ix.events.start !== null + const interactionContainsBlockIDsList = + Array.isArray(ix.events.blockIds) && ix.events.blockIds.length > 0 + invariant( interactionContainsBlockHeightRange || interactionContainsBlockIDsList, "SendGetEventsError: Unable to determine which get events request to send. Either a block height range, or block IDs must be specified." ) - + if (interactionContainsBlockHeightRange) { return await sendGetEventsForHeightRangeRequest(ix, context, opts) } else { diff --git a/packages/transport-http/src/send-get-events.test.js b/packages/transport-http/src/send-get-events.test.js index 0f8fcdc44..5853209c6 100644 --- a/packages/transport-http/src/send-get-events.test.js +++ b/packages/transport-http/src/send-get-events.test.js @@ -8,41 +8,41 @@ import {Buffer} from "@onflow/rlp" describe("Send Get Events", () => { test("GetEventsForBlockIDs", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const dateNow = new Date(Date.now()) const returnedEvents = [ - { - block_id: "a1b2c3", - block_height: "123", - block_timestamp: dateNow.toISOString(), - events: [{ - type: "MyEvent", - transaction_id: "a1b2c3", - transaction_index: "123", - event_index: "456", - payload: Buffer.from(JSON.stringify({type: "String", value: "Hello, Flow"})).toString("base64") - }] - } - ] + { + block_id: "a1b2c3", + block_height: "123", + block_timestamp: dateNow.toISOString(), + events: [ + { + type: "MyEvent", + transaction_id: "a1b2c3", + transaction_index: "123", + event_index: "456", + payload: Buffer.from( + JSON.stringify({type: "String", value: "Hello, Flow"}) + ).toString("base64"), + }, + ], + }, + ] httpRequestMock.mockReturnValue(returnedEvents) const response = await sendGetEvents( - await resolve( - await build([ - getEventsAtBlockIds("MyEvent", ["a1b2c3"]), - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getEventsAtBlockIds("MyEvent", ["a1b2c3"])])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -54,60 +54,62 @@ describe("Send Get Events", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/events?type=MyEvent&block_ids=a1b2c3", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/events?type=MyEvent&block_ids=a1b2c3", + method: "GET", + body: null, }) expect(response.events[0]).toStrictEqual({ - blockId: "a1b2c3", - blockHeight: 123, - blockTimestamp: dateNow.toISOString(), - type: "MyEvent", - transactionId: "a1b2c3", - transactionIndex: 123, - eventIndex: 456, - payload: {type: "String", value: "Hello, Flow"} + blockId: "a1b2c3", + blockHeight: 123, + blockTimestamp: dateNow.toISOString(), + type: "MyEvent", + transactionId: "a1b2c3", + transactionIndex: 123, + eventIndex: 456, + payload: {type: "String", value: "Hello, Flow"}, }) }) test("GetEventsForHeightRange", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const dateNow = new Date(Date.now()) const returnedEvents = [ - { - block_id: "a1b2c3", - block_height: "123", - block_timestamp: dateNow.toISOString(), - events: [{ - type: "MyEvent", - transaction_id: "a1b2c3", - transaction_index: "123", - event_index: "456", - payload: Buffer.from(JSON.stringify({type: "String", value: "Hello, Flow"})).toString("base64") - }] - } - ] + { + block_id: "a1b2c3", + block_height: "123", + block_timestamp: dateNow.toISOString(), + events: [ + { + type: "MyEvent", + transaction_id: "a1b2c3", + transaction_index: "123", + event_index: "456", + payload: Buffer.from( + JSON.stringify({type: "String", value: "Hello, Flow"}) + ).toString("base64"), + }, + ], + }, + ] httpRequestMock.mockReturnValue(returnedEvents) const response = await sendGetEvents( - await resolve( - await build([ - getEventsAtBlockHeightRange("MyEvent", 123, 456), - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve( + await build([getEventsAtBlockHeightRange("MyEvent", 123, 456)]) + ), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -119,22 +121,21 @@ describe("Send Get Events", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/events?type=MyEvent&start_height=123&end_height=456", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/events?type=MyEvent&start_height=123&end_height=456", + method: "GET", + body: null, }) expect(response.events[0]).toStrictEqual({ - blockId: "a1b2c3", - blockHeight: 123, - blockTimestamp: dateNow.toISOString(), - type: "MyEvent", - transactionId: "a1b2c3", - transactionIndex: 123, - eventIndex: 456, - payload: {type: "String", value: "Hello, Flow"} + blockId: "a1b2c3", + blockHeight: 123, + blockTimestamp: dateNow.toISOString(), + type: "MyEvent", + transactionId: "a1b2c3", + transactionIndex: 123, + eventIndex: 456, + payload: {type: "String", value: "Hello, Flow"}, }) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-http/src/send-get-transaction.js b/packages/transport-http/src/send-get-transaction.js index 7fad76efd..0ca52fa6b 100644 --- a/packages/transport-http/src/send-get-transaction.js +++ b/packages/transport-http/src/send-get-transaction.js @@ -2,9 +2,18 @@ import {invariant} from "@onflow/util-invariant" import {httpRequest as defaultHttpRequest} from "./http-request.js" export async function sendGetTransaction(ix, context = {}, opts = {}) { - invariant(opts.node, `SDK Send Get Transaction Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Get Transaction Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Get Transaction Error: context.Buffer must be defined.`) + invariant( + opts.node, + `SDK Send Get Transaction Error: opts.node must be defined.` + ) + invariant( + context.response, + `SDK Send Get Transaction Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Get Transaction Error: context.Buffer must be defined.` + ) const httpRequest = opts.httpRequest || defaultHttpRequest @@ -20,16 +29,17 @@ export async function sendGetTransaction(ix, context = {}, opts = {}) { const unwrapKey = key => ({ address: key.address, keyId: Number(key.key_id), - sequenceNumber: Number(key.sequence_number) + sequenceNumber: Number(key.sequence_number), }) const unwrapSignature = sig => ({ address: sig.address, keyId: Number(sig.key_index), - signature: sig.signature + signature: sig.signature, }) - const unwrapArg = arg => JSON.parse(context.Buffer.from(arg, "base64").toString()) + const unwrapArg = arg => + JSON.parse(context.Buffer.from(arg, "base64").toString()) let ret = context.response() ret.tag = ix.tag @@ -39,10 +49,12 @@ export async function sendGetTransaction(ix, context = {}, opts = {}) { referenceBlockId: res.reference_block_id, gasLimit: Number(res.gas_limit), payer: res.payer, - proposalKey: res.proposal_key ? unwrapKey(res.proposal_key) : res.proposal_key, + proposalKey: res.proposal_key + ? unwrapKey(res.proposal_key) + : res.proposal_key, authorizers: res.authorizers, payloadSignatures: [...res.payload_signatures.map(unwrapSignature)], - envelopeSignatures: [...res.envelope_signatures.map(unwrapSignature)] + envelopeSignatures: [...res.envelope_signatures.map(unwrapSignature)], } return ret diff --git a/packages/transport-http/src/send-get-transaction.test.js b/packages/transport-http/src/send-get-transaction.test.js index d8773ad49..d88a59bc3 100644 --- a/packages/transport-http/src/send-get-transaction.test.js +++ b/packages/transport-http/src/send-get-transaction.test.js @@ -7,41 +7,37 @@ import {Buffer} from "@onflow/rlp" describe("Get Transaction", () => { test("GetTransactionResult", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() const returnedTransaction = { - script: "Q2FkZW5jZSBDb2Rl", - arguments: [], - reference_block_id: "a1b2c3", - gas_limit: "123", - proposal_key: { - address: "1654653399040a61", - key_id: "1", - signer_index: "0", - sequence_number: "1" - }, - payer: "1654653399040a61", - authorizers: [], - payload_signatures: [], - envelope_signatures: [] + script: "Q2FkZW5jZSBDb2Rl", + arguments: [], + reference_block_id: "a1b2c3", + gas_limit: "123", + proposal_key: { + address: "1654653399040a61", + key_id: "1", + signer_index: "0", + sequence_number: "1", + }, + payer: "1654653399040a61", + authorizers: [], + payload_signatures: [], + envelope_signatures: [], } httpRequestMock.mockReturnValue(returnedTransaction) const response = await sendGetTransaction( - await resolve( - await build([ - getTransaction("MyTxID"), - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([getTransaction("MyTxID")])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -53,27 +49,26 @@ describe("Get Transaction", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/transactions/MyTxID", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/transactions/MyTxID", + method: "GET", + body: null, }) expect(response.transaction).toStrictEqual({ - script: "Cadence Code", - args: [], - referenceBlockId: "a1b2c3", - gasLimit: 123, - proposalKey: { - address: "1654653399040a61", - keyId: 1, - sequenceNumber: 1 - }, - payer: "1654653399040a61", - authorizers: [], - payloadSignatures: [], - envelopeSignatures: [] + script: "Cadence Code", + args: [], + referenceBlockId: "a1b2c3", + gasLimit: 123, + proposalKey: { + address: "1654653399040a61", + keyId: 1, + sequenceNumber: 1, + }, + payer: "1654653399040a61", + authorizers: [], + payloadSignatures: [], + envelopeSignatures: [], }) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-http/src/send-http.js b/packages/transport-http/src/send-http.js index 530baab6c..404a137a3 100644 --- a/packages/transport-http/src/send-http.js +++ b/packages/transport-http/src/send-http.js @@ -11,9 +11,12 @@ import {sendGetCollection} from "./send-get-collection.js" import {sendPing} from "./send-ping.js" export const send = async (ix, context = {}, opts = {}) => { - invariant(opts.node, `SDK Send Error: Either opts.node or "accessNode.api" in config must be defined.`) + invariant( + opts.node, + `SDK Send Error: Either opts.node or "accessNode.api" in config must be defined.` + ) invariant(context.ix, `SDK Send Error: context.ix must be defined.`) - + ix = await ix // prettier-ignore diff --git a/packages/transport-http/src/send-ping.js b/packages/transport-http/src/send-ping.js index 4347fa35d..67fc80de3 100644 --- a/packages/transport-http/src/send-ping.js +++ b/packages/transport-http/src/send-ping.js @@ -3,7 +3,10 @@ import {httpRequest as defaultHttpRequest} from "./http-request.js" export async function sendPing(ix, context = {}, opts = {}) { invariant(opts.node, `SDK Send Ping Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Ping Error: context.response must be defined.`) + invariant( + context.response, + `SDK Send Ping Error: context.response must be defined.` + ) const httpRequest = opts.httpRequest || defaultHttpRequest @@ -11,7 +14,7 @@ export async function sendPing(ix, context = {}, opts = {}) { hostname: opts.node, path: "/v1/blocks?height=sealed", method: "GET", - body: null + body: null, }) let ret = context.response() diff --git a/packages/transport-http/src/send-ping.test.js b/packages/transport-http/src/send-ping.test.js index 08879f7e1..dff1ecd67 100644 --- a/packages/transport-http/src/send-ping.test.js +++ b/packages/transport-http/src/send-ping.test.js @@ -7,24 +7,20 @@ import {Buffer} from "@onflow/rlp" describe("Ping", () => { test("Ping", async () => { - const httpRequestMock = jest.fn(); + const httpRequestMock = jest.fn() - httpRequestMock.mockReturnValue({}); + httpRequestMock.mockReturnValue({}) await sendPing( - await resolve( - await build([ - ping(), - ]) - ), - { - response: responseADT, - Buffer, - }, - { - httpRequest: httpRequestMock, - node: "localhost" - } + await resolve(await build([ping()])), + { + response: responseADT, + Buffer, + }, + { + httpRequest: httpRequestMock, + node: "localhost", + } ) expect(httpRequestMock.mock.calls.length).toEqual(1) @@ -36,11 +32,10 @@ describe("Ping", () => { const valueSent = httpRequestMock.mock.calls[0][0] expect(valueSent).toEqual({ - hostname: "localhost", - path: "/v1/blocks?height=sealed", - method: "GET", - body: null + hostname: "localhost", + path: "/v1/blocks?height=sealed", + method: "GET", + body: null, }) }) - -}) \ No newline at end of file +}) diff --git a/packages/transport-http/src/send-transaction.js b/packages/transport-http/src/send-transaction.js index bb32e4372..e4f79e2b5 100644 --- a/packages/transport-http/src/send-transaction.js +++ b/packages/transport-http/src/send-transaction.js @@ -4,8 +4,14 @@ import {httpRequest as defaultHttpRequest} from "./http-request.js" export async function sendTransaction(ix, context = {}, opts = {}) { invariant(opts.node, `SDK Send Transaction Error: opts.node must be defined.`) - invariant(context.response, `SDK Send Transaction Error: context.response must be defined.`) - invariant(context.Buffer, `SDK Send Transaction Error: context.Buffer must be defined.`) + invariant( + context.response, + `SDK Send Transaction Error: context.response must be defined.` + ) + invariant( + context.Buffer, + `SDK Send Transaction Error: context.Buffer must be defined.` + ) const httpRequest = opts.httpRequest || defaultHttpRequest @@ -19,11 +25,16 @@ export async function sendTransaction(ix, context = {}, opts = {}) { payloadSignatures.push({ address: sansPrefix(acct.addr), key_index: String(acct.keyId), - signature: context.Buffer.from(acct.signature, "hex").toString("base64") + signature: context.Buffer.from(acct.signature, "hex").toString( + "base64" + ), }) } } catch (error) { - console.error("SDK HTTP Send Error: Trouble applying payload signature", {acct, ix}) + console.error("SDK HTTP Send Error: Trouble applying payload signature", { + acct, + ix, + }) throw error } } @@ -37,11 +48,16 @@ export async function sendTransaction(ix, context = {}, opts = {}) { envelopeSignatures[id] = envelopeSignatures[id] || { address: sansPrefix(acct.addr), key_index: String(acct.keyId), - signature: context.Buffer.from(acct.signature, "hex").toString("base64") + signature: context.Buffer.from(acct.signature, "hex").toString( + "base64" + ), } } } catch (error) { - console.error("SDK HTTP Send Error: Trouble applying envelope signature", {acct, ix}) + console.error( + "SDK HTTP Send Error: Trouble applying envelope signature", + {acct, ix} + ) throw error } } @@ -54,10 +70,18 @@ export async function sendTransaction(ix, context = {}, opts = {}) { method: "POST", body: { script: context.Buffer.from(ix.message.cadence).toString("base64"), - "arguments": [...ix.message.arguments.map(arg => context.Buffer.from(JSON.stringify(ix.arguments[arg].asArgument)).toString("base64"))], + arguments: [ + ...ix.message.arguments.map(arg => + context.Buffer.from( + JSON.stringify(ix.arguments[arg].asArgument) + ).toString("base64") + ), + ], reference_block_id: ix.message.refBlock ? ix.message.refBlock : null, gas_limit: String(ix.message.computeLimit), - payer: sansPrefix(ix.accounts[Array.isArray(ix.payer) ? ix.payer[0] : ix.payer].addr), + payer: sansPrefix( + ix.accounts[Array.isArray(ix.payer) ? ix.payer[0] : ix.payer].addr + ), proposal_key: { address: sansPrefix(ix.accounts[ix.proposer].addr), key_index: String(ix.accounts[ix.proposer].keyId), @@ -70,13 +94,13 @@ export async function sendTransaction(ix, context = {}, opts = {}) { }, []) .map(sansPrefix), payload_signatures: payloadSignatures, - envelope_signatures: envelopeSignatures - } + envelope_signatures: envelopeSignatures, + }, }) var t2 = Date.now() let ret = context.response() - ret.tag = ix.tag + ret.tag = ix.tag ret.transactionId = res.id if (typeof window !== "undefined") { diff --git a/packages/types/src/types.js b/packages/types/src/types.js index b4ca9d24e..8109bf649 100644 --- a/packages/types/src/types.js +++ b/packages/types/src/types.js @@ -4,19 +4,19 @@ const type = (label, asArgument, asInjection) => ({ asInjection, }) -const isArray = (d) => Array.isArray(d) -const isObj = (d) => typeof d === "object" -const isNull = (d) => d == null -const isBoolean = (d) => typeof d === "boolean" -const isNumber = (d) => typeof d === "number" -const isInteger = (d) => Number.isInteger(d) -const isString = (d) => typeof d === "string" - -const throwTypeError = (msg) => { +const isArray = d => Array.isArray(d) +const isObj = d => typeof d === "object" +const isNull = d => d == null +const isBoolean = d => typeof d === "boolean" +const isNumber = d => typeof d === "number" +const isInteger = d => Number.isInteger(d) +const isString = d => typeof d === "string" + +const throwTypeError = msg => { throw new Error("Type Error: " + msg) } -const numberValuesDeprecationNotice = (type) => { +const numberValuesDeprecationNotice = type => { console.error( ` %c@onflow/types Deprecation Notice @@ -36,13 +36,13 @@ const numberValuesDeprecationNotice = (type) => { export const Identity = type( "Identity", - (v) => v, - (v) => v + v => v, + v => v ) export const UInt = type( "UInt", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("UInt") return { @@ -53,17 +53,17 @@ export const UInt = type( if (isString(v)) { return { type: "UInt", - value: v + value: v, } } throwTypeError("Expected Positive Integer for type Unsigned Int") }, - (v) => v + v => v ) export const Int = type( "Int", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("Int") return { @@ -74,17 +74,17 @@ export const Int = type( if (isString(v)) { return { type: "Int", - value: v + value: v, } } throwTypeError("Expected Integer for type Int") }, - (v) => v + v => v ) export const UInt8 = type( "UInt8", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("UInt8") return { @@ -95,17 +95,17 @@ export const UInt8 = type( if (isString(v)) { return { type: "UInt8", - value: v + value: v, } } throwTypeError("Expected integer for UInt8") }, - (v) => v + v => v ) export const Int8 = type( "Int8", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("Int8") return { @@ -116,17 +116,17 @@ export const Int8 = type( if (isString(v)) { return { type: "Int8", - value: v + value: v, } } throwTypeError("Expected positive integer for Int8") }, - (v) => v + v => v ) export const UInt16 = type( "UInt16", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("UInt16") return { @@ -137,38 +137,38 @@ export const UInt16 = type( if (isString(v)) { return { type: "UInt16", - value: v + value: v, } } throwTypeError("Expected integer for UInt16") }, - (v) => v + v => v ) export const Int16 = type( "Int16", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("Int16") return { type: "Int16", value: v.toString(), } - } + } if (isString(v)) { return { type: "Int16", - value: v + value: v, } } throwTypeError("Expected positive integer for Int16") }, - (v) => v + v => v ) export const UInt32 = type( "UInt32", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("UInt32") return { @@ -179,17 +179,17 @@ export const UInt32 = type( if (isString(v)) { return { type: "UInt32", - value: v + value: v, } } throwTypeError("Expected integer for UInt32") }, - (v) => v + v => v ) export const Int32 = type( "Int32", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("Int32") return { @@ -200,17 +200,17 @@ export const Int32 = type( if (isString(v)) { return { type: "Int32", - value: v + value: v, } } throwTypeError("Expected positive integer for Int32") }, - (v) => v + v => v ) export const UInt64 = type( "UInt64", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("UInt64") return { @@ -221,17 +221,17 @@ export const UInt64 = type( if (isString(v)) { return { type: "UInt64", - value: v + value: v, } } throwTypeError("Expected integer for UInt64") }, - (v) => v + v => v ) export const Int64 = type( "Int64", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("Int64") return { @@ -242,17 +242,17 @@ export const Int64 = type( if (isString(v)) { return { type: "Int64", - value: v + value: v, } } throwTypeError("Expected positive integer for Int64") }, - (v) => v + v => v ) export const UInt128 = type( "UInt128", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("UInt128") return { @@ -263,17 +263,17 @@ export const UInt128 = type( if (isString(v)) { return { type: "UInt128", - value: v + value: v, } } throwTypeError("Expected integer for UInt128") }, - (v) => v + v => v ) export const Int128 = type( "Int128", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("Int128") return { @@ -284,17 +284,17 @@ export const Int128 = type( if (isString(v)) { return { type: "Int128", - value: v + value: v, } } throwTypeError("Expected positive integer for Int128") }, - (v) => v + v => v ) export const UInt256 = type( "UInt256", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("UInt256") return { @@ -305,17 +305,17 @@ export const UInt256 = type( if (isString(v)) { return { type: "UInt256", - value: v + value: v, } } throwTypeError("Expected integer for UInt256") }, - (v) => v + v => v ) export const Int256 = type( "Int256", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("Int256") return { @@ -326,17 +326,17 @@ export const Int256 = type( if (isString(v)) { return { type: "Int256", - value: v + value: v, } } throwTypeError("Expected integer for Int256") }, - (v) => v + v => v ) export const Word8 = type( "Word8", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("Word8") return { @@ -347,17 +347,17 @@ export const Word8 = type( if (isString(v)) { return { type: "Word8", - value: v + value: v, } } throwTypeError("Expected positive number for Word8") }, - (v) => v + v => v ) export const Word16 = type( "Word16", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("Word16") return { @@ -368,17 +368,17 @@ export const Word16 = type( if (isString(v)) { return { type: "Word16", - value: v + value: v, } } throwTypeError("Expected positive number for Word16") }, - (v) => v + v => v ) export const Word32 = type( "Word32", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("Word32") return { @@ -389,17 +389,17 @@ export const Word32 = type( if (isString(v)) { return { type: "Word32", - value: v + value: v, } } throwTypeError("Expected positive number for Word32") }, - (v) => v + v => v ) export const Word64 = type( "Word64", - (v) => { + v => { if (isNumber(v) && isInteger(v)) { numberValuesDeprecationNotice("Word64") return { @@ -410,12 +410,12 @@ export const Word64 = type( if (isString(v)) { return { type: "Word64", - value: v + value: v, } } throwTypeError("Expected positive number for Word64") }, - (v) => v + v => v ) const UFix64AndFix64NumberDeprecationNotice = () => { @@ -437,63 +437,71 @@ const UFix64AndFix64NumberDeprecationNotice = () => { export const UFix64 = type( "UFix64", - (v) => { + v => { if (isString(v)) { const vParts = v.split(".") if (vParts.length !== 2) { - throwTypeError(`Expected one decimal but found ${vParts.length} in the [U]Fix64 value. Find out more about [U]Fix64 types here: https://docs.onflow.org/cadence/json-cadence-spec/#fixed-point-numbers`) + throwTypeError( + `Expected one decimal but found ${vParts.length} in the [U]Fix64 value. Find out more about [U]Fix64 types here: https://docs.onflow.org/cadence/json-cadence-spec/#fixed-point-numbers` + ) } if (vParts[1].length == 0 || vParts[1].length > 8) { - throwTypeError(`Expected at least one digit, and at most 8 digits following the decimal of the [U]Fix64 value but found ${vParts[1].length} digits. Find out more about [U]Fix64 types here: https://docs.onflow.org/cadence/json-cadence-spec/#fixed-point-numbers`) + throwTypeError( + `Expected at least one digit, and at most 8 digits following the decimal of the [U]Fix64 value but found ${vParts[1].length} digits. Find out more about [U]Fix64 types here: https://docs.onflow.org/cadence/json-cadence-spec/#fixed-point-numbers` + ) } return { type: "UFix64", - value: v + value: v, } } else if (isNumber(v)) { UFix64AndFix64NumberDeprecationNotice() return { type: "UFix64", - value: v.toString() + value: v.toString(), } } throwTypeError("Expected String for UFix64") }, - (v) => v + v => v ) export const Fix64 = type( "Fix64", - (v) => { + v => { if (isString(v)) { const vParts = v.split(".") if (vParts.length !== 2) { - throwTypeError(`Expected one decimal but found ${vParts.length} in the [U]Fix64 value. Find out more about [U]Fix64 types here: https://docs.onflow.org/cadence/json-cadence-spec/#fixed-point-numbers`) + throwTypeError( + `Expected one decimal but found ${vParts.length} in the [U]Fix64 value. Find out more about [U]Fix64 types here: https://docs.onflow.org/cadence/json-cadence-spec/#fixed-point-numbers` + ) } if (vParts[1].length == 0 || vParts[1].length > 8) { - throwTypeError(`Expected at least one digit, and at most 8 digits following the decimal of the [U]Fix64 value but found ${vParts[1].length} digits. Find out more about [U]Fix64 types here: https://docs.onflow.org/cadence/json-cadence-spec/#fixed-point-numbers`) + throwTypeError( + `Expected at least one digit, and at most 8 digits following the decimal of the [U]Fix64 value but found ${vParts[1].length} digits. Find out more about [U]Fix64 types here: https://docs.onflow.org/cadence/json-cadence-spec/#fixed-point-numbers` + ) } - + return { type: "Fix64", - value: v + value: v, } } else if (isNumber(v)) { UFix64AndFix64NumberDeprecationNotice() return { type: "Fix64", - value: v.toString() + value: v.toString(), } } throwTypeError("Expected String for Fix64") }, - (v) => v + v => v ) export const String = type( "String", - (v) => { + v => { if (isString(v)) return { type: "String", @@ -501,12 +509,12 @@ export const String = type( } throwTypeError("Expected String for type String") }, - (v) => v + v => v ) export const Character = type( "Character", - (v) => { + v => { if (isString(v)) return { type: "Character", @@ -514,12 +522,12 @@ export const Character = type( } throwTypeError("Expected Character for type Character") }, - (v) => v + v => v ) export const Bool = type( "Bool", - (v) => { + v => { if (isBoolean(v)) return { type: "Bool", @@ -527,12 +535,12 @@ export const Bool = type( } throwTypeError("Expected Boolean for type Bool") }, - (v) => v + v => v ) export const Address = type( "Address", - (v) => { + v => { if (isString(v)) return { type: "Address", @@ -540,34 +548,34 @@ export const Address = type( } throwTypeError("Expected Address for type Address") }, - (v) => v + v => v ) export const Void = type( "Void", - (v) => { + v => { if (!v || isNull(v)) return { type: "Void", } throwTypeError("Expected Void for type Void") }, - (v) => v + v => v ) -export const Optional = (children) => +export const Optional = children => type( "Optional", - (v) => ({ + v => ({ type: "Optional", value: isNull(v) ? null : children.asArgument(v), }), - (v) => v + v => v ) export const Reference = type( "Reference", - (v) => { + v => { if (isObj(v)) return { type: "Reference", @@ -575,21 +583,21 @@ export const Reference = type( } throwTypeError("Expected Object for type Reference") }, - (v) => v + v => v ) export const _Array = (children = []) => type( "Array", - (v) => { + v => { return { type: "Array", value: isArray(children) ? children.map((c, i) => c.asArgument(v[i])) - : v.map((x) => children.asArgument(x)), + : v.map(x => children.asArgument(x)), } }, - (v) => v + v => v ) export {_Array as Array} @@ -597,7 +605,7 @@ export {_Array as Array} export const Dictionary = (children = []) => type( "Dictionary", - (v) => { + v => { if (isObj(v)) return { type: "Dictionary", @@ -607,7 +615,7 @@ export const Dictionary = (children = []) => value: c.value.asArgument(v[i].value), })) : isArray(v) - ? v.map((x) => ({ + ? v.map(x => ({ key: children.key.asArgument(x.key), value: children.value.asArgument(x.value), })) @@ -620,13 +628,13 @@ export const Dictionary = (children = []) => } throwTypeError("Expected Object for type Dictionary") }, - (v) => v + v => v ) export const Event = (id, fields = []) => type( "Event", - (v) => { + v => { if (isObj(v)) return { type: "Event", @@ -637,7 +645,7 @@ export const Event = (id, fields = []) => name: v.fields[i].name, value: c.value.asArgument(v.fields[i].value), })) - : v.fields.map((x) => ({ + : v.fields.map(x => ({ name: x.name, value: fields.value.asArgument(x.value), })), @@ -645,13 +653,13 @@ export const Event = (id, fields = []) => } throwTypeError("Expected Object for type Event") }, - (v) => v + v => v ) export const Resource = (id, fields = []) => type( "Resource", - (v) => { + v => { if (isObj(v)) return { type: "Resource", @@ -662,7 +670,7 @@ export const Resource = (id, fields = []) => name: v.fields[i].name, value: c.value.asArgument(v.fields[i].value), })) - : v.fields.map((x) => ({ + : v.fields.map(x => ({ name: x.name, value: fields.value.asArgument(x.value), })), @@ -670,13 +678,13 @@ export const Resource = (id, fields = []) => } throwTypeError("Expected Object for type Resource") }, - (v) => v + v => v ) export const Struct = (id, fields = []) => type( "Struct", - (v) => { + v => { if (isObj(v)) return { type: "Struct", @@ -687,7 +695,7 @@ export const Struct = (id, fields = []) => name: v.fields[i].name, value: c.value.asArgument(v.fields[i].value), })) - : v.fields.map((x) => ({ + : v.fields.map(x => ({ name: x.name, value: fields.value.asArgument(x.value), })), @@ -695,34 +703,46 @@ export const Struct = (id, fields = []) => } throwTypeError("Expected Object for type Struct") }, - (v) => v + v => v ) export const Path = type( - "Path", - (v) => { - if (isObj(v)) { - if (!isString(v.domain)) { - throwTypeError(`Expected a string for the Path domain but found ${v.domain}. Find out more about the Path type here: https://docs.onflow.org/cadence/json-cadence-spec/#path`) - } + "Path", + v => { + if (isObj(v)) { + if (!isString(v.domain)) { + throwTypeError( + `Expected a string for the Path domain but found ${v.domain}. Find out more about the Path type here: https://docs.onflow.org/cadence/json-cadence-spec/#path` + ) + } - if (!(v.domain === "storage" || v.domain === "private" || v.domain === "public")) { - throwTypeError(`Expected either "storage", "private" or "public" as the Path domain but found ${v.domain}. Find out more about the Path type here: https://docs.onflow.org/cadence/json-cadence-spec/#path`) - } + if ( + !( + v.domain === "storage" || + v.domain === "private" || + v.domain === "public" + ) + ) { + throwTypeError( + `Expected either "storage", "private" or "public" as the Path domain but found ${v.domain}. Find out more about the Path type here: https://docs.onflow.org/cadence/json-cadence-spec/#path` + ) + } - if (!isString(v.identifier)) { - throwTypeError(`Expected a string for the Path identifier but found ${v.identifier}. Find out more about the Path type here: https://docs.onflow.org/cadence/json-cadence-spec/#path`) - } + if (!isString(v.identifier)) { + throwTypeError( + `Expected a string for the Path identifier but found ${v.identifier}. Find out more about the Path type here: https://docs.onflow.org/cadence/json-cadence-spec/#path` + ) + } - return { - type: "Path", - value: { - domain: v.domain, - identifier: v.identifier - }, - } + return { + type: "Path", + value: { + domain: v.domain, + identifier: v.identifier, + }, } - throwTypeError("Expected Object for type Path") - }, - (v) => v - ) + } + throwTypeError("Expected Object for type Path") + }, + v => v +) diff --git a/packages/types/src/types.test.js b/packages/types/src/types.test.js index 03eaf19f9..ccea19f30 100644 --- a/packages/types/src/types.test.js +++ b/packages/types/src/types.test.js @@ -23,8 +23,20 @@ import * as t from "./types.js" [t.Word64, "64", {type: "Word64", value: "64"}, "64"], [t.UFix64, "64", {type: "UFix64", value: "64"}, "64", true], [t.Fix64, "64", {type: "Fix64", value: "64"}, "64", true], - [t.UFix64, "64.000000001", {type: "UFix64", value: "64.000000001"}, "64.000000001", true], - [t.Fix64, "64.000000001", {type: "Fix64", value: "64.000000001"}, "64.000000001", true], + [ + t.UFix64, + "64.000000001", + {type: "UFix64", value: "64.000000001"}, + "64.000000001", + true, + ], + [ + t.Fix64, + "64.000000001", + {type: "Fix64", value: "64.000000001"}, + "64.000000001", + true, + ], [t.UFix64, "64.0", {type: "UFix64", value: "64.0"}, "64.0", false], [t.Fix64, "64.0", {type: "Fix64", value: "64.0"}, "64.0", false], [ @@ -167,46 +179,46 @@ import * as t from "./types.js" t.Path, { domain: "public", - identifier: "flowTokenVault" + identifier: "flowTokenVault", }, { type: "Path", value: { domain: "public", - identifier: "flowTokenVault" + identifier: "flowTokenVault", }, }, { domain: "public", - identifier: "flowTokenVault" + identifier: "flowTokenVault", }, ], [ t.Path, { domain: "notValidDomain", - identifier: "flowTokenVault" + identifier: "flowTokenVault", }, { type: "Path", value: { domain: "notValidDomain", - identifier: "flowTokenVault" + identifier: "flowTokenVault", }, }, { domain: "notValidDomain", - identifier: "flowTokenVault" + identifier: "flowTokenVault", }, - true - ] + true, + ], ].forEach(([cast, input, asArgument, asInjection, shouldError = false]) => { describe(cast.label, () => { test(`t.${cast.label}.asArgument(${input})`, () => { if (shouldError) { - expect(() => cast.asArgument(input)).toThrow() + expect(() => cast.asArgument(input)).toThrow() } else { - expect(cast.asArgument(input)).toStrictEqual(asArgument) + expect(cast.asArgument(input)).toStrictEqual(asArgument) } }) test(`t.${cast.label}.asInjection(${input})`, () => { diff --git a/packages/util-actor/src/index.js b/packages/util-actor/src/index.js index b443be5f0..8baac95a8 100644 --- a/packages/util-actor/src/index.js +++ b/packages/util-actor/src/index.js @@ -60,25 +60,27 @@ export const kill = addr => { delete root.FCL_REGISTRY[addr] } -const fromHandlers = (handlers = {}) => async ctx => { - if (typeof handlers[INIT] === "function") await handlers[INIT](ctx) - __loop: while (1) { - const letter = await ctx.receive() - try { - if (letter.tag === EXIT) { - if (typeof handlers[TERMINATE] === "function") { - await handlers[TERMINATE](ctx, letter, letter.data || {}) +const fromHandlers = + (handlers = {}) => + async ctx => { + if (typeof handlers[INIT] === "function") await handlers[INIT](ctx) + __loop: while (1) { + const letter = await ctx.receive() + try { + if (letter.tag === EXIT) { + if (typeof handlers[TERMINATE] === "function") { + await handlers[TERMINATE](ctx, letter, letter.data || {}) + } + break __loop } - break __loop + await handlers[letter.tag](ctx, letter, letter.data || {}) + } catch (error) { + console.error(`${ctx.self()} Error`, letter, error) + } finally { + continue __loop } - await handlers[letter.tag](ctx, letter, letter.data || {}) - } catch (error) { - console.error(`${ctx.self()} Error`, letter, error) - } finally { - continue __loop } } -} export const spawn = (fn, addr = null) => { if (addr == null) addr = ++pid diff --git a/packages/util-address/src/index.js b/packages/util-address/src/index.js index 53fc303c2..61919b03d 100644 --- a/packages/util-address/src/index.js +++ b/packages/util-address/src/index.js @@ -1,8 +1,6 @@ export function sansPrefix(address) { if (address == null) return null - return address - .replace(/^0x/, "") - .replace(/^Fx/, "") + return address.replace(/^0x/, "").replace(/^Fx/, "") } export function withPrefix(address) { diff --git a/packages/util-invariant/src/index.js b/packages/util-invariant/src/index.js index a08399e76..c29d2356f 100644 --- a/packages/util-invariant/src/index.js +++ b/packages/util-invariant/src/index.js @@ -1,4 +1,4 @@ -export function invariant (fact, msg, ...rest) { +export function invariant(fact, msg, ...rest) { if (!fact) { const error = new Error(`INVARIANT ${msg}`) error.stack = error.stack diff --git a/packages/util-logger/src/util-logger.js b/packages/util-logger/src/util-logger.js index 414c5daaa..b7dbdea2a 100644 --- a/packages/util-logger/src/util-logger.js +++ b/packages/util-logger/src/util-logger.js @@ -1,46 +1,47 @@ import {config} from "@onflow/config" export const LEVELS = Object.freeze({ - "debug": 5, - "info": 4, - "log": 3, - "warn": 2, - "error": 1 + debug: 5, + info: 4, + log: 3, + warn: 2, + error: 1, }) const buildLoggerMessageArgs = ({title, message}) => { - return [` + return [ + ` %c${title} ============================ ${message} ============================ `, - "font-weight:bold;font-family:monospace;" + "font-weight:bold;font-family:monospace;", ] } export const log = async ({title, message, level, always = false}) => { - const configLoggerLevel = await config.get("logger.level", 0) + const configLoggerLevel = await config.get("logger.level", 0) // If config level is below message level then don't show it if (!always && configLoggerLevel < level) return const loggerMessageArgs = buildLoggerMessageArgs({title, message}) - switch(level) { + switch (level) { case LEVELS.debug: console.debug(...loggerMessageArgs) - break; + break case LEVELS.info: console.info(...loggerMessageArgs) - break; + break case LEVELS.warn: console.warn(...loggerMessageArgs) - break; + break case LEVELS.error: console.error(...loggerMessageArgs) - break; + break default: console.log(...loggerMessageArgs) } -} \ No newline at end of file +} diff --git a/packages/util-logger/src/util-logger.test.js b/packages/util-logger/src/util-logger.test.js index 93c8b9147..0710764b7 100644 --- a/packages/util-logger/src/util-logger.test.js +++ b/packages/util-logger/src/util-logger.test.js @@ -15,8 +15,8 @@ describe("logger", () => { let configRef const loggerLevelConfigKey = "logger.level" const testArgs = { - title: "test title", - message: "test message" + title: "test title", + message: "test message", } beforeEach(() => { diff --git a/packages/util-node-http-modules/src/util-node-http-modules.js b/packages/util-node-http-modules/src/util-node-http-modules.js index 6e6efd157..c9e5c1b0e 100644 --- a/packages/util-node-http-modules/src/util-node-http-modules.js +++ b/packages/util-node-http-modules/src/util-node-http-modules.js @@ -10,6 +10,6 @@ export async function getNodeHttpModules() { return { nodeHttpsTransport, - nodeHttpTransport + nodeHttpTransport, } } diff --git a/packages/util-template/src/template.js b/packages/util-template/src/template.js index 90f4c631b..60a76c3ef 100644 --- a/packages/util-template/src/template.js +++ b/packages/util-template/src/template.js @@ -13,7 +13,7 @@ export function interleave(a = [], b = [], c = []) { } function recApply(d) { - return function(arg1) { + return function (arg1) { if (typeof arg1 === "function") { console.warn( ` diff --git a/packages/util-uid/src/util-uid.js b/packages/util-uid/src/util-uid.js index 917c29f9c..4a817fcc4 100644 --- a/packages/util-uid/src/util-uid.js +++ b/packages/util-uid/src/util-uid.js @@ -1,10 +1,11 @@ // Inspired by: https://github.com/lukeed/uid/blob/master/src/index.js , thank you Luke! https://github.com/lukeed -var HEX = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' +var HEX = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var T = HEX.length -export function uid () { - var str='', num=32 - while (num--) str += HEX[Math.random() * T | 0] +export function uid() { + var str = "", + num = 32 + while (num--) str += HEX[(Math.random() * T) | 0] return str }