@geeqdev/geeq-sdk 0.1.1 → 0.2.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.
Files changed (272) hide show
  1. package/dist/src/address/record-type.d.ts +10 -0
  2. package/dist/src/address/record-type.js +59 -0
  3. package/dist/src/address/record-type.js.map +1 -0
  4. package/dist/src/address/wallet-address.d.ts +34 -0
  5. package/dist/src/address/wallet-address.js +90 -0
  6. package/dist/src/address/wallet-address.js.map +1 -0
  7. package/dist/src/amount.d.ts +43 -0
  8. package/dist/src/amount.js +105 -0
  9. package/dist/src/amount.js.map +1 -0
  10. package/dist/src/assert.d.ts +12 -0
  11. package/dist/src/assert.js +24 -0
  12. package/dist/src/assert.js.map +1 -0
  13. package/dist/src/capnp/adminNetTx.capnp.d.ts +75 -0
  14. package/dist/src/capnp/adminNetTx.capnp.js +66 -0
  15. package/dist/src/capnp/adminNetTx.capnp.js.map +1 -0
  16. package/dist/src/capnp/appLayBlock.capnp.d.ts +26 -0
  17. package/dist/src/capnp/appLayBlock.capnp.js +24 -0
  18. package/dist/src/capnp/appLayBlock.capnp.js.map +1 -0
  19. package/dist/src/capnp/appLayLedger.capnp.d.ts +34 -0
  20. package/dist/src/capnp/appLayLedger.capnp.js +32 -0
  21. package/dist/src/capnp/appLayLedger.capnp.js.map +1 -0
  22. package/dist/src/capnp/appLayRec.capnp.d.ts +129 -0
  23. package/dist/src/capnp/appLayRec.capnp.js +156 -0
  24. package/dist/src/capnp/appLayRec.capnp.js.map +1 -0
  25. package/dist/src/capnp/chainStateView.capnp.d.ts +50 -0
  26. package/dist/src/capnp/chainStateView.capnp.js +48 -0
  27. package/dist/src/capnp/chainStateView.capnp.js.map +1 -0
  28. package/dist/src/capnp/coinAcctRec.capnp.d.ts +178 -0
  29. package/dist/src/capnp/coinAcctRec.capnp.js +189 -0
  30. package/dist/src/capnp/coinAcctRec.capnp.js.map +1 -0
  31. package/dist/src/capnp/genesisBlock.capnp.d.ts +61 -0
  32. package/dist/src/capnp/genesisBlock.capnp.js +55 -0
  33. package/dist/src/capnp/genesisBlock.capnp.js.map +1 -0
  34. package/dist/src/capnp/hubContentStmt.capnp.d.ts +63 -0
  35. package/dist/src/capnp/hubContentStmt.capnp.js +57 -0
  36. package/dist/src/capnp/hubContentStmt.capnp.js.map +1 -0
  37. package/dist/src/capnp/misc.capnp.d.ts +20 -0
  38. package/dist/src/capnp/misc.capnp.js +18 -0
  39. package/dist/src/capnp/misc.capnp.js.map +1 -0
  40. package/dist/src/capnp/netActorRec.capnp.d.ts +65 -0
  41. package/dist/src/capnp/netActorRec.capnp.js +65 -0
  42. package/dist/src/capnp/netActorRec.capnp.js.map +1 -0
  43. package/dist/src/capnp/nodeContentStmt.capnp.d.ts +67 -0
  44. package/dist/src/capnp/nodeContentStmt.capnp.js +61 -0
  45. package/dist/src/capnp/nodeContentStmt.capnp.js.map +1 -0
  46. package/dist/src/capnp/nodePayloadList.capnp.d.ts +28 -0
  47. package/dist/src/capnp/nodePayloadList.capnp.js +26 -0
  48. package/dist/src/capnp/nodePayloadList.capnp.js.map +1 -0
  49. package/dist/src/capnp/nodeTxList.capnp.d.ts +36 -0
  50. package/dist/src/capnp/nodeTxList.capnp.js +34 -0
  51. package/dist/src/capnp/nodeTxList.capnp.js.map +1 -0
  52. package/dist/src/capnp/paramAcctRec.capnp.d.ts +338 -0
  53. package/dist/src/capnp/paramAcctRec.capnp.js +669 -0
  54. package/dist/src/capnp/paramAcctRec.capnp.js.map +1 -0
  55. package/dist/src/capnp/payload.capnp.d.ts +237 -0
  56. package/dist/src/capnp/payload.capnp.js +260 -0
  57. package/dist/src/capnp/payload.capnp.js.map +1 -0
  58. package/dist/src/capnp/proxyAcctRec.capnp.d.ts +223 -0
  59. package/dist/src/capnp/proxyAcctRec.capnp.js +255 -0
  60. package/dist/src/capnp/proxyAcctRec.capnp.js.map +1 -0
  61. package/dist/src/capnp/relayContentStmt.capnp.d.ts +82 -0
  62. package/dist/src/capnp/relayContentStmt.capnp.js +85 -0
  63. package/dist/src/capnp/relayContentStmt.capnp.js.map +1 -0
  64. package/dist/src/capnp/sysAcctRec.capnp.d.ts +48 -0
  65. package/dist/src/capnp/sysAcctRec.capnp.js +46 -0
  66. package/dist/src/capnp/sysAcctRec.capnp.js.map +1 -0
  67. package/dist/src/capnp/userAppTx.capnp.d.ts +230 -0
  68. package/dist/src/capnp/userAppTx.capnp.js +270 -0
  69. package/dist/src/capnp/userAppTx.capnp.js.map +1 -0
  70. package/dist/src/capnp/userValTx.capnp.d.ts +1575 -0
  71. package/dist/src/capnp/userValTx.capnp.js +2004 -0
  72. package/dist/src/capnp/userValTx.capnp.js.map +1 -0
  73. package/dist/src/capnp/valLayBlock.capnp.d.ts +88 -0
  74. package/dist/src/capnp/valLayBlock.capnp.js +86 -0
  75. package/dist/src/capnp/valLayBlock.capnp.js.map +1 -0
  76. package/dist/src/capnp/valLayLedger.capnp.d.ts +85 -0
  77. package/dist/src/capnp/valLayLedger.capnp.js +75 -0
  78. package/dist/src/capnp/valLayLedger.capnp.js.map +1 -0
  79. package/dist/src/chain/geeq-chain.d.ts +474 -0
  80. package/dist/src/chain/geeq-chain.js +721 -0
  81. package/dist/src/chain/geeq-chain.js.map +1 -0
  82. package/dist/src/chain/geeq-node.d.ts +57 -0
  83. package/dist/src/chain/geeq-node.js +62 -0
  84. package/dist/src/chain/geeq-node.js.map +1 -0
  85. package/dist/src/chain/nonce-guard.d.ts +42 -0
  86. package/dist/src/chain/nonce-guard.js +68 -0
  87. package/dist/src/chain/nonce-guard.js.map +1 -0
  88. package/dist/src/chain/select.d.ts +40 -0
  89. package/dist/src/chain/select.js +114 -0
  90. package/dist/src/chain/select.js.map +1 -0
  91. package/dist/src/crypto/account-id.d.ts +35 -0
  92. package/dist/src/crypto/account-id.js +58 -0
  93. package/dist/src/crypto/account-id.js.map +1 -0
  94. package/dist/src/crypto/keypair.d.ts +24 -0
  95. package/dist/src/crypto/keypair.js +158 -0
  96. package/dist/src/crypto/keypair.js.map +1 -0
  97. package/dist/src/crypto/mnemonic.d.ts +34 -0
  98. package/dist/src/crypto/mnemonic.js +57 -0
  99. package/dist/src/crypto/mnemonic.js.map +1 -0
  100. package/dist/src/encoding/base64.d.ts +8 -0
  101. package/dist/src/encoding/base64.js +53 -0
  102. package/dist/src/encoding/base64.js.map +1 -0
  103. package/dist/src/encoding/hex.d.ts +2 -0
  104. package/dist/src/encoding/hex.js +35 -0
  105. package/dist/src/encoding/hex.js.map +1 -0
  106. package/dist/src/errors.d.ts +83 -0
  107. package/dist/src/errors.js +49 -0
  108. package/dist/src/errors.js.map +1 -0
  109. package/dist/src/index.d.ts +59 -0
  110. package/dist/src/index.js +53 -0
  111. package/dist/src/index.js.map +1 -0
  112. package/dist/src/ledger/coin-accounts.d.ts +42 -0
  113. package/dist/src/ledger/coin-accounts.js +37 -0
  114. package/dist/src/ledger/coin-accounts.js.map +1 -0
  115. package/dist/src/ledger/decode.d.ts +18 -0
  116. package/dist/src/ledger/decode.js +113 -0
  117. package/dist/src/ledger/decode.js.map +1 -0
  118. package/dist/src/ledger/geeq-ledger.d.ts +99 -0
  119. package/dist/src/ledger/geeq-ledger.js +125 -0
  120. package/dist/src/ledger/geeq-ledger.js.map +1 -0
  121. package/dist/src/ledger/net-actors.d.ts +65 -0
  122. package/dist/src/ledger/net-actors.js +53 -0
  123. package/dist/src/ledger/net-actors.js.map +1 -0
  124. package/dist/src/ledger/nft-records.d.ts +13 -0
  125. package/dist/src/ledger/nft-records.js +41 -0
  126. package/dist/src/ledger/nft-records.js.map +1 -0
  127. package/dist/src/ledger/params.d.ts +34 -0
  128. package/dist/src/ledger/params.js +71 -0
  129. package/dist/src/ledger/params.js.map +1 -0
  130. package/dist/src/ledger/proxy-accounts.d.ts +26 -0
  131. package/dist/src/ledger/proxy-accounts.js +27 -0
  132. package/dist/src/ledger/proxy-accounts.js.map +1 -0
  133. package/dist/src/net/discovery.d.ts +62 -0
  134. package/dist/src/net/discovery.js +136 -0
  135. package/dist/src/net/discovery.js.map +1 -0
  136. package/dist/src/net/explorer.d.ts +57 -0
  137. package/dist/src/net/explorer.js +64 -0
  138. package/dist/src/net/explorer.js.map +1 -0
  139. package/dist/src/net/read-ledger.d.ts +7 -0
  140. package/dist/src/net/read-ledger.js +39 -0
  141. package/dist/src/net/read-ledger.js.map +1 -0
  142. package/dist/src/net/routes.d.ts +49 -0
  143. package/dist/src/net/routes.js +70 -0
  144. package/dist/src/net/routes.js.map +1 -0
  145. package/dist/src/net/transport.d.ts +55 -0
  146. package/dist/src/net/transport.js +168 -0
  147. package/dist/src/net/transport.js.map +1 -0
  148. package/dist/src/net/websocket.d.ts +49 -0
  149. package/dist/src/net/websocket.js +54 -0
  150. package/dist/src/net/websocket.js.map +1 -0
  151. package/dist/src/runtime/bindings.d.ts +9 -0
  152. package/dist/src/runtime/bindings.js +27 -0
  153. package/dist/src/runtime/bindings.js.map +1 -0
  154. package/dist/src/runtime/init.d.ts +13 -0
  155. package/dist/src/runtime/init.js +40 -0
  156. package/dist/src/runtime/init.js.map +1 -0
  157. package/dist/src/runtime/wasm-loader.browser.d.ts +14 -0
  158. package/dist/src/runtime/wasm-loader.browser.js +20 -0
  159. package/dist/src/runtime/wasm-loader.browser.js.map +1 -0
  160. package/dist/src/runtime/wasm-loader.node.d.ts +7 -0
  161. package/dist/src/runtime/wasm-loader.node.js +14 -0
  162. package/dist/src/runtime/wasm-loader.node.js.map +1 -0
  163. package/dist/src/socket/geeq-socket.d.ts +232 -0
  164. package/dist/src/socket/geeq-socket.js +634 -0
  165. package/dist/src/socket/geeq-socket.js.map +1 -0
  166. package/dist/src/socket/tracked-tx.d.ts +148 -0
  167. package/dist/src/socket/tracked-tx.js +212 -0
  168. package/dist/src/socket/tracked-tx.js.map +1 -0
  169. package/dist/src/socket/tx-status.d.ts +69 -0
  170. package/dist/src/socket/tx-status.js +72 -0
  171. package/dist/src/socket/tx-status.js.map +1 -0
  172. package/dist/src/tx/attestation.d.ts +60 -0
  173. package/dist/src/tx/attestation.js +163 -0
  174. package/dist/src/tx/attestation.js.map +1 -0
  175. package/dist/src/tx/content.d.ts +27 -0
  176. package/dist/src/tx/content.js +62 -0
  177. package/dist/src/tx/content.js.map +1 -0
  178. package/dist/src/tx/encode.d.ts +60 -0
  179. package/dist/src/tx/encode.js +82 -0
  180. package/dist/src/tx/encode.js.map +1 -0
  181. package/dist/src/tx/expiry.d.ts +11 -0
  182. package/dist/src/tx/expiry.js +12 -0
  183. package/dist/src/tx/expiry.js.map +1 -0
  184. package/dist/src/tx/fee.d.ts +16 -0
  185. package/dist/src/tx/fee.js +29 -0
  186. package/dist/src/tx/fee.js.map +1 -0
  187. package/dist/src/tx/metadata.d.ts +39 -0
  188. package/dist/src/tx/metadata.js +66 -0
  189. package/dist/src/tx/metadata.js.map +1 -0
  190. package/dist/src/tx/nft.d.ts +16 -0
  191. package/dist/src/tx/nft.js +98 -0
  192. package/dist/src/tx/nft.js.map +1 -0
  193. package/dist/src/tx/proxy.d.ts +37 -0
  194. package/dist/src/tx/proxy.js +134 -0
  195. package/dist/src/tx/proxy.js.map +1 -0
  196. package/dist/src/tx/transfer.d.ts +31 -0
  197. package/dist/src/tx/transfer.js +123 -0
  198. package/dist/src/tx/transfer.js.map +1 -0
  199. package/dist/src/types.d.ts +448 -0
  200. package/dist/src/types.js +2 -0
  201. package/dist/src/types.js.map +1 -0
  202. package/dist/tests/account-id.test.d.ts +1 -0
  203. package/dist/tests/account-id.test.js +27 -0
  204. package/dist/tests/account-id.test.js.map +1 -0
  205. package/dist/tests/amount.test.d.ts +1 -0
  206. package/dist/tests/amount.test.js +113 -0
  207. package/dist/tests/amount.test.js.map +1 -0
  208. package/dist/tests/attestation.test.d.ts +1 -0
  209. package/dist/tests/attestation.test.js +182 -0
  210. package/dist/tests/attestation.test.js.map +1 -0
  211. package/dist/tests/chain.test.d.ts +1 -0
  212. package/dist/tests/chain.test.js +647 -0
  213. package/dist/tests/chain.test.js.map +1 -0
  214. package/dist/tests/content.test.d.ts +1 -0
  215. package/dist/tests/content.test.js +90 -0
  216. package/dist/tests/content.test.js.map +1 -0
  217. package/dist/tests/documented-api.test.d.ts +1 -0
  218. package/dist/tests/documented-api.test.js +229 -0
  219. package/dist/tests/documented-api.test.js.map +1 -0
  220. package/dist/tests/explorer.test.d.ts +1 -0
  221. package/dist/tests/explorer.test.js +95 -0
  222. package/dist/tests/explorer.test.js.map +1 -0
  223. package/dist/tests/fee.test.d.ts +1 -0
  224. package/dist/tests/fee.test.js +179 -0
  225. package/dist/tests/fee.test.js.map +1 -0
  226. package/dist/tests/fixtures/build-vll.d.ts +71 -0
  227. package/dist/tests/fixtures/build-vll.js +141 -0
  228. package/dist/tests/fixtures/build-vll.js.map +1 -0
  229. package/dist/tests/fixtures/fake-socket.d.ts +44 -0
  230. package/dist/tests/fixtures/fake-socket.js +93 -0
  231. package/dist/tests/fixtures/fake-socket.js.map +1 -0
  232. package/dist/tests/fixtures/fake-transport.d.ts +24 -0
  233. package/dist/tests/fixtures/fake-transport.js +30 -0
  234. package/dist/tests/fixtures/fake-transport.js.map +1 -0
  235. package/dist/tests/keypair.test.d.ts +1 -0
  236. package/dist/tests/keypair.test.js +163 -0
  237. package/dist/tests/keypair.test.js.map +1 -0
  238. package/dist/tests/ledger.test.d.ts +1 -0
  239. package/dist/tests/ledger.test.js +234 -0
  240. package/dist/tests/ledger.test.js.map +1 -0
  241. package/dist/tests/mnemonic.test.d.ts +1 -0
  242. package/dist/tests/mnemonic.test.js +97 -0
  243. package/dist/tests/mnemonic.test.js.map +1 -0
  244. package/dist/tests/nft-transfer.test.d.ts +1 -0
  245. package/dist/tests/nft-transfer.test.js +170 -0
  246. package/dist/tests/nft-transfer.test.js.map +1 -0
  247. package/dist/tests/nft.test.d.ts +1 -0
  248. package/dist/tests/nft.test.js +180 -0
  249. package/dist/tests/nft.test.js.map +1 -0
  250. package/dist/tests/offline.test.d.ts +1 -0
  251. package/dist/tests/offline.test.js +95 -0
  252. package/dist/tests/offline.test.js.map +1 -0
  253. package/dist/tests/proxy.test.d.ts +1 -0
  254. package/dist/tests/proxy.test.js +183 -0
  255. package/dist/tests/proxy.test.js.map +1 -0
  256. package/dist/tests/select.test.d.ts +1 -0
  257. package/dist/tests/select.test.js +200 -0
  258. package/dist/tests/select.test.js.map +1 -0
  259. package/dist/tests/socket.test.d.ts +1 -0
  260. package/dist/tests/socket.test.js +607 -0
  261. package/dist/tests/socket.test.js.map +1 -0
  262. package/dist/tests/transfer.test.d.ts +1 -0
  263. package/dist/tests/transfer.test.js +225 -0
  264. package/dist/tests/transfer.test.js.map +1 -0
  265. package/dist/tests/wallet-address.test.d.ts +1 -0
  266. package/dist/tests/wallet-address.test.js +101 -0
  267. package/dist/tests/wallet-address.test.js.map +1 -0
  268. package/dist/tests/wasm-loader.jest.d.ts +13 -0
  269. package/dist/tests/wasm-loader.jest.js +15 -0
  270. package/dist/tests/wasm-loader.jest.js.map +1 -0
  271. package/package.json +2 -2
  272. package/tsconfig.json +2 -1
