@ocap/client 1.30.2 → 1.30.4
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/README.md +44 -0
- package/dist/base.js +36 -39
- package/dist/base.js.map +1 -1
- package/dist/browser.d.ts +7 -1
- package/dist/bundle.js +1 -1
- package/dist/client.js +19 -3
- package/dist/client.js.map +1 -1
- package/dist/encode.js +156 -0
- package/dist/encode.js.map +1 -0
- package/dist/extension.js +71 -52
- package/dist/extension.js.map +1 -1
- package/dist/helpers/lite.js +78 -0
- package/dist/helpers/lite.js.map +1 -0
- package/dist/legacy.d.ts +8 -0
- package/dist/legacy.js +82 -0
- package/dist/legacy.js.map +1 -0
- package/dist/report.html +2 -2
- package/dist/subscribe.js +38 -0
- package/dist/subscribe.js.map +1 -0
- package/encode.d.ts +62 -0
- package/encode.js +1 -0
- package/lib/base.js +36 -39
- package/lib/base.js.map +1 -1
- package/lib/client.js +19 -3
- package/lib/client.js.map +1 -1
- package/lib/encode.js +158 -0
- package/lib/encode.js.map +1 -0
- package/lib/extension.js +71 -52
- package/lib/extension.js.map +1 -1
- package/lib/helpers/lite.js +80 -0
- package/lib/helpers/lite.js.map +1 -0
- package/lib/legacy.d.ts +8 -0
- package/lib/legacy.js +84 -0
- package/lib/legacy.js.map +1 -0
- package/lib/node.d.ts +7 -1
- package/lib/node.js +6 -0
- package/lib/node.js.map +1 -1
- package/lib/subscribe.js +40 -0
- package/lib/subscribe.js.map +1 -0
- package/package.json +35 -13
package/lib/encode.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Lightweight transaction encoder — only depends on @ocap/message/cbor.
|
|
5
|
+
*
|
|
6
|
+
* Cuts out @ocap/asset (~11 MB), @arcblock/did-util, graphql, @arcblock/sdk-util,
|
|
7
|
+
* and the full client/extension.js dependency tree. After the CBOR switch the
|
|
8
|
+
* google-protobuf runtime is no longer pulled in on the client; tree-shaken
|
|
9
|
+
* bundles only include @ocap/proto/schema + cborg (~8 KB).
|
|
10
|
+
*
|
|
11
|
+
* @module @ocap/client/encode
|
|
12
|
+
*/
|
|
13
|
+
const { toTypeUrl } = require('@ocap/proto/schema');
|
|
14
|
+
const { encodeTx: encodeTxCbor } = require('@ocap/message/cbor');
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Normalize wallet to { address, publicKey }.
|
|
18
|
+
* Handles @ocap/wallet instances, plain objects with pk or publicKey.
|
|
19
|
+
*/
|
|
20
|
+
function normalizeWallet(wallet) {
|
|
21
|
+
if (!wallet) return { address: '', publicKey: '' };
|
|
22
|
+
if (typeof wallet.toAddress === 'function') {
|
|
23
|
+
return { address: wallet.address, publicKey: wallet.publicKey };
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
address: wallet.address,
|
|
27
|
+
publicKey: wallet.pk || wallet.publicKey || ''
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Encode a transaction to protobuf binary.
|
|
33
|
+
*
|
|
34
|
+
* Pure function — no network IO, no side effects.
|
|
35
|
+
* Logic extracted from extension.js txEncodeFn for standalone use.
|
|
36
|
+
*
|
|
37
|
+
* @param {object} params
|
|
38
|
+
* @param {string} params.type - Transaction type name, e.g. 'TransferV2Tx'
|
|
39
|
+
* @param {object} params.tx - Transaction data (same shape as client.encodeXxxTx({ tx }))
|
|
40
|
+
* @param {object} params.wallet - Wallet { address, publicKey|pk }
|
|
41
|
+
* @param {string} [params.delegator=''] - Delegator address
|
|
42
|
+
* @param {string} [params.chainId=''] - Chain ID (from getChainInfo)
|
|
43
|
+
* @param {Array} [params.feeConfig=[]] - Fee config [{ typeUrl, fee }] (from getForgeState)
|
|
44
|
+
* @returns {{ object: object, buffer: Buffer }}
|
|
45
|
+
*/
|
|
46
|
+
function encodeTx({ type, tx, wallet, delegator = '', chainId = '', feeConfig = [] }) {
|
|
47
|
+
const w = normalizeWallet(wallet);
|
|
48
|
+
const address = tx.from || w.address;
|
|
49
|
+
const pk = tx.pk || w.publicKey;
|
|
50
|
+
const nonce = typeof tx.nonce === 'undefined' ? Date.now() : tx.nonce;
|
|
51
|
+
const resolvedChainId = tx.chainId || chainId;
|
|
52
|
+
|
|
53
|
+
let signatures = [];
|
|
54
|
+
if (Array.isArray(tx.signatures)) {
|
|
55
|
+
signatures = tx.signatures;
|
|
56
|
+
}
|
|
57
|
+
if (Array.isArray(tx.signaturesList)) {
|
|
58
|
+
signatures = tx.signaturesList;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
62
|
+
const itx = tx.itx && tx.itx.typeUrl && tx.itx.value ? tx.itx : { type, value: tx.itx };
|
|
63
|
+
|
|
64
|
+
const typeUrl = itx.typeUrl || toTypeUrl(itx.type);
|
|
65
|
+
const fee = feeConfig.find(t => t.typeUrl === typeUrl);
|
|
66
|
+
|
|
67
|
+
const txParams = {
|
|
68
|
+
from: tx.delegator ? address : delegator || address,
|
|
69
|
+
nonce,
|
|
70
|
+
pk,
|
|
71
|
+
chainId: resolvedChainId,
|
|
72
|
+
signature: tx.signature || new Uint8Array(0),
|
|
73
|
+
signatures,
|
|
74
|
+
delegator: tx.delegator || (delegator ? address : ''),
|
|
75
|
+
itx,
|
|
76
|
+
serviceFee: fee ? fee.fee : '0'
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const bytes = encodeTxCbor(txParams);
|
|
80
|
+
return { object: txParams, buffer: Buffer.from(bytes) };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// ---- Context fetcher (lightweight replacement for client.getContext) ----
|
|
84
|
+
|
|
85
|
+
const contextCache = new Map();
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Fetch minimal chain context (chainId + fee config) via raw HTTP.
|
|
89
|
+
* Cached per endpoint — call clearContextCache() to invalidate.
|
|
90
|
+
*
|
|
91
|
+
* @param {string} chainHost - Chain RPC endpoint URL
|
|
92
|
+
* @returns {Promise<{ chainId: string, txFee: Array }>}
|
|
93
|
+
*/
|
|
94
|
+
async function fetchContext(chainHost) {
|
|
95
|
+
if (contextCache.has(chainHost)) {
|
|
96
|
+
return contextCache.get(chainHost);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const post = async query => {
|
|
100
|
+
const res = await fetch(chainHost, {
|
|
101
|
+
method: 'POST',
|
|
102
|
+
headers: { 'content-type': 'application/json' },
|
|
103
|
+
body: JSON.stringify({ query })
|
|
104
|
+
});
|
|
105
|
+
if (!res.ok) {
|
|
106
|
+
throw new Error(`fetchContext: HTTP ${res.status} from ${chainHost}`);
|
|
107
|
+
}
|
|
108
|
+
return (await res.json()).data;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const [info, state] = await Promise.all([post('{ getChainInfo { code info { network } } }'), post('{ getForgeState { code state { txConfig { txFee { fee typeUrl } } } } }')]);
|
|
112
|
+
|
|
113
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
114
|
+
const chainInfo = info && info.getChainInfo && info.getChainInfo.info;
|
|
115
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
116
|
+
const txConfig = state && state.getForgeState && state.getForgeState.state && state.getForgeState.state.txConfig;
|
|
117
|
+
|
|
118
|
+
const context = {
|
|
119
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
120
|
+
chainId: chainInfo && chainInfo.network || '',
|
|
121
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
122
|
+
txFee: txConfig && txConfig.txFee || []
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
contextCache.set(chainHost, context);
|
|
126
|
+
return context;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function clearContextCache() {
|
|
130
|
+
contextCache.clear();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Create a TxEncoder function compatible with @arcblock/did-connect-js WalletAuthenticator.
|
|
135
|
+
*
|
|
136
|
+
* Usage:
|
|
137
|
+
* const { createTxEncoder } = require('@ocap/client/encode');
|
|
138
|
+
* const authenticator = new WalletAuthenticator({ txEncoder: createTxEncoder(), ... });
|
|
139
|
+
*
|
|
140
|
+
* @returns {function} async ({ type, data, wallet, chainHost }) => Buffer
|
|
141
|
+
*/
|
|
142
|
+
function createTxEncoder() {
|
|
143
|
+
return async ({ type, data, wallet, chainHost }) => {
|
|
144
|
+
const context = await fetchContext(chainHost);
|
|
145
|
+
const { buffer } = encodeTx({
|
|
146
|
+
type,
|
|
147
|
+
tx: data,
|
|
148
|
+
wallet,
|
|
149
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
150
|
+
chainId: data && data.chainId || context.chainId,
|
|
151
|
+
feeConfig: context.txFee
|
|
152
|
+
});
|
|
153
|
+
return buffer;
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
module.exports = { encodeTx, createTxEncoder, fetchContext, clearContextCache };
|
|
158
|
+
//# sourceMappingURL=encode.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/encode.js"],"names":["toTypeUrl","require","encodeTx","encodeTxCbor","normalizeWallet","wallet","address","publicKey","toAddress","pk","type","tx","delegator","chainId","feeConfig","w","from","nonce","Date","now","resolvedChainId","signatures","Array","isArray","signaturesList","itx","typeUrl","value","fee","find","t","txParams","signature","Uint8Array","serviceFee","bytes","object","buffer","Buffer","contextCache","Map","fetchContext","chainHost","has","get","post","query","res","fetch","method","headers","body","JSON","stringify","ok","Error","status","json","data","info","state","Promise","all","chainInfo","getChainInfo","txConfig","getForgeState","context","network","txFee","set","clearContextCache","clear","createTxEncoder","module","exports"],"mappings":";;AAAA;;;;;;;;;;AAUA,MAAM,EAAEA,SAAF,KAAgBC,QAAQ,oBAAR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OC,OAAP,GAAiB,EAAEzE,QAAF,EAAYuE,eAAZ,EAA6BhC,YAA7B,EAA2C8B,iBAA3C,EAAjB","file":"encode.js","sourcesContent":["/**\n * Lightweight transaction encoder — only depends on @ocap/message/cbor.\n *\n * Cuts out @ocap/asset (~11 MB), @arcblock/did-util, graphql, @arcblock/sdk-util,\n * and the full client/extension.js dependency tree. After the CBOR switch the\n * google-protobuf runtime is no longer pulled in on the client; tree-shaken\n * bundles only include @ocap/proto/schema + cborg (~8 KB).\n *\n * @module @ocap/client/encode\n */\nconst { toTypeUrl } = require('@ocap/proto/schema');\nconst { encodeTx: encodeTxCbor } = require('@ocap/message/cbor');\n\n/**\n * Normalize wallet to { address, publicKey }.\n * Handles @ocap/wallet instances, plain objects with pk or publicKey.\n */\nfunction normalizeWallet(wallet) {\n if (!wallet) return { address: '', publicKey: '' };\n if (typeof wallet.toAddress === 'function') {\n return { address: wallet.address, publicKey: wallet.publicKey };\n }\n return {\n address: wallet.address,\n publicKey: wallet.pk || wallet.publicKey || '',\n };\n}\n\n/**\n * Encode a transaction to protobuf binary.\n *\n * Pure function — no network IO, no side effects.\n * Logic extracted from extension.js txEncodeFn for standalone use.\n *\n * @param {object} params\n * @param {string} params.type - Transaction type name, e.g. 'TransferV2Tx'\n * @param {object} params.tx - Transaction data (same shape as client.encodeXxxTx({ tx }))\n * @param {object} params.wallet - Wallet { address, publicKey|pk }\n * @param {string} [params.delegator=''] - Delegator address\n * @param {string} [params.chainId=''] - Chain ID (from getChainInfo)\n * @param {Array} [params.feeConfig=[]] - Fee config [{ typeUrl, fee }] (from getForgeState)\n * @returns {{ object: object, buffer: Buffer }}\n */\nfunction encodeTx({ type, tx, wallet, delegator = '', chainId = '', feeConfig = [] }) {\n const w = normalizeWallet(wallet);\n const address = tx.from || w.address;\n const pk = tx.pk || w.publicKey;\n const nonce = typeof tx.nonce === 'undefined' ? Date.now() : tx.nonce;\n const resolvedChainId = tx.chainId || chainId;\n\n let signatures = [];\n if (Array.isArray(tx.signatures)) {\n signatures = tx.signatures;\n }\n if (Array.isArray(tx.signaturesList)) {\n signatures = tx.signaturesList;\n }\n\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n const itx = tx.itx && tx.itx.typeUrl && tx.itx.value ? tx.itx : { type, value: tx.itx };\n\n const typeUrl = itx.typeUrl || toTypeUrl(itx.type);\n const fee = feeConfig.find((t) => t.typeUrl === typeUrl);\n\n const txParams = {\n from: tx.delegator ? address : delegator || address,\n nonce,\n pk,\n chainId: resolvedChainId,\n signature: tx.signature || new Uint8Array(0),\n signatures,\n delegator: tx.delegator || (delegator ? address : ''),\n itx,\n serviceFee: fee ? fee.fee : '0',\n };\n\n const bytes = encodeTxCbor(txParams);\n return { object: txParams, buffer: Buffer.from(bytes) };\n}\n\n// ---- Context fetcher (lightweight replacement for client.getContext) ----\n\nconst contextCache = new Map();\n\n/**\n * Fetch minimal chain context (chainId + fee config) via raw HTTP.\n * Cached per endpoint — call clearContextCache() to invalidate.\n *\n * @param {string} chainHost - Chain RPC endpoint URL\n * @returns {Promise<{ chainId: string, txFee: Array }>}\n */\nasync function fetchContext(chainHost) {\n if (contextCache.has(chainHost)) {\n return contextCache.get(chainHost);\n }\n\n const post = async (query) => {\n const res = await fetch(chainHost, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ query }),\n });\n if (!res.ok) {\n throw new Error(`fetchContext: HTTP ${res.status} from ${chainHost}`);\n }\n return (await res.json()).data;\n };\n\n const [info, state] = await Promise.all([\n post('{ getChainInfo { code info { network } } }'),\n post('{ getForgeState { code state { txConfig { txFee { fee typeUrl } } } } }'),\n ]);\n\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n const chainInfo = info && info.getChainInfo && info.getChainInfo.info;\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n const txConfig = state && state.getForgeState && state.getForgeState.state && state.getForgeState.state.txConfig;\n\n const context = {\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n chainId: (chainInfo && chainInfo.network) || '',\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n txFee: (txConfig && txConfig.txFee) || [],\n };\n\n contextCache.set(chainHost, context);\n return context;\n}\n\nfunction clearContextCache() {\n contextCache.clear();\n}\n\n/**\n * Create a TxEncoder function compatible with @arcblock/did-connect-js WalletAuthenticator.\n *\n * Usage:\n * const { createTxEncoder } = require('@ocap/client/encode');\n * const authenticator = new WalletAuthenticator({ txEncoder: createTxEncoder(), ... });\n *\n * @returns {function} async ({ type, data, wallet, chainHost }) => Buffer\n */\nfunction createTxEncoder() {\n return async ({ type, data, wallet, chainHost }) => {\n const context = await fetchContext(chainHost);\n const { buffer } = encodeTx({\n type,\n tx: data,\n wallet,\n // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining\n chainId: (data && data.chainId) || context.chainId,\n feeConfig: context.txFee,\n });\n return buffer;\n };\n}\n\nmodule.exports = { encodeTx, createTxEncoder, fetchContext, clearContextCache };\n"]}
|
package/lib/extension.js
CHANGED
|
@@ -1,41 +1,57 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const get = require('
|
|
4
|
-
const set = require('lodash/set');
|
|
5
|
-
const omit = require('lodash/omit');
|
|
6
|
-
const cloneDeep = require('lodash/cloneDeep');
|
|
7
|
-
const camelCase = require('lodash/camelCase');
|
|
3
|
+
const { get, set, omit, camelCase } = require('./helpers/lite');
|
|
8
4
|
const { isValid } = require('@arcblock/did');
|
|
9
|
-
const ocapProto = require('@ocap/proto');
|
|
5
|
+
const ocapProto = require('@ocap/proto/schema');
|
|
10
6
|
const { toTxHash } = require('@ocap/mcrypto');
|
|
11
|
-
const {
|
|
7
|
+
const { encodeTx: encodeTxCbor, decodeTx: decodeTxCbor } = require('@ocap/message/cbor');
|
|
12
8
|
const { bytesToHex, toBase58, toBase64, toHex, toBuffer, fromTokenToUnit, fromUnitToToken } = require('@ocap/util');
|
|
13
9
|
const { DEFAULT_TOKEN_DECIMAL } = require('@ocap/util/lib/constant');
|
|
14
|
-
const { formatFactoryState, preMintFromFactory
|
|
10
|
+
const { formatFactoryState, preMintFromFactory: preMintFromFactoryCbor } = require('@ocap/asset/mint/client');
|
|
15
11
|
const {
|
|
16
12
|
toDelegateAddress,
|
|
17
|
-
toAssetAddress,
|
|
18
|
-
toFactoryAddress,
|
|
19
|
-
toTokenAddress,
|
|
20
|
-
toTokenFactoryAddress,
|
|
13
|
+
toAssetAddress: toAssetAddressCbor,
|
|
14
|
+
toFactoryAddress: toFactoryAddressCbor,
|
|
15
|
+
toTokenAddress: toTokenAddressCbor,
|
|
16
|
+
toTokenFactoryAddress: toTokenFactoryAddressCbor,
|
|
21
17
|
toStakeAddress,
|
|
22
|
-
toRollupAddress
|
|
23
|
-
} = require('@arcblock/did-util');
|
|
18
|
+
toRollupAddress: toRollupAddressCbor
|
|
19
|
+
} = require('@arcblock/did-util/cbor');
|
|
24
20
|
|
|
25
21
|
const debug = require('debug')(require('../package.json').name);
|
|
26
22
|
|
|
27
|
-
const { transactions, typeUrls, multiSignTxs, multiSignV2Txs } = ocapProto;
|
|
23
|
+
const { transactions, typeUrls, toTypeUrl, multiSignTxs, multiSignV2Txs } = ocapProto;
|
|
24
|
+
|
|
25
|
+
// Default CBOR-only dependency bundle. `@ocap/client/legacy` re-invokes
|
|
26
|
+
// `createExtensionMethods` with a protobuf-wired bundle so the main entry
|
|
27
|
+
// stays free of `google-protobuf` / `*_pb.js`. See README §4.7 / §4.10.
|
|
28
|
+
const defaultDeps = {
|
|
29
|
+
encodeTx: encodeTxCbor,
|
|
30
|
+
decodeTx: decodeTxCbor,
|
|
31
|
+
preMintFromFactory: preMintFromFactoryCbor,
|
|
32
|
+
toAssetAddress: toAssetAddressCbor,
|
|
33
|
+
toFactoryAddress: toFactoryAddressCbor,
|
|
34
|
+
toTokenAddress: toTokenAddressCbor,
|
|
35
|
+
toTokenFactoryAddress: toTokenFactoryAddressCbor,
|
|
36
|
+
toRollupAddress: toRollupAddressCbor
|
|
37
|
+
};
|
|
28
38
|
|
|
29
39
|
// FIXME: delete this after @ocap/proto updated
|
|
30
40
|
const filteredTransactions = transactions.filter(x => !['DeclareTx'].includes(x));
|
|
31
41
|
|
|
32
42
|
/**
|
|
33
|
-
* Generate extension methods on the fly
|
|
43
|
+
* Generate extension methods on the fly.
|
|
44
|
+
*
|
|
45
|
+
* The `deps` parameter lets the `@ocap/client/legacy` subpath re-invoke this
|
|
46
|
+
* factory with protobuf-wired encoders and address helpers. Callers of the
|
|
47
|
+
* main entry use the default CBOR bundle and never drag `google-protobuf`
|
|
48
|
+
* or any `*_pb.js` module into the graph.
|
|
34
49
|
*
|
|
35
50
|
* @public
|
|
36
51
|
* @param {GraphQLClient} client
|
|
52
|
+
* @param {object} [deps=defaultDeps]
|
|
37
53
|
*/
|
|
38
|
-
const createExtensionMethods = client => {
|
|
54
|
+
const createExtensionMethods = (client, deps = defaultDeps) => {
|
|
39
55
|
Object.defineProperty(client, 'ctx', {
|
|
40
56
|
value: {
|
|
41
57
|
loading: false,
|
|
@@ -44,6 +60,17 @@ const createExtensionMethods = client => {
|
|
|
44
60
|
}
|
|
45
61
|
});
|
|
46
62
|
|
|
63
|
+
const {
|
|
64
|
+
encodeTx,
|
|
65
|
+
decodeTx,
|
|
66
|
+
preMintFromFactory,
|
|
67
|
+
toAssetAddress,
|
|
68
|
+
toFactoryAddress,
|
|
69
|
+
toTokenAddress,
|
|
70
|
+
toTokenFactoryAddress,
|
|
71
|
+
toRollupAddress
|
|
72
|
+
} = deps;
|
|
73
|
+
|
|
47
74
|
/**
|
|
48
75
|
* Format big number presentation amount to token number
|
|
49
76
|
*
|
|
@@ -113,17 +140,6 @@ const createExtensionMethods = client => {
|
|
|
113
140
|
*/
|
|
114
141
|
client.getTxMultiSignMethods = () => multiSignTxs.concat(multiSignV2Txs).map(x => camelCase(`multi_sign_${x}`));
|
|
115
142
|
|
|
116
|
-
/**
|
|
117
|
-
* Get protobuf message class by name, only supports forge-built-in types
|
|
118
|
-
*
|
|
119
|
-
* @memberof GraphQLClient
|
|
120
|
-
* @function
|
|
121
|
-
* @name GraphQLClient#getType
|
|
122
|
-
* @param {string} x
|
|
123
|
-
* @returns {class|null} message type
|
|
124
|
-
*/
|
|
125
|
-
client.getType = x => getMessageType(x).fn;
|
|
126
|
-
|
|
127
143
|
/**
|
|
128
144
|
* Decode transaction buffer/base64/base58 to an object
|
|
129
145
|
*
|
|
@@ -133,10 +149,7 @@ const createExtensionMethods = client => {
|
|
|
133
149
|
* @param {buffer|hex|base48|base64} input
|
|
134
150
|
* @returns {object} transaction object
|
|
135
151
|
*/
|
|
136
|
-
client.decodeTx = input =>
|
|
137
|
-
const Transaction = client.getType('Transaction');
|
|
138
|
-
return Transaction.deserializeBinary(toBuffer(input)).toObject();
|
|
139
|
-
};
|
|
152
|
+
client.decodeTx = input => decodeTx(toBuffer(input));
|
|
140
153
|
|
|
141
154
|
/**
|
|
142
155
|
* Ensure a connection is bootstrapped with some meta info fetched from chain node
|
|
@@ -341,10 +354,14 @@ const createExtensionMethods = client => {
|
|
|
341
354
|
signatures = tx.signaturesList;
|
|
342
355
|
}
|
|
343
356
|
|
|
344
|
-
// Determine itx
|
|
357
|
+
// Determine itx. If the caller already wrapped tx.itx as {type, value}
|
|
358
|
+
// via a prior sign call (e.g. signExchangeTx → multiSignExchangeV2Tx),
|
|
359
|
+
// unwrap and re-tag with the current outer type to avoid double-nesting.
|
|
345
360
|
let itx = null;
|
|
346
361
|
if (tx.itx.typeUrl && tx.itx.value) {
|
|
347
362
|
itx = tx.itx;
|
|
363
|
+
} else if (tx.itx.type && tx.itx.value && !Array.isArray(tx.itx.value)) {
|
|
364
|
+
itx = { type: x, value: tx.itx.value };
|
|
348
365
|
} else {
|
|
349
366
|
itx = { type: x, value: tx.itx };
|
|
350
367
|
}
|
|
@@ -352,22 +369,22 @@ const createExtensionMethods = client => {
|
|
|
352
369
|
const type = itx.typeUrl || toTypeUrl(itx.type);
|
|
353
370
|
const feeConfig = get(context, 'txConfig.txFee', []).find(t => t.typeUrl === type);
|
|
354
371
|
|
|
355
|
-
const
|
|
372
|
+
const txParams = {
|
|
356
373
|
from: tx.delegator ? address : delegator || address,
|
|
357
374
|
nonce,
|
|
358
375
|
pk,
|
|
359
376
|
chainId,
|
|
360
|
-
signature: tx.signature ||
|
|
377
|
+
signature: tx.signature || new Uint8Array(0),
|
|
361
378
|
signatures,
|
|
362
379
|
delegator: tx.delegator || (delegator ? address : ''),
|
|
363
380
|
itx,
|
|
364
381
|
serviceFee: feeConfig ? feeConfig.fee : '0'
|
|
365
|
-
}
|
|
366
|
-
const txToSignBytes =
|
|
382
|
+
};
|
|
383
|
+
const txToSignBytes = encodeTx(txParams);
|
|
367
384
|
|
|
368
|
-
debug(`encodeTx.${x}.
|
|
385
|
+
debug(`encodeTx.${x}.txParams`, txParams);
|
|
369
386
|
|
|
370
|
-
return { object:
|
|
387
|
+
return { object: txParams, buffer: Buffer.from(txToSignBytes) };
|
|
371
388
|
};
|
|
372
389
|
|
|
373
390
|
const encodeMethod = camelCase(`encode_${x}`);
|
|
@@ -416,11 +433,10 @@ const createExtensionMethods = client => {
|
|
|
416
433
|
return new Promise(async (resolve, reject) => {
|
|
417
434
|
let txHash = null;
|
|
418
435
|
try {
|
|
419
|
-
const
|
|
420
|
-
const txBytes = txMsg.serializeBinary();
|
|
436
|
+
const txBytes = encodeTx(encoded);
|
|
421
437
|
const txStr = toBase64(txBytes);
|
|
422
438
|
txHash = toTxHash(txBytes);
|
|
423
|
-
debug(`sendTx.${x}.
|
|
439
|
+
debug(`sendTx.${x}.txParams`, encoded);
|
|
424
440
|
const { hash } = await client.sendTx({ tx: txStr, commit, extra: typeof txExtra === 'string' ? txExtra : JSON.stringify(txExtra) }, extra);
|
|
425
441
|
resolve(hash);
|
|
426
442
|
} catch (err) {
|
|
@@ -474,16 +490,16 @@ const createExtensionMethods = client => {
|
|
|
474
490
|
if (typeof wallet.toAddress !== 'function') {
|
|
475
491
|
throw new Error('Multisig requires a valid wallet');
|
|
476
492
|
}
|
|
477
|
-
tx.
|
|
493
|
+
tx.signatures = tx.signatures || tx.signaturesList || [];
|
|
478
494
|
if (delegator) {
|
|
479
|
-
tx.
|
|
495
|
+
tx.signatures.unshift({
|
|
480
496
|
pk: wallet.publicKey,
|
|
481
497
|
signer: delegator,
|
|
482
498
|
delegator: wallet.address,
|
|
483
499
|
data
|
|
484
500
|
});
|
|
485
501
|
} else {
|
|
486
|
-
tx.
|
|
502
|
+
tx.signatures.unshift({
|
|
487
503
|
pk: wallet.publicKey,
|
|
488
504
|
signer: wallet.address,
|
|
489
505
|
delegator: '',
|
|
@@ -492,7 +508,7 @@ const createExtensionMethods = client => {
|
|
|
492
508
|
}
|
|
493
509
|
|
|
494
510
|
const { object, buffer } = await txEncodeFn({ tx, wallet });
|
|
495
|
-
object.
|
|
511
|
+
object.signatures[0].signature = await wallet.sign(bytesToHex(buffer));
|
|
496
512
|
return _formatEncodedTx(object, encoding);
|
|
497
513
|
};
|
|
498
514
|
const multiSignMethod = camelCase(`multi_sign_${x}`);
|
|
@@ -507,17 +523,17 @@ const createExtensionMethods = client => {
|
|
|
507
523
|
}
|
|
508
524
|
|
|
509
525
|
const signer = wallet.address;
|
|
510
|
-
const signatures =
|
|
526
|
+
const signatures = structuredClone(tx.signatures || tx.signaturesList || []);
|
|
511
527
|
const item = signatures.find(s => s.signer === signer || s.delegator === signer);
|
|
512
528
|
if (!item) {
|
|
513
529
|
throw new Error('Signer not in the list');
|
|
514
530
|
}
|
|
515
531
|
|
|
516
|
-
tx.
|
|
532
|
+
tx.signatures = signatures.map(s => omit(s, ['signature']));
|
|
517
533
|
const { object, buffer } = await txEncodeFn({ tx, wallet });
|
|
518
534
|
|
|
519
535
|
item.signature = await wallet.sign(bytesToHex(buffer));
|
|
520
|
-
object.
|
|
536
|
+
object.signatures = signatures;
|
|
521
537
|
return _formatEncodedTx(object, encoding);
|
|
522
538
|
};
|
|
523
539
|
const multiSignMethod = camelCase(`multi_sign_${x}`);
|
|
@@ -715,8 +731,11 @@ const createExtensionMethods = client => {
|
|
|
715
731
|
|
|
716
732
|
itx.address = toFactoryAddress(itx);
|
|
717
733
|
|
|
718
|
-
isValidFactory
|
|
719
|
-
|
|
734
|
+
// Client-side factory schema validation (isValidFactory → valibot +
|
|
735
|
+
// @ocap/validator) removed in Phase 5: it pulled ~92 KB into every bundle
|
|
736
|
+
// but duplicated validation the server pipeline already performs on
|
|
737
|
+
// sendCreateFactoryTx. Invalid factories now surface as the chain's
|
|
738
|
+
// `factory validation failed: ...` GraphQL error.
|
|
720
739
|
const hash = await client.sendCreateFactoryTx({ tx: { itx }, wallet }, extra);
|
|
721
740
|
return [hash, itx.address];
|
|
722
741
|
};
|
|
@@ -1434,5 +1453,5 @@ const createExtensionMethods = client => {
|
|
|
1434
1453
|
};
|
|
1435
1454
|
};
|
|
1436
1455
|
|
|
1437
|
-
module.exports = { createExtensionMethods };
|
|
1456
|
+
module.exports = { createExtensionMethods, defaultDeps };
|
|
1438
1457
|
//# sourceMappingURL=extension.js.map
|