@lifi/composer-sdk 0.0.1-alpha

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 (160) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +220 -0
  3. package/dist/authoring/FlowBuilderCore.cjs +115 -0
  4. package/dist/authoring/FlowBuilderCore.cjs.map +1 -0
  5. package/dist/authoring/FlowBuilderCore.d.cts +114 -0
  6. package/dist/authoring/FlowBuilderCore.d.ts +114 -0
  7. package/dist/authoring/FlowBuilderCore.js +91 -0
  8. package/dist/authoring/FlowBuilderCore.js.map +1 -0
  9. package/dist/authoring/handles.cjs +43 -0
  10. package/dist/authoring/handles.cjs.map +1 -0
  11. package/dist/authoring/handles.d.cts +61 -0
  12. package/dist/authoring/handles.d.ts +61 -0
  13. package/dist/authoring/handles.js +17 -0
  14. package/dist/authoring/handles.js.map +1 -0
  15. package/dist/authoring/raw.cjs +41 -0
  16. package/dist/authoring/raw.cjs.map +1 -0
  17. package/dist/authoring/raw.d.cts +47 -0
  18. package/dist/authoring/raw.d.ts +47 -0
  19. package/dist/authoring/raw.js +16 -0
  20. package/dist/authoring/raw.js.map +1 -0
  21. package/dist/authoring/signatureArgs.cjs +114 -0
  22. package/dist/authoring/signatureArgs.cjs.map +1 -0
  23. package/dist/authoring/signatureArgs.d.cts +146 -0
  24. package/dist/authoring/signatureArgs.d.ts +146 -0
  25. package/dist/authoring/signatureArgs.js +87 -0
  26. package/dist/authoring/signatureArgs.js.map +1 -0
  27. package/dist/client.cjs +140 -0
  28. package/dist/client.cjs.map +1 -0
  29. package/dist/client.d.cts +67 -0
  30. package/dist/client.d.ts +67 -0
  31. package/dist/client.js +116 -0
  32. package/dist/client.js.map +1 -0
  33. package/dist/discovery.cjs +17 -0
  34. package/dist/discovery.cjs.map +1 -0
  35. package/dist/discovery.d.cts +56 -0
  36. package/dist/discovery.d.ts +56 -0
  37. package/dist/discovery.js +1 -0
  38. package/dist/discovery.js.map +1 -0
  39. package/dist/errors.cjs +91 -0
  40. package/dist/errors.cjs.map +1 -0
  41. package/dist/errors.d.cts +77 -0
  42. package/dist/errors.d.ts +77 -0
  43. package/dist/errors.js +65 -0
  44. package/dist/errors.js.map +1 -0
  45. package/dist/generated/config.generated.cjs +17 -0
  46. package/dist/generated/config.generated.cjs.map +1 -0
  47. package/dist/generated/config.generated.d.cts +144 -0
  48. package/dist/generated/config.generated.d.ts +144 -0
  49. package/dist/generated/config.generated.js +1 -0
  50. package/dist/generated/config.generated.js.map +1 -0
  51. package/dist/generated/guards.generated.cjs +32 -0
  52. package/dist/generated/guards.generated.cjs.map +1 -0
  53. package/dist/generated/guards.generated.d.cts +4 -0
  54. package/dist/generated/guards.generated.d.ts +4 -0
  55. package/dist/generated/guards.generated.js +8 -0
  56. package/dist/generated/guards.generated.js.map +1 -0
  57. package/dist/generated/materialisers.generated.cjs +44 -0
  58. package/dist/generated/materialisers.generated.cjs.map +1 -0
  59. package/dist/generated/materialisers.generated.d.cts +4 -0
  60. package/dist/generated/materialisers.generated.d.ts +4 -0
  61. package/dist/generated/materialisers.generated.js +18 -0
  62. package/dist/generated/materialisers.generated.js.map +1 -0
  63. package/dist/generated/operations.generated.cjs +110 -0
  64. package/dist/generated/operations.generated.cjs.map +1 -0
  65. package/dist/generated/operations.generated.d.cts +337 -0
  66. package/dist/generated/operations.generated.d.ts +337 -0
  67. package/dist/generated/operations.generated.js +89 -0
  68. package/dist/generated/operations.generated.js.map +1 -0
  69. package/dist/generated/preconditions.generated.cjs +44 -0
  70. package/dist/generated/preconditions.generated.cjs.map +1 -0
  71. package/dist/generated/preconditions.generated.d.cts +4 -0
  72. package/dist/generated/preconditions.generated.d.ts +4 -0
  73. package/dist/generated/preconditions.generated.js +18 -0
  74. package/dist/generated/preconditions.generated.js.map +1 -0
  75. package/dist/guards.generated-DKKDKREA.d.ts +14 -0
  76. package/dist/guards.generated-hrQ1KPNv.d.cts +14 -0
  77. package/dist/index.cjs +76 -0
  78. package/dist/index.cjs.map +1 -0
  79. package/dist/index.d.cts +99 -0
  80. package/dist/index.d.ts +99 -0
  81. package/dist/index.js +30 -0
  82. package/dist/index.js.map +1 -0
  83. package/dist/materialisers.generated-BsA1uDW8.d.ts +24 -0
  84. package/dist/materialisers.generated-nMxTAaVi.d.cts +24 -0
  85. package/dist/preconditions.generated-DblS13Wq.d.cts +24 -0
  86. package/dist/preconditions.generated-U7YpVh30.d.ts +24 -0
  87. package/dist/raw-Dj_2rBSQ.d.cts +19 -0
  88. package/dist/raw-IxCF_bSS.d.ts +19 -0
  89. package/dist/raw.cjs +34 -0
  90. package/dist/raw.cjs.map +1 -0
  91. package/dist/raw.d.cts +4 -0
  92. package/dist/raw.d.ts +4 -0
  93. package/dist/raw.js +8 -0
  94. package/dist/raw.js.map +1 -0
  95. package/dist/resources-BKlFxjo8.d.cts +56 -0
  96. package/dist/resources-CYis1_DS.d.ts +56 -0
  97. package/dist/resources.cjs +39 -0
  98. package/dist/resources.cjs.map +1 -0
  99. package/dist/resources.d.cts +3 -0
  100. package/dist/resources.d.ts +3 -0
  101. package/dist/resources.js +14 -0
  102. package/dist/resources.js.map +1 -0
  103. package/dist/run/inputs.cjs +51 -0
  104. package/dist/run/inputs.cjs.map +1 -0
  105. package/dist/run/inputs.d.cts +91 -0
  106. package/dist/run/inputs.d.ts +91 -0
  107. package/dist/run/inputs.js +26 -0
  108. package/dist/run/inputs.js.map +1 -0
  109. package/dist/sdk.cjs +60 -0
  110. package/dist/sdk.cjs.map +1 -0
  111. package/dist/sdk.d.cts +112 -0
  112. package/dist/sdk.d.ts +112 -0
  113. package/dist/sdk.js +40 -0
  114. package/dist/sdk.js.map +1 -0
  115. package/dist/types.cjs +17 -0
  116. package/dist/types.cjs.map +1 -0
  117. package/dist/types.d.cts +74 -0
  118. package/dist/types.d.ts +74 -0
  119. package/dist/types.js +1 -0
  120. package/dist/types.js.map +1 -0
  121. package/package.json +81 -0
  122. package/src/authoring/FlowBuilderCore.ts +270 -0
  123. package/src/authoring/handles.ts +81 -0
  124. package/src/authoring/raw.ts +60 -0
  125. package/src/authoring/signatureArgs.ts +249 -0
  126. package/src/client.ts +230 -0
  127. package/src/discovery.ts +51 -0
  128. package/src/errors.ts +150 -0
  129. package/src/examples/approveAndDeposit.ts +84 -0
  130. package/src/examples/callContract.ts +199 -0
  131. package/src/examples/config.ts +9 -0
  132. package/src/examples/consolidateToEth.ts +94 -0
  133. package/src/examples/consolidateToUsdc.ts +95 -0
  134. package/src/examples/depositFromProxy.ts +87 -0
  135. package/src/examples/dustSweep.ts +66 -0
  136. package/src/examples/lifiSwap.ts +56 -0
  137. package/src/examples/lifiZap.ts +60 -0
  138. package/src/examples/rawCallWithArithmetic.ts +78 -0
  139. package/src/examples/readContractState.ts +77 -0
  140. package/src/examples/run.ts +168 -0
  141. package/src/examples/splitAndZap.ts +73 -0
  142. package/src/examples/splitWithArithmetic.ts +93 -0
  143. package/src/examples/swapAndZap.ts +72 -0
  144. package/src/examples/swapToRecipient.ts +109 -0
  145. package/src/examples/swapWithAllowRevert.ts +119 -0
  146. package/src/examples/swapWithBalanceCheck.ts +73 -0
  147. package/src/examples/swapWithOutputValidation.ts +125 -0
  148. package/src/examples/transferTokens.ts +123 -0
  149. package/src/examples/untypedOpWithTypedRef.ts +77 -0
  150. package/src/generated/config.generated.ts +174 -0
  151. package/src/generated/guards.generated.ts +14 -0
  152. package/src/generated/materialisers.generated.ts +44 -0
  153. package/src/generated/operations.generated.ts +568 -0
  154. package/src/generated/preconditions.generated.ts +43 -0
  155. package/src/index.ts +149 -0
  156. package/src/raw.ts +10 -0
  157. package/src/resources.ts +61 -0
  158. package/src/run/inputs.ts +117 -0
  159. package/src/sdk.ts +173 -0
  160. package/src/types.ts +101 -0
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 LI.FI
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,220 @@
1
+ # @lifi/composer-sdk
2
+
3
+ TypeScript SDK for building and submitting LI.FI Compose flows.
4
+
5
+ ## Install
6
+
7
+ `@lifi/compose-spec` is a peer dependency and must be installed alongside the SDK at the same version (they are versioned in lockstep).
8
+
9
+ ```bash
10
+ npm install @lifi/composer-sdk @lifi/compose-spec
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ Swap WETH to USDC, then zap the USDC into an Aave lending position — all in a single transaction.
16
+
17
+ ```ts
18
+ import {
19
+ createComposeSdk,
20
+ resources,
21
+ guards,
22
+ materialisers,
23
+ } from '@lifi/composer-sdk';
24
+
25
+ const WETH = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
26
+ const USDC = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48';
27
+ const A_ETH_USDC = '0x98C23E9d8f34FEFb1B7BD6a91B7FF122F4e16F5c'; // Aave aEthUSDC
28
+ const OWNER = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045';
29
+
30
+ // Create the SDK pointed at the Compose API.
31
+ const sdk = createComposeSdk({
32
+ baseUrl: 'https://compose.li.fi',
33
+ apiKey: process.env.LIFI_API_KEY, // optional
34
+ });
35
+
36
+ // Build a two-step flow on Ethereum mainnet.
37
+ const builder = sdk.flow(1, {
38
+ name: 'swap-and-zap-weth-to-aave',
39
+ inputs: {
40
+ amountIn: resources.erc20(WETH, 1),
41
+ },
42
+ });
43
+
44
+ // Step 1: Swap WETH → USDC via LI.FI.
45
+ const swapOutputs = builder.lifi.swap('swap', {
46
+ bind: { amountIn: builder.inputs.amountIn },
47
+ config: {
48
+ resourceOut: resources.erc20(USDC, 1),
49
+ slippage: 0.03,
50
+ },
51
+ });
52
+
53
+ // Step 2: Zap the swapped USDC into Aave.
54
+ // The swap's amountOut handle threads directly into the zap's amountIn.
55
+ builder.lifi.zap('zap', {
56
+ bind: { amountIn: swapOutputs.amountOut },
57
+ config: {
58
+ resourceOut: resources.erc20(A_ETH_USDC, 1),
59
+ },
60
+ guards: [guards.slippage({ port: 'amountOut', bps: 100 })],
61
+ });
62
+
63
+ const flow = builder.build();
64
+
65
+ // Compile the flow into transaction calldata.
66
+ const request = sdk.request(flow, {
67
+ signer: OWNER,
68
+ inputs: {
69
+ amountIn: materialisers.directDeposit({
70
+ amount: '1000000000000000000',
71
+ }),
72
+ },
73
+ sweepTo: builder.context.sender,
74
+ });
75
+
76
+ const result = await sdk.client.compile(request);
77
+
78
+ if (result.status === 'success') {
79
+ // Full success — transactionRequest includes gasLimit.
80
+ console.log(result.transactionRequest);
81
+ } else {
82
+ // result.status === 'partial' — simulation reverted.
83
+ // Transaction is still available but without gasLimit.
84
+ console.log(result.simulationRevert);
85
+ }
86
+ ```
87
+
88
+ ## Core concepts
89
+
90
+ **Flows and operations** — A flow is a sequence of on-chain operations. You declare inputs, chain operations together, and the backend compiles everything into a single transaction. Operations are namespaced (e.g., `builder.lifi.swap`, `builder.core.split`).
91
+
92
+ **Resources** — `resources.erc20(address, chainId)` and `resources.native(chainId)` describe the tokens flowing through your operations. They carry chain and address metadata used for routing and validation.
93
+
94
+ **Handles** — Operations produce typed output handles (e.g. `OutputHandle<'resource'>`, `OutputHandle<'uint256'>`) that you bind to downstream inputs. The type system enforces compatibility at compile time — a resource handle can flow into a `uint256` slot (since resources are amounts), but an `address` handle cannot.
95
+
96
+ **Runtime inputs (materialisers)** — Materialisers resolve input values at execution time rather than at build time. `directDeposit` is exact by default when you provide an amount; pass `allowNonExact: true` to permit capped ERC-20 deposits or deposit-all behavior. `balanceOf` reads the wallet's current balance; `call` measures a balance delta after an arbitrary contract call.
97
+
98
+ **Preconditions** — Expected on-chain state at execution time: `erc20Balance` and `nativeBalance` assert wallet holdings, `erc20Allowance` asserts token approvals.
99
+
100
+ **Guards** — Protect against slippage and other runtime conditions. Applied per-operation via the `guards` field.
101
+
102
+ ## API surface
103
+
104
+ **SDK factory**
105
+ - `createComposeSdk({ baseUrl, fetch?, apiKey? })` — creates the SDK instance
106
+
107
+ **Flow building**
108
+ - `sdk.flow(chainId, options)` — creates a `FlowBuilder`
109
+ - `builder.<namespace>.<operation>(id, { bind, config })` — adds an operation, returns typed `OutputHandle<T>` per port
110
+ - `builder.untypedOp(id, op, args)` — escape hatch for operations not in the manifest (returns `void`; use `raw.ref<T>()` to reference its outputs)
111
+ - `builder.build()` — produces a `Flow` document
112
+ - `sdk.request(flow, { signer, inputs, preconditions, sweepTo, ... })` — builds a compile request
113
+
114
+ **HTTP client**
115
+ - `sdk.client.compile(request)` — sends the flow to the backend and returns a `ComposeCompileResult` (discriminated union: `status: 'success'` or `status: 'partial'`)
116
+ - `sdk.client.getManifest()` — fetches the operation manifest
117
+
118
+ **Helpers**
119
+ - `resources.erc20(address, chainId)` / `resources.native(chainId)` — resource constructors
120
+ - `guards.*` — guard factories (e.g., slippage)
121
+ - `materialisers.*` — materialiser factories (directDeposit, balanceOf, call)
122
+ - `preconditions.*` — precondition factories (erc20Balance, nativeBalance, erc20Allowance)
123
+ - `raw.ref<T>(path)` — create a typed `$ref` pointer for use in bind slots (escape hatch for `untypedOp` outputs)
124
+ - `raw.guard(kind, config?)` / `raw.materialiser(kind, config?)` — low-level factories for guards and materialisers
125
+
126
+ ## Simulation policy and partial results
127
+
128
+ By default, the Compose backend simulates the compiled transaction and returns an error (HTTP 422) if simulation detects a revert. You can opt into receiving a **partial result** instead by passing `simulationPolicy: 'allow-revert'`:
129
+
130
+ ```ts
131
+ const result = await builder.compile({
132
+ signer: OWNER,
133
+ inputs: { amountIn: materialisers.balanceOf({ owner: OWNER }) },
134
+ simulationPolicy: 'allow-revert',
135
+ });
136
+
137
+ if (result.status === 'success') {
138
+ // Simulation succeeded. transactionRequest includes gasLimit.
139
+ const tx = result.transactionRequest;
140
+ console.log(tx.gasLimit); // string
141
+ } else {
142
+ // result.status === 'partial'
143
+ // Simulation reverted, but a transaction is still available (without gasLimit).
144
+ console.log(result.error.kind); // 'simulation_revert'
145
+ console.log(result.error.message); // human-readable revert description
146
+
147
+ // Revert diagnostics
148
+ const revert = result.simulationRevert;
149
+ console.log(revert.code); // e.g. 3
150
+ console.log(revert.rawErrorBytes); // raw ABI-encoded error
151
+
152
+ // Decoded error candidates (when available)
153
+ if (revert.decodeResult?.errorCandidates) {
154
+ for (const c of revert.decodeResult.errorCandidates) {
155
+ console.log(c.decodedErrorSignature, c.decodedParams);
156
+ }
157
+ }
158
+
159
+ // The transactionRequest is still usable — the caller must estimate gas themselves.
160
+ const tx = result.transactionRequest;
161
+ console.log(tx.to, tx.data, tx.value);
162
+ }
163
+ ```
164
+
165
+ The `simulationPolicy` field accepts two values:
166
+ - `'strict'` (default) — revert causes a thrown `ComposeError` with code `VALIDATION_ERROR`
167
+ - `'allow-revert'` — revert returns a partial result with `status: 'partial'`
168
+
169
+ You can also pass `checkOnChainAllowances: true` to have the server filter the returned `approvals` array against current on-chain allowances, omitting approvals that are already sufficient:
170
+
171
+ ```ts
172
+ const result = await builder.compile({
173
+ signer: OWNER,
174
+ inputs: { amountIn: materialisers.balanceOf({ owner: OWNER }) },
175
+ checkOnChainAllowances: true,
176
+ });
177
+ ```
178
+
179
+ ## Error handling
180
+
181
+ All SDK errors are thrown as `ComposeError` with a `code` property:
182
+
183
+ ```ts
184
+ import { isComposeError } from '@lifi/composer-sdk';
185
+
186
+ try {
187
+ const result = await sdk.client.compile(request);
188
+ } catch (err) {
189
+ if (isComposeError(err)) {
190
+ console.error(err.code, err.message);
191
+ // Codes: VALIDATION_ERROR, SERVER_ERROR, RATE_LIMITED, NETWORK_ERROR, ...
192
+ }
193
+ }
194
+ ```
195
+
196
+ ## Examples
197
+
198
+ The `src/examples/` directory contains complete working examples:
199
+
200
+ - **lifiSwap** — Single token swap (WETH to USDC)
201
+ - **lifiZap** — Swap into a DeFi position
202
+ - **swapAndZap** — Multi-step: swap then deposit
203
+ - **splitAndZap** — Split a resource and zap each portion into a different vault
204
+ - **splitWithArithmetic** — Split then verify with add/subtract/assertEqual assertions
205
+ - **dustSweep** — Split and partially use tokens, sweep leftover dust back to sender
206
+ - **depositFromProxy** — Read tokens already on the proxy via `balanceOf`, with a precondition guard
207
+ - **approveAndDeposit** — Approve a vault, deposit, and graduate shares via `asResource`
208
+ - **consolidateToUsdc** — Consolidate multiple tokens into USDC
209
+ - **consolidateToEth** — Consolidate multiple tokens into ETH
210
+ - **swapToRecipient** — Swap and send to a different address
211
+ - **swapWithBalanceCheck** — Swap with balance precondition
212
+ - **swapWithOutputValidation** — Swap with computed slippage bounds using bpsDown/bpsUp/assertInRange
213
+ - **rawCallWithArithmetic** — Query a contract with pre-encoded calldata, then scale with multiply/divide
214
+ - **readContractState** — Compare peek (compile-time), staticCall (execution-time), and balanceOf (resource)
215
+ - **swapWithAllowRevert** — Swap with `simulationPolicy: 'allow-revert'` and handle the `ComposeCompileResult` discriminated union
216
+ - **untypedOpWithTypedRef** — Insert an untyped operation node via `untypedOp`, then bridge its output into typed operations using `raw.ref<T>()`
217
+
218
+ ## License
219
+
220
+ Apache-2.0
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var FlowBuilderCore_exports = {};
20
+ __export(FlowBuilderCore_exports, {
21
+ createFlowBuilderCore: () => createFlowBuilderCore
22
+ });
23
+ module.exports = __toCommonJS(FlowBuilderCore_exports);
24
+ var import_handles = require("./handles.js");
25
+ var import_raw = require("./raw.js");
26
+ const toRef = (bindable) => {
27
+ if ("_tag" in bindable) return (0, import_handles.handleToRef)(bindable);
28
+ return bindable;
29
+ };
30
+ const isResource = (decl) => typeof decl === "object" && decl !== null && "kind" in decl;
31
+ const createFlowBuilderCore = (chainId, options) => {
32
+ const id = options.name ?? crypto.randomUUID();
33
+ const flowInputs = [];
34
+ const nodes = [];
35
+ const nodeIds = /* @__PURE__ */ new Set();
36
+ const inputHandles = {};
37
+ for (const [name, decl] of Object.entries(options.inputs)) {
38
+ if (isResource(decl)) {
39
+ if (decl.chainId !== chainId) {
40
+ throw new Error(
41
+ `Input "${name}" has chainId ${decl.chainId} but flow targets chain ${chainId}`
42
+ );
43
+ }
44
+ flowInputs.push({ name, resource: decl });
45
+ inputHandles[name] = { _tag: "input", inputName: name, resource: decl };
46
+ } else {
47
+ flowInputs.push({ name, type: decl });
48
+ inputHandles[name] = { _tag: "input", inputName: name };
49
+ }
50
+ }
51
+ const call = (nodeId, op, args, outputs) => {
52
+ if (nodeIds.has(nodeId)) throw new Error(`Duplicate node id: "${nodeId}"`);
53
+ nodeIds.add(nodeId);
54
+ const bind = {};
55
+ for (const [key, val] of Object.entries(args.bind)) {
56
+ bind[key] = toRef(val);
57
+ }
58
+ const node = {
59
+ id: nodeId,
60
+ op,
61
+ bind,
62
+ config: args.config ?? {},
63
+ ...args.guards && args.guards.length > 0 && { guards: args.guards }
64
+ };
65
+ nodes.push(node);
66
+ return new Proxy({}, {
67
+ get: (_target, prop) => {
68
+ if (typeof prop !== "string" || prop === "then") return void 0;
69
+ if (!(prop in outputs)) {
70
+ throw new Error(
71
+ `Op "${op}" has no output port "${prop}". Valid ports: ${Object.keys(
72
+ outputs
73
+ ).join(", ")}`
74
+ );
75
+ }
76
+ return { _tag: "output", nodeId, portName: prop };
77
+ }
78
+ });
79
+ };
80
+ const untypedOp = (nodeId, op, args) => {
81
+ if (nodeIds.has(nodeId)) throw new Error(`Duplicate node id: "${nodeId}"`);
82
+ nodeIds.add(nodeId);
83
+ const node = {
84
+ id: nodeId,
85
+ op,
86
+ bind: args.bind,
87
+ config: args.config,
88
+ ...args.guards && args.guards.length > 0 && { guards: args.guards }
89
+ };
90
+ nodes.push(node);
91
+ };
92
+ const build = () => ({
93
+ version: 1,
94
+ id,
95
+ chainId,
96
+ inputs: [...flowInputs],
97
+ nodes: [...nodes]
98
+ });
99
+ const context = {
100
+ sender: (0, import_raw.ref)("context.sender"),
101
+ executionAddress: (0, import_raw.ref)("context.executionAddress")
102
+ };
103
+ return {
104
+ context,
105
+ inputs: inputHandles,
106
+ call,
107
+ untypedOp,
108
+ build
109
+ };
110
+ };
111
+ // Annotate the CommonJS export names for ESM import in node:
112
+ 0 && (module.exports = {
113
+ createFlowBuilderCore
114
+ });
115
+ //# sourceMappingURL=FlowBuilderCore.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/authoring/FlowBuilderCore.ts"],"sourcesContent":["import type {\n AppliedGuard,\n Call,\n Flow,\n FlowInput,\n Ref,\n Resource,\n SolType,\n} from '@lifi/compose-spec';\n\nimport type {\n InputDecl,\n InputSchema,\n OutputKind,\n TypedGuard,\n TypedRef,\n} from '../types.js';\n\nimport type {\n InputHandle,\n OutputHandle,\n ResourceInputHandle,\n} from './handles.js';\nimport { handleToRef } from './handles.js';\nimport { ref } from './raw.js';\n\n/**\n * Arguments for calling an operation node in a flow.\n */\nexport interface CallArgs {\n /** Maps parameter names to input/output handles or raw `$ref` pointers. */\n readonly bind: Record<string, AnyBindable>;\n /** Optional operation-specific configuration. */\n readonly config?: object;\n /** Optional guards (e.g. slippage checks) applied to this operation's outputs. */\n readonly guards?: readonly TypedGuard[];\n}\n\n/**\n * Any value that can be bound to an operation parameter: an input handle,\n * an output handle from a previous operation, or a typed `$ref` pointer.\n *\n * Use `raw.ref<T>()` to create a typed ref from a raw path string.\n */\nexport type AnyBindable = InputHandle | OutputHandle | TypedRef;\n\nconst toRef = (bindable: AnyBindable): Ref => {\n if ('_tag' in bindable) return handleToRef(bindable);\n return bindable;\n};\n\n/**\n * Provides references to runtime context values available inside a flow.\n * Access via `builder.context`.\n */\nexport interface ContextAccessor {\n /** A `$ref` pointing to the transaction sender (signer) address. */\n readonly sender: TypedRef<'address'>;\n /** A `$ref` pointing to the on-chain execution (proxy) address. */\n readonly executionAddress: TypedRef<'address'>;\n}\n\ntype InputHandleOf<D extends InputDecl> = D extends Resource\n ? ResourceInputHandle\n : D extends SolType\n ? InputHandle<D>\n : InputHandle;\n\n/**\n * A mapped type that converts an input schema into typed handles.\n * Resource inputs produce {@link ResourceInputHandle}; scalar inputs produce {@link InputHandle}.\n *\n * @typeParam T - The flow's input schema.\n */\nexport type InputHandles<T extends InputSchema> = {\n readonly [K in keyof T]: InputHandleOf<T[K]>;\n};\n\n/**\n * Options for creating a new flow builder.\n *\n * @typeParam T - The flow's input schema.\n */\nexport interface FlowOptions<T extends InputSchema> {\n /** Optional human-readable name for the flow. Defaults to a random UUID. */\n readonly name?: string;\n /** Input declarations mapping names to resource or scalar types. */\n readonly inputs: T;\n}\n\n/**\n * A Flow document branded with its input schema for type-safe request building.\n *\n * The `__inputs` field is a phantom type — it exists only at compile time for\n * TypeScript inference and is never present at runtime.\n */\nexport type TypedFlow<T extends InputSchema = InputSchema> = Flow & {\n readonly __inputs?: T;\n};\n\n/**\n * Core flow builder interface providing low-level access to flow construction.\n *\n * For most use cases, prefer the {@link FlowBuilder} type returned by `sdk.flow()`\n * which adds generated operation methods and a `compile` method.\n *\n * @typeParam T - The flow's input schema.\n */\nexport interface FlowBuilderCore<T extends InputSchema = InputSchema> {\n /** Runtime context references (sender address, execution address). */\n readonly context: ContextAccessor;\n /** Typed handles for each declared flow input, used to bind inputs to operations. */\n readonly inputs: InputHandles<T>;\n /**\n * Appends an untyped operation node to the flow. This is an escape hatch\n * for operations not yet covered by the generated methods.\n *\n * Use `raw.ref<T>()` to reference this node's outputs in subsequent typed\n * operations.\n *\n * @param id - Unique node identifier within the flow.\n * @param op - The operation name (e.g. `\"custom.vaultQuery\"`).\n * @param args - Bind map, config, and optional guards for the node.\n * @throws Error if a node with the same `id` already exists in the flow.\n */\n readonly untypedOp: (\n id: string,\n op: string,\n args: {\n readonly bind: Record<string, Ref>;\n readonly config: Record<string, unknown>;\n readonly guards?: readonly AppliedGuard[];\n },\n ) => void;\n /** Serialises the builder state into a {@link TypedFlow} document. */\n readonly build: () => TypedFlow<T>;\n}\n\n/** Maps output port names to their output kind for compile-time and runtime validation. */\nexport type OutputSpec = Record<string, OutputKind>;\n\n/** Internal interface exposed to bindGeneratedOps — not part of the public API. */\nexport interface FlowBuilderInternal<\n T extends InputSchema = InputSchema,\n> extends FlowBuilderCore<T> {\n readonly call: <O extends OutputSpec>(\n nodeId: string,\n op: string,\n args: CallArgs,\n outputs: O,\n ) => { readonly [K in keyof O & string]: OutputHandle<O[K]> };\n}\n\nconst isResource = (decl: InputDecl): decl is Resource =>\n typeof decl === 'object' && decl !== null && 'kind' in decl;\n\n/**\n * Creates a new flow builder targeting the given chain.\n *\n * @param chainId - The EVM chain ID (e.g. `1` for Ethereum mainnet).\n * @param options - Flow configuration including input declarations.\n * @returns A {@link FlowBuilderInternal} instance.\n * @internal\n */\nexport const createFlowBuilderCore = <T extends InputSchema>(\n chainId: number,\n options: FlowOptions<T>,\n): FlowBuilderInternal<T> => {\n const id = options.name ?? crypto.randomUUID();\n const flowInputs: FlowInput[] = [];\n const nodes: Call[] = [];\n const nodeIds = new Set<string>();\n\n const inputHandles = {} as Record<string, InputHandle | ResourceInputHandle>;\n for (const [name, decl] of Object.entries(options.inputs)) {\n if (isResource(decl)) {\n if (decl.chainId !== chainId) {\n throw new Error(\n `Input \"${name}\" has chainId ${decl.chainId} but flow targets chain ${chainId}`,\n );\n }\n flowInputs.push({ name, resource: decl });\n inputHandles[name] = { _tag: 'input', inputName: name, resource: decl };\n } else {\n flowInputs.push({ name, type: decl });\n inputHandles[name] = { _tag: 'input', inputName: name };\n }\n }\n\n const call = <O extends OutputSpec>(\n nodeId: string,\n op: string,\n args: CallArgs,\n outputs: O,\n ): { readonly [K in keyof O & string]: OutputHandle<O[K]> } => {\n if (nodeIds.has(nodeId)) throw new Error(`Duplicate node id: \"${nodeId}\"`);\n nodeIds.add(nodeId);\n\n const bind: Record<string, Ref> = {};\n for (const [key, val] of Object.entries(args.bind)) {\n bind[key] = toRef(val);\n }\n\n const node: Call = {\n id: nodeId,\n op,\n bind,\n config: (args.config ?? {}) as Record<string, unknown>,\n ...(args.guards && args.guards.length > 0 && { guards: args.guards }),\n };\n nodes.push(node);\n\n type Result = { readonly [K in keyof O & string]: OutputHandle<O[K]> };\n return new Proxy({} as Result, {\n get: (_target, prop): OutputHandle | undefined => {\n if (typeof prop !== 'string' || prop === 'then') return undefined;\n if (!(prop in outputs)) {\n throw new Error(\n `Op \"${op}\" has no output port \"${prop}\". Valid ports: ${Object.keys(\n outputs,\n ).join(', ')}`,\n );\n }\n return { _tag: 'output', nodeId, portName: prop };\n },\n });\n };\n\n const untypedOp = (\n nodeId: string,\n op: string,\n args: {\n readonly bind: Record<string, Ref>;\n readonly config: Record<string, unknown>;\n readonly guards?: readonly AppliedGuard[];\n },\n ): void => {\n if (nodeIds.has(nodeId)) throw new Error(`Duplicate node id: \"${nodeId}\"`);\n nodeIds.add(nodeId);\n const node: Call = {\n id: nodeId,\n op,\n bind: args.bind,\n config: args.config,\n ...(args.guards && args.guards.length > 0 && { guards: args.guards }),\n };\n nodes.push(node);\n };\n\n const build = (): TypedFlow<T> => ({\n version: 1,\n id,\n chainId,\n inputs: [...flowInputs],\n nodes: [...nodes],\n });\n\n const context: ContextAccessor = {\n sender: ref<'address'>('context.sender'),\n executionAddress: ref<'address'>('context.executionAddress'),\n };\n\n return {\n context,\n inputs: inputHandles as InputHandles<T>,\n call,\n untypedOp,\n build,\n };\n};\n"],"mappings":"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","names":[]}
@@ -0,0 +1,114 @@
1
+ import { Resource, SolType, Ref, AppliedGuard, Flow } from '@lifi/compose-spec';
2
+ import { TypedRef, InputSchema, InputDecl, TypedGuard, OutputKind } from '../types.cjs';
3
+ import { InputHandle, OutputHandle, ResourceInputHandle } from './handles.cjs';
4
+
5
+ /**
6
+ * Arguments for calling an operation node in a flow.
7
+ */
8
+ interface CallArgs {
9
+ /** Maps parameter names to input/output handles or raw `$ref` pointers. */
10
+ readonly bind: Record<string, AnyBindable>;
11
+ /** Optional operation-specific configuration. */
12
+ readonly config?: object;
13
+ /** Optional guards (e.g. slippage checks) applied to this operation's outputs. */
14
+ readonly guards?: readonly TypedGuard[];
15
+ }
16
+ /**
17
+ * Any value that can be bound to an operation parameter: an input handle,
18
+ * an output handle from a previous operation, or a typed `$ref` pointer.
19
+ *
20
+ * Use `raw.ref<T>()` to create a typed ref from a raw path string.
21
+ */
22
+ type AnyBindable = InputHandle | OutputHandle | TypedRef;
23
+ /**
24
+ * Provides references to runtime context values available inside a flow.
25
+ * Access via `builder.context`.
26
+ */
27
+ interface ContextAccessor {
28
+ /** A `$ref` pointing to the transaction sender (signer) address. */
29
+ readonly sender: TypedRef<'address'>;
30
+ /** A `$ref` pointing to the on-chain execution (proxy) address. */
31
+ readonly executionAddress: TypedRef<'address'>;
32
+ }
33
+ type InputHandleOf<D extends InputDecl> = D extends Resource ? ResourceInputHandle : D extends SolType ? InputHandle<D> : InputHandle;
34
+ /**
35
+ * A mapped type that converts an input schema into typed handles.
36
+ * Resource inputs produce {@link ResourceInputHandle}; scalar inputs produce {@link InputHandle}.
37
+ *
38
+ * @typeParam T - The flow's input schema.
39
+ */
40
+ type InputHandles<T extends InputSchema> = {
41
+ readonly [K in keyof T]: InputHandleOf<T[K]>;
42
+ };
43
+ /**
44
+ * Options for creating a new flow builder.
45
+ *
46
+ * @typeParam T - The flow's input schema.
47
+ */
48
+ interface FlowOptions<T extends InputSchema> {
49
+ /** Optional human-readable name for the flow. Defaults to a random UUID. */
50
+ readonly name?: string;
51
+ /** Input declarations mapping names to resource or scalar types. */
52
+ readonly inputs: T;
53
+ }
54
+ /**
55
+ * A Flow document branded with its input schema for type-safe request building.
56
+ *
57
+ * The `__inputs` field is a phantom type — it exists only at compile time for
58
+ * TypeScript inference and is never present at runtime.
59
+ */
60
+ type TypedFlow<T extends InputSchema = InputSchema> = Flow & {
61
+ readonly __inputs?: T;
62
+ };
63
+ /**
64
+ * Core flow builder interface providing low-level access to flow construction.
65
+ *
66
+ * For most use cases, prefer the {@link FlowBuilder} type returned by `sdk.flow()`
67
+ * which adds generated operation methods and a `compile` method.
68
+ *
69
+ * @typeParam T - The flow's input schema.
70
+ */
71
+ interface FlowBuilderCore<T extends InputSchema = InputSchema> {
72
+ /** Runtime context references (sender address, execution address). */
73
+ readonly context: ContextAccessor;
74
+ /** Typed handles for each declared flow input, used to bind inputs to operations. */
75
+ readonly inputs: InputHandles<T>;
76
+ /**
77
+ * Appends an untyped operation node to the flow. This is an escape hatch
78
+ * for operations not yet covered by the generated methods.
79
+ *
80
+ * Use `raw.ref<T>()` to reference this node's outputs in subsequent typed
81
+ * operations.
82
+ *
83
+ * @param id - Unique node identifier within the flow.
84
+ * @param op - The operation name (e.g. `"custom.vaultQuery"`).
85
+ * @param args - Bind map, config, and optional guards for the node.
86
+ * @throws Error if a node with the same `id` already exists in the flow.
87
+ */
88
+ readonly untypedOp: (id: string, op: string, args: {
89
+ readonly bind: Record<string, Ref>;
90
+ readonly config: Record<string, unknown>;
91
+ readonly guards?: readonly AppliedGuard[];
92
+ }) => void;
93
+ /** Serialises the builder state into a {@link TypedFlow} document. */
94
+ readonly build: () => TypedFlow<T>;
95
+ }
96
+ /** Maps output port names to their output kind for compile-time and runtime validation. */
97
+ type OutputSpec = Record<string, OutputKind>;
98
+ /** Internal interface exposed to bindGeneratedOps — not part of the public API. */
99
+ interface FlowBuilderInternal<T extends InputSchema = InputSchema> extends FlowBuilderCore<T> {
100
+ readonly call: <O extends OutputSpec>(nodeId: string, op: string, args: CallArgs, outputs: O) => {
101
+ readonly [K in keyof O & string]: OutputHandle<O[K]>;
102
+ };
103
+ }
104
+ /**
105
+ * Creates a new flow builder targeting the given chain.
106
+ *
107
+ * @param chainId - The EVM chain ID (e.g. `1` for Ethereum mainnet).
108
+ * @param options - Flow configuration including input declarations.
109
+ * @returns A {@link FlowBuilderInternal} instance.
110
+ * @internal
111
+ */
112
+ declare const createFlowBuilderCore: <T extends InputSchema>(chainId: number, options: FlowOptions<T>) => FlowBuilderInternal<T>;
113
+
114
+ export { type AnyBindable, type CallArgs, type ContextAccessor, type FlowBuilderCore, type FlowBuilderInternal, type FlowOptions, type InputHandles, type OutputSpec, type TypedFlow, createFlowBuilderCore };