@midnightntwrk/mnkit-coins 0.0.0-stage → 0.2.0-rc.2
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 +201 -0
- package/README.md +34 -2
- package/dist/coins.d.ts +156 -0
- package/dist/coins.js +192 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +5 -0
- package/package.json +43 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,35 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @midnightntwrk/mnkit-coins
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Shielded-coin helpers for Midnight tests. Part of
|
|
4
|
+
[mnkit](https://www.npmjs.com/package/mnkit); `mnkit derive` imports them
|
|
5
|
+
when a circuit takes a coin.
|
|
6
|
+
|
|
7
|
+
- `tokenColor(domain, contractAddress)`, `domainSeparator`: a minting
|
|
8
|
+
contract's token color.
|
|
9
|
+
- `freshCoin(color, value)`: a new coin for a `ShieldedCoinInfo` circuit
|
|
10
|
+
argument, with a random nonce. The wallet pays for it; never build one from
|
|
11
|
+
the wallet's own coins.
|
|
12
|
+
- `simCoin(value, color)`: the same, for in-memory tests.
|
|
13
|
+
- `shieldedCoins`, `shieldedBalance`, `waitForShieldedBalance`: a wallet's
|
|
14
|
+
coins and balances.
|
|
15
|
+
- `recipientOf`, `encryptionKeys`, `mintNonce`: the arguments a mint to
|
|
16
|
+
another wallet needs.
|
|
17
|
+
- `contractCoinMtIndex`: a contract-held coin's tree index, from the indexer.
|
|
18
|
+
|
|
19
|
+
## Install outside mnkit
|
|
20
|
+
|
|
21
|
+
An mnkit project already has these. Anywhere else, add the peer and these
|
|
22
|
+
`overrides` to your `package.json`:
|
|
23
|
+
|
|
24
|
+
```json
|
|
25
|
+
"overrides": {
|
|
26
|
+
"@midnightntwrk/ledger-v9": "1.0.2",
|
|
27
|
+
"@midnightntwrk/onchain-runtime-v4": "4.0.2"
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
midnight-js-protocol 5.0.1 pins these at these versions today, but
|
|
32
|
+
compact-runtime 0.21.0 asks for `onchain-runtime-v4` `^4.0.0-rc.3`. The
|
|
33
|
+
overrides keep a later release, which mnkit doesn't test, out of your tree.
|
|
34
|
+
|
|
35
|
+
Apache-2.0. Source: [midnight-examples/packages/coins](https://github.com/midnightntwrk/midnight-examples/tree/main/packages/coins).
|
package/dist/coins.d.ts
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { type ContractAddress } from '@midnight-ntwrk/midnight-js-protocol/v9/compact-runtime';
|
|
2
|
+
/** A coin as a circuit takes it: Compact's `ShieldedCoinInfo`. */
|
|
3
|
+
export type ShieldedCoinArg = {
|
|
4
|
+
nonce: Uint8Array;
|
|
5
|
+
color: Uint8Array;
|
|
6
|
+
value: bigint;
|
|
7
|
+
};
|
|
8
|
+
/** A token color in both forms: `hex` is what the wallet keys coins and balances by, `bytes` what circuits take. */
|
|
9
|
+
export type TokenColor = {
|
|
10
|
+
hex: string;
|
|
11
|
+
bytes: Uint8Array;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The slice of the wallet facade's state these helpers read. `FacadeState`
|
|
15
|
+
* from @midnightntwrk/wallet-sdk fits it, and so does a hand-built object in
|
|
16
|
+
* a unit test.
|
|
17
|
+
*/
|
|
18
|
+
export interface ShieldedStateView {
|
|
19
|
+
shielded: {
|
|
20
|
+
/** Spendable balance per token color (hex). */
|
|
21
|
+
balances: Record<string, bigint>;
|
|
22
|
+
/** Spendable coins; `type` and `nonce` are hex. */
|
|
23
|
+
availableCoins: readonly {
|
|
24
|
+
coin: {
|
|
25
|
+
type: string;
|
|
26
|
+
nonce: string;
|
|
27
|
+
value: bigint;
|
|
28
|
+
};
|
|
29
|
+
}[];
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** What the helpers need from a wallet provider. Every example's MidnightWalletProvider has it. */
|
|
33
|
+
export interface CoinWallet {
|
|
34
|
+
wallet: {
|
|
35
|
+
waitForSyncedState(): Promise<ShieldedStateView>;
|
|
36
|
+
};
|
|
37
|
+
/** Hex coin public key. */
|
|
38
|
+
getCoinPublicKey(): string;
|
|
39
|
+
/** Hex encryption public key. */
|
|
40
|
+
getEncryptionPublicKey(): string;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The same 32 bytes as Compact's `pad(32, s)`: UTF-8, zero-filled on the
|
|
44
|
+
* right. A contract that mints with `pad(32, "my-app:token:")` as its domain
|
|
45
|
+
* separator gets its color from `tokenColor(domainSeparator("my-app:token:"), …)`.
|
|
46
|
+
*/
|
|
47
|
+
export declare function domainSeparator(s: string): Uint8Array;
|
|
48
|
+
/**
|
|
49
|
+
* The color of the token a contract mints under `domain`. A token's color is
|
|
50
|
+
* hash(domain separator, minting contract's address), so it is known only
|
|
51
|
+
* once the minting contract is deployed. Derive it off chain like this rather
|
|
52
|
+
* than storing it in the contract: MIP-0011 forbids computing it in the
|
|
53
|
+
* constructor, where `kernel.self()` resolves differently.
|
|
54
|
+
*/
|
|
55
|
+
export declare function tokenColor(domain: string | Uint8Array, contractAddress: ContractAddress): TokenColor;
|
|
56
|
+
/**
|
|
57
|
+
* The wallet's spendable coins of `color`, in circuit-argument form. Waits for
|
|
58
|
+
* the wallet to be synced. Useful for reading nonces (a privacy test checks
|
|
59
|
+
* none of them reaches public state). Don't pass one to a circuit that
|
|
60
|
+
* `receiveShielded`s it: use `freshCoin`.
|
|
61
|
+
*/
|
|
62
|
+
export declare function shieldedCoins(w: CoinWallet, color: TokenColor | string): Promise<ShieldedCoinArg[]>;
|
|
63
|
+
/**
|
|
64
|
+
* The argument for a circuit that `receiveShielded`s a coin: a new coin of
|
|
65
|
+
* `value` with a uniformly random nonce (the ledger's `createShieldedCoinInfo`).
|
|
66
|
+
* The wallet pays for it when it balances the transaction, from whichever
|
|
67
|
+
* coins of `color` it selects, and takes the change back under fresh nonces.
|
|
68
|
+
* So any amount works without making an exact-value coin first, and the nonce
|
|
69
|
+
* is in no commitment but the contract's own.
|
|
70
|
+
*
|
|
71
|
+
* The contract can't tell a fresh nonce from a reused one. If it keys a map by
|
|
72
|
+
* this nonce, it should refuse one already present (a same-nonce coin of a
|
|
73
|
+
* different value would overwrite the entry).
|
|
74
|
+
*/
|
|
75
|
+
export declare function freshCoin(color: TokenColor | string, value: bigint): ShieldedCoinArg;
|
|
76
|
+
/**
|
|
77
|
+
* The slice of a finalized transaction `contractCoinMtIndex` reads: its id and
|
|
78
|
+
* its guaranteed Zswap outputs. `FinalizedTxData` from submitCallTx's
|
|
79
|
+
* `.public` fits it.
|
|
80
|
+
*/
|
|
81
|
+
export interface TxWithOutputs {
|
|
82
|
+
txId: string;
|
|
83
|
+
tx: {
|
|
84
|
+
guaranteedOffer?: {
|
|
85
|
+
outputs: readonly {
|
|
86
|
+
commitment: string;
|
|
87
|
+
}[];
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The Zswap Merkle-tree index of `coin`, a coin that `tx` created for the
|
|
93
|
+
* contract at `contractAddress` (`receiveShielded`), as `mt_index` for
|
|
94
|
+
* spending it later with `sendShielded`.
|
|
95
|
+
*
|
|
96
|
+
* A contract that stores a coin with `insertCoin` gets the index for free. One
|
|
97
|
+
* that keeps the coin off chain (an escrow it holds only a commitment to)
|
|
98
|
+
* leaves its depositor to recover it. A transaction's outputs enter the tree
|
|
99
|
+
* in order from its `zswapStartIndex` (the indexer has it), so the index is
|
|
100
|
+
* that start plus the coin's position among the outputs. The position is found
|
|
101
|
+
* by commitment, because the wallet's change output can come first. A
|
|
102
|
+
* contract-owned output's commitment follows from the coin and the address.
|
|
103
|
+
*/
|
|
104
|
+
export declare function contractCoinMtIndex(indexerUri: string, tx: TxWithOutputs, coin: ShieldedCoinArg, contractAddress: ContractAddress): Promise<bigint>;
|
|
105
|
+
/**
|
|
106
|
+
* One spendable coin of `color` from the wallet: one worth exactly `value` if
|
|
107
|
+
* given, else the first.
|
|
108
|
+
*
|
|
109
|
+
* @deprecated Don't pass a wallet coin to a circuit that `receiveShielded`s it.
|
|
110
|
+
* The argument describes a new coin, so use `freshCoin(color, value)`: the
|
|
111
|
+
* wallet pays for it and makes change. Passing this coin instead puts its
|
|
112
|
+
* nonce, which its minter or sender knows, into the contract's coin.
|
|
113
|
+
*/
|
|
114
|
+
export declare function takeCoin(w: CoinWallet, color: TokenColor | string, value?: bigint): Promise<ShieldedCoinArg>;
|
|
115
|
+
/** The wallet's spendable balance of `color` (0n if it holds none). */
|
|
116
|
+
export declare function shieldedBalance(w: CoinWallet, color: TokenColor | string): Promise<bigint>;
|
|
117
|
+
/**
|
|
118
|
+
* Polls until the balance of `color` equals `until` (or `until(balance)` is
|
|
119
|
+
* true), and returns it. A submitted transaction is accepted before it is on
|
|
120
|
+
* chain and indexed, so a coin minted or sent to a wallet shows up some
|
|
121
|
+
* seconds later: wait for it before the next call that pays from it.
|
|
122
|
+
*/
|
|
123
|
+
export declare function waitForShieldedBalance(w: CoinWallet, color: TokenColor | string, until: bigint | ((balance: bigint) => boolean), opts?: {
|
|
124
|
+
timeoutMs?: number;
|
|
125
|
+
pollMs?: number;
|
|
126
|
+
logger?: {
|
|
127
|
+
info(msg: string): void;
|
|
128
|
+
};
|
|
129
|
+
}): Promise<bigint>;
|
|
130
|
+
/**
|
|
131
|
+
* The wallet as a mint or send recipient: the `ZswapCoinPublicKey` argument
|
|
132
|
+
* ({ bytes }) of a circuit like `mint(recipient, amount, nonce)`.
|
|
133
|
+
*/
|
|
134
|
+
export declare function recipientOf(w: CoinWallet): {
|
|
135
|
+
bytes: Uint8Array;
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* `additionalCoinEncPublicKeyMappings` for a call that creates coins for
|
|
139
|
+
* other wallets. The caller's wallet builds the output coin and must encrypt
|
|
140
|
+
* it to the recipient, so it needs each recipient's encryption key, keyed by
|
|
141
|
+
* coin public key. Without it the coin is made but the recipient's wallet
|
|
142
|
+
* never sees it.
|
|
143
|
+
*/
|
|
144
|
+
export declare function encryptionKeys(...recipients: CoinWallet[]): Map<string, string>;
|
|
145
|
+
/**
|
|
146
|
+
* A fresh random nonce for a mint. The circuit can't make one: uniqueness is
|
|
147
|
+
* the caller's job (MIP-0011), and the nonce stays secret between minter and
|
|
148
|
+
* recipient, which is what keeps the recipient unlinkable to outsiders.
|
|
149
|
+
*/
|
|
150
|
+
export declare function mintNonce(): Uint8Array;
|
|
151
|
+
/**
|
|
152
|
+
* A made-up coin for an in-memory (Sim) test. Sim doesn't check that a coin
|
|
153
|
+
* exists or is paid for, so any nonce does; a random one by default. On the
|
|
154
|
+
* devnet use `freshCoin`.
|
|
155
|
+
*/
|
|
156
|
+
export declare function simCoin(value: bigint, color: Uint8Array, nonce?: Uint8Array): ShieldedCoinArg;
|
package/dist/coins.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// Shielded-coin helpers for the examples' tests.
|
|
2
|
+
//
|
|
3
|
+
// A contract that takes a shielded coin (a tip, a bet, a deposit) declares a
|
|
4
|
+
// `ShieldedCoinInfo` argument: { nonce, color, value }, and calls
|
|
5
|
+
// `receiveShielded` on it. That argument is not one of the wallet's coins. It
|
|
6
|
+
// describes a NEW coin the transaction creates for the contract, and the
|
|
7
|
+
// wallet pays for it from whichever coins it selects, making change. So the
|
|
8
|
+
// argument comes from `freshCoin(color, value)`, with a random nonce. Never
|
|
9
|
+
// copy a wallet coin's nonce into it: that nonce is also in the wallet coin's
|
|
10
|
+
// commitment, so publishing it (or anything derived from it) links the
|
|
11
|
+
// contract's coin to that wallet coin, and whoever minted or sent it to you
|
|
12
|
+
// knows it.
|
|
13
|
+
//
|
|
14
|
+
// Every shielded example used to write its own converters, token-color
|
|
15
|
+
// derivation and balance polling. They live here instead. The helpers take a
|
|
16
|
+
// structural wallet (CoinWallet), not an example's MidnightWalletProvider,
|
|
17
|
+
// because each example owns its src/wallet.ts and they drift. Any provider
|
|
18
|
+
// with `wallet.waitForSyncedState()` and the two public keys fits.
|
|
19
|
+
import { randomBytes } from 'node:crypto';
|
|
20
|
+
import { decodeShieldedCoinInfo, encodeCoinPublicKey, encodeRawTokenType, encodeShieldedCoinInfo, } from '@midnight-ntwrk/midnight-js-protocol/v9/compact-runtime';
|
|
21
|
+
import { createShieldedCoinInfo, rawTokenType, ZswapOutput } from '@midnight-ntwrk/midnight-js-protocol/v9';
|
|
22
|
+
const fromHex = (h) => Uint8Array.from(Buffer.from(h, 'hex'));
|
|
23
|
+
const colorHex = (color) => (typeof color === 'string' ? color : color.hex);
|
|
24
|
+
/**
|
|
25
|
+
* The same 32 bytes as Compact's `pad(32, s)`: UTF-8, zero-filled on the
|
|
26
|
+
* right. A contract that mints with `pad(32, "my-app:token:")` as its domain
|
|
27
|
+
* separator gets its color from `tokenColor(domainSeparator("my-app:token:"), …)`.
|
|
28
|
+
*/
|
|
29
|
+
export function domainSeparator(s) {
|
|
30
|
+
const utf8 = new TextEncoder().encode(s);
|
|
31
|
+
if (utf8.length > 32)
|
|
32
|
+
throw new Error(`domain separator '${s}' is ${utf8.length} bytes; pad(32, …) takes at most 32`);
|
|
33
|
+
const out = new Uint8Array(32);
|
|
34
|
+
out.set(utf8);
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The color of the token a contract mints under `domain`. A token's color is
|
|
39
|
+
* hash(domain separator, minting contract's address), so it is known only
|
|
40
|
+
* once the minting contract is deployed. Derive it off chain like this rather
|
|
41
|
+
* than storing it in the contract: MIP-0011 forbids computing it in the
|
|
42
|
+
* constructor, where `kernel.self()` resolves differently.
|
|
43
|
+
*/
|
|
44
|
+
export function tokenColor(domain, contractAddress) {
|
|
45
|
+
const hex = rawTokenType(typeof domain === 'string' ? domainSeparator(domain) : domain, contractAddress);
|
|
46
|
+
return { hex, bytes: encodeRawTokenType(hex) };
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The wallet's spendable coins of `color`, in circuit-argument form. Waits for
|
|
50
|
+
* the wallet to be synced. Useful for reading nonces (a privacy test checks
|
|
51
|
+
* none of them reaches public state). Don't pass one to a circuit that
|
|
52
|
+
* `receiveShielded`s it: use `freshCoin`.
|
|
53
|
+
*/
|
|
54
|
+
export async function shieldedCoins(w, color) {
|
|
55
|
+
const hex = colorHex(color);
|
|
56
|
+
const bytes = encodeRawTokenType(hex);
|
|
57
|
+
const state = await w.wallet.waitForSyncedState();
|
|
58
|
+
return state.shielded.availableCoins
|
|
59
|
+
.filter((c) => c.coin.type === hex)
|
|
60
|
+
.map((c) => ({ nonce: fromHex(c.coin.nonce), color: bytes, value: c.coin.value }));
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The argument for a circuit that `receiveShielded`s a coin: a new coin of
|
|
64
|
+
* `value` with a uniformly random nonce (the ledger's `createShieldedCoinInfo`).
|
|
65
|
+
* The wallet pays for it when it balances the transaction, from whichever
|
|
66
|
+
* coins of `color` it selects, and takes the change back under fresh nonces.
|
|
67
|
+
* So any amount works without making an exact-value coin first, and the nonce
|
|
68
|
+
* is in no commitment but the contract's own.
|
|
69
|
+
*
|
|
70
|
+
* The contract can't tell a fresh nonce from a reused one. If it keys a map by
|
|
71
|
+
* this nonce, it should refuse one already present (a same-nonce coin of a
|
|
72
|
+
* different value would overwrite the entry).
|
|
73
|
+
*/
|
|
74
|
+
export function freshCoin(color, value) {
|
|
75
|
+
return encodeShieldedCoinInfo(createShieldedCoinInfo(colorHex(color), value));
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The Zswap Merkle-tree index of `coin`, a coin that `tx` created for the
|
|
79
|
+
* contract at `contractAddress` (`receiveShielded`), as `mt_index` for
|
|
80
|
+
* spending it later with `sendShielded`.
|
|
81
|
+
*
|
|
82
|
+
* A contract that stores a coin with `insertCoin` gets the index for free. One
|
|
83
|
+
* that keeps the coin off chain (an escrow it holds only a commitment to)
|
|
84
|
+
* leaves its depositor to recover it. A transaction's outputs enter the tree
|
|
85
|
+
* in order from its `zswapStartIndex` (the indexer has it), so the index is
|
|
86
|
+
* that start plus the coin's position among the outputs. The position is found
|
|
87
|
+
* by commitment, because the wallet's change output can come first. A
|
|
88
|
+
* contract-owned output's commitment follows from the coin and the address.
|
|
89
|
+
*/
|
|
90
|
+
export async function contractCoinMtIndex(indexerUri, tx, coin, contractAddress) {
|
|
91
|
+
const expected = ZswapOutput.newContractOwned(decodeShieldedCoinInfo(coin), 0, contractAddress).commitment;
|
|
92
|
+
const position = (tx.tx.guaranteedOffer?.outputs ?? []).findIndex((o) => o.commitment === expected);
|
|
93
|
+
if (position < 0)
|
|
94
|
+
throw new Error(`Transaction ${tx.txId} has no output for that coin to ${contractAddress}`);
|
|
95
|
+
const query = `query ($id: HexEncoded!) { transactions(offset: { identifier: $id }) {
|
|
96
|
+
... on RegularTransaction { zswapStartIndex } } }`;
|
|
97
|
+
const res = await fetch(indexerUri, {
|
|
98
|
+
method: 'POST',
|
|
99
|
+
headers: { 'Content-Type': 'application/json' },
|
|
100
|
+
body: JSON.stringify({ query, variables: { id: tx.txId } }),
|
|
101
|
+
});
|
|
102
|
+
if (!res.ok)
|
|
103
|
+
throw new Error(`Indexer query failed: HTTP ${res.status}`);
|
|
104
|
+
const body = (await res.json());
|
|
105
|
+
if (body.errors?.length)
|
|
106
|
+
throw new Error(`Indexer query failed: ${body.errors[0].message}`);
|
|
107
|
+
const start = body.data?.transactions?.[0]?.zswapStartIndex;
|
|
108
|
+
if (start === undefined)
|
|
109
|
+
throw new Error(`The indexer has no zswap index for tx ${tx.txId}`);
|
|
110
|
+
return BigInt(start + position);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* One spendable coin of `color` from the wallet: one worth exactly `value` if
|
|
114
|
+
* given, else the first.
|
|
115
|
+
*
|
|
116
|
+
* @deprecated Don't pass a wallet coin to a circuit that `receiveShielded`s it.
|
|
117
|
+
* The argument describes a new coin, so use `freshCoin(color, value)`: the
|
|
118
|
+
* wallet pays for it and makes change. Passing this coin instead puts its
|
|
119
|
+
* nonce, which its minter or sender knows, into the contract's coin.
|
|
120
|
+
*/
|
|
121
|
+
export async function takeCoin(w, color, value) {
|
|
122
|
+
const coins = await shieldedCoins(w, color);
|
|
123
|
+
const coin = value === undefined ? coins[0] : coins.find((c) => c.value === value);
|
|
124
|
+
if (!coin) {
|
|
125
|
+
const want = value === undefined ? 'coin' : `${value}-value coin`;
|
|
126
|
+
throw new Error(`No ${want} of color ${colorHex(color).slice(0, 16)}… in the wallet; ` +
|
|
127
|
+
`saw values [${coins.map((c) => c.value).join(', ')}]. ` +
|
|
128
|
+
'Has the mint or transfer that pays it been synced? See waitForShieldedBalance.');
|
|
129
|
+
}
|
|
130
|
+
return coin;
|
|
131
|
+
}
|
|
132
|
+
/** The wallet's spendable balance of `color` (0n if it holds none). */
|
|
133
|
+
export async function shieldedBalance(w, color) {
|
|
134
|
+
const state = await w.wallet.waitForSyncedState();
|
|
135
|
+
return state.shielded.balances[colorHex(color)] ?? 0n;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Polls until the balance of `color` equals `until` (or `until(balance)` is
|
|
139
|
+
* true), and returns it. A submitted transaction is accepted before it is on
|
|
140
|
+
* chain and indexed, so a coin minted or sent to a wallet shows up some
|
|
141
|
+
* seconds later: wait for it before the next call that pays from it.
|
|
142
|
+
*/
|
|
143
|
+
export async function waitForShieldedBalance(w, color, until, opts = {}) {
|
|
144
|
+
const done = typeof until === 'bigint' ? (b) => b === until : until;
|
|
145
|
+
const { timeoutMs = 300_000, pollMs = 2_000, logger } = opts;
|
|
146
|
+
const deadline = Date.now() + timeoutMs;
|
|
147
|
+
for (;;) {
|
|
148
|
+
const balance = await shieldedBalance(w, color);
|
|
149
|
+
if (done(balance))
|
|
150
|
+
return balance;
|
|
151
|
+
if (Date.now() >= deadline) {
|
|
152
|
+
throw new Error(`Balance of ${colorHex(color).slice(0, 16)}… is ${balance}` +
|
|
153
|
+
(typeof until === 'bigint' ? `, not ${until},` : '') +
|
|
154
|
+
` after ${Math.round(timeoutMs / 1000)}s`);
|
|
155
|
+
}
|
|
156
|
+
logger?.info(`Waiting for balance of ${colorHex(color).slice(0, 16)}… (now ${balance})`);
|
|
157
|
+
await new Promise((resolve) => setTimeout(resolve, pollMs));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* The wallet as a mint or send recipient: the `ZswapCoinPublicKey` argument
|
|
162
|
+
* ({ bytes }) of a circuit like `mint(recipient, amount, nonce)`.
|
|
163
|
+
*/
|
|
164
|
+
export function recipientOf(w) {
|
|
165
|
+
return { bytes: encodeCoinPublicKey(w.getCoinPublicKey()) };
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* `additionalCoinEncPublicKeyMappings` for a call that creates coins for
|
|
169
|
+
* other wallets. The caller's wallet builds the output coin and must encrypt
|
|
170
|
+
* it to the recipient, so it needs each recipient's encryption key, keyed by
|
|
171
|
+
* coin public key. Without it the coin is made but the recipient's wallet
|
|
172
|
+
* never sees it.
|
|
173
|
+
*/
|
|
174
|
+
export function encryptionKeys(...recipients) {
|
|
175
|
+
return new Map(recipients.map((w) => [w.getCoinPublicKey(), w.getEncryptionPublicKey()]));
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* A fresh random nonce for a mint. The circuit can't make one: uniqueness is
|
|
179
|
+
* the caller's job (MIP-0011), and the nonce stays secret between minter and
|
|
180
|
+
* recipient, which is what keeps the recipient unlinkable to outsiders.
|
|
181
|
+
*/
|
|
182
|
+
export function mintNonce() {
|
|
183
|
+
return new Uint8Array(randomBytes(32));
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* A made-up coin for an in-memory (Sim) test. Sim doesn't check that a coin
|
|
187
|
+
* exists or is paid for, so any nonce does; a random one by default. On the
|
|
188
|
+
* devnet use `freshCoin`.
|
|
189
|
+
*/
|
|
190
|
+
export function simCoin(value, color, nonce = mintNonce()) {
|
|
191
|
+
return { nonce, color, value };
|
|
192
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { contractCoinMtIndex, domainSeparator, encryptionKeys, freshCoin, mintNonce, recipientOf, shieldedBalance, shieldedCoins, simCoin, takeCoin, tokenColor, waitForShieldedBalance, type CoinWallet, type ShieldedCoinArg, type ShieldedStateView, type TokenColor, type TxWithOutputs, } from './coins.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// Shielded-coin helpers for the examples' tests: token colors, fresh coins as
|
|
2
|
+
// circuit arguments, a wallet's coins and balances and waiting for them, the
|
|
3
|
+
// arguments a mint to another wallet needs, and the tree index of a coin a
|
|
4
|
+
// contract received. See src/coins.ts.
|
|
5
|
+
export { contractCoinMtIndex, domainSeparator, encryptionKeys, freshCoin, mintNonce, recipientOf, shieldedBalance, shieldedCoins, simCoin, takeCoin, tokenColor, waitForShieldedBalance, } from './coins.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@midnightntwrk/mnkit-coins",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0-rc.2",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Shielded-coin helpers for Midnight tests: token colors, fresh coins as circuit arguments, a wallet's coins and balances and waiting for them, and the arguments a mint to another wallet needs. Part of mnkit.",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/midnightntwrk/midnight-examples.git",
|
|
10
|
+
"directory": "packages/coins"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/midnightntwrk/midnight-examples/tree/main/packages/coins#readme",
|
|
13
|
+
"bugs": "https://github.com/midnightntwrk/midnight-examples/issues",
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=22.0.0"
|
|
16
|
+
},
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"default": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsc -p tsconfig.build.json",
|
|
30
|
+
"prepack": "tsc -p tsconfig.build.json && node ../../scripts/pack-extras.mjs add LICENSE",
|
|
31
|
+
"postpack": "node ../../scripts/pack-extras.mjs remove LICENSE",
|
|
32
|
+
"typecheck": "tsc --noEmit -p .",
|
|
33
|
+
"test:sim": "vitest run"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@midnight-ntwrk/midnight-js-protocol": "~5.0.1"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@midnight-ntwrk/midnight-js-protocol": "5.0.1",
|
|
40
|
+
"@types/node": "^22.0.0",
|
|
41
|
+
"typescript": "^5.7.0",
|
|
42
|
+
"vite": "6.4.5",
|
|
43
|
+
"vitest": "^5.0.4"
|
|
44
|
+
}
|
|
45
|
+
}
|