@agoric/client-utils 0.1.1-dev-02c06c4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # Client Utils
2
+
3
+ Utilities for building clients of an Agoric chain
4
+
5
+ ## Overview
6
+
7
+ The Agoric chain takes mutations through signed messages and reveals state updates through vstorage. This package abstracts the calls to RPC nodes into a [CQRS](https://en.wikipedia.org/wiki/Command%E2%80%93query_separation) interface. The commands are made mostly through an on-chain Smart Wallet and the queries through vstorage.
8
+
9
+ ## Design
10
+
11
+ This package will be used in several kinds of clients:
12
+ - CLI (such as the `agoric` command)
13
+ - GUI (such as dapps)
14
+ - Tests (such as a3p-integration tests)
15
+
16
+ As such the modules cannot assume they're running in Node. There are some ambient authorities in common in the above environments (e.g. `setTimeout`) but a further constraint is that these modules will not export ambient authority. Instead they will provide interfaces that are ergonomic for creating empowered objects in the client context.
17
+
18
+ ## Related packages
19
+
20
+ ### cli
21
+ `agoric` package has a command line UI (CLI) for working with an Agoric chain. It's in this repository at `packages/agoric-cli`.
22
+
23
+ ### rpc
24
+ `@agoric/rpc` is a small library that currently just has utilities for watching vstorage. This package avoids depending on `@agoric/rpc` for now because it:
25
+ - is in a separate repository ([ui-kit](https://github.com/Agoric/ui-kit/blob/main/packages/rpc)) so not part of agoric-sdk CI
26
+ - depends on `axios` and `vite` which are unnecessary constraints
27
+
28
+ Some of the functionality in this package could make sense in that package, but for now it will be ignored.
29
+
30
+ ### cosmic-proto
31
+
32
+ `@agoric/cosmic-proto` is a package that contains the protobuf stubs for the Agoric cosmos-sdk module. At various points it has also held generated RPC clients. Because that package is imported into contracts we've kept those out. They may end up in `@agoric/rpc` eventually.
33
+
34
+ ### * / clientSupport
35
+
36
+ The `clientSupport.js` module of several packages. Some packages export this module with certain helpers that this package may abstract.
37
+
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@agoric/client-utils",
3
+ "version": "0.1.1-dev-02c06c4.0+02c06c4",
4
+ "description": "Utilities for building Agoric clients",
5
+ "license": "Apache-2.0",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "type": "module",
10
+ "main": "src/main.js",
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "scripts": {
15
+ "build": "exit 0",
16
+ "prepack": "tsc --build tsconfig.build.json",
17
+ "postpack": "git clean -f '*.d.ts*' '*.tsbuildinfo'",
18
+ "test": "ava",
19
+ "test:c8": "c8 $C8_OPTIONS ava --config=ava-nesm.config.js",
20
+ "test:xs": "exit 0",
21
+ "lint-fix": "yarn lint:eslint --fix",
22
+ "lint": "run-s --continue-on-error lint:*",
23
+ "lint:types": "tsc",
24
+ "lint:eslint": "eslint ."
25
+ },
26
+ "devDependencies": {
27
+ "ava": "^5.3.0",
28
+ "c8": "^9.1.0",
29
+ "ts-blank-space": "^0.4.1"
30
+ },
31
+ "dependencies": {
32
+ "@agoric/casting": "0.4.3-dev-02c06c4.0+02c06c4",
33
+ "@agoric/ertp": "0.16.3-dev-02c06c4.0+02c06c4",
34
+ "@agoric/internal": "0.3.3-dev-02c06c4.0+02c06c4",
35
+ "@agoric/smart-wallet": "0.5.4-dev-02c06c4.0+02c06c4",
36
+ "@agoric/vats": "0.15.2-dev-02c06c4.0+02c06c4",
37
+ "@cosmjs/stargate": "^0.32.3",
38
+ "@cosmjs/tendermint-rpc": "^0.32.3",
39
+ "@endo/common": "^1.2.7",
40
+ "@endo/errors": "^1.2.7",
41
+ "@endo/marshal": "^1.6.1",
42
+ "@endo/pass-style": "^1.4.6",
43
+ "@endo/patterns": "^1.4.6",
44
+ "@endo/promise-kit": "^1.1.7"
45
+ },
46
+ "ava": {
47
+ "extensions": {
48
+ "js": true,
49
+ "ts": "module"
50
+ },
51
+ "files": [
52
+ "test/**/*.test.*"
53
+ ],
54
+ "nodeArguments": [
55
+ "--import=ts-blank-space/register",
56
+ "--no-warnings"
57
+ ],
58
+ "require": [
59
+ "@endo/init/legacy.js"
60
+ ],
61
+ "timeout": "20m"
62
+ },
63
+ "gitHead": "02c06c489677233c0daa112284d16c314aff97c6"
64
+ }
package/src/chain.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export function pollBlocks(opts: {
2
+ client: StargateClient;
3
+ delay: (ms: number) => Promise<void>;
4
+ period?: number;
5
+ retryMessage?: string;
6
+ }): <T>(l: (b: {
7
+ time: string;
8
+ height: number;
9
+ }) => Promise<T>) => Promise<T>;
10
+ import type { StargateClient } from '@cosmjs/stargate';
11
+ //# sourceMappingURL=chain.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chain.d.ts","sourceRoot":"","sources":["chain.js"],"names":[],"mappings":"AAaO,iCARI;IACN,MAAM,EAAE,cAAc,CAAC;IACvB,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACrC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,GACS,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,CA2BrF;oCArCgC,kBAAkB"}
package/src/chain.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @import {StargateClient} from '@cosmjs/stargate';
3
+ */
4
+
5
+ /**
6
+ * @param {{
7
+ * client: StargateClient,
8
+ * delay: (ms: number) => Promise<void>,
9
+ * period?: number,
10
+ * retryMessage?: string,
11
+ * }} opts
12
+ * @returns {<T>(l: (b: { time: string, height: number }) => Promise<T>) => Promise<T>}
13
+ */
14
+ export const pollBlocks = opts => async lookup => {
15
+ const { client, delay, period = 3 * 1000 } = opts;
16
+ const { retryMessage } = opts;
17
+
18
+ await null; // separate sync prologue
19
+
20
+ for (;;) {
21
+ const status = await client.getBlock();
22
+ const {
23
+ header: { time, height },
24
+ } = status;
25
+ try {
26
+ // see await null above
27
+ const result = await lookup({ time, height });
28
+ return result;
29
+ } catch (_err) {
30
+ console.error(
31
+ time,
32
+ retryMessage || 'not in block',
33
+ height,
34
+ 'retrying...',
35
+ );
36
+ await delay(period);
37
+ }
38
+ }
39
+ };
package/src/main.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from "./rpc.js";
2
+ export * from "./sync-tools.js";
3
+ export * from "./vstorage-kit.js";
4
+ export * from "./wallet-utils.js";
5
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["main.js"],"names":[],"mappings":""}
package/src/main.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './rpc.js';
2
+ export * from './sync-tools.js';
3
+ export * from './vstorage-kit.js';
4
+ export * from './wallet-utils.js';
package/src/rpc.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ export function pickEndpoint({ rpcAddrs }: {
2
+ rpcAddrs: any;
3
+ }): any;
4
+ export function makeTendermint34Client(endpoint: string, { fetch }: {
5
+ fetch: typeof window.fetch;
6
+ }): Promise<Tendermint34Client>;
7
+ export function makeStargateClient(config: MinimalNetworkConfig, { fetch }: {
8
+ fetch: typeof window.fetch;
9
+ }): Promise<StargateClient>;
10
+ export type MinimalNetworkConfig = {
11
+ rpcAddrs: string[];
12
+ chainName: string;
13
+ };
14
+ import { Tendermint34Client } from '@cosmjs/tendermint-rpc';
15
+ import { StargateClient } from '@cosmjs/stargate';
16
+ //# sourceMappingURL=rpc.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc.d.ts","sourceRoot":"","sources":["rpc.js"],"names":[],"mappings":"AASO;;QAAkD;AAOlD,iDAJI,MAAM,aACN;IAAE,KAAK,EAAE,OAAO,MAAM,CAAC,KAAK,CAAA;CAAE,GAC5B,OAAO,CAAC,kBAAkB,CAAC,CAKvC;AAOM,2CAJI,oBAAoB,aACpB;IAAE,KAAK,EAAE,OAAO,MAAM,CAAC,KAAK,CAAA;CAAE,GAC5B,OAAO,CAAC,cAAc,CAAC,CAMnC;mCAzBY;IAAE,QAAQ,EAAE,MAAM,EAAE,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE;mCAHnB,wBAAwB;+BAD5B,kBAAkB"}
package/src/rpc.js ADDED
@@ -0,0 +1,31 @@
1
+ import { makeTendermintRpcClient } from '@agoric/casting';
2
+ import { StargateClient } from '@cosmjs/stargate';
3
+ import { Tendermint34Client } from '@cosmjs/tendermint-rpc';
4
+
5
+ /**
6
+ * @typedef {{ rpcAddrs: string[], chainName: string }} MinimalNetworkConfig
7
+ */
8
+
9
+ // TODO distribute load
10
+ export const pickEndpoint = ({ rpcAddrs }) => rpcAddrs[0];
11
+
12
+ /**
13
+ * @param {string} endpoint
14
+ * @param {{ fetch: typeof window.fetch }} io
15
+ * @returns {Promise<Tendermint34Client>}
16
+ */
17
+ export const makeTendermint34Client = (endpoint, { fetch }) => {
18
+ const rpcClient = makeTendermintRpcClient(endpoint, fetch);
19
+ return Tendermint34Client.create(rpcClient);
20
+ };
21
+
22
+ /**
23
+ * @param {MinimalNetworkConfig} config
24
+ * @param {{ fetch: typeof window.fetch }} io
25
+ * @returns {Promise<StargateClient>}
26
+ */
27
+ export const makeStargateClient = async (config, { fetch }) => {
28
+ const url = pickEndpoint(config);
29
+ const tm = await makeTendermint34Client(url, { fetch });
30
+ return StargateClient.create(tm);
31
+ };
@@ -0,0 +1,43 @@
1
+ export function sleep(ms: number, { log, setTimeout }: {
2
+ log: (message: string) => void;
3
+ setTimeout: typeof global.setTimeout;
4
+ }): Promise<any>;
5
+ export function retryUntilCondition(operation: () => Promise<any>, condition: (result: any) => boolean, message: string, { maxRetries, retryIntervalMs, log, setTimeout }: RetryOptions & {
6
+ log?: typeof console.log;
7
+ setTimeout: typeof global.setTimeout;
8
+ }): Promise<any>;
9
+ export function waitUntilContractDeployed(contractName: string, ambientAuthority: {
10
+ log: (message: string) => void;
11
+ follow: () => object;
12
+ setTimeout: typeof global.setTimeout;
13
+ }, options: WaitUntilOptions): Promise<any>;
14
+ export function waitUntilAccountFunded(destAcct: string, io: {
15
+ log: (message: string) => void;
16
+ query: () => Promise<object>;
17
+ setTimeout: typeof global.setTimeout;
18
+ }, threshold: {
19
+ denom: string;
20
+ value: number;
21
+ }, options: WaitUntilOptions): Promise<any>;
22
+ export function waitUntilOfferResult(addr: string, offerId: string, waitForPayouts: boolean, io: {
23
+ log: typeof console.log;
24
+ follow: () => object;
25
+ setTimeout: typeof global.setTimeout;
26
+ }, options: WaitUntilOptions): Promise<any>;
27
+ export function waitUntilInvitationReceived(addr: string, io: {
28
+ follow: () => object;
29
+ log: typeof console.log;
30
+ setTimeout: typeof global.setTimeout;
31
+ }, options: WaitUntilOptions): Promise<any>;
32
+ export type RetryOptions = {
33
+ maxRetries?: number | undefined;
34
+ retryIntervalMs?: number | undefined;
35
+ };
36
+ export type WaitUntilOptions = RetryOptions & {
37
+ errorMessage: string;
38
+ };
39
+ export type CosmosBalanceThreshold = {
40
+ denom: string;
41
+ value: number;
42
+ };
43
+ //# sourceMappingURL=sync-tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync-tools.d.ts","sourceRoot":"","sources":["sync-tools.js"],"names":[],"mappings":"AAgCO,0BAHI,MAAM,uBACN;IAAC,GAAG,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAAC,UAAU,EAAE,OAAO,MAAM,CAAC,UAAU,CAAA;CAAC,gBAM7E;AAUG,+CALI,kBAAa,aACb,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,WACxB,MAAM,oDACN,YAAY,GAAG;IAAC,GAAG,CAAC,EAAE,OAAO,OAAO,CAAC,GAAG,CAAC;IAAC,UAAU,EAAE,OAAO,MAAM,CAAC,UAAU,CAAA;CAAC,gBAoCzF;AAiCM,wDAJI,MAAM,oBACN;IAAE,GAAG,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAAC,MAAM,EAAE,MAAM,MAAM,CAAC;IAAC,UAAU,EAAE,OAAO,MAAM,CAAC,UAAU,CAAA;CAAE,WAC9F,gBAAgB,gBAkB1B;AA0BM,iDALI,MAAM,MACN;IAAE,GAAG,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAAC,KAAK,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAAC,UAAU,EAAE,OAAO,MAAM,CAAC,UAAU,CAAA;CAAC,aACrG;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAC,WAC9B,gBAAgB,gBAc1B;AAqCM,2CANI,MAAM,WACN,MAAM,kBACN,OAAO,MACP;IAAE,GAAG,EAAE,OAAO,OAAO,CAAC,GAAG,CAAC;IAAC,MAAM,EAAE,MAAM,MAAM,CAAC;IAAC,UAAU,EAAE,OAAO,MAAM,CAAC,UAAU,CAAA;CAAE,WACvF,gBAAgB,gBAoB1B;AAwBM,kDAJI,MAAM,MACN;IAAE,MAAM,EAAE,MAAM,MAAM,CAAC;IAAC,GAAG,EAAE,OAAO,OAAO,CAAC,GAAG,CAAC;IAAC,UAAU,EAAE,OAAO,MAAM,CAAC,UAAU,CAAA;CAAC,WACtF,gBAAgB,gBAc1B;;;;;+BA/OY,YAAY,GAAG;IAAC,YAAY,EAAE,MAAM,CAAA;CAAC;;WAGpC,MAAM;WACN,MAAM"}
@@ -0,0 +1,259 @@
1
+ /**
2
+ * @file The purpose of this file is to bring together a set of tools that
3
+ * developers can use to synchronize operations they carry out in their tests.
4
+ *
5
+ * These operations include;
6
+ * - Making sure a core-eval resulted in successfully deploying a contract
7
+ * - Making sure a core-eval successfully sent zoe invitations to committee members for governance
8
+ * - Making sure an account is successfully funded with vbank assets like IST, BLD etc.
9
+ * - operation: query dest account's balance
10
+ * - condition: dest account has a balance >= sent token
11
+ * - Making sure an offer resulted successfully
12
+ *
13
+ */
14
+
15
+ /**
16
+ * @typedef {object} RetryOptions
17
+ * @property {number} [maxRetries]
18
+ * @property {number} [retryIntervalMs]
19
+ *
20
+ * @typedef {RetryOptions & {errorMessage: string}} WaitUntilOptions
21
+ *
22
+ * @typedef {object} CosmosBalanceThreshold
23
+ * @property {string} denom
24
+ * @property {number} value
25
+ */
26
+
27
+ /**
28
+ * From https://github.com/Agoric/agoric-sdk/blob/442f07c8f0af03281b52b90e90c27131eef6f331/multichain-testing/tools/sleep.ts#L10
29
+ *
30
+ * @param {number} ms
31
+ * @param {{log: (message: string) => void, setTimeout: typeof global.setTimeout}} io
32
+ */
33
+ export const sleep = (ms, { log = () => {}, setTimeout }) =>
34
+ new Promise(resolve => {
35
+ log(`Sleeping for ${ms}ms...`);
36
+ setTimeout(resolve, ms);
37
+ });
38
+
39
+ /**
40
+ * From https://github.com/Agoric/agoric-sdk/blob/442f07c8f0af03281b52b90e90c27131eef6f331/multichain-testing/tools/sleep.ts#L24
41
+ *
42
+ * @param {() => Promise} operation
43
+ * @param {(result: any) => boolean} condition
44
+ * @param {string} message
45
+ * @param {RetryOptions & {log?: typeof console.log, setTimeout: typeof global.setTimeout}} options
46
+ */
47
+ export const retryUntilCondition = async (
48
+ operation,
49
+ condition,
50
+ message,
51
+ { maxRetries = 6, retryIntervalMs = 3500, log = console.log, setTimeout },
52
+ ) => {
53
+ console.log({ maxRetries, retryIntervalMs, message });
54
+ let retries = 0;
55
+
56
+ await null; // separate sync prologue
57
+
58
+ while (retries < maxRetries) {
59
+ try {
60
+ const result = await operation();
61
+ log('RESULT', result);
62
+ if (condition(result)) {
63
+ return result;
64
+ }
65
+ } catch (error) {
66
+ if (error instanceof Error) {
67
+ log(`Error: ${error.message}`);
68
+ } else {
69
+ log(`Unknown error: ${String(error)}`);
70
+ }
71
+ }
72
+
73
+ retries += 1;
74
+ console.log(
75
+ `Retry ${retries}/${maxRetries} - Waiting for ${retryIntervalMs}ms for ${message}...`,
76
+ );
77
+ await sleep(retryIntervalMs, { log, setTimeout });
78
+ }
79
+
80
+ throw Error(`${message} condition failed after ${maxRetries} retries.`);
81
+ };
82
+
83
+ /**
84
+ * @param {WaitUntilOptions} options
85
+ */
86
+ const overrideDefaultOptions = options => {
87
+ const defaultValues = {
88
+ maxRetries: 6,
89
+ retryIntervalMs: 3500,
90
+ log: console.log,
91
+ errorMessage: 'Error',
92
+ };
93
+
94
+ return { ...defaultValues, ...options };
95
+ };
96
+
97
+ /// ////////// Making sure a core-eval resulted successfully deploying a contract /////////////
98
+
99
+ const makeGetInstances = follow => async () => {
100
+ const instanceEntries = await follow(
101
+ '-lF',
102
+ `:published.agoricNames.instance`,
103
+ );
104
+
105
+ return Object.fromEntries(instanceEntries);
106
+ };
107
+
108
+ /**
109
+ *
110
+ * @param {string} contractName
111
+ * @param {{ log: (message: string) => void, follow: () => object, setTimeout: typeof global.setTimeout }} ambientAuthority
112
+ * @param {WaitUntilOptions} options
113
+ */
114
+ export const waitUntilContractDeployed = (
115
+ contractName,
116
+ ambientAuthority,
117
+ options,
118
+ ) => {
119
+ const { follow, setTimeout } = ambientAuthority;
120
+ const getInstances = makeGetInstances(follow);
121
+ const { maxRetries, retryIntervalMs, errorMessage, log } =
122
+ overrideDefaultOptions(options);
123
+
124
+ return retryUntilCondition(
125
+ getInstances,
126
+ instanceObject => Object.keys(instanceObject).includes(contractName),
127
+ errorMessage,
128
+ { maxRetries, retryIntervalMs, log, setTimeout },
129
+ );
130
+ };
131
+
132
+ /// ////////// Making sure an account is successfully funded with vbank assets like IST, BLD etc. ///////////////
133
+
134
+ const makeQueryCosmosBalance = queryCb => async dest => {
135
+ const coins = await queryCb('bank', 'balances', dest);
136
+ return coins.balances;
137
+ };
138
+
139
+ /**
140
+ *
141
+ * @param {Array} balances
142
+ * @param {CosmosBalanceThreshold} threshold
143
+ * @returns {boolean}
144
+ */
145
+ const checkCosmosBalance = (balances, threshold) => {
146
+ const balance = [...balances].find(({ denom }) => denom === threshold.denom);
147
+ return Number(balance.amount) >= threshold.value;
148
+ };
149
+
150
+ /**
151
+ * @param {string} destAcct
152
+ * @param {{ log: (message: string) => void, query: () => Promise<object>, setTimeout: typeof global.setTimeout}} io
153
+ * @param {{denom: string, value: number}} threshold
154
+ * @param {WaitUntilOptions} options
155
+ */
156
+ export const waitUntilAccountFunded = (destAcct, io, threshold, options) => {
157
+ const { query, setTimeout } = io;
158
+ const queryCosmosBalance = makeQueryCosmosBalance(query);
159
+ const { maxRetries, retryIntervalMs, errorMessage, log } =
160
+ overrideDefaultOptions(options);
161
+
162
+ return retryUntilCondition(
163
+ async () => queryCosmosBalance(destAcct),
164
+ balances => checkCosmosBalance(balances, threshold),
165
+ errorMessage,
166
+ { maxRetries, retryIntervalMs, log, setTimeout },
167
+ );
168
+ };
169
+
170
+ /// ////////// Making sure an offers get results /////////////
171
+
172
+ const makeQueryWallet = follow => async (/** @type {string} */ addr) => {
173
+ const update = await follow('-lF', `:published.wallet.${addr}`);
174
+
175
+ return update;
176
+ };
177
+
178
+ /**
179
+ *
180
+ * @param {object} offerStatus
181
+ * @param {boolean} waitForPayouts
182
+ * @param {string} offerId
183
+ */
184
+ const checkOfferState = (offerStatus, waitForPayouts, offerId) => {
185
+ const { updated, status } = offerStatus;
186
+
187
+ if (updated !== 'offerStatus') return false;
188
+ if (!status) return false;
189
+ if (status.id !== offerId) return false;
190
+ if (!status.numWantsSatisfied || status.numWantsSatisfied !== 1) return false;
191
+ if (waitForPayouts && status.payouts) return true;
192
+ if (!waitForPayouts && status.result) return true;
193
+
194
+ return false;
195
+ };
196
+
197
+ /**
198
+ *
199
+ * @param {string} addr
200
+ * @param {string} offerId
201
+ * @param {boolean} waitForPayouts
202
+ * @param {{ log: typeof console.log, follow: () => object, setTimeout: typeof global.setTimeout }} io
203
+ * @param {WaitUntilOptions} options
204
+ */
205
+ export const waitUntilOfferResult = (
206
+ addr,
207
+ offerId,
208
+ waitForPayouts,
209
+ io,
210
+ options,
211
+ ) => {
212
+ const { follow, setTimeout } = io;
213
+ const queryWallet = makeQueryWallet(follow);
214
+ const { maxRetries, retryIntervalMs, errorMessage, log } =
215
+ overrideDefaultOptions(options);
216
+
217
+ return retryUntilCondition(
218
+ async () => queryWallet(addr),
219
+ status => checkOfferState(status, waitForPayouts, offerId),
220
+ errorMessage,
221
+ { maxRetries, retryIntervalMs, log, setTimeout },
222
+ );
223
+ };
224
+
225
+ /// ////////// Making sure a core-eval successfully sent zoe invitations to committee members for governance /////////////
226
+
227
+ /**
228
+ *
229
+ * @param {{ updated: string, currentAmount: any }} update
230
+ * @returns {boolean}
231
+ */
232
+ const checkForInvitation = update => {
233
+ const { updated, currentAmount } = update;
234
+
235
+ if (updated !== 'balance') return false;
236
+ if (!currentAmount || !currentAmount.brand) return false;
237
+
238
+ return currentAmount.brand.includes('Invitation');
239
+ };
240
+
241
+ /**
242
+ *
243
+ * @param {string} addr
244
+ * @param {{ follow: () => object, log: typeof console.log, setTimeout: typeof global.setTimeout}} io
245
+ * @param {WaitUntilOptions} options
246
+ */
247
+ export const waitUntilInvitationReceived = (addr, io, options) => {
248
+ const { follow, setTimeout } = io;
249
+ const queryWallet = makeQueryWallet(follow);
250
+ const { maxRetries, retryIntervalMs, errorMessage, log } =
251
+ overrideDefaultOptions(options);
252
+
253
+ return retryUntilCondition(
254
+ async () => queryWallet(addr),
255
+ checkForInvitation,
256
+ errorMessage,
257
+ { maxRetries, retryIntervalMs, log, setTimeout },
258
+ );
259
+ };
@@ -0,0 +1,108 @@
1
+ export { boardSlottingMarshaller };
2
+ export function makeVStorage(powers: {
3
+ fetch: typeof window.fetch;
4
+ }, config: MinimalNetworkConfig): {
5
+ url: (path?: string, { kind, height }?: {
6
+ kind?: string | undefined;
7
+ height?: number | undefined;
8
+ }) => string;
9
+ decode({ result: { response } }: {
10
+ result: {
11
+ response: any;
12
+ };
13
+ }): string;
14
+ /**
15
+ *
16
+ * @param {string} path
17
+ * @returns {Promise<string>} latest vstorage value at path
18
+ */
19
+ readLatest(path?: string): Promise<string>;
20
+ keys(path?: string): Promise<any>;
21
+ /**
22
+ * @param {string} path
23
+ * @param {number} [height] default is highest
24
+ * @returns {Promise<{blockHeight: number, values: string[]}>}
25
+ */
26
+ readAt(path: string, height?: number | undefined): Promise<{
27
+ blockHeight: number;
28
+ values: string[];
29
+ }>;
30
+ /**
31
+ * Read values going back as far as available
32
+ *
33
+ * @param {string} path
34
+ * @param {number | string} [minHeight]
35
+ * @returns {Promise<string[]>}
36
+ */
37
+ readFully(path: string, minHeight?: string | number | undefined): Promise<string[]>;
38
+ };
39
+ export function makeFromBoard(): {
40
+ convertSlotToVal: (boardId: any, iface: any) => any;
41
+ };
42
+ export namespace storageHelper {
43
+ function parseCapData(txt: string): {
44
+ blockHeight: any;
45
+ capDatas: {
46
+ body: string;
47
+ slots: string[];
48
+ }[];
49
+ };
50
+ function unserializeTxt(txt: string, ctx: IdMap): any[];
51
+ function parseMany(capDataStrings: string[]): {
52
+ body: string;
53
+ slots: string[];
54
+ }[];
55
+ }
56
+ export function makeAgoricNames(ctx: IdMap, vstorage: VStorage): Promise<import("@agoric/vats/tools/board-utils.js").AgoricNamesRemotes>;
57
+ export function makeVstorageKit({ fetch }: {
58
+ fetch: typeof window.fetch;
59
+ }, config: MinimalNetworkConfig): Promise<{
60
+ agoricNames: import("@agoric/vats/tools/board-utils.js").AgoricNamesRemotes;
61
+ fromBoard: {
62
+ convertSlotToVal: (boardId: any, iface: any) => any;
63
+ };
64
+ marshaller: Omit<import("@endo/marshal").Marshal<string | null>, "serialize" | "unserialize">;
65
+ readLatestHead: (path: string) => Promise<unknown>;
66
+ unserializeHead: (txt: string) => unknown;
67
+ vstorage: {
68
+ url: (path?: string, { kind, height }?: {
69
+ kind?: string | undefined;
70
+ height?: number | undefined;
71
+ }) => string;
72
+ decode({ result: { response } }: {
73
+ result: {
74
+ response: any;
75
+ };
76
+ }): string;
77
+ /**
78
+ *
79
+ * @param {string} path
80
+ * @returns {Promise<string>} latest vstorage value at path
81
+ */
82
+ readLatest(path?: string): Promise<string>;
83
+ keys(path?: string): Promise<any>;
84
+ /**
85
+ * @param {string} path
86
+ * @param {number} [height] default is highest
87
+ * @returns {Promise<{blockHeight: number, values: string[]}>}
88
+ */
89
+ readAt(path: string, height?: number | undefined): Promise<{
90
+ blockHeight: number;
91
+ values: string[];
92
+ }>;
93
+ /**
94
+ * Read values going back as far as available
95
+ *
96
+ * @param {string} path
97
+ * @param {number | string} [minHeight]
98
+ * @returns {Promise<string[]>}
99
+ */
100
+ readFully(path: string, minHeight?: string | number | undefined): Promise<string[]>;
101
+ };
102
+ }>;
103
+ export type VStorage = ReturnType<typeof makeVStorage>;
104
+ export type IdMap = ReturnType<typeof makeFromBoard>;
105
+ export type VstorageKit = Awaited<ReturnType<typeof makeVstorageKit>>;
106
+ import { boardSlottingMarshaller } from '@agoric/vats/tools/board-utils.js';
107
+ import type { MinimalNetworkConfig } from './rpc.js';
108
+ //# sourceMappingURL=vstorage-kit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"vstorage-kit.d.ts","sourceRoot":"","sources":["vstorage-kit.js"],"names":[],"mappings":";AAiBO,qCAHJ;IAAoC,KAAK,EAAjC,OAAO,MAAM,CAAC,KAAK;CAC3B,UAAQ,oBAAoB;;;;;;;;;;IA4C3B;;;;OAIG;sBAFQ,MAAM,GACJ,OAAO,CAAC,MAAM,CAAC;;IAU5B;;;;OAIG;iBAHQ,MAAM,gCAEJ,OAAO,CAAC;QAAC,WAAW,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,EAAE,CAAA;KAAC,CAAC;IAS7D;;;;;;OAMG;oBAHQ,MAAM,4CAEJ,OAAO,CAAC,MAAM,EAAE,CAAC;EAuCjC;AAIM;;EAWN;;IAMe,2BADD,MAAM;;;kBAwBE,MAAM;mBAAS,MAAM,EAAE;;MAd3C;IAKe,6BAHL,MAAM,OACN,KAAK,SAOf;IAEU,mCADC,MAAM,EAAE;cAGC,MAAM;eAAS,MAAM,EAAE;QAS3C;;AAUI,qCAJI,KAAK,YACL,QAAQ,GACN,OAAO,CAAC,OAAO,mCAAmC,EAAE,kBAAkB,CAAC,CAoBnF;AAMM,2CAHI;IAAE,KAAK,EAAE,OAAO,MAAM,CAAC,KAAK,CAAA;CAAE,UAC9B,oBAAoB;;;;;;2BAiBV,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC;2BAN3B,MAAM,KAAK,OAAO;;;;;;;;;;;QArKnC;;;;WAIG;0BAFQ,MAAM,GACJ,OAAO,CAAC,MAAM,CAAC;;QAU5B;;;;WAIG;qBAHQ,MAAM,gCAEJ,OAAO,CAAC;YAAC,WAAW,EAAE,MAAM,CAAC;YAAC,MAAM,EAAE,MAAM,EAAE,CAAA;SAAC,CAAC;QAS7D;;;;;;WAMG;wBAHQ,MAAM,4CAEJ,OAAO,CAAC,MAAM,EAAE,CAAC;;GA6JjC;uBArHa,UAAU,CAAC,OAAO,YAAY,CAAC;oBAe/B,UAAU,CAAC,OAAO,aAAa,CAAC;0BAuGhC,OAAO,CAAC,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;wCAnPlD,mCAAmC;0CAKH,UAAU"}
@@ -0,0 +1,248 @@
1
+ /* global Buffer */
2
+ import {
3
+ boardSlottingMarshaller,
4
+ makeBoardRemote,
5
+ } from '@agoric/vats/tools/board-utils.js';
6
+
7
+ export { boardSlottingMarshaller };
8
+
9
+ /**
10
+ * @import {MinimalNetworkConfig} from './rpc.js';
11
+ */
12
+
13
+ /**
14
+ * @param {object} powers
15
+ * @param {typeof window.fetch} powers.fetch
16
+ * @param {MinimalNetworkConfig} config
17
+ */
18
+ export const makeVStorage = (powers, config) => {
19
+ /** @param {string} path */
20
+ const getJSON = path => {
21
+ const url = config.rpcAddrs[0] + path;
22
+ // console.warn('fetching', url);
23
+ return powers.fetch(url, { keepalive: true }).then(res => res.json());
24
+ };
25
+ // height=0 is the same as omitting height and implies the highest block
26
+ const url = (path = 'published', { kind = 'children', height = 0 } = {}) =>
27
+ `/abci_query?path=%22/custom/vstorage/${kind}/${path}%22&height=${height}`;
28
+
29
+ const readStorage = (path = 'published', { kind = 'children', height = 0 }) =>
30
+ getJSON(url(path, { kind, height }))
31
+ .catch(err => {
32
+ throw Error(`cannot read ${kind} of ${path}: ${err.message}`);
33
+ })
34
+ .then(data => {
35
+ const {
36
+ result: { response },
37
+ } = data;
38
+ if (response?.code !== 0) {
39
+ /** @type {any} */
40
+ const err = Error(
41
+ `error code ${response?.code} reading ${kind} of ${path}: ${response.log}`,
42
+ );
43
+ err.code = response?.code;
44
+ err.codespace = response?.codespace;
45
+ throw err;
46
+ }
47
+ return data;
48
+ });
49
+
50
+ return {
51
+ url,
52
+ decode({ result: { response } }) {
53
+ const { code } = response;
54
+ if (code !== 0) {
55
+ throw response;
56
+ }
57
+ const { value } = response;
58
+ return Buffer.from(value, 'base64').toString();
59
+ },
60
+ /**
61
+ *
62
+ * @param {string} path
63
+ * @returns {Promise<string>} latest vstorage value at path
64
+ */
65
+ async readLatest(path = 'published') {
66
+ const raw = await readStorage(path, { kind: 'data' });
67
+ return this.decode(raw);
68
+ },
69
+ async keys(path = 'published') {
70
+ const raw = await readStorage(path, { kind: 'children' });
71
+ return JSON.parse(this.decode(raw)).children;
72
+ },
73
+ /**
74
+ * @param {string} path
75
+ * @param {number} [height] default is highest
76
+ * @returns {Promise<{blockHeight: number, values: string[]}>}
77
+ */
78
+ async readAt(path, height = undefined) {
79
+ const raw = await readStorage(path, { kind: 'data', height });
80
+ const txt = this.decode(raw);
81
+ /** @type {{ value: string }} */
82
+ const { value } = JSON.parse(txt);
83
+ return JSON.parse(value);
84
+ },
85
+ /**
86
+ * Read values going back as far as available
87
+ *
88
+ * @param {string} path
89
+ * @param {number | string} [minHeight]
90
+ * @returns {Promise<string[]>}
91
+ */
92
+ async readFully(path, minHeight = undefined) {
93
+ const parts = [];
94
+ // undefined the first iteration, to query at the highest
95
+ let blockHeight;
96
+ await null;
97
+ do {
98
+ // console.debug('READING', { blockHeight });
99
+ let values;
100
+ try {
101
+ ({ blockHeight, values } = await this.readAt(
102
+ path,
103
+ blockHeight && Number(blockHeight) - 1,
104
+ ));
105
+ // console.debug('readAt returned', { blockHeight });
106
+ } catch (err) {
107
+ if (
108
+ // CosmosSDK ErrInvalidRequest with particular message text;
109
+ // misrepresentation of pruned data
110
+ // TODO replace after incorporating a fix to
111
+ // https://github.com/cosmos/cosmos-sdk/issues/19992
112
+ err.codespace === 'sdk' &&
113
+ err.code === 18 &&
114
+ err.message.match(/pruned/)
115
+ ) {
116
+ // console.error(err);
117
+ break;
118
+ }
119
+ throw err;
120
+ }
121
+ parts.push(values);
122
+ // console.debug('PUSHED', values);
123
+ // console.debug('NEW', { blockHeight, minHeight });
124
+ if (minHeight && Number(blockHeight) <= Number(minHeight)) break;
125
+ } while (blockHeight > 0);
126
+ return parts.flat();
127
+ },
128
+ };
129
+ };
130
+ /** @typedef {ReturnType<typeof makeVStorage>} VStorage */
131
+
132
+ /** @deprecated */
133
+ export const makeFromBoard = () => {
134
+ const cache = new Map();
135
+ const convertSlotToVal = (boardId, iface) => {
136
+ if (cache.has(boardId)) {
137
+ return cache.get(boardId);
138
+ }
139
+ const val = makeBoardRemote({ boardId, iface });
140
+ cache.set(boardId, val);
141
+ return val;
142
+ };
143
+ return harden({ convertSlotToVal });
144
+ };
145
+ /** @typedef {ReturnType<typeof makeFromBoard>} IdMap */
146
+
147
+ /** @deprecated */
148
+ export const storageHelper = {
149
+ /** @param { string } txt */
150
+ parseCapData: txt => {
151
+ assert(typeof txt === 'string', typeof txt);
152
+ /** @type {{ value: string }} */
153
+ const { value } = JSON.parse(txt);
154
+ const specimen = JSON.parse(value);
155
+ const { blockHeight, values } = specimen;
156
+ assert(values, `empty values in specimen ${value}`);
157
+ const capDatas = storageHelper.parseMany(values);
158
+ return { blockHeight, capDatas };
159
+ },
160
+ /**
161
+ * @param {string} txt
162
+ * @param {IdMap} ctx
163
+ */
164
+ unserializeTxt: (txt, ctx) => {
165
+ const { capDatas } = storageHelper.parseCapData(txt);
166
+ return capDatas.map(capData =>
167
+ boardSlottingMarshaller(ctx.convertSlotToVal).fromCapData(capData),
168
+ );
169
+ },
170
+ /** @param {string[]} capDataStrings array of stringified capData */
171
+ parseMany: capDataStrings => {
172
+ assert(capDataStrings && capDataStrings.length);
173
+ /** @type {{ body: string, slots: string[] }[]} */
174
+ const capDatas = capDataStrings.map(s => JSON.parse(s));
175
+ for (const capData of capDatas) {
176
+ assert(typeof capData === 'object' && capData !== null);
177
+ assert('body' in capData && 'slots' in capData);
178
+ assert(typeof capData.body === 'string');
179
+ assert(Array.isArray(capData.slots));
180
+ }
181
+ return capDatas;
182
+ },
183
+ };
184
+ harden(storageHelper);
185
+
186
+ /**
187
+ * @deprecated
188
+ * @param {IdMap} ctx
189
+ * @param {VStorage} vstorage
190
+ * @returns {Promise<import('@agoric/vats/tools/board-utils.js').AgoricNamesRemotes>}
191
+ */
192
+ export const makeAgoricNames = async (ctx, vstorage) => {
193
+ const reverse = {};
194
+ const entries = await Promise.all(
195
+ ['brand', 'instance', 'vbankAsset'].map(async kind => {
196
+ const content = await vstorage.readLatest(
197
+ `published.agoricNames.${kind}`,
198
+ );
199
+ /** @type {Array<[string, import('@agoric/vats/tools/board-utils.js').BoardRemote]>} */
200
+ const parts = storageHelper.unserializeTxt(content, ctx).at(-1);
201
+ for (const [name, remote] of parts) {
202
+ if ('getBoardId' in remote) {
203
+ reverse[remote.getBoardId()] = name;
204
+ }
205
+ }
206
+ return [kind, Object.fromEntries(parts)];
207
+ }),
208
+ );
209
+ return { ...Object.fromEntries(entries), reverse };
210
+ };
211
+
212
+ /**
213
+ * @param {{ fetch: typeof window.fetch }} io
214
+ * @param {MinimalNetworkConfig} config
215
+ */
216
+ export const makeVstorageKit = async ({ fetch }, config) => {
217
+ await null;
218
+ try {
219
+ const vstorage = makeVStorage({ fetch }, config);
220
+ const fromBoard = makeFromBoard();
221
+ const agoricNames = await makeAgoricNames(fromBoard, vstorage);
222
+
223
+ const marshaller = boardSlottingMarshaller(fromBoard.convertSlotToVal);
224
+
225
+ /** @type {(txt: string) => unknown} */
226
+ const unserializeHead = txt =>
227
+ storageHelper.unserializeTxt(txt, fromBoard).at(-1);
228
+
229
+ /**
230
+ * Read latest at path and unmarshal it
231
+ * @type {(path: string) => Promise<unknown>}
232
+ */
233
+ const readLatestHead = path =>
234
+ vstorage.readLatest(path).then(unserializeHead);
235
+
236
+ return {
237
+ agoricNames,
238
+ fromBoard,
239
+ marshaller,
240
+ readLatestHead,
241
+ unserializeHead,
242
+ vstorage,
243
+ };
244
+ } catch (err) {
245
+ throw Error(`RPC failure (${config.rpcAddrs}): ${err.message}`);
246
+ }
247
+ };
248
+ /** @typedef {Awaited<ReturnType<typeof makeVstorageKit>>} VstorageKit */
@@ -0,0 +1,49 @@
1
+ export function makeWalletUtils({ fetch, delay }: {
2
+ fetch: typeof globalThis.fetch;
3
+ delay: (ms: number) => Promise<void>;
4
+ }, networkConfig: MinimalNetworkConfig): Promise<{
5
+ networkConfig: MinimalNetworkConfig;
6
+ agoricNames: import("@agoric/vats/tools/board-utils.js").AgoricNamesRemotes;
7
+ fromBoard: {
8
+ convertSlotToVal: (boardId: any, iface: any) => any;
9
+ };
10
+ marshaller: Omit<import("@endo/marshal").Marshal<string | null>, "serialize" | "unserialize">;
11
+ vstorage: {
12
+ url: (path?: string, { kind, height }?: {
13
+ kind?: string | undefined;
14
+ height?: number | undefined;
15
+ }) => string;
16
+ decode({ result: { response } }: {
17
+ result: {
18
+ response: any;
19
+ };
20
+ }): string;
21
+ readLatest(path?: string): Promise<string>;
22
+ keys(path?: string): Promise<any>;
23
+ readAt(path: string, height?: number | undefined): Promise<{
24
+ blockHeight: number;
25
+ values: string[];
26
+ }>;
27
+ readFully(path: string, minHeight?: string | number | undefined): Promise<string[]>;
28
+ };
29
+ getLastUpdate: (addr: string) => Promise<UpdateRecord>;
30
+ getCurrentWalletRecord: (addr: string) => Promise<CurrentWalletRecord>;
31
+ readLatestHead: (path: string) => Promise<unknown>;
32
+ storedWalletState: (from: string, minHeight?: string | number | undefined) => Promise<{
33
+ invitationsReceived: Map<import("@agoric/smart-wallet/src/offers.js").OfferId, {
34
+ acceptedIn: import("@agoric/smart-wallet/src/offers.js").OfferId;
35
+ description: string;
36
+ instance: Instance;
37
+ }>;
38
+ offerStatuses: Map<import("@agoric/smart-wallet/src/offers.js").OfferId, import("@agoric/smart-wallet/src/offers.js").OfferStatus>;
39
+ balances: Map<Brand, Amount>;
40
+ }>;
41
+ pollOffer: (from: string, id: string | number, minHeight: number | string, untilNumWantsSatisfied?: boolean | undefined) => Promise<import("@agoric/smart-wallet/src/offers.js").OfferStatus>;
42
+ }>;
43
+ export type WalletUtils = Awaited<ReturnType<typeof makeWalletUtils>>;
44
+ import type { MinimalNetworkConfig } from './rpc.js';
45
+ import type { UpdateRecord } from '@agoric/smart-wallet/src/smartWallet.js';
46
+ import type { CurrentWalletRecord } from '@agoric/smart-wallet/src/smartWallet.js';
47
+ import type { Brand } from '@agoric/ertp/src/types.js';
48
+ import type { Amount } from '@agoric/ertp/src/types.js';
49
+ //# sourceMappingURL=wallet-utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wallet-utils.d.ts","sourceRoot":"","sources":["wallet-utils.js"],"names":[],"mappings":"AAkBO,kDAJJ;IAAuC,KAAK,EAApC,OAAO,UAAU,CAAC,KAAK;IACc,KAAK,EAA1C,CAAC,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC;CACrC,iBAAQ,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;0BAoElB,MAAM,KACJ,OAAO,CAAC,YAAY,CAAC;mCASvB,MAAM,KACJ,OAAO,CAAC,mBAAmB,CAAC;;8BArE9B,MAAM;;;;;;;;;sBA2BN,MAAM,MACN,MAAM,GAAC,MAAM,aACb,MAAM,GAAC,MAAM;GA4DzB;0BACa,OAAO,CAAC,UAAU,CAAC,OAAO,eAAe,CAAC,CAAC;0CA5GlB,UAAU;kCADG,yCAAyC;yCAAzC,yCAAyC;2BAD7D,2BAA2B;4BAA3B,2BAA2B"}
@@ -0,0 +1,117 @@
1
+ import { makeWalletStateCoalescer } from '@agoric/smart-wallet/src/utils.js';
2
+ import { pollBlocks } from './chain.js';
3
+ import { makeStargateClient } from './rpc.js';
4
+ import { boardSlottingMarshaller, makeVstorageKit } from './vstorage-kit.js';
5
+
6
+ /**
7
+ * @import {Amount, Brand} from '@agoric/ertp/src/types.js'
8
+ * @import {CurrentWalletRecord, UpdateRecord} from '@agoric/smart-wallet/src/smartWallet.js';
9
+ * @import {MinimalNetworkConfig} from './rpc.js';
10
+ */
11
+
12
+ /**
13
+ *
14
+ * @param {object} root0
15
+ * @param {typeof globalThis.fetch} root0.fetch
16
+ * @param {(ms: number) => Promise<void>} root0.delay
17
+ * @param {MinimalNetworkConfig} networkConfig
18
+ */
19
+ export const makeWalletUtils = async ({ fetch, delay }, networkConfig) => {
20
+ const { agoricNames, fromBoard, marshaller, readLatestHead, vstorage } =
21
+ await makeVstorageKit({ fetch }, networkConfig);
22
+ const m = boardSlottingMarshaller(fromBoard.convertSlotToVal);
23
+
24
+ const client = await makeStargateClient(networkConfig, { fetch });
25
+
26
+ /**
27
+ * @param {string} from
28
+ * @param {number|string} [minHeight]
29
+ */
30
+ const storedWalletState = async (from, minHeight = undefined) => {
31
+ const history = await vstorage.readFully(
32
+ `published.wallet.${from}`,
33
+ minHeight,
34
+ );
35
+
36
+ /** @type {{ Invitation: Brand<'set'> }} */
37
+ // @ts-expect-error XXX how to narrow AssetKind to set?
38
+ const { Invitation } = agoricNames.brand;
39
+ const coalescer = makeWalletStateCoalescer(Invitation);
40
+ // update with oldest first
41
+ for (const txt of history.reverse()) {
42
+ const { body, slots } = JSON.parse(txt);
43
+ const record = m.fromCapData({ body, slots });
44
+ coalescer.update(record);
45
+ }
46
+ const coalesced = coalescer.state;
47
+ harden(coalesced);
48
+ return coalesced;
49
+ };
50
+
51
+ /**
52
+ * Get OfferStatus by id, polling until available.
53
+ *
54
+ * @param {string} from
55
+ * @param {string|number} id
56
+ * @param {number|string} minHeight
57
+ * @param {boolean} [untilNumWantsSatisfied]
58
+ */
59
+ const pollOffer = async (
60
+ from,
61
+ id,
62
+ minHeight,
63
+ untilNumWantsSatisfied = false,
64
+ ) => {
65
+ const poll = pollBlocks({
66
+ client,
67
+ delay,
68
+ retryMessage: 'offer not in wallet at block',
69
+ });
70
+
71
+ const lookup = async () => {
72
+ const { offerStatuses } = await storedWalletState(from, minHeight);
73
+ const offerStatus = [...offerStatuses.values()].find(s => s.id === id);
74
+ if (!offerStatus) throw Error('retry');
75
+ harden(offerStatus);
76
+ if (untilNumWantsSatisfied && !('numWantsSatisfied' in offerStatus)) {
77
+ throw Error('retry (no numWantsSatisfied yet)');
78
+ }
79
+ return offerStatus;
80
+ };
81
+ return poll(lookup);
82
+ };
83
+
84
+ /**
85
+ * @param {string} addr
86
+ * @returns {Promise<UpdateRecord>}
87
+ */
88
+ const getLastUpdate = addr => {
89
+ return /** @type {Promise<UpdateRecord>} */ (
90
+ readLatestHead(`published.wallet.${addr}`)
91
+ );
92
+ };
93
+
94
+ /**
95
+ * @param {string} addr
96
+ * @returns {Promise<CurrentWalletRecord>}
97
+ */
98
+ const getCurrentWalletRecord = addr => {
99
+ return /** @type {Promise<CurrentWalletRecord>} */ (
100
+ readLatestHead(`published.wallet.${addr}.current`)
101
+ );
102
+ };
103
+
104
+ return {
105
+ networkConfig,
106
+ agoricNames,
107
+ fromBoard,
108
+ marshaller,
109
+ vstorage,
110
+ getLastUpdate,
111
+ getCurrentWalletRecord,
112
+ readLatestHead,
113
+ storedWalletState,
114
+ pollOffer,
115
+ };
116
+ };
117
+ /** @typedef {Awaited<ReturnType<typeof makeWalletUtils>>} WalletUtils */