@ar.io/sdk 3.24.0 → 4.0.0-alpha.1

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.
Files changed (169) hide show
  1. package/README.md +682 -600
  2. package/lib/esm/cli/cli.js +188 -152
  3. package/lib/esm/cli/commands/antCommands.js +23 -58
  4. package/lib/esm/cli/commands/arnsPurchaseCommands.js +48 -30
  5. package/lib/esm/cli/commands/escrowCommands.js +221 -0
  6. package/lib/esm/cli/commands/gatewayWriteCommands.js +142 -23
  7. package/lib/esm/cli/commands/pruneCommands.js +150 -0
  8. package/lib/esm/cli/commands/readCommands.js +22 -3
  9. package/lib/esm/cli/commands/transfer.js +6 -6
  10. package/lib/esm/cli/options.js +124 -58
  11. package/lib/esm/cli/utils.js +280 -174
  12. package/lib/esm/common/ant-registry.js +17 -143
  13. package/lib/esm/common/ant.js +44 -1167
  14. package/lib/esm/common/faucet.js +11 -6
  15. package/lib/esm/common/index.js +0 -4
  16. package/lib/esm/common/io.js +25 -1412
  17. package/lib/esm/constants.js +13 -19
  18. package/lib/esm/solana/ant-readable.js +724 -0
  19. package/lib/esm/solana/ant-registry-readable.js +133 -0
  20. package/lib/esm/solana/ant-registry-writeable.js +472 -0
  21. package/lib/esm/solana/ant-writeable.js +384 -0
  22. package/lib/esm/solana/ata.js +70 -0
  23. package/lib/esm/solana/canonical-message.js +128 -0
  24. package/lib/esm/solana/clusters.js +111 -0
  25. package/lib/esm/solana/constants.js +146 -0
  26. package/lib/esm/solana/delegation-math.js +112 -0
  27. package/lib/esm/solana/deserialize.js +711 -0
  28. package/lib/esm/solana/escrow.js +839 -0
  29. package/lib/{cjs/utils/json.js → esm/solana/events.js} +15 -10
  30. package/lib/esm/solana/funding-plan.js +699 -0
  31. package/lib/esm/solana/index.js +126 -0
  32. package/lib/esm/solana/instruction.js +39 -0
  33. package/lib/esm/solana/io-readable.js +2182 -0
  34. package/lib/esm/solana/io-writeable.js +3196 -0
  35. package/lib/esm/solana/json-rpc.js +90 -0
  36. package/lib/esm/solana/metadata.js +81 -0
  37. package/lib/esm/solana/mpl-core.js +192 -0
  38. package/lib/esm/solana/pda.js +332 -0
  39. package/lib/esm/solana/predict-prescribed-observers.js +110 -0
  40. package/lib/esm/solana/retry.js +117 -0
  41. package/lib/esm/solana/rpc-circuit-breaker.js +258 -0
  42. package/lib/esm/solana/send.js +372 -0
  43. package/lib/esm/solana/spawn-ant.js +224 -0
  44. package/lib/esm/solana/types.js +1 -0
  45. package/lib/esm/types/ant.js +27 -15
  46. package/lib/esm/types/io.js +8 -11
  47. package/lib/esm/utils/ant.js +0 -63
  48. package/lib/esm/utils/index.js +0 -3
  49. package/lib/esm/version.js +1 -1
  50. package/lib/types/cli/commands/antCommands.d.ts +5 -13
  51. package/lib/types/cli/commands/arnsPurchaseCommands.d.ts +33 -7
  52. package/lib/types/cli/commands/escrowCommands.d.ts +68 -0
  53. package/lib/types/cli/commands/gatewayWriteCommands.d.ts +12 -11
  54. package/lib/types/cli/commands/pruneCommands.d.ts +31 -0
  55. package/lib/types/cli/commands/readCommands.d.ts +27 -22
  56. package/lib/types/cli/commands/transfer.d.ts +9 -9
  57. package/lib/types/cli/options.d.ts +76 -21
  58. package/lib/types/cli/types.d.ts +11 -13
  59. package/lib/types/cli/utils.d.ts +71 -31
  60. package/lib/types/common/ant-registry.d.ts +49 -47
  61. package/lib/types/common/ant.d.ts +54 -539
  62. package/lib/types/common/faucet.d.ts +20 -8
  63. package/lib/types/common/index.d.ts +0 -3
  64. package/lib/types/common/io.d.ts +51 -263
  65. package/lib/types/constants.d.ts +11 -18
  66. package/lib/types/solana/ant-readable.d.ts +180 -0
  67. package/lib/types/solana/ant-registry-readable.d.ts +105 -0
  68. package/lib/types/solana/ant-registry-writeable.d.ts +249 -0
  69. package/lib/types/solana/ant-writeable.d.ts +177 -0
  70. package/lib/types/solana/ata.d.ts +44 -0
  71. package/lib/types/solana/canonical-message.d.ts +121 -0
  72. package/lib/types/solana/clusters.d.ts +109 -0
  73. package/lib/types/solana/constants.d.ts +119 -0
  74. package/lib/types/solana/delegation-math.d.ts +45 -0
  75. package/lib/types/solana/deserialize.d.ts +262 -0
  76. package/lib/types/solana/escrow.d.ts +480 -0
  77. package/lib/types/solana/events.d.ts +38 -0
  78. package/lib/types/solana/funding-plan.d.ts +225 -0
  79. package/lib/types/solana/index.d.ts +87 -0
  80. package/lib/types/solana/instruction.d.ts +39 -0
  81. package/lib/types/solana/io-readable.d.ts +499 -0
  82. package/lib/types/solana/io-writeable.d.ts +893 -0
  83. package/lib/types/solana/json-rpc.d.ts +47 -0
  84. package/lib/types/solana/metadata.d.ts +84 -0
  85. package/lib/types/solana/mpl-core.d.ts +120 -0
  86. package/lib/types/solana/pda.d.ts +95 -0
  87. package/lib/types/solana/predict-prescribed-observers.d.ts +28 -0
  88. package/lib/types/solana/retry.d.ts +62 -0
  89. package/lib/types/solana/rpc-circuit-breaker.d.ts +78 -0
  90. package/lib/types/solana/send.d.ts +94 -0
  91. package/lib/types/solana/spawn-ant.d.ts +145 -0
  92. package/lib/types/solana/types.d.ts +82 -0
  93. package/lib/types/types/ant-registry.d.ts +43 -4
  94. package/lib/types/types/ant.d.ts +114 -96
  95. package/lib/types/types/common.d.ts +18 -74
  96. package/lib/types/types/faucet.d.ts +2 -2
  97. package/lib/types/types/io.d.ts +244 -158
  98. package/lib/types/types/token.d.ts +0 -12
  99. package/lib/types/utils/ant.d.ts +1 -12
  100. package/lib/types/utils/index.d.ts +0 -3
  101. package/lib/types/version.d.ts +1 -1
  102. package/package.json +36 -33
  103. package/lib/cjs/cli/cli.js +0 -822
  104. package/lib/cjs/cli/commands/antCommands.js +0 -113
  105. package/lib/cjs/cli/commands/arnsPurchaseCommands.js +0 -212
  106. package/lib/cjs/cli/commands/gatewayWriteCommands.js +0 -210
  107. package/lib/cjs/cli/commands/readCommands.js +0 -215
  108. package/lib/cjs/cli/commands/transfer.js +0 -159
  109. package/lib/cjs/cli/options.js +0 -470
  110. package/lib/cjs/cli/types.js +0 -2
  111. package/lib/cjs/cli/utils.js +0 -639
  112. package/lib/cjs/common/ant-registry.js +0 -155
  113. package/lib/cjs/common/ant-versions.js +0 -93
  114. package/lib/cjs/common/ant.js +0 -1182
  115. package/lib/cjs/common/arweave.js +0 -27
  116. package/lib/cjs/common/contracts/ao-process.js +0 -224
  117. package/lib/cjs/common/error.js +0 -64
  118. package/lib/cjs/common/faucet.js +0 -150
  119. package/lib/cjs/common/hyperbeam/hb.js +0 -173
  120. package/lib/cjs/common/index.js +0 -42
  121. package/lib/cjs/common/io.js +0 -1423
  122. package/lib/cjs/common/logger.js +0 -83
  123. package/lib/cjs/common/loggers/winston.js +0 -68
  124. package/lib/cjs/common/marketplace.js +0 -731
  125. package/lib/cjs/common/turbo.js +0 -223
  126. package/lib/cjs/constants.js +0 -41
  127. package/lib/cjs/node/index.js +0 -39
  128. package/lib/cjs/package.json +0 -1
  129. package/lib/cjs/types/ant-registry.js +0 -2
  130. package/lib/cjs/types/ant.js +0 -168
  131. package/lib/cjs/types/common.js +0 -2
  132. package/lib/cjs/types/faucet.js +0 -2
  133. package/lib/cjs/types/index.js +0 -37
  134. package/lib/cjs/types/io.js +0 -51
  135. package/lib/cjs/types/token.js +0 -116
  136. package/lib/cjs/utils/ant.js +0 -108
  137. package/lib/cjs/utils/ao.js +0 -432
  138. package/lib/cjs/utils/arweave.js +0 -285
  139. package/lib/cjs/utils/base64.js +0 -62
  140. package/lib/cjs/utils/hash.js +0 -56
  141. package/lib/cjs/utils/index.js +0 -38
  142. package/lib/cjs/utils/processes.js +0 -173
  143. package/lib/cjs/utils/random.js +0 -30
  144. package/lib/cjs/utils/schema.js +0 -15
  145. package/lib/cjs/utils/url.js +0 -37
  146. package/lib/cjs/version.js +0 -20
  147. package/lib/cjs/web/index.js +0 -41
  148. package/lib/esm/common/ant-versions.js +0 -87
  149. package/lib/esm/common/arweave.js +0 -21
  150. package/lib/esm/common/contracts/ao-process.js +0 -220
  151. package/lib/esm/common/hyperbeam/hb.js +0 -169
  152. package/lib/esm/common/marketplace.js +0 -724
  153. package/lib/esm/common/turbo.js +0 -215
  154. package/lib/esm/node/index.js +0 -20
  155. package/lib/esm/utils/ao.js +0 -420
  156. package/lib/esm/utils/arweave.js +0 -271
  157. package/lib/esm/utils/processes.js +0 -167
  158. package/lib/esm/web/index.js +0 -20
  159. package/lib/types/common/ant-versions.d.ts +0 -39
  160. package/lib/types/common/arweave.d.ts +0 -17
  161. package/lib/types/common/contracts/ao-process.d.ts +0 -47
  162. package/lib/types/common/hyperbeam/hb.d.ts +0 -88
  163. package/lib/types/common/marketplace.d.ts +0 -568
  164. package/lib/types/common/turbo.d.ts +0 -61
  165. package/lib/types/node/index.d.ts +0 -20
  166. package/lib/types/utils/ao.d.ts +0 -80
  167. package/lib/types/utils/arweave.d.ts +0 -79
  168. package/lib/types/utils/processes.d.ts +0 -39
  169. package/lib/types/web/index.d.ts +0 -20
