@ocap/client 1.31.0 → 1.31.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/dist/extension.js CHANGED
@@ -1,13 +1,16 @@
1
1
  const { get, set, omit, camelCase } = require('./helpers/lite');
2
+
2
3
  const { isValid, isFromPublicKey, toTypeInfo } = require('@arcblock/did');
3
4
  const ocapProto = require('@ocap/proto/schema');
4
- const { toTxHash } = require('@ocap/mcrypto');
5
+ const { toTxHash, parseStrictEthAddress, buildBridgeWithdrawEnvelopeExtra } = require('@ocap/mcrypto');
5
6
  const { fromPublicKey } = require('@ocap/wallet');
6
7
  const { encodeTx: encodeTxCbor, decodeTx: decodeTxCbor } = require('@ocap/message/cbor');
7
8
  const { bytesToHex, toBase58, toBase64, toHex, toBuffer, fromTokenToUnit, fromUnitToToken } = require('@ocap/util');
8
9
  const { DEFAULT_TOKEN_DECIMAL } = require('@ocap/util/lib/constant');
10
+
9
11
  const { formatFactoryState, preMintFromFactory: preMintFromFactoryCbor } = require('@ocap/asset/mint/client');
10
12
  const { verifyTxInclusion } = require('./verify');
13
+ const { createBridgeGovernance } = require('./bridge');
11
14
  const {
12
15
  toDelegateAddress,
13
16
  toAssetAddress: toAssetAddressCbor,
@@ -15,11 +18,15 @@ const {
15
18
  toTokenAddress: toTokenAddressCbor,
16
19
  toTokenFactoryAddress: toTokenFactoryAddressCbor,
17
20
  toStakeAddress,
18
- toRollupAddress: toRollupAddressCbor
21
+ toRollupAddress: toRollupAddressCbor,
22
+ toBridgeReserveAddress
19
23
  } = require('@arcblock/did-util/cbor');
20
24
 
21
25
  const debug = require('debug')(require('../package.json').name);
22
26
 
27
+ // An encoded tx carries `signature: new Uint8Array(0)` until it is signed; an empty value is not a signature.
28
+ const hasSignature = s => !!s && (typeof s === 'string' ? s.length > 0 && s !== '0x' : s.length === undefined || s.length > 0);
29
+
23
30
  const { transactions, typeUrls, toTypeUrl, multiSignTxs, multiSignV2Txs } = ocapProto;
24
31
 
25
32
  // Default CBOR-only dependency bundle. `@ocap/client/legacy` re-invokes
@@ -427,7 +434,7 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
427
434
  if (signature) {
428
435
  encoded = tx;
429
436
  encoded.signature = signature;
430
- } else if (tx.signature) {
437
+ } else if (hasSignature(tx.signature)) {
431
438
  const res = await txEncodeFn({ tx, wallet, delegator });
432
439
  encoded = res.object;
433
440
  } else {
@@ -658,6 +665,97 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
658
665
  toWallet: to
659
666
  }, extra);
660
667
 