@@ -0,0 +1,721 @@
1
+ import { assertDuration, assertUint32 } from '../assert';
2
+ import { resolveAccountId } from '../crypto/account-id';
3
+ import { toBase64 } from '../encoding/base64';
4
+ import { accountNotAttestable, accountNotFound, amountBelowMinimum, chainMismatch, insufficientFunds, invalidArgument, nftNotOwned, noChain, } from '../errors';
5
+ import { decimalsOf, formatGeeq, toPennies } from '../amount';
6
+ import { decodeWalletAddressSync } from '../address/wallet-address';
7
+ import { createCoinTransferTxSync } from '../tx/transfer';
8
+ import { createNftMintProxyTxSync, nftMintProxiesIn, nftMintProxyId } from '../tx/proxy';
9
+ import { createNftMintTxSync } from '../tx/nft';
10
+ import { discover } from '../net/discovery';
11
+ import { readLedger, readNftRecords } from '../net/read-ledger';
12
+ import { defaultTransport, raceAbort } from '../net/transport';
13
+ import { initGeeq } from '../runtime/init';
14
+ import { createAttestationTxSync } from '../tx/attestation';
15
+ import { ATTEST_HASH_BYTES, attestHashOf } from '../tx/content';
16
+ import { GeeqNode } from './geeq-node';
17
+ import { NonceGuard } from './nonce-guard';
18
+ import { GEEQ_NODE_PORT, originOf, selectNode, serviceOriginOf } from './select';
19
+ const DEFAULT_TIMEOUT_MS = 10_000;
20
+ const DEFAULT_LEDGER_MAX_AGE_MS = 5_000;
21
+ const DEFAULT_RETRIES = 1;
22
+ /** The process-wide default, installed by {@link GeeqChain.init}. */
23
+ let defaultChain = null;
24
+ /**
25
+ * Refuse a nonsense option before anything is read. Left to the network layer, a negative
26
+ * `retries` sends no request at all and a zero `timeoutMs` times every request out — both
27
+ * reported as an unreachable node, which is the one thing they are not.
28
+ */
29
+ function assertChainOptions(options) {
30
+ assertDuration(options.timeoutMs, 'timeoutMs');
31
+ if (options.timeoutMs === 0) {
32
+ throw invalidArgument('timeoutMs must be more than 0, or every request times out at once.');
33
+ }
34
+ assertDuration(options.ledgerMaxAgeMs, 'ledgerMaxAgeMs');
35
+ const { retries, nodePort } = options;
36
+ if (retries !== undefined && (!Number.isInteger(retries) || retries < 0)) {
37
+ throw invalidArgument(`retries must be a whole number, 0 or more, received ${String(retries)}.`);
38
+ }
39
+ if (nodePort !== undefined && (!Number.isInteger(nodePort) || nodePort < 1 || nodePort > 65_535)) {
40
+ throw invalidArgument(`nodePort must be a port from 1 to 65535, received ${JSON.stringify(nodePort)}.`);
41
+ }
42
+ if (options.chainNumber !== undefined)
43
+ assertUint32(options.chainNumber, 'chainNumber');
44
+ if (options.nodeNumber !== undefined)
45
+ assertUint32(options.nodeNumber, 'nodeNumber');
46
+ }
47
+ /**
48
+ * Refuse a transaction its payer cannot cover. The node checks the balance against the
49
+ * amount plus the fee, so this does too — after building, because the fee is charged on
50
+ * the signed bytes.
51
+ */
52
+ function assertAffordable(penniesPerGeeq, payer, balance, amount, fee, block) {
53
+ const cost = amount + (fee?.total ?? 0n);
54
+ if (balance >= cost)
55
+ return;
56
+ const geeq = (pennies) => formatGeeq(pennies, penniesPerGeeq);
57
+ const needed = fee === undefined
58
+ ? geeq(amount)
59
+ : amount === 0n
60
+ ? `a fee of ${geeq(fee.total)}`
61
+ : `${geeq(amount)} plus a fee of ${geeq(fee.total)}`;
62
+ throw insufficientFunds(`${payer} holds ${geeq(balance)} geeq at block ${block}, and this needs ${needed} geeq.`);
63
+ }
64
+ /**
65
+ * A chain, reached through one node.
66
+ *
67
+ * Holds the node directory, the metadata limits and a short-lived ledger cache, so an
68
+ * attestation needs only a keypair and something to attest. Everything a transaction is
69
+ * pinned to — chain number, target block, node number, nonce — is read from the ledger
70
+ * rather than asked of the caller, because none of it can be known offline and a wrong
71
+ * value is rejected by the chain.
72
+ *
73
+ * A chain is bound to the endpoint it was connected to. To use a different node, connect
74
+ * another one: a different node means a different address, certificate and CORS origin,
75
+ * which is not something to switch silently.
76
+ *
77
+ * In a reactive framework, mark an instance raw (Vue's `markRaw`) rather than letting it
78
+ * be proxied.
79
+ */
80
+ export class GeeqChain {
81
+ /** @internal */
82
+ constructor(init) {
83
+ this.endpoint = init.endpoint;
84
+ this.candidates = Object.freeze([...init.candidates]);
85
+ this.chainName = init.chainName;
86
+ this.penniesPerGeeq = init.penniesPerGeeq;
87
+ // Non-enumerable and TS-private, never `#private` — see GeeqNode for why.
88
+ const hidden = (key, value, writable = false) => {
89
+ Object.defineProperty(this, key, { value, enumerable: false, writable });
90
+ };
91
+ hidden('request', init.request);
92
+ hidden('ledgerMaxAgeMs', init.ledgerMaxAgeMs);
93
+ hidden('declaredChainNumber', init.chainNumber);
94
+ hidden('nodeNumberOverride', init.nodeNumber);
95
+ hidden('nonces', new NonceGuard());
96
+ hidden('cached', null, true);
97
+ hidden('resolved', null, true);
98
+ hidden('inflight', null, true);
99
+ }
100
+ /**
101
+ * Choose a chain and a node, without reading anything from the chain itself.
102
+ *
103
+ * With `discovery`, the directory is asked which nodes exist and one of the active
104
+ * ones is taken. With `endpoint`, that node is used as given. Either way **no ledger
105
+ * is fetched here** — a ledger read is only valid for a few blocks, so it happens when
106
+ * a transaction is actually being built rather than when the app starts.
107
+ */
108
+ static async connect(options) {
109
+ const hasDiscovery = options.discovery !== undefined;
110
+ const hasEndpoint = options.endpoint !== undefined;
111
+ if (hasDiscovery === hasEndpoint) {
112
+ throw invalidArgument('Provide exactly one of discovery (a node directory to pick an active node ' +
113
+ 'from) or endpoint (a node you already know).');
114
+ }
115
+ decimalsOf(options.penniesPerGeeq);
116
+ assertChainOptions(options);
117
+ const request = Object.freeze({
118
+ transport: options.transport ?? defaultTransport,
119
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
120
+ retries: options.retries ?? DEFAULT_RETRIES,
121
+ headers: options.headers,
122
+ });
123
+ let endpoint;
124
+ let candidates = [];
125
+ let chainName = options.chainName;
126
+ let chainNumber = options.chainNumber;
127
+ if (hasDiscovery) {
128
+ const found = await discover({
129
+ origin: serviceOriginOf(options.discovery),
130
+ ...(options.chainName === undefined ? {} : { chainName: options.chainName }),
131
+ chainNumber: options.chainNumber,
132
+ ...(options.nodePort === undefined ? {} : { port: options.nodePort }),
133
+ request: {
134
+ ...request,
135
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
136
+ },
137
+ });
138
+ candidates = found.nodes;
139
+ chainName = found.chain.name;
140
+ chainNumber = found.chain.chainNumber;
141
+ // Spread across the usable nodes rather than everyone hammering the first one.
142
+ // The directory's order is stable, so picking [0] would concentrate every client
143
+ // of every app on one machine.
144
+ endpoint = found.usable[Math.floor(Math.random() * found.usable.length)].url;
145
+ }
146
+ else {
147
+ endpoint = originOf(options.endpoint);
148
+ }
149
+ return new GeeqChain({
150
+ endpoint,
151
+ candidates,
152
+ chainName,
153
+ chainNumber,
154
+ nodeNumber: options.nodeNumber,
155
+ penniesPerGeeq: options.penniesPerGeeq,
156
+ request,
157
+ ledgerMaxAgeMs: options.ledgerMaxAgeMs ?? DEFAULT_LEDGER_MAX_AGE_MS,
158
+ });
159
+ }
160
+ /** {@link GeeqChain.connect}, and install the result as the process-wide default. */
161
+ static async init(options) {
162
+ const chain = await GeeqChain.connect(options);
163
+ defaultChain = chain;
164
+ return chain;
165
+ }
166
+ /** The default chain. Throws `not-initialized` when there is none. */
167
+ static current() {
168
+ if (defaultChain === null)
169
+ throw noChain('GeeqChain.current()');
170
+ return defaultChain;
171
+ }
172
+ /** Whether a default chain has been installed. */
173
+ static get initialized() {
174
+ return defaultChain !== null;
175
+ }
176
+ /** Clear the default. Call this from `afterEach` so tests do not leak into each other. */
177
+ static reset() {
178
+ defaultChain = null;
179
+ }
180
+ /** Resolve an amount to pennies, reading a `{ geeq }` figure at {@link penniesPerGeeq}. */
181
+ toPennies(amount) {
182
+ return toPennies(amount, this.penniesPerGeeq);
183
+ }
184
+ /** Show pennies as a Geeq figure at {@link penniesPerGeeq}, as the Geeq wallet does. */
185
+ formatGeeq(pennies) {
186
+ return formatGeeq(pennies, this.penniesPerGeeq);
187
+ }
188
+ /**
189
+ * This chain's number.
190
+ *
191
+ * Known immediately when a directory named the chain, or once a ledger has been read.
192
+ * `undefined` in between — with a bare endpoint and no declared number, only the node
193
+ * can say.
194
+ */
195
+ get chainNumber() {
196
+ return this.cached?.chainNumber ?? this.declaredChainNumber;
197
+ }
198
+ /**
199
+ * The node, once a ledger read has identified it in the net actor list.
200
+ *
201
+ * `undefined` until then: a node's number is the one thing the directory cannot say,
202
+ * so it is not known before the first read.
203
+ */
204
+ get node() {
205
+ return this.resolved ?? undefined;
206
+ }
207
+ /** The net actor directory from the last ledger read, if there has been one. */
208
+ get nodes() {
209
+ return this.cached?.nodes ?? [];
210
+ }
211
+ /** Those of them that accept transactions. */
212
+ get processingNodes() {
213
+ return this.cached?.processingNodes ?? [];
214
+ }
215
+ /** The ledger from the last read, if it is still cached. */
216
+ get ledger() {
217
+ return this.cached ?? undefined;
218
+ }
219
+ /**
220
+ * A URL for another node in this chain.
221
+ *
222
+ * Every node answers client traffic on {@link GEEQ_NODE_PORT}, so only the scheme is
223
+ * carried over from the endpoint in use. The port recorded against a node in the
224
+ * ledger is its own internal listener and is never what you connect to.
225
+ */
226
+ endpointFor(host) {
227
+ return `${new URL(this.endpoint).protocol}//${host}:${GEEQ_NODE_PORT}`;
228
+ }
229
+ /**
230
+ * The current ledger, from cache when it is fresh enough.
231
+ *
232
+ * Staleness is safe in exactly one direction. The node accepts a target block within
233
+ * `[N-8, N+1]` of its own head, and a cached ledger can only be *behind*, so the
234
+ * target it yields is never in the future — the only rejected direction. The default
235
+ * five seconds is set by the node list and metadata limits, which have no such
236
+ * tolerance, not by the block window.
237
+ */
238
+ async getLedger(options = {}) {
239
+ const maxAge = options.maxAgeMs ?? this.ledgerMaxAgeMs;
240
+ const cached = this.cached;
241
+ if (cached !== null && maxAge > 0 && Date.now() - cached.readAt < maxAge)
242
+ return cached;
243
+ return this.read(options.signal);
244
+ }
245
+ /** Discard the cached ledger and read again. */
246
+ async refresh(options = {}) {
247
+ this.cached = null;
248
+ return this.read(options.signal);
249
+ }
250
+ /**
251
+ * One read at a time.
252
+ *
253
+ * Same single-flight shape as `initGeeq`, including clearing the promise on failure so
254
+ * a later call can retry rather than being stuck with the first error. Without it, a
255
+ * page that builds several transactions at once pulls the whole ledger several times
256
+ * from an endpoint with no rate limiting of any kind.
257
+ *
258
+ * The read is shared, so it carries no caller's signal: one caller aborting must not
259
+ * fail the others waiting on it. Each caller stops waiting on its own signal instead,
260
+ * and the read runs on, bounded by `timeoutMs`, to fill the cache for whoever is next.
261
+ */
262
+ read(signal) {
263
+ if (signal?.aborted === true)
264
+ return Promise.reject(signal.reason);
265
+ if (this.inflight !== null)
266
+ return raceAbort(this.inflight, signal);
267
+ const pending = readLedger(this.endpoint, this.request)
268
+ .then((ledger) => {
269
+ const declared = this.declaredChainNumber;
270
+ if (declared !== undefined && ledger.chainNumber !== declared) {
271
+ throw chainMismatch(`This chain was opened as chain ${declared} but the node at ${this.endpoint} ` +
272
+ `serves chain ${ledger.chainNumber}. A transaction signed for the wrong ` +
273
+ 'chain is rejected, so either drop chainNumber to accept the node\'s, or ' +
274
+ `use a node on chain ${declared}.`);
275
+ }
276
+ // The node's own number lives only in the ledger, so this is the first moment it
277
+ // can be known — and the first moment the node can be checked for being able to
278
+ // take work at all.
279
+ const selected = selectNode(ledger, this.endpoint, {
280
+ ...(this.nodeNumberOverride === undefined ? {} : { nodeNumber: this.nodeNumberOverride }),
281
+ });
282
+ this.resolved = new GeeqNode({ ...this.request, ...selected, url: this.endpoint });
283
+ this.cached = ledger;
284
+ return ledger;
285
+ })
286
+ .finally(() => {
287
+ this.inflight = null;
288
+ });
289
+ this.inflight = pending;
290
+ return raceAbort(pending, signal);
291
+ }
292
+ /**
293
+ * Everything a transaction must be pinned to, read from this chain.
294
+ *
295
+ * Throws rather than guessing when the account cannot sign: absent from the ledger
296
+ * (the ordinary state of an unfunded keypair), or present as a record type the
297
+ * protocol will not accept.
298
+ */
299
+ async getChainState(request) {
300
+ const ledger = await this.getLedger({
301
+ ...(request.maxAgeMs === undefined ? {} : { maxAgeMs: request.maxAgeMs }),
302
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
303
+ });
304
+ return this.stateIn(ledger, request.account);
305
+ }
306
+ /**
307
+ * What every transaction built from `ledger` is pinned to, bar the signer's nonce: the
308
+ * same for a signer's own transaction and for a proxy's.
309
+ */
310
+ pinnedTo(ledger) {
311
+ return {
312
+ chainNumber: ledger.chainNumber,
313
+ blockNumber: ledger.targetBlockNumber,
314
+ nodeNumber: this.resolved.nodeNumber,
315
+ metadataLimits: ledger.metadataLimits,
316
+ geeqNorm: ledger.geeqNorm,
317
+ ledgerBlockNumber: ledger.blockNumber,
318
+ readAt: ledger.readAt,
319
+ nodeUrl: this.endpoint,
320
+ };
321
+ }
322
+ /** {@link getChainState} against a ledger already in hand, so a build reads only one. */
323
+ stateIn(ledger, ref) {
324
+ const accountId = resolveAccountId(ref);
325
+ const account = ledger.findCoinAccount(accountId);
326
+ const shown = toBase64(accountId);
327
+ if (account === undefined) {
328
+ throw accountNotFound(`Account ${shown} is not in the ledger of chain ${ledger.chainNumber} at block ` +
329
+ `${ledger.blockNumber}. An account exists on a Geeq chain only once it has ` +
330
+ 'received coins, so a freshly generated keypair will not be there. Fund it, ' +
331
+ 'then try again.');
332
+ }
333
+ if (account.kind !== 'asset' || account.nonce === undefined) {
334
+ const described = account.kind === 'hl'
335
+ ? 'a hash-lock record, which carries no nonce at all'
336
+ : account.kind === 'micro'
337
+ ? 'a micro-coin record'
338
+ : 'a record whose subtype could not be read';
339
+ throw accountNotAttestable(`Account ${shown} is in the ledger at block ${ledger.blockNumber} as ${described}, ` +
340
+ 'but an attestation must be signed by a coin-asset account. Sign with a ' +
341
+ 'coin-asset key on this chain instead.');
342
+ }
343
+ return Object.freeze({
344
+ ...this.pinnedTo(ledger),
345
+ nonce: account.nonce,
346
+ balance: account.balance,
347
+ minimumTransfer: ledger.minimumTransfer,
348
+ });
349
+ }
350
+ /**
351
+ * The ledger a build is made from, and the state of `signer` in it.
352
+ *
353
+ * A cached ledger is up to a few seconds old, so "this account already built against
354
+ * this block" may only mean "we are looking at an old block". Look again once before
355
+ * letting the nonce guard refuse — otherwise a caller who waited out the block interval
356
+ * is told to wait for a block that has already passed. An explicit nonce is the caller
357
+ * taking responsibility, so it skips the check.
358
+ *
359
+ * Everything the build then needs — what the sender holds, which proxies exist — comes
360
+ * from this same ledger, so it all describes one block.
361
+ */
362
+ async readForBuild(signer, explicitNonce, signal) {
363
+ const options = signal === undefined ? {} : { signal };
364
+ const [cached] = await Promise.all([this.getLedger(options), initGeeq()]);
365
+ const ledger = await this.recheckIfClaimed(cached, explicitNonce === undefined ? toBase64(signer.accountId) : undefined, options);
366
+ const chainState = this.stateIn(ledger, signer);
367
+ return {
368
+ ledger,
369
+ chainState: explicitNonce === undefined ? chainState : { ...chainState, nonce: explicitNonce },
370
+ };
371
+ }
372
+ /** Read afresh if `guardKey` already built against `ledger`'s block. See {@link readForBuild}. */
373
+ async recheckIfClaimed(ledger, guardKey, options) {
374
+ if (guardKey === undefined || !this.nonces.wouldCollide(guardKey, ledger.blockNumber)) {
375
+ return ledger;
376
+ }
377
+ return this.refresh(options);
378
+ }
379
+ /**
380
+ * Build and sign an attestation, deriving everything the chain decides.
381
+ *
382
+ * This is where the ledger is read, because this is the first moment the values it
383
+ * carries are actually needed — and they go stale within a handful of blocks, so
384
+ * reading them any earlier would only mean reading them twice.
385
+ *
386
+ * The result is **not submitted**. Hand it to {@link GeeqSocket.track} first, so its
387
+ * verdict has somewhere to arrive, then POST `transaction` and `payload` to
388
+ * {@link AttestationTx.nodeUrl}; any other node rejects it, because the node number is
389
+ * checked with strict equality.
390
+ */
391
+ async createAttestation(input) {
392
+ if ((input.content === undefined) === (input.attestHash === undefined)) {
393
+ throw invalidArgument('Provide exactly one of content (hashed here with BLAKE3) or attestHash (a ' +
394
+ `${ATTEST_HASH_BYTES}-byte digest you produced yourself).`);
395
+ }
396
+ const attestHash = input.attestHash ?? (await attestHashOf(input.content));
397
+ const { chainState } = await this.readForBuild(input.keypair, input.nonce, input.signal);
398
+ const tx = createAttestationTxSync({
399
+ keypair: input.keypair,
400
+ attestHash,
401
+ ...(input.metadata === undefined ? {} : { metadata: input.metadata }),
402
+ chainState,
403
+ });
404
+ assertAffordable(this.penniesPerGeeq, 'This account', chainState.balance, 0n, tx.fee, chainState.ledgerBlockNumber);
405
+ this.claimNonce(input.keypair, input.nonce, chainState, tx);
406
+ return tx;
407
+ }
408
+ /**
409
+ * Record the nonce a finished build took, so a second build against the same block is
410
+ * refused rather than sent to share it.
411
+ *
412
+ * Claimed only once a transaction really exists, so a build that failed validation does
413
+ * not consume the account's one nonce for this block. An explicit nonce is the caller
414
+ * taking responsibility, so it bypasses the guard entirely.
415
+ */
416
+ claimNonce(signer, explicitNonce, chainState, tx) {
417
+ if (explicitNonce !== undefined)
418
+ return;
419
+ this.nonces.claim(toBase64(signer.accountId), chainState.ledgerBlockNumber, chainState.nonce, toBase64(tx.transactionHash));
420
+ }
421
+ /**
422
+ * Resolve a recipient, checking the chain it belongs to when one is stated.
423
+ *
424
+ * An address carries a chain number, and an address from another chain is almost
425
+ * always a paste from the wrong place. The account id inside it would still be
426
+ * technically usable here, which is exactly why this is worth refusing rather than
427
+ * quietly sending.
428
+ */
429
+ resolveRecipient(to, chainNumber) {
430
+ if (typeof to !== 'string')
431
+ return resolveAccountId(to);
432
+ const decoded = decodeWalletAddressSync(to);
433
+ if (decoded.chainNumber !== chainNumber) {
434
+ throw chainMismatch(`The recipient address is for chain ${decoded.chainNumber} but this is chain ` +
435
+ `${chainNumber}. An address encodes its chain, so this one was almost certainly ` +
436
+ 'copied from somewhere else — check it before sending.');
437
+ }
438
+ return decoded.accountId;
439
+ }
440
+ /**
441
+ * Send coin to another account, and NFTs with it if you name them.
442
+ *
443
+ * Reads the ledger, so it also knows what the sender holds and what the chain's minimum
444
+ * transfer is. The amount is checked against the minimum, and the sender's NFTs against
445
+ * the ones named, before anything is signed; the balance against the amount plus the
446
+ * fee once the signed transaction gives the fee. NFTs always travel with coin: leave
447
+ * `amount` out and they go with the chain's minimum transfer.
448
+ *
449
+ * The result is **not submitted**. Hand it to {@link GeeqSocket.track} first, then POST
450
+ * `transaction` to {@link CoinTransferTx.nodeUrl} using `coinTransferSubmitBody`, which
451
+ * sends it as type `uvt` — a different shape from an attestation, and with no separate
452
+ * payload.
453
+ */
454
+ async createTransfer(input) {
455
+ const nfts = input.nfts ?? [];
456
+ if (input.amount === undefined && nfts.length === 0) {
457
+ throw invalidArgument('Say what to send: an amount, NFTs, or both.');
458
+ }
459
+ const asked = input.amount === undefined ? undefined : this.toPennies(input.amount);
460
+ const { ledger, chainState } = await this.readForBuild(input.from, input.nonce, input.signal);
461
+ const to = this.resolveRecipient(input.to, chainState.chainNumber);
462
+ const minimum = chainState.minimumTransfer;
463
+ const pennies = asked ?? minimum;
464
+ if (pennies === undefined) {
465
+ throw invalidArgument('This chain publishes no minimum transfer to send with the NFTs by default, so pass amount.');
466
+ }
467
+ if (minimum !== undefined && pennies < minimum) {
468
+ throw amountBelowMinimum(`This chain will not accept a transfer below ${this.formatGeeq(minimum)} geeq, and ` +
469
+ `${this.formatGeeq(pennies)} is smaller. The minimum comes from the chain's own ` +
470
+ 'minTxAmt and geeqNorm parameters, read at block ' +
471
+ `${chainState.ledgerBlockNumber}.`);
472
+ }
473
+ // The transaction names each NFT by id and by its place in the sender's list, read
474
+ // from the same ledger as the nonce, so both describe one block.
475
+ const held = ledger.findCoinAccount(input.from)?.nfts ?? [];
476
+ const entries = nfts.map((id) => {
477
+ const position = held.findIndex((nft) => toBase64(nft.id) === toBase64(id));
478
+ if (position === -1) {
479
+ throw nftNotOwned(`This account does not hold NFT ${toBase64(id)} at block ${ledger.blockNumber}. ` +
480
+ 'findNfts lists the ones it does; one just sent away is gone once a block confirms it.');
481
+ }
482
+ if (held[position]?.counterparty === true) {
483
+ throw invalidArgument(`NFT ${toBase64(id)} is a counterparty NFT, which a plain transfer cannot move.`);
484
+ }
485
+ return { id, position };
486
+ });
487
+ // The chain gives an NFT only to a wallet account (or a multisig proxy). A proxy's
488
+ // address is the likely paste here.
489
+ if (entries.length > 0) {
490
+ const proxy = ledger.findProxyAccount(to);
491
+ const account = ledger.findCoinAccount(to);
492
+ if ((proxy !== undefined && proxy.kind !== 'multisig') || (account !== undefined && account.kind !== 'asset')) {
493
+ throw invalidArgument(`The recipient is a ${proxy?.kind ?? account?.kind} record, and the chain gives NFTs ` +
494
+ 'only to a wallet account. Send them to a wallet address instead.');
495
+ }
496
+ }
497
+ const tx = createCoinTransferTxSync({
498
+ keypair: input.from,
499
+ to,
500
+ amount: pennies,
501
+ nfts: entries,
502
+ chainState,
503
+ });
504
+ assertAffordable(this.penniesPerGeeq, 'This account', chainState.balance, pennies, tx.fee, chainState.ledgerBlockNumber);
505
+ this.claimNonce(input.from, input.nonce, chainState, tx);
506
+ return tx;
507
+ }
508
+ /**
509
+ * The NFTs an account holds on this chain, in the order its record lists them, each with
510
+ * the hash and labels it was minted with.
511
+ *
512
+ * Which NFTs it holds comes from the validation layer ledger; what each stands for, from
513
+ * the application layer ledger, which is read afresh every time. An account the chain
514
+ * does not know holds none. A new NFT shows once a block has confirmed it, so pass
515
+ * `maxAgeMs: 0` to look straight after one was minted or sent.
516
+ */
517
+ async findNfts(request) {
518
+ const signal = request.signal === undefined ? {} : { signal: request.signal };
519
+ const [ledger, records] = await Promise.all([
520
+ this.getLedger({
521
+ ...(request.maxAgeMs === undefined ? {} : { maxAgeMs: request.maxAgeMs }),
522
+ ...signal,
523
+ }),
524
+ readNftRecords(this.endpoint, { ...this.request, ...signal }),
525
+ ]);
526
+ const held = ledger.findCoinAccount(request.owner)?.nfts ?? [];
527
+ return Object.freeze(held.map((nft) => {
528
+ const record = records.get(toBase64(nft.id));
529
+ return Object.freeze({ ...nft, attestHash: record?.attestHash, metadata: record?.metadata ?? [] });
530
+ }));
531
+ }
532
+ /**
533
+ * The NFT mint proxies an admin has on this chain, each with its index, and the index
534
+ * its next proxy takes: one past the highest in use, or 1 for an admin with none.
535
+ *
536
+ * A proxy appears once a block has confirmed it, so pass `maxAgeMs: 0` to look
537
+ * straight after one was submitted.
538
+ */
539
+ async findNftMintProxies(request) {
540
+ const [ledger] = await Promise.all([
541
+ this.getLedger({
542
+ ...(request.maxAgeMs === undefined ? {} : { maxAgeMs: request.maxAgeMs }),
543
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
544
+ }),
545
+ initGeeq(),
546
+ ]);
547
+ return nftMintProxiesIn(ledger, request.admin);
548
+ }
549
+ /**
550
+ * Create a proxy to mint NFTs through.
551
+ *
552
+ * A proxy is a record of its own: it holds coin, carries its own nonce, and names one
553
+ * admin — `admin` here — who signs every mint made through it. Its id is derived from
554
+ * the admin's key and an index, as the Geeq wallet derives it: by default the next
555
+ * index {@link findNftMintProxies} reports, so it is found again from the key alone.
556
+ *
557
+ * Checks the funding against the chain's minimum, and the admin's balance against the
558
+ * funding plus the fee. The result is **not submitted** — track it, then post it with
559
+ * `coinTransferSubmitBody`, exactly as a transfer. The proxy exists once a block
560
+ * confirms it.
561
+ */
562
+ async createNftMintProxy(input) {
563
+ const pennies = this.toPennies(input.amount);
564
+ const { ledger, chainState } = await this.readForBuild(input.admin, input.nonce, input.signal);
565
+ // The node holds proxy funding to the same minimum as any transfer.
566
+ const minimum = chainState.minimumTransfer;
567
+ if (minimum !== undefined && pennies < minimum) {
568
+ throw amountBelowMinimum(`A proxy must be funded with at least ${this.formatGeeq(minimum)} geeq, and ` +
569
+ `${this.formatGeeq(pennies)} is smaller. It is the same minimum as a transfer, from ` +
570
+ "the chain's minTxAmt and geeqNorm parameters, read at block " +
571
+ `${chainState.ledgerBlockNumber}.`);
572
+ }
573
+ const existing = nftMintProxiesIn(ledger, input.admin);
574
+ const index = input.index ?? existing.nextIndex;
575
+ if (existing.proxies.some((proxy) => proxy.index === index)) {
576
+ throw invalidArgument(`This admin already has a proxy at index ${index}. Leave index out to take the ` +
577
+ `next one, ${existing.nextIndex}.`);
578
+ }
579
+ const tx = createNftMintProxyTxSync({
580
+ keypair: input.admin,
581
+ index,
582
+ amount: pennies,
583
+ chainState,
584
+ });
585
+ assertAffordable(this.penniesPerGeeq, 'This account', chainState.balance, pennies, tx.fee, chainState.ledgerBlockNumber);
586
+ this.claimNonce(input.admin, input.nonce, chainState, tx);
587
+ return tx;
588
+ }
589
+ /**
590
+ * Mint an NFT through one of the admin's proxies.
591
+ *
592
+ * The proxy is the sender: it pays the fee and the coin sent with the NFT, and spends
593
+ * its own nonce, not the admin's. The admin signs. The NFT itself is the content's hash
594
+ * and labels, as an attestation is, and its id is derived from them — so the same
595
+ * content with the same labels through the same proxy cannot be minted twice.
596
+ *
597
+ * Reads the ledger to find the proxy and check what it holds. The result is **not
598
+ * submitted** — track it, then post it with `attestationSubmitBody`, exactly as an
599
+ * attestation: two fields, as `uat`.
600
+ */
601
+ async mintNft(input) {
602
+ if ((input.content === undefined) === (input.attestHash === undefined)) {
603
+ throw invalidArgument('Provide exactly one of content (hashed here with BLAKE3) or attestHash (a ' +
604
+ `${ATTEST_HASH_BYTES}-byte digest you produced yourself).`);
605
+ }
606
+ assertUint32(input.index, 'index');
607
+ const attestHash = input.attestHash ?? (await attestHashOf(input.content));
608
+ const signal = input.signal === undefined ? {} : { signal: input.signal };
609
+ const [cached] = await Promise.all([this.getLedger(signal), initGeeq()]);
610
+ const proxyKey = toBase64(nftMintProxyId(input.admin.publicKey, input.index));
611
+ // The proxy spends its own nonce, so the guard is keyed on the proxy, not the admin.
612
+ const ledger = await this.recheckIfClaimed(cached, input.nonce === undefined ? proxyKey : undefined, signal);
613
+ const proxy = ledger
614
+ .findProxyAccounts({ admin: input.admin })
615
+ .find((found) => toBase64(found.accountId) === proxyKey);
616
+ if (proxy === undefined) {
617
+ throw accountNotFound(`This admin has no NFT mint proxy at index ${input.index} in the ledger of chain ` +
618
+ `${ledger.chainNumber} at block ${ledger.blockNumber}. A new proxy appears once a ` +
619
+ 'block has confirmed it; findNftMintProxies lists the ones there are.');
620
+ }
621
+ const minimum = ledger.minimumTransfer;
622
+ const pennies = input.amount === undefined ? minimum : this.toPennies(input.amount);
623
+ if (pennies === undefined) {
624
+ throw invalidArgument('This chain publishes no minimum transfer to send with the NFT by default, so pass amount.');
625
+ }
626
+ if (minimum !== undefined && pennies < minimum) {
627
+ throw amountBelowMinimum(`A mint must send at least ${this.formatGeeq(minimum)} geeq with the NFT, and ` +
628
+ `${this.formatGeeq(pennies)} is smaller. It is the same minimum as a transfer, from ` +
629
+ "the chain's minTxAmt and geeqNorm parameters, read at block " +
630
+ `${ledger.blockNumber}.`);
631
+ }
632
+ const tx = createNftMintTxSync({
633
+ keypair: input.admin,
634
+ proxyAccountId: proxy.accountId,
635
+ attestHash,
636
+ ...(input.metadata === undefined ? {} : { metadata: input.metadata }),
637
+ to: input.to === undefined
638
+ ? input.admin.accountId
639
+ : this.resolveRecipient(input.to, ledger.chainNumber),
640
+ amount: pennies,
641
+ chainState: { ...this.pinnedTo(ledger), nonce: input.nonce ?? proxy.nonce },
642
+ });
643
+ // The proxy pays, not the admin. Topping it up is a plain transfer to its address.
644
+ assertAffordable(this.penniesPerGeeq, `Proxy ${input.index}`, proxy.balance, pennies, tx.fee, ledger.blockNumber);
645
+ if (input.nonce === undefined) {
646
+ this.nonces.claim(proxyKey, ledger.blockNumber, proxy.nonce, toBase64(tx.transactionHash));
647
+ }
648
+ return tx;
649
+ }
650
+ /**
651
+ * Whether a built transaction is now too old to send: the chain is past its
652
+ * `validUntilBlock`, and a node would refuse it with an HTTP 400.
653
+ *
654
+ * Reads the ledger afresh, because a cached one can only be behind the chain and would
655
+ * say "not yet" when it already is. Call it before submitting a transaction that may
656
+ * have waited.
657
+ */
658
+ async isExpired(tx) {
659
+ const ledger = await this.getLedger({ maxAgeMs: 0 });
660
+ return ledger.blockNumber > tx.validUntilBlock;
661
+ }
662
+ /**
663
+ * Give back the nonce a built transaction took, because it will never be sent — the
664
+ * user changed something and is building again. The next build may then take the same
665
+ * nonce in the same block instead of being refused with `nonce-collision`.
666
+ *
667
+ * Only for a transaction that was not submitted: if it reaches the node as well as its
668
+ * rebuild, the two share a nonce and the node rejects both.
669
+ */
670
+ discard(tx) {
671
+ this.nonces.release(toBase64(tx.transactionHash));
672
+ }
673
+ /** Forget which accounts have built a transaction against the current block. */
674
+ forgetNonces() {
675
+ this.nonces.clear();
676
+ }
677
+ /** Drop cached state, and step down as the default if this chain holds that slot. */
678
+ dispose() {
679
+ this.cached = null;
680
+ this.resolved = null;
681
+ this.inflight = null;
682
+ this.nonces.clear();
683
+ if (defaultChain === this)
684
+ defaultChain = null;
685
+ }
686
+ toJSON() {
687
+ return {
688
+ chainNumber: this.chainNumber,
689
+ endpoint: this.endpoint,
690
+ node: this.node,
691
+ ledgerBlockNumber: this.cached?.blockNumber,
692
+ candidateCount: this.candidates.length,
693
+ };
694
+ }
695
+ toString() {
696
+ return `GeeqChain(chain ${this.chainNumber ?? 'unread'} via ${this.endpoint})`;
697
+ }
698
+ }
699
+ /**
700
+ * Connect to a chain and make it the default.
701
+ *
702
+ * Thin alias for {@link GeeqChain.init} — the name most applications reach for, and one
703
+ * line so there is no second implementation to keep in step.
704
+ *
705
+ * ```ts
706
+ * await initChain({ endpoint: 'https://1.2.3.4:2082' })
707
+ * const tx = await attest({ keypair, content: fileBytes })
708
+ * ```
709
+ */
710
+ export function initChain(options) {
711
+ return GeeqChain.init(options);
712
+ }
713
+ /** Build an attestation on the default chain. See {@link GeeqChain.createAttestation}. */
714
+ export function attest(input) {
715
+ return GeeqChain.current().createAttestation(input);
716
+ }
717
+ /** Send coin on the default chain. See {@link GeeqChain.createTransfer}. */
718
+ export function transfer(input) {
719
+ return GeeqChain.current().createTransfer(input);
720
+ }
721
+ //# sourceMappingURL=geeq-chain.js.map