@@ -1,37 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.urlWithSearchParams = void 0;
4
- /**
5
- * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
6
- *
7
- * Licensed under the Apache License, Version 2.0 (the "License");
8
- * you may not use this file except in compliance with the License.
9
- * You may obtain a copy of the License at
10
- *
11
- * http://www.apache.org/licenses/LICENSE-2.0
12
- *
13
- * Unless required by applicable law or agreed to in writing, software
14
- * distributed under the License is distributed on an "AS IS" BASIS,
15
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
- * See the License for the specific language governing permissions and
17
- * limitations under the License.
18
- */
19
- const urlWithSearchParams = ({ baseUrl, params, }) => {
20
- const urlObj = new URL(baseUrl);
21
- Object.entries(params).forEach(([key, value]) => {
22
- if (value === undefined || value === null)
23
- return;
24
- if (Array.isArray(value) && value.length > 0) {
25
- for (const v of value) {
26
- if (v === undefined || v === null)
27
- continue;
28
- urlObj.searchParams.append(key, v.toString());
29
- }
30
- }
31
- else {
32
- urlObj.searchParams.set(key, value.toString());
33
- }
34
- });
35
- return urlObj.toString();
36
- };
37
- exports.urlWithSearchParams = urlWithSearchParams;
@@ -1,20 +0,0 @@
1
- "use strict";
2
- /**
3
- * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.version = void 0;
19
- // AUTOMATICALLY GENERATED FILE - DO NOT TOUCH
20
- exports.version = '3.24.0';
@@ -1,41 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.EthereumSigner = exports.InjectedEthereumSigner = exports.ArconnectSigner = exports.ArweaveSigner = void 0;
18
- /**
19
- * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
20
- *
21
- * Licensed under the Apache License, Version 2.0 (the "License");
22
- * you may not use this file except in compliance with the License.
23
- * You may obtain a copy of the License at
24
- *
25
- * http://www.apache.org/licenses/LICENSE-2.0
26
- *
27
- * Unless required by applicable law or agreed to in writing, software
28
- * distributed under the License is distributed on an "AS IS" BASIS,
29
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
30
- * See the License for the specific language governing permissions and
31
- * limitations under the License.
32
- */
33
- var arbundles_1 = require("@dha-team/arbundles");
34
- Object.defineProperty(exports, "ArweaveSigner", { enumerable: true, get: function () { return arbundles_1.ArweaveSigner; } });
35
- Object.defineProperty(exports, "ArconnectSigner", { enumerable: true, get: function () { return arbundles_1.ArconnectSigner; } });
36
- Object.defineProperty(exports, "InjectedEthereumSigner", { enumerable: true, get: function () { return arbundles_1.InjectedEthereumSigner; } });
37
- Object.defineProperty(exports, "EthereumSigner", { enumerable: true, get: function () { return arbundles_1.EthereumSigner; } });
38
- __exportStar(require("../types/index.js"), exports);
39
- __exportStar(require("../common/index.js"), exports);
40
- __exportStar(require("../constants.js"), exports);
41
- __exportStar(require("../utils/index.js"), exports);
@@ -1,87 +0,0 @@
1
- /**
2
- * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- import { ANT_REGISTRY_ID } from '../constants.js';
17
- import { isProcessConfiguration, isProcessIdConfiguration, } from '../types/io.js';
18
- import { createAoSigner } from '../utils/ao.js';
19
- import { pruneTags } from '../utils/arweave.js';
20
- import { AOProcess } from './contracts/ao-process.js';
21
- import { InvalidContractConfigurationError } from './error.js';
22
- export class ANTVersions {
23
- static init(config) {
24
- if (config !== undefined && 'signer' in config) {
25
- return new ANTVersionsWritable(config);
26
- }
27
- return new ANTVersionsReadable(config);
28
- }
29
- }
30
- export class ANTVersionsReadable {
31
- process;
32
- constructor(config) {
33
- if (config === undefined || Object.keys(config).length === 0) {
34
- this.process = new AOProcess({
35
- processId: ANT_REGISTRY_ID,
36
- });
37
- }
38
- else if (isProcessConfiguration(config)) {
39
- this.process = config.process;
40
- }
41
- else if (isProcessIdConfiguration(config)) {
42
- this.process = new AOProcess({
43
- processId: config.processId,
44
- });
45
- }
46
- else {
47
- throw new InvalidContractConfigurationError();
48
- }
49
- }
50
- async getANTVersions() {
51
- const res = await this.process.read({
52
- tags: [{ name: 'Action', value: 'Get-Versions' }],
53
- });
54
- return Object.fromEntries(Object.entries(res).sort(([a], [b]) => a.localeCompare(b)));
55
- }
56
- async getLatestANTVersion() {
57
- const versions = await this.getANTVersions();
58
- const lastestVersion = Object.entries(versions).at(-1);
59
- if (!lastestVersion)
60
- throw new Error('No version found');
61
- return {
62
- version: lastestVersion[0],
63
- ...lastestVersion[1],
64
- };
65
- }
66
- }
67
- export class ANTVersionsWritable extends ANTVersionsReadable {
68
- signer;
69
- constructor({ signer, ...config }) {
70
- super(config);
71
- this.signer = createAoSigner(signer);
72
- }
73
- async addVersion(params, options) {
74
- const { version, moduleId, luaSourceId, notes } = params;
75
- return this.process.send({
76
- tags: pruneTags([
77
- { name: 'Action', value: 'Add-Version' },
78
- { name: 'Version', value: version },
79
- { name: 'Module-Id', value: moduleId },
80
- { name: 'Lua-Source-Id', value: luaSourceId },
81
- { name: 'Notes', value: notes },
82
- ...(options?.tags ?? []),
83
- ]),
84
- signer: this.signer,
85
- });
86
- }
87
- }
@@ -1,21 +0,0 @@
1
- /**
2
- * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- import Arweave from 'arweave/node/index.js';
17
- export const defaultArweave = Arweave.init({
18
- host: 'arweave.net',
19
- port: 443,
20
- protocol: 'https',
21
- });
@@ -1,220 +0,0 @@
1
- /**
2
- * Copyright (C) 2022-2024 Permanent Data Solutions, Inc.
3
- *
4
- * Licensed under the Apache License, Version 2.0 (the "License");
5
- * you may not use this file except in compliance with the License.
6
- * You may obtain a copy of the License at
7
- *
8
- * http://www.apache.org/licenses/LICENSE-2.0
9
- *
10
- * Unless required by applicable law or agreed to in writing, software
11
- * distributed under the License is distributed on an "AS IS" BASIS,
12
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- * See the License for the specific language governing permissions and
14
- * limitations under the License.
15
- */
16
- import { connect } from '@permaweb/aoconnect';
17
- import { getRandomText } from '../../utils/base64.js';
18
- import { errorMessageFromOutput } from '../../utils/index.js';
19
- import { safeDecode } from '../../utils/json.js';
20
- import { version } from '../../version.js';
21
- import { WriteInteractionError } from '../error.js';
22
- import { Logger } from '../logger.js';
23
- export class AOProcess {
24
- logger;
25
- ao;
26
- processId;
27
- constructor({ processId, ao = connect({
28
- MODE: 'legacy',
29
- }), logger = Logger.default, }) {
30
- this.processId = processId;
31
- this.logger = logger;
32
- this.ao = ao;
33
- }
34
- isMessageDataEmpty(messageData) {
35
- return (messageData === undefined ||
36
- messageData === 'null' || // This is what the CU returns for 'nil' values that are json.encoded
37
- messageData === '' ||
38
- messageData === null);
39
- }
40
- async read({ tags, retries = 3, fromAddress, select, }) {
41
- this.logger.debug(`Evaluating read interaction on process`, {
42
- tags,
43
- processId: this.processId,
44
- });
45
- // map tags to inputs
46
- const dryRunInput = {
47
- process: this.processId,
48
- tags,
49
- };
50
- if (fromAddress !== undefined) {
51
- dryRunInput['Owner'] = fromAddress;
52
- }
53
- let attempts = 0;
54
- let result = undefined;
55
- while (attempts < retries) {
56
- try {
57
- result = await this.ao.dryrun(dryRunInput);
58
- // break on successful return of result
59
- break;
60
- }
61
- catch (error) {
62
- attempts++;
63
- this.logger.debug(`Read attempt ${attempts} failed`, {
64
- error: error?.message,
65
- stack: error?.stack,
66
- tags,
67
- processId: this.processId,
68
- });
69
- if (attempts >= retries) {
70
- this.logger.debug(`Maximum read attempts exceeded`, {
71
- error: error?.message,
72
- stack: error?.stack,
73
- tags,
74
- processId: this.processId,
75
- ao: JSON.stringify(this.ao),
76
- });
77
- throw new Error(`Failed to evaluate dry-run on process ${this.processId}.`, {
78
- cause: error,
79
- });
80
- }
81
- // exponential backoff
82
- await new Promise((resolve) => setTimeout(resolve, 2 ** attempts * 1000));
83
- }
84
- }
85
- if (result === undefined) {
86
- throw new Error('Unexpected error when evaluating read interaction');
87
- }
88
- this.logger.debug(`Read interaction result`, {
89
- result,
90
- processId: this.processId,
91
- });
92
- const error = errorMessageFromOutput(result);
93
- if (error !== undefined) {
94
- throw new Error(error);
95
- }
96
- if (result.Messages === undefined || result.Messages.length === 0) {
97
- this.logger.debug(`Empty result - process ${this.processId} does not support provided action.`, {
98
- result,
99
- tags,
100
- processId: this.processId,
101
- });
102
- throw new Error(result.message ||
103
- `Process ${this.processId} did not return a valid response. Response: ${JSON.stringify(result)}`);
104
- }
105
- const messageData = select
106
- ? result.Messages.find(select)?.Data
107
- : result.Messages?.[0]?.Data;
108
- // return undefined if no data is returned
109
- if (this.isMessageDataEmpty(messageData)) {
110
- return undefined;
111
- }
112
- const response = safeDecode(messageData);
113
- return response;
114
- }
115
- async send({ tags, data, signer, retries = 3, select, }) {
116
- let messageId;
117
- const anchor = getRandomText(32); // anchor is a random text produce non-deterministic messages IDs when deterministic signers are provided (ETH)
118
- try {
119
- this.logger.debug(`Evaluating send interaction on contract`, {
120
- tags,
121
- data,
122
- processId: this.processId,
123
- });
124
- /**
125
- * DO NOT retry messaging if a message was already sent.
126
- * This could result in a double entry-like condition when sending tokens for example.
127
- * If the message fails to send we will throw an error and the caller can retry.
128
- */
129
- messageId = await this.ao.message({
130
- process: this.processId,
131
- tags: [...tags, { name: 'AR-IO-SDK', value: version }],
132
- data,
133
- signer,
134
- anchor,
135
- });
136
- this.logger.debug(`Sent message to process`, {
137
- messageId,
138
- processId: this.processId,
139
- anchor,
140
- });
141
- }
142
- catch (error) {
143
- this.logger.debug('Error sending message to process', {
144
- error: error?.message,
145
- stack: error?.stack,
146
- processId: this.processId,
147
- tags,
148
- });
149
- // throw the error so it can be handled by the caller
150
- throw error;
151
- }
152
- if (messageId === undefined) {
153
- throw new Error('Failed to send message to process.');
154
- }
155
- // get the result of the message before returning, using retries to handle network errors/new process delays
156
- let result = undefined;
157
- let attempts = 0;
158
- while (attempts < retries) {
159
- try {
160
- result = await this.ao.result({
161
- message: messageId,
162
- process: this.processId,
163
- });
164
- this.logger.debug('Message result', {
165
- result,
166
- messageId,
167
- processId: this.processId,
168
- });
169
- break;
170
- }
171
- catch (error) {
172
- attempts++;
173
- this.logger.debug('Retrying send interaction', {
174
- attempts,
175
- retries,
176
- error: error?.message,
177
- processId: this.processId,
178
- });
179
- if (attempts >= retries) {
180
- this.logger.debug(`Message was sent to process ${this.processId} with id ${messageId} but result was not returned. Review transactions for more details.`, {
181
- error: error?.message,
182
- stack: error?.stack,
183
- tags,
184
- processId: this.processId,
185
- messageId,
186
- });
187
- return { id: messageId };
188
- }
189
- // exponential backoff
190
- await new Promise((resolve) => setTimeout(resolve, 2 ** attempts * 2000));
191
- }
192
- }
193
- if (result === undefined) {
194
- this.logger.debug(`Message was sent to process ${this.processId} with id ${messageId} but the result was not returned. Review transactions for more details.`, {
195
- tags,
196
- processId: this.processId,
197
- messageId,
198
- });
199
- return { id: messageId };
200
- }
201
- const error = errorMessageFromOutput(result);
202
- if (error !== undefined) {
203
- throw new WriteInteractionError(error);
204
- }
205
- // check if there are any Messages in the output
206
- if (result.Messages?.length === 0 || result.Messages === undefined) {
207
- return { id: messageId };
208
- }
209
- if (this.isMessageDataEmpty(result.Messages[0].Data)) {
210
- return { id: messageId };
211
- }
212
- const resultData = safeDecode(select ? result.Messages.find(select)?.Data : result.Messages[0].Data);
213
- this.logger.debug('Message result data', {
214
- resultData,
215
- messageId,
216
- processId: this.processId,
217
- });
218
- return { id: messageId, result: resultData };
219
- }
220
- }
@@ -1,169 +0,0 @@
1
- import { Logger } from '../logger.js';
2
- export class HB {
3
- url;
4
- processId;
5
- isHyperBeamCompatible;
6
- checkHyperBeamPromise;
7
- logger;
8
- hbTimeoutMs;
9
- constructor(config) {
10
- this.url = config.url;
11
- this.processId = config.processId;
12
- this.logger = config.logger ?? Logger.default;
13
- this.hbTimeoutMs = config.hbTimeoutMs ?? 5000;
14
- this.isHyperBeamCompatible = undefined;
15
- this.checkHyperBeamPromise = this.checkHyperBeamCompatibility();
16
- }
17
- /**
18
- * fetches the meta data for the process
19
- *
20
- * @returns The meta data for the process
21
- *
22
- * @example
23
- * const hyperbeam = new Hyperbeam({ url: 'https://hyperbeam.ario.permaweb.services', processId: 'qNvAoz0TgcH7DMg8BCVn8jF32QH5L6T29VjHxhHqqGE' });
24
- * const meta = await hyperbeam.meta();
25
- * console.log(meta);
26
- */
27
- async meta() {
28
- const url = new URL(`${this.url}/${this.processId}~process@1.0/meta`);
29
- return this.fetchHyperbeamPath({
30
- path: url.toString(),
31
- });
32
- }
33
- /**
34
- * calls the process device /now function, which evaluates the current process state pulling new messages
35
- * to get the latest state
36
- *
37
- * @param path - The path to the hb state
38
- * @param json - Whether to return the result as JSON, defaults to true
39
- * @returns The result of the compute operation
40
- *
41
- * @example
42
- * const hyperbeam = new Hyperbeam({ url: 'https://hyperbeam.ario.permaweb.services', processId: 'qNvAoz0TgcH7DMg8BCVn8jF32QH5L6T29VjHxhHqqGE' });
43
- * const result = await hyperbeam.now({ path: 'balances/QGWqtJdLLgm2ehFWiiPzMaoFLD50CnGuzZIPEdoDRGQ' });
44
- * console.log(result);
45
- */
46
- async now({ path, json = false, }) {
47
- return this.fetchHyperbeamPath({
48
- path: `${this.url}/${this.processId}~process@1.0/now/${path}`,
49
- json,
50
- });
51
- }
52
- /**
53
- * calls the process device /compute function, which uses the currently evaluated state in the node
54
- *
55
- * @param path - The path to the compute resource
56
- * @param json - Whether to return the result as JSON, defaults to true
57
- * @returns The result of the compute operation
58
- *
59
- * @example
60
- * const hyperbeam = new Hyperbeam({ url: 'https://hyperbeam.ario.permaweb.services', processId: 'qNvAoz0TgcH7DMg8BCVn8jF32QH5L6T29VjHxhHqqGE' });
61
- * const result = await hyperbeam.compute({ path: 'balances/QGWqtJdLLgm2ehFWiiPzMaoFLD50CnGuzZIPEdoDRGQ' });
62
- * console.log(result);
63
- */
64
- async compute({ path, json = true, }) {
65
- return this.fetchHyperbeamPath({
66
- path: `${this.url}/${this.processId}~process@1.0/compute/${path}`,
67
- json,
68
- });
69
- }
70
- /**
71
- * Checks if the process is HyperBeam compatible and caches the result.
72
- *
73
- * @returns {Promise<boolean>} True if the process is HyperBeam compatible, false otherwise.
74
- */
75
- async checkHyperBeamCompatibility({ minSlot, } = {}) {
76
- // refetch if min slot is provided
77
- if (minSlot !== undefined) {
78
- this.isHyperBeamCompatible = undefined;
79
- this.checkHyperBeamPromise = undefined;
80
- }
81
- if (this.checkHyperBeamPromise !== undefined) {
82
- return this.checkHyperBeamPromise;
83
- }
84
- if (this.isHyperBeamCompatible !== undefined) {
85
- return Promise.resolve(this.isHyperBeamCompatible);
86
- }
87
- const result = fetch(
88
- // use /now to force a refresh of the cache state, then compute when calling it for keys
89
- `${this.url.toString()}/${this.processId}~process@1.0/now`, {
90
- method: 'HEAD',
91
- signal: AbortSignal.timeout(this.hbTimeoutMs),
92
- })
93
- .then(async (res) => {
94
- if (res.ok) {
95
- if (minSlot !== undefined) {
96
- const slotRes = await this.compute({
97
- path: 'at-slot',
98
- json: false,
99
- });
100
- const slot = Number(slotRes);
101
- if (slot < minSlot) {
102
- return false;
103
- }
104
- }
105
- this.isHyperBeamCompatible = true;
106
- return true;
107
- }
108
- this.isHyperBeamCompatible = false;
109
- return false;
110
- })
111
- .catch((error) => {
112
- this.logger.error('Failed to check HyperBeam compatibility', {
113
- cause: error,
114
- });
115
- this.isHyperBeamCompatible = false;
116
- return false;
117
- });
118
- this.checkHyperBeamPromise = result;
119
- return result;
120
- }
121
- async fetchHyperbeamPath({ path, json = true, }) {
122
- try {
123
- const url = new URL(path);
124
- if (json) {
125
- this.logger.debug('Fetching path as JSON', { path });
126
- /**
127
- * This is the (current) way to access data as json
128
- * the old way is /~json@1.0/serialize path
129
- */
130
- url.searchParams.set('require-codec', 'application/json');
131
- url.searchParams.set('accept-bundle', 'true');
132
- const res = await fetch(url);
133
- if (!res.ok) {
134
- throw new Error(`Failed to fetch path as JSON: ${res.statusText}`);
135
- }
136
- const jsonResult = await res
137
- .json()
138
- .then((json) => json)
139
- .catch((error) => {
140
- this.logger.error('Failed to parse JSON', {
141
- cause: error,
142
- });
143
- throw new Error(`Received response but failed to parse JSON: ${error.message}`);
144
- });
145
- if (typeof jsonResult !== 'object' ||
146
- jsonResult === null ||
147
- !('body' in jsonResult)) {
148
- throw new Error('Response body missing in JSON response');
149
- }
150
- return jsonResult.body;
151
- }
152
- else {
153
- this.logger.debug('Fetching path as text', { path });
154
- const res = await fetch(url);
155
- if (!res.ok) {
156
- throw new Error(`Failed to fetch path: ${res.statusText}`);
157
- }
158
- const body = await res.text();
159
- return body;
160
- }
161
- }
162
- catch (error) {
163
- this.logger.error('Failed to fetch path as JSON', {
164
- cause: error,
165
- });
166
- throw error;
167
- }
168
- }
169
- }