668
+ /**
669
+ * Build and sign a bridge withdraw (a `transfer_v2` into the bridge reserve, #1465), ready for `sendTransferV2Tx`.
670
+ *
671
+ * Signing modes (`signing`):
672
+ * - `eip712` (default for Ethereum-type wallets): `ArcBridgeWithdraw` clear-signing envelope, shows amount, token and
673
+ * Ethereum destination in the wallet UI;
674
+ * - `eip191`: personal_sign over the canonical text, which carries the same three fields;
675
+ * - `raw`: the plain transaction signature (what `sendTransferV2Tx` does by default). The chain only accepts it from
676
+ * signers that do not use wallet envelopes.
677
+ *
678
+ * @memberof GraphQLClient
679
+ * @function
680
+ * @name GraphQLClient#buildBridgeWithdrawTx
681
+ * @param {object} params
682
+ * @param {WalletObject} params.wallet - the sender
683
+ * @param {string} params.bridge - address of the bridge (rollup); the reserve (`itx.to`) is derived from it
684
+ * @param {string|number|bigint} params.amount - amount in base units
685
+ * @param {string} params.ethRecipient - Ethereum recipient, `0x` + 40 hex, lowercase or EIP-55 (checked locally)
686
+ * @param {string} [params.token] - the bridge's OCAP token, defaults to the chain's official token
687
+ * @param {string} [params.signing='eip712'] - `eip712` | `eip191` | `raw`
688
+ * @param {string|number} [params.nonce] - defaults to Date.now()
689
+ * @param {string} [params.chainId] - defaults to the connected chain
690
+ * @param {object} [params.domain] - `{ name, version }` of the envelope domain, defaults to the chain's default
691
+ * @returns {Promise<{ tx: object, signature: string, extra: string }>} pass as `client.sendTransferV2Tx({ tx, signature, extra })`
692
+ */
693
+ client.buildBridgeWithdrawTx = async ({
694
+ wallet,
695
+ bridge,
696
+ amount,
697
+ ethRecipient,
698
+ token,
699
+ signing = 'eip712',
700
+ nonce,
701
+ chainId,
702
+ domain = {}
703
+ }) => {
704
+ if (!bridge) throw new Error('buildBridgeWithdrawTx requires the bridge address');
705
+ const recipient = parseStrictEthAddress(ethRecipient);
706
+ if (!recipient.ok) throw new Error(`Invalid Ethereum recipient: ${recipient.reason}`);
707
+ const amountStr = String(amount);
708
+ if (!/^[1-9][0-9]*$/.test(amountStr)) throw new Error('amount must be a positive integer in base units');
709
+ const context = await client.getContext();
710
+ const tokenAddress = token || get(context, 'token.address');
711
+ if (!tokenAddress) throw new Error('token is required when the chain has no official token');
712
+
713
+ const tx = {
714
+ itx: {
715
+ to: toBridgeReserveAddress(bridge),
716
+ tokens: [{ address: tokenAddress, value: amountStr }],
717
+ data: { typeUrl: 'fg:x:address', value: ethRecipient }
718
+ }
719
+ };
720
+ if (nonce !== undefined) tx.nonce = nonce;
721
+ if (chainId) tx.chainId = chainId;
722
+ const { object, buffer } = await client.encodeTransferV2Tx({ tx, wallet });
723
+
724
+ if (signing === 'raw') {
725
+ return { tx: object, signature: await wallet.sign(bytesToHex(buffer)), extra: '' };
726
+ }
727
+ if (signing !== 'eip712' && signing !== 'eip191') throw new Error(`Unknown signing mode ${signing}`);
728
+ const envelopeExtra = buildBridgeWithdrawEnvelopeExtra({
729
+ envelope: signing,
730
+ chainId: object.chainId,
731
+ from: wallet.address,
732
+ nonce: String(object.nonce),
733
+ bridge,
734
+ amount: amountStr,
735
+ token: tokenAddress,
736
+ ethRecipient,
737
+ domainName: domain.name,
738
+ domainVersion: domain.version
739
+ });
740
+ const signed = await wallet.signEnvelope(buffer, envelopeExtra);
741
+ return { tx: object, signature: signed.signature, extra: signed.extra };
742
+ };
743
+
744
+ /**
745
+ * Build, sign and send a bridge withdraw, see `buildBridgeWithdrawTx`.
746
+ *
747
+ * @memberof GraphQLClient
748
+ * @function
749
+ * @name GraphQLClient#bridgeWithdraw
750
+ * @param {object} params - same as `buildBridgeWithdrawTx`, plus `commit`
751
+ * @param {object} extra - other param to underlying client implementation
752
+ * @returns {Promise<string>} the transaction hash once resolved
753
+ */
754
+ client.bridgeWithdraw = async (params, extra) => {
755
+ const { tx, signature, extra: txExtra } = await client.buildBridgeWithdrawTx(omit(params, ['commit']));
756
+ return client.sendTransferV2Tx({ tx, signature, commit: !!params.commit, extra: txExtra }, extra);
757
+ };
758
+
661
759
  /**
662
760
  * Delegate some privileges to another account
663
761
  * So that that account can send transactions on behalf of the delegator
@@ -1524,7 +1622,7 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
1524
1622
  * @name GraphQLClient#burnToken
1525
1623
  * @param {object} params
1526
1624
  * @param {string} params.address - token factory address
1527
- * @param {number} params.feeRate - fee for the mint and burn
1625
+ * @param {number} params.feeRate - fee for the mint and burn, can only be lowered after creation: the chain rejects an increase
1528
1626
  * @param {object} params.token - token factory token payload
1529
1627
  * @param {object} params.data - token factory data payload
1530
1628
  * @param {WalletObject} params.wallet - the wallet who is the owner
@@ -1671,6 +1769,15 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
1671
1769
  * @returns {Promise<{ verified: boolean, reason?: string }>}
1672
1770
  */
1673
1771
  client.verifyTxInclusion = params => verifyTxInclusion(params);
1772
+
1773
+ /**
1774
+ * On-chain bridge governance helpers (create, update, join, leave, pause, resume, close, migrate).
1775
+ * See `@ocap/client/bridge` and bridge/docs/ocap-protocols.md §v2.2.
1776
+ *
1777
+ * @memberof GraphQLClient
1778
+ * @name GraphQLClient#bridge
1779
+ */
1780
+ client.bridge = createBridgeGovernance(client, deps);
1674
1781
  };
1675
1782
 
1676
1783
  module.exports = { createExtensionMethods, defaultDeps };