@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/dist/client.js
CHANGED
|
@@ -2,9 +2,15 @@ const { createExtensionMethods } = require('./extension');
|
|
|
2
2
|
const GraphQLClientBase = require('./base');
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* An http client that
|
|
5
|
+
* An http client that reads/writes OCAP blockchain data. CBOR-only wire
|
|
6
|
+
* encoding — browser / Worker / Node bundles stay off the protobuf runtime.
|
|
6
7
|
*
|
|
7
|
-
*
|
|
8
|
+
* For back-compat with chain nodes that still decode legacy protobuf
|
|
9
|
+
* transactions, or to test the dual-encoding path end-to-end, import the
|
|
10
|
+
* `@ocap/client/legacy` subpath which ships both encoders.
|
|
11
|
+
*
|
|
12
|
+
* Internal protobuf repeated-field naming (`xxxList`) is preserved in
|
|
13
|
+
* response objects the chain returns — this is a server-side convention.
|
|
8
14
|
*
|
|
9
15
|
* @class
|
|
10
16
|
* @example
|
|
@@ -21,14 +27,24 @@ class GraphQLClient extends GraphQLClientBase {
|
|
|
21
27
|
* @constructor
|
|
22
28
|
* @param {string} endpoint the graphql endpoint of the chain
|
|
23
29
|
* @param {boolean} autoInit whether auto warmup context
|
|
30
|
+
* @param {object} [options] reserved for future use
|
|
24
31
|
* @see GraphQLClient#getQueries
|
|
25
32
|
* @see GraphQLClient#getMutations
|
|
26
33
|
* @see GraphQLClient#getSubscriptions
|
|
27
34
|
* @see GraphQLClient#getTxSendMethods
|
|
28
35
|
* @see GraphQLClient#getTxEncodeMethods
|
|
29
36
|
*/
|
|
30
|
-
constructor(endpoint, autoInit = true) {
|
|
37
|
+
constructor(endpoint, autoInit = true, options = {}) {
|
|
31
38
|
super(endpoint);
|
|
39
|
+
// Phase 4.10 — the main entry is CBOR-only. `options.encoding` is
|
|
40
|
+
// rejected here so callers that still pass it don't silently get a CBOR
|
|
41
|
+
// client when they expected protobuf. Swap to `@ocap/client/legacy`
|
|
42
|
+
// (the only supported way to get the protobuf path now).
|
|
43
|
+
// biome-ignore lint/complexity/useOptionalChain: babel-preset-env 1.7 cannot parse optional chaining
|
|
44
|
+
if (options && options.encoding && options.encoding !== 'cbor') {
|
|
45
|
+
throw new Error(`@ocap/client main entry is CBOR-only (got encoding=${JSON.stringify(options.encoding)}). Import '@ocap/client/legacy' for the protobuf path.`);
|
|
46
|
+
}
|
|
47
|
+
this.txEncoding = 'cbor';
|
|
32
48
|
createExtensionMethods(this);
|
|
33
49
|
|
|
34
50
|
// warmup the context
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.js"],"names":["createExtensionMethods","require","GraphQLClientBase","GraphQLClient","constructor","endpoint","autoInit","getContext","catch","err","console","warn","message","module","exports"],"mappings":"AAAA,MAAM,EAAEA,sBAAF,KAA6BC,QAAQ,aAAR,CAAnC;AACA,MAAMC,oBAAoBD,QAAQ,QAAR,CAA1B;;AAEA
|
|
1
|
+
{"version":3,"sources":["../src/client.js"],"names":["createExtensionMethods","require","GraphQLClientBase","GraphQLClient","constructor","endpoint","autoInit","options","encoding","Error","JSON","stringify","txEncoding","getContext","catch","err","console","warn","message","module","exports"],"mappings":"AAAA,MAAM,EAAEA,sBAAF,KAA6BC,QAAQ,aAAR,CAAnC;AACA,MAAMC,oBAAoBD,QAAQ,QAAR,CAA1B;;AAEA;;;;;;;;;;;;;;;;;;;AAmBA,MAAME,aAAN,SAA4BD,iBAA5B,CAA8C;AAC5C;;;;;;;;;;;;;AAaAE,cAAYC,QAAZ,EAAsBC,WAAW,IAAjC,EAAuCC,UAAU,EAAjD,EAAqD;AACnD,UAAMF,QAAN;AACA;AACA;AACA;AACA;AACA;AACA,QAAIE,WAAWA,QAAQC,QAAnB,IAA+BD,QAAQC,QAAR,KAAqB,MAAxD,EAAgE;AAC9D,YAAM,IAAIC,KAAJ,CACH,sDAAqDC,KAAKC,SAAL,CACpDJ,QAAQC,QAD4C,CAEpD,wDAHE,CAAN;AAKD;AACD,SAAKI,UAAL,GAAkB,MAAlB;AACAZ,2BAAuB,IAAvB;;AAEA;AACA,QAAIM,QAAJ,EAAc;AACZ,WAAKO,UAAL,GAAkBC,KAAlB,CAAyBC,GAAD,IAAS;AAC/BC,gBAAQC,IAAR,CAAa,0BAAb,EAAyCF,IAAIG,OAA7C;AACD,OAFD;AAGD;AACF;AArC2C;;AAwC9CC,OAAOC,OAAP,GAAiBjB,aAAjB","file":"client.js","sourcesContent":["const { createExtensionMethods } = require('./extension');\nconst GraphQLClientBase = require('./base');\n\n/**\n * An http client that reads/writes OCAP blockchain data. CBOR-only wire\n * encoding — browser / Worker / Node bundles stay off the protobuf runtime.\n *\n * For back-compat with chain nodes that still decode legacy protobuf\n * transactions, or to test the dual-encoding path end-to-end, import the\n * `@ocap/client/legacy` subpath which ships both encoders.\n *\n * Internal protobuf repeated-field naming (`xxxList`) is preserved in\n * response objects the chain returns — this is a server-side convention.\n *\n * @class\n * @example\n * const GraphQLClient = require('@ocap/client');\n *\n * const client = new GraphQLClient('https://beta.abtnetwork.io/api');\n *\n * const res = await client.getChainInfo();\n */\nclass GraphQLClient extends GraphQLClientBase {\n /**\n * Create an instance of GraphQLClient\n *\n * @constructor\n * @param {string} endpoint the graphql endpoint of the chain\n * @param {boolean} autoInit whether auto warmup context\n * @param {object} [options] reserved for future use\n * @see GraphQLClient#getQueries\n * @see GraphQLClient#getMutations\n * @see GraphQLClient#getSubscriptions\n * @see GraphQLClient#getTxSendMethods\n * @see GraphQLClient#getTxEncodeMethods\n */\n constructor(endpoint, autoInit = true, options = {}) {\n super(endpoint);\n // Phase 4.10 — the main entry is CBOR-only. `options.encoding` is\n // rejected here so callers that still pass it don't silently get a CBOR\n // client when they expected protobuf. Swap to `@ocap/client/legacy`\n // (the only supported way to get the protobuf path now).\n // biome-ignore lint/complexity/useOptionalChain: babel-preset-env 1.7 cannot parse optional chaining\n if (options && options.encoding && options.encoding !== 'cbor') {\n throw new Error(\n `@ocap/client main entry is CBOR-only (got encoding=${JSON.stringify(\n options.encoding\n )}). Import '@ocap/client/legacy' for the protobuf path.`\n );\n }\n this.txEncoding = 'cbor';\n createExtensionMethods(this);\n\n // warmup the context\n if (autoInit) {\n this.getContext().catch((err) => {\n console.warn('failed to warmup context', err.message);\n });\n }\n }\n}\n\nmodule.exports = GraphQLClient;\n"]}
|
package/dist/encode.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight transaction encoder — only depends on @ocap/message/cbor.
|
|
3
|
+
*
|
|
4
|
+
* Cuts out @ocap/asset (~11 MB), @arcblock/did-util, graphql, @arcblock/sdk-util,
|
|
5
|
+
* and the full client/extension.js dependency tree. After the CBOR switch the
|
|
6
|
+
* google-protobuf runtime is no longer pulled in on the client; tree-shaken
|
|
7
|
+
* bundles only include @ocap/proto/schema + cborg (~8 KB).
|
|
8
|
+
*
|
|
9
|
+
* @module @ocap/client/encode
|
|
10
|
+
*/
|
|
11
|
+
const { toTypeUrl } = require('@ocap/proto/schema');
|
|
12
|
+
const { encodeTx: encodeTxCbor } = require('@ocap/message/cbor');
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Normalize wallet to { address, publicKey }.
|
|
16
|
+
* Handles @ocap/wallet instances, plain objects with pk or publicKey.
|
|
17
|
+
*/
|
|
18
|
+
function normalizeWallet(wallet) {
|
|
19
|
+
if (!wallet) return { address: '', publicKey: '' };
|
|
20
|
+
if (typeof wallet.toAddress === 'function') {
|
|
21
|
+
return { address: wallet.address, publicKey: wallet.publicKey };
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
address: wallet.address,
|
|
25
|
+
publicKey: wallet.pk || wallet.publicKey || ''
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Encode a transaction to protobuf binary.
|
|
31
|
+
*
|
|
32
|
+
* Pure function — no network IO, no side effects.
|
|
33
|
+
* Logic extracted from extension.js txEncodeFn for standalone use.
|
|
34
|
+
*
|
|
35
|
+
* @param {object} params
|
|
36
|
+
* @param {string} params.type - Transaction type name, e.g. 'TransferV2Tx'
|
|
37
|
+
* @param {object} params.tx - Transaction data (same shape as client.encodeXxxTx({ tx }))
|
|
38
|
+
* @param {object} params.wallet - Wallet { address, publicKey|pk }
|
|
39
|
+
* @param {string} [params.delegator=''] - Delegator address
|
|
40
|
+
* @param {string} [params.chainId=''] - Chain ID (from getChainInfo)
|
|
41
|
+
* @param {Array} [params.feeConfig=[]] - Fee config [{ typeUrl, fee }] (from getForgeState)
|
|
42
|
+
* @returns {{ object: object, buffer: Buffer }}
|
|
43
|
+
*/
|
|
44
|
+
function encodeTx({ type, tx, wallet, delegator = '', chainId = '', feeConfig = [] }) {
|
|
45
|
+
const w = normalizeWallet(wallet);
|
|
46
|
+
const address = tx.from || w.address;
|
|
47
|
+
const pk = tx.pk || w.publicKey;
|
|
48
|
+
const nonce = typeof tx.nonce === 'undefined' ? Date.now() : tx.nonce;
|
|
49
|
+
const resolvedChainId = tx.chainId || chainId;
|
|
50
|
+
|
|
51
|
+
let signatures = [];
|
|
52
|
+
if (Array.isArray(tx.signatures)) {
|
|
53
|
+
signatures = tx.signatures;
|
|
54
|
+
}
|
|
55
|
+
if (Array.isArray(tx.signaturesList)) {
|
|
56
|
+
signatures = tx.signaturesList;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
60
|
+
const itx = tx.itx && tx.itx.typeUrl && tx.itx.value ? tx.itx : { type, value: tx.itx };
|
|
61
|
+
|
|
62
|
+
const typeUrl = itx.typeUrl || toTypeUrl(itx.type);
|
|
63
|
+
const fee = feeConfig.find(t => t.typeUrl === typeUrl);
|
|
64
|
+
|
|
65
|
+
const txParams = {
|
|
66
|
+
from: tx.delegator ? address : delegator || address,
|
|
67
|
+
nonce,
|
|
68
|
+
pk,
|
|
69
|
+
chainId: resolvedChainId,
|
|
70
|
+
signature: tx.signature || new Uint8Array(0),
|
|
71
|
+
signatures,
|
|
72
|
+
delegator: tx.delegator || (delegator ? address : ''),
|
|
73
|
+
itx,
|
|
74
|
+
serviceFee: fee ? fee.fee : '0'
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const bytes = encodeTxCbor(txParams);
|
|
78
|
+
return { object: txParams, buffer: Buffer.from(bytes) };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ---- Context fetcher (lightweight replacement for client.getContext) ----
|
|
82
|
+
|
|
83
|
+
const contextCache = new Map();
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Fetch minimal chain context (chainId + fee config) via raw HTTP.
|
|
87
|
+
* Cached per endpoint — call clearContextCache() to invalidate.
|
|
88
|
+
*
|
|
89
|
+
* @param {string} chainHost - Chain RPC endpoint URL
|
|
90
|
+
* @returns {Promise<{ chainId: string, txFee: Array }>}
|
|
91
|
+
*/
|
|
92
|
+
async function fetchContext(chainHost) {
|
|
93
|
+
if (contextCache.has(chainHost)) {
|
|
94
|
+
return contextCache.get(chainHost);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const post = async query => {
|
|
98
|
+
const res = await fetch(chainHost, {
|
|
99
|
+
method: 'POST',
|
|
100
|
+
headers: { 'content-type': 'application/json' },
|
|
101
|
+
body: JSON.stringify({ query })
|
|
102
|
+
});
|
|
103
|
+
if (!res.ok) {
|
|
104
|
+
throw new Error(`fetchContext: HTTP ${res.status} from ${chainHost}`);
|
|
105
|
+
}
|
|
106
|
+
return (await res.json()).data;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const [info, state] = await Promise.all([post('{ getChainInfo { code info { network } } }'), post('{ getForgeState { code state { txConfig { txFee { fee typeUrl } } } } }')]);
|
|
110
|
+
|
|
111
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
112
|
+
const chainInfo = info && info.getChainInfo && info.getChainInfo.info;
|
|
113
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
114
|
+
const txConfig = state && state.getForgeState && state.getForgeState.state && state.getForgeState.state.txConfig;
|
|
115
|
+
|
|
116
|
+
const context = {
|
|
117
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
118
|
+
chainId: chainInfo && chainInfo.network || '',
|
|
119
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
120
|
+
txFee: txConfig && txConfig.txFee || []
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
contextCache.set(chainHost, context);
|
|
124
|
+
return context;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function clearContextCache() {
|
|
128
|
+
contextCache.clear();
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Create a TxEncoder function compatible with @arcblock/did-connect-js WalletAuthenticator.
|
|
133
|
+
*
|
|
134
|
+
* Usage:
|
|
135
|
+
* const { createTxEncoder } = require('@ocap/client/encode');
|
|
136
|
+
* const authenticator = new WalletAuthenticator({ txEncoder: createTxEncoder(), ... });
|
|
137
|
+
*
|
|
138
|
+
* @returns {function} async ({ type, data, wallet, chainHost }) => Buffer
|
|
139
|
+
*/
|
|
140
|
+
function createTxEncoder() {
|
|
141
|
+
return async ({ type, data, wallet, chainHost }) => {
|
|
142
|
+
const context = await fetchContext(chainHost);
|
|
143
|
+
const { buffer } = encodeTx({
|
|
144
|
+
type,
|
|
145
|
+
tx: data,
|
|
146
|
+
wallet,
|
|
147
|
+
// biome-ignore lint/complexity/useOptionalChain: Babel 6 does not support optional chaining
|
|
148
|
+
chainId: data && data.chainId || context.chainId,
|
|
149
|
+
feeConfig: context.txFee
|
|
150
|
+
});
|
|
151
|
+
return buffer;
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
module.exports = { encodeTx, createTxEncoder, fetchContext, clearContextCache };
|
|
156
|
+
//# 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","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,QAAQtD,OALjB;AAM1BC,iBAAWqD,QAAQE;AANO,KAAT,CAAnB;AAQA,WAAOhC,MAAP;AACD,GAXD;AAYD;;AAEDqC,OAAOC,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/dist/extension.js
CHANGED
|
@@ -1,39 +1,55 @@
|
|
|
1
|
-
const get = require('
|
|
2
|
-
const set = require('lodash/set');
|
|
3
|
-
const omit = require('lodash/omit');
|
|
4
|
-
const cloneDeep = require('lodash/cloneDeep');
|
|
5
|
-
const camelCase = require('lodash/camelCase');
|
|
1
|
+
const { get, set, omit, camelCase } = require('./helpers/lite');
|
|
6
2
|
const { isValid } = require('@arcblock/did');
|
|
7
|
-
const ocapProto = require('@ocap/proto');
|
|
3
|
+
const ocapProto = require('@ocap/proto/schema');
|
|
8
4
|
const { toTxHash } = require('@ocap/mcrypto');
|
|
9
|
-
const {
|
|
5
|
+
const { encodeTx: encodeTxCbor, decodeTx: decodeTxCbor } = require('@ocap/message/cbor');
|
|
10
6
|
const { bytesToHex, toBase58, toBase64, toHex, toBuffer, fromTokenToUnit, fromUnitToToken } = require('@ocap/util');
|
|
11
7
|
const { DEFAULT_TOKEN_DECIMAL } = require('@ocap/util/lib/constant');
|
|
12
|
-
const { formatFactoryState, preMintFromFactory
|
|
8
|
+
const { formatFactoryState, preMintFromFactory: preMintFromFactoryCbor } = require('@ocap/asset/mint/client');
|
|
13
9
|
const {
|
|
14
10
|
toDelegateAddress,
|
|
15
|
-
toAssetAddress,
|
|
16
|
-
toFactoryAddress,
|
|
17
|
-
toTokenAddress,
|
|
18
|
-
toTokenFactoryAddress,
|
|
11
|
+
toAssetAddress: toAssetAddressCbor,
|
|
12
|
+
toFactoryAddress: toFactoryAddressCbor,
|
|
13
|
+
toTokenAddress: toTokenAddressCbor,
|
|
14
|
+
toTokenFactoryAddress: toTokenFactoryAddressCbor,
|
|
19
15
|
toStakeAddress,
|
|
20
|
-
toRollupAddress
|
|
21
|
-
} = require('@arcblock/did-util');
|
|
16
|
+
toRollupAddress: toRollupAddressCbor
|
|
17
|
+
} = require('@arcblock/did-util/cbor');
|
|
22
18
|
|
|
23
19
|
const debug = require('debug')(require('../package.json').name);
|
|
24
20
|
|
|
25
|
-
const { transactions, typeUrls, multiSignTxs, multiSignV2Txs } = ocapProto;
|
|
21
|
+
const { transactions, typeUrls, toTypeUrl, multiSignTxs, multiSignV2Txs } = ocapProto;
|
|
22
|
+
|
|
23
|
+
// Default CBOR-only dependency bundle. `@ocap/client/legacy` re-invokes
|
|
24
|
+
// `createExtensionMethods` with a protobuf-wired bundle so the main entry
|
|
25
|
+
// stays free of `google-protobuf` / `*_pb.js`. See README §4.7 / §4.10.
|
|
26
|
+
const defaultDeps = {
|
|
27
|
+
encodeTx: encodeTxCbor,
|
|
28
|
+
decodeTx: decodeTxCbor,
|
|
29
|
+
preMintFromFactory: preMintFromFactoryCbor,
|
|
30
|
+
toAssetAddress: toAssetAddressCbor,
|
|
31
|
+
toFactoryAddress: toFactoryAddressCbor,
|
|
32
|
+
toTokenAddress: toTokenAddressCbor,
|
|
33
|
+
toTokenFactoryAddress: toTokenFactoryAddressCbor,
|
|
34
|
+
toRollupAddress: toRollupAddressCbor
|
|
35
|
+
};
|
|
26
36
|
|
|
27
37
|
// FIXME: delete this after @ocap/proto updated
|
|
28
38
|
const filteredTransactions = transactions.filter(x => !['DeclareTx'].includes(x));
|
|
29
39
|
|
|
30
40
|
/**
|
|
31
|
-
* Generate extension methods on the fly
|
|
41
|
+
* Generate extension methods on the fly.
|
|
42
|
+
*
|
|
43
|
+
* The `deps` parameter lets the `@ocap/client/legacy` subpath re-invoke this
|
|
44
|
+
* factory with protobuf-wired encoders and address helpers. Callers of the
|
|
45
|
+
* main entry use the default CBOR bundle and never drag `google-protobuf`
|
|
46
|
+
* or any `*_pb.js` module into the graph.
|
|
32
47
|
*
|
|
33
48
|
* @public
|
|
34
49
|
* @param {GraphQLClient} client
|
|
50
|
+
* @param {object} [deps=defaultDeps]
|
|
35
51
|
*/
|
|
36
|
-
const createExtensionMethods = client => {
|
|
52
|
+
const createExtensionMethods = (client, deps = defaultDeps) => {
|
|
37
53
|
Object.defineProperty(client, 'ctx', {
|
|
38
54
|
value: {
|
|
39
55
|
loading: false,
|
|
@@ -42,6 +58,17 @@ const createExtensionMethods = client => {
|
|
|
42
58
|
}
|
|
43
59
|
});
|
|
44
60
|
|
|
61
|
+
const {
|
|
62
|
+
encodeTx,
|
|
63
|
+
decodeTx,
|
|
64
|
+
preMintFromFactory,
|
|
65
|
+
toAssetAddress,
|
|
66
|
+
toFactoryAddress,
|
|
67
|
+
toTokenAddress,
|
|
68
|
+
toTokenFactoryAddress,
|
|
69
|
+
toRollupAddress
|
|
70
|
+
} = deps;
|
|
71
|
+
|
|
45
72
|
/**
|
|
46
73
|
* Format big number presentation amount to token number
|
|
47
74
|
*
|
|
@@ -111,17 +138,6 @@ const createExtensionMethods = client => {
|
|
|
111
138
|
*/
|
|
112
139
|
client.getTxMultiSignMethods = () => multiSignTxs.concat(multiSignV2Txs).map(x => camelCase(`multi_sign_${x}`));
|
|
113
140
|
|
|
114
|
-
/**
|
|
115
|
-
* Get protobuf message class by name, only supports forge-built-in types
|
|
116
|
-
*
|
|
117
|
-
* @memberof GraphQLClient
|
|
118
|
-
* @function
|
|
119
|
-
* @name GraphQLClient#getType
|
|
120
|
-
* @param {string} x
|
|
121
|
-
* @returns {class|null} message type
|
|
122
|
-
*/
|
|
123
|
-
client.getType = x => getMessageType(x).fn;
|
|
124
|
-
|
|
125
141
|
/**
|
|
126
142
|
* Decode transaction buffer/base64/base58 to an object
|
|
127
143
|
*
|
|
@@ -131,10 +147,7 @@ const createExtensionMethods = client => {
|
|
|
131
147
|
* @param {buffer|hex|base48|base64} input
|
|
132
148
|
* @returns {object} transaction object
|
|
133
149
|
*/
|
|
134
|
-
client.decodeTx = input =>
|
|
135
|
-
const Transaction = client.getType('Transaction');
|
|
136
|
-
return Transaction.deserializeBinary(toBuffer(input)).toObject();
|
|
137
|
-
};
|
|
150
|
+
client.decodeTx = input => decodeTx(toBuffer(input));
|
|
138
151
|
|
|
139
152
|
/**
|
|
140
153
|
* Ensure a connection is bootstrapped with some meta info fetched from chain node
|
|
@@ -339,10 +352,14 @@ const createExtensionMethods = client => {
|
|
|
339
352
|
signatures = tx.signaturesList;
|
|
340
353
|
}
|
|
341
354
|
|
|
342
|
-
// Determine itx
|
|
355
|
+
// Determine itx. If the caller already wrapped tx.itx as {type, value}
|
|
356
|
+
// via a prior sign call (e.g. signExchangeTx → multiSignExchangeV2Tx),
|
|
357
|
+
// unwrap and re-tag with the current outer type to avoid double-nesting.
|
|
343
358
|
let itx = null;
|
|
344
359
|
if (tx.itx.typeUrl && tx.itx.value) {
|
|
345
360
|
itx = tx.itx;
|
|
361
|
+
} else if (tx.itx.type && tx.itx.value && !Array.isArray(tx.itx.value)) {
|
|
362
|
+
itx = { type: x, value: tx.itx.value };
|
|
346
363
|
} else {
|
|
347
364
|
itx = { type: x, value: tx.itx };
|
|
348
365
|
}
|
|
@@ -350,22 +367,22 @@ const createExtensionMethods = client => {
|
|
|
350
367
|
const type = itx.typeUrl || toTypeUrl(itx.type);
|
|
351
368
|
const feeConfig = get(context, 'txConfig.txFee', []).find(t => t.typeUrl === type);
|
|
352
369
|
|
|
353
|
-
const
|
|
370
|
+
const txParams = {
|
|
354
371
|
from: tx.delegator ? address : delegator || address,
|
|
355
372
|
nonce,
|
|
356
373
|
pk,
|
|
357
374
|
chainId,
|
|
358
|
-
signature: tx.signature ||
|
|
375
|
+
signature: tx.signature || new Uint8Array(0),
|
|
359
376
|
signatures,
|
|
360
377
|
delegator: tx.delegator || (delegator ? address : ''),
|
|
361
378
|
itx,
|
|
362
379
|
serviceFee: feeConfig ? feeConfig.fee : '0'
|
|
363
|
-
}
|
|
364
|
-
const txToSignBytes =
|
|
380
|
+
};
|
|
381
|
+
const txToSignBytes = encodeTx(txParams);
|
|
365
382
|
|
|
366
|
-
debug(`encodeTx.${x}.
|
|
383
|
+
debug(`encodeTx.${x}.txParams`, txParams);
|
|
367
384
|
|
|
368
|
-
return { object:
|
|
385
|
+
return { object: txParams, buffer: Buffer.from(txToSignBytes) };
|
|
369
386
|
};
|
|
370
387
|
|
|
371
388
|
const encodeMethod = camelCase(`encode_${x}`);
|
|
@@ -414,11 +431,10 @@ const createExtensionMethods = client => {
|
|
|
414
431
|
return new Promise(async (resolve, reject) => {
|
|
415
432
|
let txHash = null;
|
|
416
433
|
try {
|
|
417
|
-
const
|
|
418
|
-
const txBytes = txMsg.serializeBinary();
|
|
434
|
+
const txBytes = encodeTx(encoded);
|
|
419
435
|
const txStr = toBase64(txBytes);
|
|
420
436
|
txHash = toTxHash(txBytes);
|
|
421
|
-
debug(`sendTx.${x}.
|
|
437
|
+
debug(`sendTx.${x}.txParams`, encoded);
|
|
422
438
|
const { hash } = await client.sendTx({ tx: txStr, commit, extra: typeof txExtra === 'string' ? txExtra : JSON.stringify(txExtra) }, extra);
|
|
423
439
|
resolve(hash);
|
|
424
440
|
} catch (err) {
|
|
@@ -472,16 +488,16 @@ const createExtensionMethods = client => {
|
|
|
472
488
|
if (typeof wallet.toAddress !== 'function') {
|
|
473
489
|
throw new Error('Multisig requires a valid wallet');
|
|
474
490
|
}
|
|
475
|
-
tx.
|
|
491
|
+
tx.signatures = tx.signatures || tx.signaturesList || [];
|
|
476
492
|
if (delegator) {
|
|
477
|
-
tx.
|
|
493
|
+
tx.signatures.unshift({
|
|
478
494
|
pk: wallet.publicKey,
|
|
479
495
|
signer: delegator,
|
|
480
496
|
delegator: wallet.address,
|
|
481
497
|
data
|
|
482
498
|
});
|
|
483
499
|
} else {
|
|
484
|
-
tx.
|
|
500
|
+
tx.signatures.unshift({
|
|
485
501
|
pk: wallet.publicKey,
|
|
486
502
|
signer: wallet.address,
|
|
487
503
|
delegator: '',
|
|
@@ -490,7 +506,7 @@ const createExtensionMethods = client => {
|
|
|
490
506
|
}
|
|
491
507
|
|
|
492
508
|
const { object, buffer } = await txEncodeFn({ tx, wallet });
|
|
493
|
-
object.
|
|
509
|
+
object.signatures[0].signature = await wallet.sign(bytesToHex(buffer));
|
|
494
510
|
return _formatEncodedTx(object, encoding);
|
|
495
511
|
};
|
|
496
512
|
const multiSignMethod = camelCase(`multi_sign_${x}`);
|
|
@@ -505,17 +521,17 @@ const createExtensionMethods = client => {
|
|
|
505
521
|
}
|
|
506
522
|
|
|
507
523
|
const signer = wallet.address;
|
|
508
|
-
const signatures =
|
|
524
|
+
const signatures = structuredClone(tx.signatures || tx.signaturesList || []);
|
|
509
525
|
const item = signatures.find(s => s.signer === signer || s.delegator === signer);
|
|
510
526
|
if (!item) {
|
|
511
527
|
throw new Error('Signer not in the list');
|
|
512
528
|
}
|
|
513
529
|
|
|
514
|
-
tx.
|
|
530
|
+
tx.signatures = signatures.map(s => omit(s, ['signature']));
|
|
515
531
|
const { object, buffer } = await txEncodeFn({ tx, wallet });
|
|
516
532
|
|
|
517
533
|
item.signature = await wallet.sign(bytesToHex(buffer));
|
|
518
|
-
object.
|
|
534
|
+
object.signatures = signatures;
|
|
519
535
|
return _formatEncodedTx(object, encoding);
|
|
520
536
|
};
|
|
521
537
|
const multiSignMethod = camelCase(`multi_sign_${x}`);
|
|
@@ -713,8 +729,11 @@ const createExtensionMethods = client => {
|
|
|
713
729
|
|
|
714
730
|
itx.address = toFactoryAddress(itx);
|
|
715
731
|
|
|
716
|
-
isValidFactory
|
|
717
|
-
|
|
732
|
+
// Client-side factory schema validation (isValidFactory → valibot +
|
|
733
|
+
// @ocap/validator) removed in Phase 5: it pulled ~92 KB into every bundle
|
|
734
|
+
// but duplicated validation the server pipeline already performs on
|
|
735
|
+
// sendCreateFactoryTx. Invalid factories now surface as the chain's
|
|
736
|
+
// `factory validation failed: ...` GraphQL error.
|
|
718
737
|
const hash = await client.sendCreateFactoryTx({ tx: { itx }, wallet }, extra);
|
|
719
738
|
return [hash, itx.address];
|
|
720
739
|
};
|
|
@@ -1432,5 +1451,5 @@ const createExtensionMethods = client => {
|
|
|
1432
1451
|
};
|
|
1433
1452
|
};
|
|
1434
1453
|
|
|
1435
|
-
module.exports = { createExtensionMethods };
|
|
1454
|
+
module.exports = { createExtensionMethods, defaultDeps };
|
|
1436
1455
|
//# sourceMappingURL=extension.js.map
|