sui-gas-station 0.1.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 +190 -0
- package/README.md +244 -0
- package/dist/coin-pool.d.ts +97 -0
- package/dist/coin-pool.d.ts.map +1 -0
- package/dist/coin-pool.js +382 -0
- package/dist/coin-pool.js.map +1 -0
- package/dist/errors.d.ts +12 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +13 -0
- package/dist/errors.js.map +1 -0
- package/dist/gas-sponsor.d.ts +71 -0
- package/dist/gas-sponsor.d.ts.map +1 -0
- package/dist/gas-sponsor.js +278 -0
- package/dist/gas-sponsor.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/policy.d.ts +14 -0
- package/dist/policy.d.ts.map +1 -0
- package/dist/policy.js +85 -0
- package/dist/policy.js.map +1 -0
- package/dist/types.d.ts +108 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +4 -0
- package/dist/types.js.map +1 -0
- package/package.json +54 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
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 the 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 the 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 any 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
|
+
Copyright 2026 Danny
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
# sui-gas-station
|
|
2
|
+
|
|
3
|
+
Self-hosted gas sponsorship library for Sui. Enable gasless transactions in your dApp — users transact without owning SUI.
|
|
4
|
+
|
|
5
|
+
Zero runtime dependencies. One peer dependency: `@mysten/sui`.
|
|
6
|
+
|
|
7
|
+
## Quick Start
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
import { SuiClient } from "@mysten/sui/client";
|
|
11
|
+
import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
|
|
12
|
+
import { GasSponsor } from "sui-gas-station";
|
|
13
|
+
|
|
14
|
+
const client = new SuiClient({ url: "https://fullnode.mainnet.sui.io" });
|
|
15
|
+
const keypair = Ed25519Keypair.fromSecretKey(process.env.SPONSOR_KEY!);
|
|
16
|
+
|
|
17
|
+
// 1. Initialize (splits coins into a pool)
|
|
18
|
+
const sponsor = new GasSponsor({ client, signer: keypair });
|
|
19
|
+
await sponsor.initialize();
|
|
20
|
+
|
|
21
|
+
// 2. Sponsor a transaction
|
|
22
|
+
const result = await sponsor.sponsorTransaction({
|
|
23
|
+
sender: "0xUSER_ADDRESS",
|
|
24
|
+
transactionKindBytes: kindBytes, // from Transaction.build({ onlyTransactionKind: true })
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
// 3. Client executes with dual signatures
|
|
28
|
+
const response = await client.executeTransactionBlock({
|
|
29
|
+
transactionBlock: result.transactionBytes,
|
|
30
|
+
signature: [senderSignature, result.sponsorSignature],
|
|
31
|
+
options: { showEffects: true },
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// 4. Report execution (recycles the gas coin)
|
|
35
|
+
sponsor.reportExecution(result.reservation, response.effects!);
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## How It Works
|
|
39
|
+
|
|
40
|
+
Sui supports **sponsored transactions** where one address (the sponsor) pays gas on behalf of another (the sender). This requires:
|
|
41
|
+
|
|
42
|
+
1. The sender builds a **transaction kind** (the operations, without gas data)
|
|
43
|
+
2. The sponsor attaches gas data (coin, budget, price) and signs
|
|
44
|
+
3. The sender signs the full transaction
|
|
45
|
+
4. Both signatures are submitted together
|
|
46
|
+
|
|
47
|
+
`sui-gas-station` handles step 2 internally — managing a pool of pre-split gas coins, caching gas prices, handling epoch boundaries, and signing as sponsor.
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
Client (sender) Your Server (sponsor)
|
|
51
|
+
───────────────── ─────────────────────
|
|
52
|
+
Build tx kind bytes ──────────────→ sponsorTransaction()
|
|
53
|
+
├─ Reserve gas coin
|
|
54
|
+
├─ Attach gas data
|
|
55
|
+
├─ Build full tx
|
|
56
|
+
└─ Sign as sponsor
|
|
57
|
+
←────────────── { txBytes, sponsorSig }
|
|
58
|
+
Sign as sender
|
|
59
|
+
Execute with [senderSig, sponsorSig]
|
|
60
|
+
──────────────→ reportExecution(effects)
|
|
61
|
+
└─ Recycle gas coin
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Installation
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
npm install sui-gas-station @mysten/sui
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`@mysten/sui` is a **peer dependency** — you bring your own version (`^1.45.0`).
|
|
71
|
+
|
|
72
|
+
## API Reference
|
|
73
|
+
|
|
74
|
+
### `new GasSponsor(options)`
|
|
75
|
+
|
|
76
|
+
| Option | Type | Default | Description |
|
|
77
|
+
| ---------------------- | ----------------- | -------------- | -------------------------------------- |
|
|
78
|
+
| `client` | `SuiClient` | _required_ | Sui JSON-RPC client |
|
|
79
|
+
| `signer` | `Signer` | _required_ | Sponsor keypair (must own SUI) |
|
|
80
|
+
| `policy` | `SponsorPolicy` | — | Default policy for all requests |
|
|
81
|
+
| `targetPoolSize` | `number` | `20` | Number of gas coins to maintain |
|
|
82
|
+
| `targetCoinBalance` | `bigint` | `500_000_000n` | Target balance per coin (0.5 SUI) |
|
|
83
|
+
| `minCoinBalance` | `bigint` | `50_000_000n` | Remove coins below this (0.05 SUI) |
|
|
84
|
+
| `reservationTimeoutMs` | `number` | `30_000` | Auto-release reserved coins after this |
|
|
85
|
+
| `epochBoundaryWindow` | `number` | `1_000` | Pause near epoch boundaries (ms) |
|
|
86
|
+
| `onPoolDepleted` | `(stats) => void` | — | Callback when pool has no coins left |
|
|
87
|
+
|
|
88
|
+
### `sponsor.initialize(): Promise<void>`
|
|
89
|
+
|
|
90
|
+
Fetches existing coins, splits them to target pool size, and caches the current gas price. **Must be called before `sponsorTransaction()`.**
|
|
91
|
+
|
|
92
|
+
### `sponsor.sponsorTransaction(options): Promise<SponsoredTransaction>`
|
|
93
|
+
|
|
94
|
+
| Option | Type | Required | Description |
|
|
95
|
+
| ---------------------- | ---------------------- | -------- | ------------------------------------------- |
|
|
96
|
+
| `sender` | `string` | yes | Sender's Sui address |
|
|
97
|
+
| `transactionKindBytes` | `string \| Uint8Array` | yes | Transaction kind (base64 or bytes) |
|
|
98
|
+
| `gasBudget` | `bigint` | no | Explicit budget (auto-estimated if omitted) |
|
|
99
|
+
| `policy` | `SponsorPolicy` | no | Override default policy for this request |
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
{
|
|
105
|
+
transactionBytes: string; // Base64 — full tx ready for sender to sign
|
|
106
|
+
sponsorSignature: string; // Base64 — sponsor's signature
|
|
107
|
+
gasBudget: bigint; // Actual budget (may differ if auto-estimated)
|
|
108
|
+
gasPrice: bigint; // Current reference gas price
|
|
109
|
+
reservation: GasCoinReservation; // Pass to reportExecution()
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### `sponsor.reportExecution(reservation, effects): void`
|
|
114
|
+
|
|
115
|
+
**Must be called after every sponsored transaction executes.** Updates the gas coin's version/digest from the transaction effects and recycles it back into the pool.
|
|
116
|
+
|
|
117
|
+
Pass `response.effects` from `executeTransactionBlock({ options: { showEffects: true } })`.
|
|
118
|
+
|
|
119
|
+
### `sponsor.getStats(): PoolStats`
|
|
120
|
+
|
|
121
|
+
Returns current pool statistics for monitoring:
|
|
122
|
+
|
|
123
|
+
```typescript
|
|
124
|
+
{
|
|
125
|
+
totalCoins: number;
|
|
126
|
+
availableCoins: number;
|
|
127
|
+
reservedCoins: number;
|
|
128
|
+
totalBalance: bigint;
|
|
129
|
+
sponsorAddress: string;
|
|
130
|
+
currentEpoch: string;
|
|
131
|
+
gasPrice: bigint;
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### `sponsor.replenish(): Promise<void>`
|
|
136
|
+
|
|
137
|
+
Re-fetches and splits coins to refill the pool. Call from `onPoolDepleted` or on a schedule.
|
|
138
|
+
|
|
139
|
+
### `sponsor.close(): Promise<void>`
|
|
140
|
+
|
|
141
|
+
Merges remaining pool coins back into one. Call on graceful shutdown.
|
|
142
|
+
|
|
143
|
+
## Policy Enforcement
|
|
144
|
+
|
|
145
|
+
Control who can use your gas station and how much they can spend:
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
const sponsor = new GasSponsor({
|
|
149
|
+
client,
|
|
150
|
+
signer: keypair,
|
|
151
|
+
policy: {
|
|
152
|
+
maxBudgetPerTx: 50_000_000n, // Cap at 0.05 SUI per tx
|
|
153
|
+
blockedAddresses: ["0x..."], // Deny specific addresses
|
|
154
|
+
allowedMoveTargets: [
|
|
155
|
+
"0xpkg::module::function", // Only sponsor these Move calls
|
|
156
|
+
],
|
|
157
|
+
customValidator: async (sender, kindBytes) => {
|
|
158
|
+
// Your logic: rate limits, auth checks, allowlists, etc.
|
|
159
|
+
return isAllowed(sender);
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
Override the default policy per-request:
|
|
166
|
+
|
|
167
|
+
```typescript
|
|
168
|
+
await sponsor.sponsorTransaction({
|
|
169
|
+
sender,
|
|
170
|
+
transactionKindBytes: kindBytes,
|
|
171
|
+
policy: { maxBudgetPerTx: 100_000_000n }, // Higher limit for this request
|
|
172
|
+
});
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
## Error Handling
|
|
176
|
+
|
|
177
|
+
All errors are `GasStationError` instances with typed codes:
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
import { GasStationError } from "sui-gas-station";
|
|
181
|
+
|
|
182
|
+
try {
|
|
183
|
+
await sponsor.sponsorTransaction({ ... });
|
|
184
|
+
} catch (err) {
|
|
185
|
+
if (err instanceof GasStationError) {
|
|
186
|
+
switch (err.code) {
|
|
187
|
+
case "POOL_EXHAUSTED": // No coins available — retry later
|
|
188
|
+
case "POOL_NOT_INITIALIZED": // Forgot to call initialize()
|
|
189
|
+
case "POLICY_VIOLATION": // Request rejected by policy
|
|
190
|
+
case "BUILD_FAILED": // Transaction build/dry-run failed
|
|
191
|
+
case "SIGN_FAILED": // Sponsor signing failed
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
## Architecture
|
|
198
|
+
|
|
199
|
+
The library has two internal components:
|
|
200
|
+
|
|
201
|
+
- **`GasSponsor`** — Public API. Handles the sponsorship flow, gas price caching, epoch boundary detection.
|
|
202
|
+
- **`CoinPool`** — Internal. Manages a pool of pre-split SUI coins. Handles reservations, timeouts, and effects-based coin recycling (no extra RPC calls).
|
|
203
|
+
|
|
204
|
+
Key design decisions:
|
|
205
|
+
|
|
206
|
+
- **Effects-based coin refresh** — After execution, the gas coin's new version/digest comes from `TransactionEffects`, not an extra RPC call. Zero latency, no race conditions.
|
|
207
|
+
- **Epoch boundary handling** — Gas price is cached with epoch-aware TTL. Near epoch boundaries, sponsorship pauses briefly to avoid stale gas prices.
|
|
208
|
+
- **Reservation timeouts** — Coins auto-release after 30s if `reportExecution()` is never called (crashed clients).
|
|
209
|
+
- **Structural typing for effects** — The library accepts any object matching the `ExecutionEffects` shape, compatible with the SDK's `TransactionEffects` type.
|
|
210
|
+
|
|
211
|
+
## Client-Side Integration
|
|
212
|
+
|
|
213
|
+
The sender (client) builds transaction kind bytes — the operations without any gas data:
|
|
214
|
+
|
|
215
|
+
```typescript
|
|
216
|
+
import { Transaction } from "@mysten/sui/transactions";
|
|
217
|
+
|
|
218
|
+
const tx = new Transaction();
|
|
219
|
+
tx.moveCall({ target: "0xpkg::module::function", arguments: [...] });
|
|
220
|
+
|
|
221
|
+
// Build kind bytes (no gas data)
|
|
222
|
+
const kindBytes = await tx.build({ onlyTransactionKind: true });
|
|
223
|
+
|
|
224
|
+
// Send kindBytes to your gas station server
|
|
225
|
+
// Receive back: { transactionBytes, sponsorSignature }
|
|
226
|
+
|
|
227
|
+
// Sign the full transaction as sender
|
|
228
|
+
const { signature } = await keypair.signTransaction(
|
|
229
|
+
Uint8Array.from(atob(transactionBytes), (c) => c.charCodeAt(0)),
|
|
230
|
+
);
|
|
231
|
+
|
|
232
|
+
// Submit with both signatures
|
|
233
|
+
await client.executeTransactionBlock({
|
|
234
|
+
transactionBlock: transactionBytes,
|
|
235
|
+
signature: [signature, sponsorSignature],
|
|
236
|
+
options: { showEffects: true },
|
|
237
|
+
});
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
`coinWithBalance` and `splitCoins(tx.gas, ...)` both work — they reference the gas coin, which the sponsor provides.
|
|
241
|
+
|
|
242
|
+
## License
|
|
243
|
+
|
|
244
|
+
Apache-2.0
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal coin pool for gas sponsorship.
|
|
3
|
+
* NOT exported from the public API — used only by GasSponsor.
|
|
4
|
+
*
|
|
5
|
+
* Ported from ParallelTransactionExecutor patterns in @mysten/sui SDK.
|
|
6
|
+
* Key insight: after execution, we update coin refs from the JSON-RPC
|
|
7
|
+
* effects response (gasObject.reference) — zero extra RPC calls.
|
|
8
|
+
*/
|
|
9
|
+
import type { SuiClient } from "@mysten/sui/client";
|
|
10
|
+
import type { Signer } from "@mysten/sui/cryptography";
|
|
11
|
+
import type { CoinEntry, ExecutionEffects } from "./types.js";
|
|
12
|
+
export interface CoinPoolOptions {
|
|
13
|
+
targetPoolSize?: number;
|
|
14
|
+
targetCoinBalance?: bigint;
|
|
15
|
+
minCoinBalance?: bigint;
|
|
16
|
+
reservationTimeoutMs?: number;
|
|
17
|
+
}
|
|
18
|
+
export declare class CoinPool {
|
|
19
|
+
private coins;
|
|
20
|
+
private readonly targetPoolSize;
|
|
21
|
+
private readonly targetCoinBalance;
|
|
22
|
+
private readonly minCoinBalance;
|
|
23
|
+
private readonly reservationTimeoutMs;
|
|
24
|
+
constructor(options?: CoinPoolOptions);
|
|
25
|
+
/**
|
|
26
|
+
* Query sponsor's coins and split into pool-sized pieces.
|
|
27
|
+
* If sponsor already has enough small coins, skips splitting.
|
|
28
|
+
*
|
|
29
|
+
* WARNING: Clears ALL pool state including reserved coins.
|
|
30
|
+
* Do NOT call while transactions are in-flight — use replenish() instead.
|
|
31
|
+
*/
|
|
32
|
+
initialize(client: SuiClient, signer: Signer): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Add new coins to the pool without disturbing existing entries.
|
|
35
|
+
* Safe to call while transactions are in-flight — reserved coins are untouched.
|
|
36
|
+
*
|
|
37
|
+
* Fetches all coins from the network, skips any already tracked (by objectId),
|
|
38
|
+
* and adds new ones up to targetPoolSize. Splits large coins if needed.
|
|
39
|
+
*/
|
|
40
|
+
replenish(client: SuiClient, signer: Signer): Promise<void>;
|
|
41
|
+
/**
|
|
42
|
+
* Reserve an available coin with sufficient balance.
|
|
43
|
+
* Returns null if no coins available (caller should throw POOL_EXHAUSTED).
|
|
44
|
+
*/
|
|
45
|
+
reserve(minBalance?: bigint): CoinEntry | null;
|
|
46
|
+
/**
|
|
47
|
+
* Release a reserved coin back to the pool.
|
|
48
|
+
*/
|
|
49
|
+
release(objectId: string): void;
|
|
50
|
+
/**
|
|
51
|
+
* Update a coin's ObjectRef from execution effects.
|
|
52
|
+
* The gas coin's version and digest change after every transaction.
|
|
53
|
+
* We read the new values from the effects response — zero RPC calls.
|
|
54
|
+
*/
|
|
55
|
+
updateFromEffects(effects: ExecutionEffects, objectId: string): void;
|
|
56
|
+
/**
|
|
57
|
+
* Remove coins whose reservations have expired.
|
|
58
|
+
*
|
|
59
|
+
* Expired coins are DELETED from the pool rather than recycled to "available".
|
|
60
|
+
* This is a deliberate safety choice: if a client reserved a coin and never
|
|
61
|
+
* called reportExecution(), we can't know whether the transaction was actually
|
|
62
|
+
* submitted. If it was, the coin's ObjectRef on-chain has changed — reusing
|
|
63
|
+
* the stale ref would cause a version mismatch or object equivocation.
|
|
64
|
+
*
|
|
65
|
+
* The pool shrinks naturally; operators should monitor getStats() and call
|
|
66
|
+
* initialize() to replenish when needed.
|
|
67
|
+
*/
|
|
68
|
+
recycleExpired(now: number): string[];
|
|
69
|
+
/**
|
|
70
|
+
* Re-fetch all coin ObjectRefs from the network.
|
|
71
|
+
* Called after epoch change when coin versions may have shifted.
|
|
72
|
+
*/
|
|
73
|
+
revalidatePool(client: SuiClient, _address: string): Promise<void>;
|
|
74
|
+
/**
|
|
75
|
+
* Merge remaining pool coins back into source on close.
|
|
76
|
+
* Only merges available coins — reserved coins are abandoned
|
|
77
|
+
* (their transactions are presumably still in-flight).
|
|
78
|
+
*/
|
|
79
|
+
close(client: SuiClient, signer: Signer): Promise<void>;
|
|
80
|
+
getStats(): {
|
|
81
|
+
total: number;
|
|
82
|
+
available: number;
|
|
83
|
+
reserved: number;
|
|
84
|
+
totalBalance: bigint;
|
|
85
|
+
};
|
|
86
|
+
get size(): number;
|
|
87
|
+
/**
|
|
88
|
+
* Fetch all SUI coins owned by an address, handling pagination.
|
|
89
|
+
*/
|
|
90
|
+
private fetchAllCoins;
|
|
91
|
+
/**
|
|
92
|
+
* Split source coins into pool-sized pieces.
|
|
93
|
+
* Ported from ParallelTransactionExecutor.refillCoinPool.
|
|
94
|
+
*/
|
|
95
|
+
private splitCoins;
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=coin-pool.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"coin-pool.d.ts","sourceRoot":"","sources":["../src/coin-pool.ts"],"names":[],"mappings":"AAGA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAEvD,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAW9D,MAAM,WAAW,eAAe;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED,qBAAa,QAAQ;IACnB,OAAO,CAAC,KAAK,CAAgC;IAC7C,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAS;IAC3C,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAS;IACxC,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAS;gBAElC,OAAO,GAAE,eAAoB;IASzC;;;;;;OAMG;IACG,UAAU,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAwDlE;;;;;;OAMG;IACG,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA4DjE;;;OAGG;IACH,OAAO,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;IAkB9C;;OAEG;IACH,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI;IAQ/B;;;;OAIG;IACH,iBAAiB,CAAC,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IA0CpE;;;;;;;;;;;OAWG;IACH,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE;IAerC;;;OAGG;IACG,cAAc,CAAC,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAwCxE;;;;OAIG;IACG,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAkD7D,QAAQ,IAAI;QACV,KAAK,EAAE,MAAM,CAAC;QACd,SAAS,EAAE,MAAM,CAAC;QAClB,QAAQ,EAAE,MAAM,CAAC;QACjB,YAAY,EAAE,MAAM,CAAC;KACtB;IAcD,IAAI,IAAI,IAAI,MAAM,CAEjB;IAID;;OAEG;YACW,aAAa;IAkC3B;;;OAGG;YACW,UAAU;CA+CzB"}
|