@ocap/client 1.30.2 → 1.30.3

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/encode.js ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Lightweight transaction encoder — only depends on @ocap/message.
3
+ *
4
+ * Cuts out @ocap/asset (~11 MB), @arcblock/did-util, graphql, @arcblock/sdk-util,
5
+ * and the full client/extension.js dependency tree.
6
+ *
7
+ * Unavoidable: @ocap/message → @ocap/proto (~1.7 MB) + google-protobuf (~800 KB).
8
+ *
9
+ * @module @ocap/client/encode
10
+ */
11
+ const { createMessage, toTypeUrl } = require('@ocap/message');
12
+
13
+ /**
14
+ * Normalize wallet to { address, publicKey }.
15
+ * Handles @ocap/wallet instances, plain objects with pk or publicKey.
16
+ */
17
+ function normalizeWallet(wallet) {
18
+ if (!wallet) return { address: '', publicKey: '' };
19
+ if (typeof wallet.toAddress === 'function') {
20
+ return { address: wallet.address, publicKey: wallet.publicKey };
21
+ }
22
+ return {
23
+ address: wallet.address,
24
+ publicKey: wallet.pk || wallet.publicKey || ''
25
+ };
26
+ }
27
+
28
+ /**
29
+ * Encode a transaction to protobuf binary.
30
+ *
31
+ * Pure function — no network IO, no side effects.
32
+ * Logic extracted from extension.js txEncodeFn for standalone use.
33
+ *
34
+ * @param {object} params
35
+ * @param {string} params.type - Transaction type name, e.g. 'TransferV2Tx'
36
+ * @param {object} params.tx - Transaction data (same shape as client.encodeXxxTx({ tx }))
37
+ * @param {object} params.wallet - Wallet { address, publicKey|pk }
38
+ * @param {string} [params.delegator=''] - Delegator address
39
+ * @param {string} [params.chainId=''] - Chain ID (from getChainInfo)
40
+ * @param {Array} [params.feeConfig=[]] - Fee config [{ typeUrl, fee }] (from getForgeState)
41
+ * @returns {{ object: object, buffer: Buffer }}
42
+ */
43
+ function encodeTx({ type, tx, wallet, delegator = '', chainId = '', feeConfig = [] }) {
44
+ const w = normalizeWallet(wallet);
45
+ const address = tx.from || w.address;
46
+ const pk = tx.pk || w.publicKey;
47
+ const nonce = typeof tx.nonce === 'undefined' ? Date.now() : tx.nonce;
48
+ const resolvedChainId = tx.chainId || chainId;
49
+
50
+ let signatures = [];
51
+ if (Array.isArray(tx.signatures)) {
52
+ signatures = tx.signatures;
53
+ }
54
+ if (Array.isArray(tx.signaturesList)) {
55
+ signatures = tx.signaturesList;
56
+ }
57
+
58
+ // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
59
+ const itx = tx.itx && tx.itx.typeUrl && tx.itx.value ? tx.itx : { type, value: tx.itx };
60
+
61
+ const typeUrl = itx.typeUrl || toTypeUrl(itx.type);
62
+ const fee = feeConfig.find(t => t.typeUrl === typeUrl);
63
+
64
+ const txObj = createMessage('Transaction', {
65
+ from: tx.delegator ? address : delegator || address,
66
+ nonce,
67
+ pk,
68
+ chainId: resolvedChainId,
69
+ signature: tx.signature || Buffer.from([]),
70
+ signatures,
71
+ delegator: tx.delegator || (delegator ? address : ''),
72
+ itx,
73
+ serviceFee: fee ? fee.fee : '0'
74
+ });
75
+
76
+ const bytes = txObj.serializeBinary();
77
+ return { object: txObj.toObject(), buffer: Buffer.from(bytes) };
78
+ }
79
+
80
+ // ---- Context fetcher (lightweight replacement for client.getContext) ----
81
+
82
+ const contextCache = new Map();
83
+
84
+ /**
85
+ * Fetch minimal chain context (chainId + fee config) via raw HTTP.
86
+ * Cached per endpoint — call clearContextCache() to invalidate.
87
+ *
88
+ * @param {string} chainHost - Chain RPC endpoint URL
89
+ * @returns {Promise<{ chainId: string, txFee: Array }>}
90
+ */
91
+ async function fetchContext(chainHost) {
92
+ if (contextCache.has(chainHost)) {
93
+ return contextCache.get(chainHost);
94
+ }
95
+
96
+ const post = async query => {
97
+ const res = await fetch(chainHost, {
98
+ method: 'POST',
99
+ headers: { 'content-type': 'application/json' },
100
+ body: JSON.stringify({ query })
101
+ });
102
+ if (!res.ok) {
103
+ throw new Error(`fetchContext: HTTP ${res.status} from ${chainHost}`);
104
+ }
105
+ return (await res.json()).data;
106
+ };
107
+
108
+ const [info, state] = await Promise.all([post('{ getChainInfo { code info { network } } }'), post('{ getForgeState { code state { txConfig { txFee { fee typeUrl } } } } }')]);
109
+
110
+ // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
111
+ const chainInfo = info && info.getChainInfo && info.getChainInfo.info;
112
+ // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
113
+ const txConfig = state && state.getForgeState && state.getForgeState.state && state.getForgeState.state.txConfig;
114
+
115
+ const context = {
116
+ // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
117
+ chainId: chainInfo && chainInfo.network || '',
118
+ // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
119
+ txFee: txConfig && txConfig.txFee || []
120
+ };
121
+
122
+ contextCache.set(chainHost, context);
123
+ return context;
124
+ }
125
+
126
+ function clearContextCache() {
127
+ contextCache.clear();
128
+ }
129
+
130
+ /**
131
+ * Create a TxEncoder function compatible with @arcblock/did-connect-js WalletAuthenticator.
132
+ *
133
+ * Usage:
134
+ * const { createTxEncoder } = require('@ocap/client/encode');
135
+ * const authenticator = new WalletAuthenticator({ txEncoder: createTxEncoder(), ... });
136
+ *
137
+ * @returns {function} async ({ type, data, wallet, chainHost }) => Buffer
138
+ */
139
+ function createTxEncoder() {
140
+ return async ({ type, data, wallet, chainHost }) => {
141
+ const context = await fetchContext(chainHost);
142
+ const { buffer } = encodeTx({
143
+ type,
144
+ tx: data,
145
+ wallet,
146
+ // biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
147
+ chainId: data && data.chainId || context.chainId,
148
+ feeConfig: context.txFee
149
+ });
150
+ return buffer;
151
+ };
152
+ }
153
+
154
+ module.exports = { encodeTx, createTxEncoder, fetchContext, clearContextCache };
155
+ //# sourceMappingURL=encode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/encode.js"],"names":["createMessage","toTypeUrl","require","normalizeWallet","wallet","address","publicKey","toAddress","pk","encodeTx","type","tx","delegator","chainId","feeConfig","w","from","nonce","Date","now","resolvedChainId","signatures","Array","isArray","signaturesList","itx","typeUrl","value","fee","find","t","txObj","signature","Buffer","serviceFee","bytes","serializeBinary","object","toObject","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,aAAF,EAAiBC,SAAjB,KAA+BC,QAAQ,eAAR,CAArC;;AAEA;;;;AAIA,SAASC,eAAT,CAAyBC,MAAzB,EAAiC;AAC/B,MAAI,CAACA,MAAL,EAAa,OAAO,EAAEC,SAAS,EAAX,EAAeC,WAAW,EAA1B,EAAP;AACb,MAAI,OAAOF,OAAOG,SAAd,KAA4B,UAAhC,EAA4C;AAC1C,WAAO,EAAEF,SAASD,OAAOC,OAAlB,EAA2BC,WAAWF,OAAOE,SAA7C,EAAP;AACD;AACD,SAAO;AACLD,aAASD,OAAOC,OADX;AAELC,eAAWF,OAAOI,EAAP,IAAaJ,OAAOE,SAApB,IAAiC;AAFvC,GAAP;AAID;;AAED;;;;;;;;;;;;;;;AAeA,SAASG,QAAT,CAAkB,EAAEC,IAAF,EAAQC,EAAR,EAAYP,MAAZ,EAAoBQ,YAAY,EAAhC,EAAoCC,UAAU,EAA9C,EAAkDC,YAAY,EAA9D,EAAlB,EAAsF;AACpF,QAAMC,IAAIZ,gBAAgBC,MAAhB,CAAV;AACA,QAAMC,UAAUM,GAAGK,IAAH,IAAWD,EAAEV,OAA7B;AACA,QAAMG,KAAKG,GAAGH,EAAH,IAASO,EAAET,SAAtB;AACA,QAAMW,QAAQ,OAAON,GAAGM,KAAV,KAAoB,WAApB,GAAkCC,KAAKC,GAAL,EAAlC,GAA+CR,GAAGM,KAAhE;AACA,QAAMG,kB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AA2B;AACzB,SAAO,OAAO,EAAEhE,IAAF,EAAQiD,IAAR,EAAcvD,MAAd,EAAsBuC,SAAtB,EAAP,KAA6C;AAClD,UAAMyB,UAAU,MAAM1B,aAAaC,SAAb,CAAtB;AACA,UAAM,EAAEJ,MAAF,KAAa9B,SAAS;AAC1BC,UAD0B;AAE1BC,UAAIgD,IAFsB;AAG1BvD,YAH0B;AAI1B;AACAS,eAAU8C,QAAQA,KAAK9C,OAAd,IAA0BuD,QAAQvD,OALjB;AAM1BC,iBAAWsD,QAAQE;AANO,KAAT,CAAnB;AAQA,WAAO/B,MAAP;AACD,GAXD;AAYD;;AAEDoC,OAAOC,OAAP,GAAiB,EAAEnE,QAAF,EAAYiE,eAAZ,EAA6BhC,YAA7B,EAA2C8B,iBAA3C,EAAjB","file":"encode.js","sourcesContent":["/**\n * Lightweight transaction encoder — only depends on @ocap/message.\n *\n * Cuts out @ocap/asset (~11 MB), @arcblock/did-util, graphql, @arcblock/sdk-util,\n * and the full client/extension.js dependency tree.\n *\n * Unavoidable: @ocap/message → @ocap/proto (~1.7 MB) + google-protobuf (~800 KB).\n *\n * @module @ocap/client/encode\n */\nconst { createMessage, toTypeUrl } = require('@ocap/message');\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 txObj = createMessage('Transaction', {\n from: tx.delegator ? address : delegator || address,\n nonce,\n pk,\n chainId: resolvedChainId,\n signature: tx.signature || Buffer.from([]),\n signatures,\n delegator: tx.delegator || (delegator ? address : ''),\n itx,\n serviceFee: fee ? fee.fee : '0',\n });\n\n const bytes = txObj.serializeBinary();\n return { object: txObj.toObject(), 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"]}