@ocap/client 1.30.23 → 1.30.25

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/client.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const { createExtensionMethods } = require('./extension');
2
+ const { verifyTxInclusion } = require('./verify');
2
3
  const GraphQLClientBase = require('./base');
3
4
 
4
5
  /**
@@ -56,5 +57,7 @@ class GraphQLClient extends GraphQLClientBase {
56
57
  }
57
58
  }
58
59
 
60
+ GraphQLClient.verifyTxInclusion = verifyTxInclusion;
61
+
59
62
  module.exports = GraphQLClient;
60
63
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
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"]}
1
+ {"version":3,"sources":["../src/client.js"],"names":["createExtensionMethods","require","verifyTxInclusion","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,MAAM,EAAEC,iBAAF,KAAwBD,QAAQ,UAAR,CAA9B;AACA,MAAME,oBAAoBF,QAAQ,QAAR,CAA1B;;AAEA;;;;;;;;;;;;;;;;;;;AAmBA,MAAMG,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;AACAb,2BAAuB,IAAvB;;AAEA;AACA,QAAIO,QAAJ,EAAc;AACZ,WAAKO,UAAL,GAAkBC,KAAlB,CAAyBC,GAAD,IAAS;AAC/BC,gBAAQC,IAAR,CAAa,0BAAb,EAAyCF,IAAIG,OAA7C;AACD,OAFD;AAGD;AACF;AArC2C;;AAwC9Cf,cAAcF,iBAAd,GAAkCA,iBAAlC;;AAEAkB,OAAOC,OAAP,GAAiBjB,aAAjB","file":"client.js","sourcesContent":["const { createExtensionMethods } = require('./extension');\nconst { verifyTxInclusion } = require('./verify');\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\nGraphQLClient.verifyTxInclusion = verifyTxInclusion;\n\nmodule.exports = GraphQLClient;\n"]}
package/dist/encode.js CHANGED
@@ -80,18 +80,23 @@ function encodeTx({ type, tx, wallet, delegator = '', chainId = '', feeConfig =
80
80
 
81
81
  // ---- Context fetcher (lightweight replacement for client.getContext) ----
82
82
 
83
+ // Same rationale as extension.js's CONTEXT_TTL_MS: fee/gas config can change on
84
+ // chain without the process restarting, so don't cache it forever (#625).
85
+ const CONTEXT_TTL_MS = 30 * 1000;
86
+
83
87
  const contextCache = new Map();
84
88
 
85
89
  /**
86
90
  * Fetch minimal chain context (chainId + fee config) via raw HTTP.
87
- * Cached per endpoint — call clearContextCache() to invalidate.
91
+ * Cached per endpoint for CONTEXT_TTL_MS — call clearContextCache() to invalidate sooner.
88
92
  *
89
93
  * @param {string} chainHost - Chain RPC endpoint URL
90
94
  * @returns {Promise<{ chainId: string, txFee: Array }>}
91
95
  */
92
96
  async function fetchContext(chainHost) {
93
- if (contextCache.has(chainHost)) {
94
- return contextCache.get(chainHost);
97
+ const cached = contextCache.get(chainHost);
98
+ if (cached && Date.now() - cached.fetchedAt < CONTEXT_TTL_MS) {
99
+ return cached.context;
95
100
  }
96
101
 
97
102
  const post = async query => {
@@ -120,7 +125,7 @@ async function fetchContext(chainHost) {
120
125
  txFee: txConfig && txConfig.txFee || []
121
126
  };
122
127
 
123
- contextCache.set(chainHost, context);
128
+ contextCache.set(chainHost, { context, fetchedAt: Date.now() });
124
129
  return context;
125
130
  }
126
131
 
@@ -1 +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,CAAtB;AACA,MAAM,EAAEC,UAAUC,YAAZ,KAA6BF,QAAQ,oBAAR,CAAnC;;AAEA;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3C,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"]}
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","CONTEXT_TTL_MS","contextCache","Map","fetchContext","chainHost","cached","get","fetchedAt","context","post","query","res","fetch","method","headers","body","JSON","stringify","ok","Error","status","json","data","info","state","Promise","all","chainInfo","getChainInfo","txConfig","getForgeState","network","txFee","set","clearContextCache","clear","createTxEncoder","module","exports"],"mappings":"AAAA;;;;;;;;;;AAUA,MAAM,EAAEA,SAAF,KAAgBC,QAAQ,oBAAR,CAAtB;AACA,MAAM,EAAEC,UAAUC,YAAZ,KAA6BF,QAAQ,oBAAR,CAAnC;;AAEA;;;;AAIA,SAASG,eAAT,CAAyBC,MAAzB,EAAiC;AAC/B,MAAI,CAACA,MAAL,EAAa,OAAO,EAAEC,SAAS,E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AAF,EAAYyE,eAAZ,EAA6BjC,YAA7B,EAA2C+B,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\n// Same rationale as extension.js's CONTEXT_TTL_MS: fee/gas config can change on\n// chain without the process restarting, so don't cache it forever (#625).\nconst CONTEXT_TTL_MS = 30 * 1000;\n\nconst contextCache = new Map();\n\n/**\n * Fetch minimal chain context (chainId + fee config) via raw HTTP.\n * Cached per endpoint for CONTEXT_TTL_MS — call clearContextCache() to invalidate sooner.\n *\n * @param {string} chainHost - Chain RPC endpoint URL\n * @returns {Promise<{ chainId: string, txFee: Array }>}\n */\nasync function fetchContext(chainHost) {\n const cached = contextCache.get(chainHost);\n if (cached && Date.now() - cached.fetchedAt < CONTEXT_TTL_MS) {\n return cached.context;\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, fetchedAt: Date.now() });\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,11 +1,13 @@
1
1
  const { get, set, omit, camelCase } = require('./helpers/lite');
2
- const { isValid } = require('@arcblock/did');
2
+ const { isValid, isFromPublicKey, toTypeInfo } = require('@arcblock/did');
3
3
  const ocapProto = require('@ocap/proto/schema');
4
4
  const { toTxHash } = require('@ocap/mcrypto');
5
+ const { fromPublicKey } = require('@ocap/wallet');
5
6
  const { encodeTx: encodeTxCbor, decodeTx: decodeTxCbor } = require('@ocap/message/cbor');
6
7
  const { bytesToHex, toBase58, toBase64, toHex, toBuffer, fromTokenToUnit, fromUnitToToken } = require('@ocap/util');
7
8
  const { DEFAULT_TOKEN_DECIMAL } = require('@ocap/util/lib/constant');
8
9
  const { formatFactoryState, preMintFromFactory: preMintFromFactoryCbor } = require('@ocap/asset/mint/client');
10
+ const { verifyTxInclusion } = require('./verify');
9
11
  const {
10
12
  toDelegateAddress,
11
13
  toAssetAddress: toAssetAddressCbor,
@@ -49,11 +51,16 @@ const filteredTransactions = transactions.filter(x => !['DeclareTx'].includes(x)
49
51
  * @param {GraphQLClient} client
50
52
  * @param {object} [deps=defaultDeps]
51
53
  */
54
+ // Chain-side fee/gas config (txConfig, vaults) can change without a client restart;
55
+ // re-fetch it periodically instead of caching it for the lifetime of the process (#625).
56
+ const CONTEXT_TTL_MS = 30 * 1000;
57
+
52
58
  const createExtensionMethods = (client, deps = defaultDeps) => {
53
59
  Object.defineProperty(client, 'ctx', {
54
60
  value: {
55
61
  loading: false,
56
62
  ready: false,
63
+ fetchedAt: 0,
57
64
  callbacks: []
58
65
  }
59
66
  });
@@ -157,7 +164,7 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
157
164
  * @returns {object}
158
165
  */
159
166
  client.getContext = async () => {
160
- if (client.ctx.ready) {
167
+ if (client.ctx.ready && Date.now() - client.ctx.fetchedAt < CONTEXT_TTL_MS) {
161
168
  return client.context;
162
169
  }
163
170
 
@@ -225,8 +232,10 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
225
232
  getForgeState: forgeStateResult.getForgeState
226
233
  };
227
234
  } catch (err) {
228
- client.ctx.loading = true;
229
- client.ctx.callbacks.forEach(cb => cb(err));
235
+ client.ctx.loading = false;
236
+ const callbacks = client.ctx.callbacks;
237
+ client.ctx.callbacks = [];
238
+ callbacks.forEach(cb => cb(err));
230
239
  throw err;
231
240
  }
232
241
 
@@ -240,9 +249,12 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
240
249
  };
241
250
 
242
251
  client.ctx.ready = true;
252
+ client.ctx.fetchedAt = Date.now();
243
253
  client.ctx.loading = false;
244
254
 
245
- client.ctx.callbacks.forEach(cb => cb());
255
+ const callbacks = client.ctx.callbacks;
256
+ client.ctx.callbacks = [];
257
+ callbacks.forEach(cb => cb());
246
258
 
247
259
  debug('context ready');
248
260
 
@@ -265,6 +277,9 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
265
277
  }
266
278
 
267
279
  const getTokenState = async address => {
280
+ if (typeof address !== 'string' || !/^(?:did:[a-z0-9]+:)?[a-zA-Z0-9_-]+$/.test(address)) {
281
+ throw new Error(`Invalid token address: ${address}`);
282
+ }
268
283
  const {
269
284
  getTokenState: { code, state }
270
285
  } = await client.doRawQuery(`{
@@ -481,14 +496,44 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
481
496
  txSignFn.__tx__ = signMethod;
482
497
  client[signMethod] = txSignFn;
483
498
 
484
- // TODO: verify existing signatures before adding new signatures
499
+ const verifySignerPkBinding = entry => {
500
+ if (!entry || !entry.pk) return;
501
+ const matchesSigner = entry.signer && isFromPublicKey(entry.signer, entry.pk);
502
+ const matchesDelegator = entry.delegator && isFromPublicKey(entry.delegator, entry.pk);
503
+ if (!matchesSigner && !matchesDelegator) {
504
+ throw new Error('Invalid multisig signer public key');
505
+ }
506
+ };
507
+
485
508
  // Generate transaction multi sign function
486
509
  if (multiSignTxs.includes(x)) {
487
- const txMultiSignFn = async ({ tx, wallet, delegator, data, encoding = '' }) => {
510
+ const txMultiSignFn = async ({ tx, wallet, delegator, data, extra: sigExtra = '', encoding = '' }) => {
488
511
  if (typeof wallet.toAddress !== 'function') {
489
512
  throw new Error('Multisig requires a valid wallet');
490
513
  }
491
- tx.signatures = tx.signatures || tx.signaturesList || [];
514
+ const existingSignatures = structuredClone(tx.signatures || tx.signaturesList || []);
515
+ delete tx.signaturesList;
516
+ for (let i = 0; i < existingSignatures.length; i++) {
517
+ const entry = existingSignatures[i] || {};
518
+ verifySignerPkBinding(entry);
519
+ if (entry.signature) {
520
+ if (!entry.pk) {
521
+ throw new Error('Invalid existing multisig signature: missing public key');
522
+ }
523
+ const priorTx = Object.assign({}, tx, {
524
+ signatures: [omit(entry, ['signature', 'extra'])].concat(existingSignatures.slice(i + 1))
525
+ });
526
+ const { buffer: priorBuffer } = await txEncodeFn({ tx: priorTx, wallet });
527
+ const entryDid = entry.delegator || entry.signer;
528
+ const entryType = entryDid ? toTypeInfo(entryDid) : undefined;
529
+ const verified = await fromPublicKey(entry.pk, entryType).verify(bytesToHex(priorBuffer), entry.signature, true, entry.extra);
530
+ if (!verified) {
531
+ throw new Error('Invalid existing multisig signature');
532
+ }
533
+ }
534
+ }
535
+
536
+ tx.signatures = existingSignatures;
492
537
  if (delegator) {
493
538
  tx.signatures.unshift({
494
539
  pk: wallet.publicKey,
@@ -507,6 +552,9 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
507
552
 
508
553
  const { object, buffer } = await txEncodeFn({ tx, wallet });
509
554
  object.signatures[0].signature = await wallet.sign(bytesToHex(buffer));
555
+ if (sigExtra) {
556
+ object.signatures[0].extra = typeof sigExtra === 'string' ? sigExtra : JSON.stringify(sigExtra);
557
+ }
510
558
  return _formatEncodedTx(object, encoding);
511
559
  };
512
560
  const multiSignMethod = camelCase(`multi_sign_${x}`);
@@ -515,22 +563,58 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
515
563
  }
516
564
 
517
565
  if (multiSignV2Txs.includes(x)) {
518
- const txMultiSignFn = async ({ tx, wallet, encoding = '' }) => {
566
+ const txMultiSignFn = async ({ tx, wallet, delegator = '', extra: sigExtra = '', encoding = '' }) => {
519
567
  if (typeof wallet.toAddress !== 'function') {
520
568
  throw new Error('Multisig requires a valid wallet');
521
569
  }
522
570
 
523
571
  const signer = wallet.address;
524
572
  const signatures = structuredClone(tx.signatures || tx.signaturesList || []);
525
- const item = signatures.find(s => s.signer === signer || s.delegator === signer);
573
+ delete tx.signaturesList;
574
+ const matchEntry = s => delegator ? s.signer === signer && (!s.delegator || s.delegator === delegator) || s.signer === delegator && (!s.delegator || s.delegator === signer) : s.signer === signer || s.delegator === signer;
575
+ const item = signatures.find(s => !s.signature && matchEntry(s)) || signatures.find(matchEntry);
526
576
  if (!item) {
527
577
  throw new Error('Signer not in the list');
528
578
  }
579
+ const hasExistingSignature = signatures.some(s => s !== item && s && s.signature);
580
+ if (!hasExistingSignature) {
581
+ if (delegator && item.signer === delegator && !item.delegator) {
582
+ item.delegator = signer;
583
+ }
584
+ if (!item.pk && (item.delegator === signer || !item.delegator && item.signer === signer)) {
585
+ item.pk = wallet.publicKey;
586
+ }
587
+ }
529
588
 
530
- tx.signatures = signatures.map(s => omit(s, ['signature']));
589
+ for (const entry of signatures) {
590
+ if (!entry || !entry.pk) {
591
+ throw new Error('Multisig requires all signature entries to specify pk before signing');
592
+ }
593
+ verifySignerPkBinding(entry);
594
+ }
595
+
596
+ tx.signatures = signatures.map(s => omit(s, ['signature', 'extra']));
531
597
  const { object, buffer } = await txEncodeFn({ tx, wallet });
532
598
 
599
+ for (const rawEntry of signatures) {
600
+ const entry = rawEntry || {};
601
+ if (entry.signature && rawEntry !== item) {
602
+ if (!entry.pk) {
603
+ throw new Error('Invalid existing multisig signature: missing public key');
604
+ }
605
+ const entryDid = entry.delegator || entry.signer;
606
+ const entryType = entryDid ? toTypeInfo(entryDid) : undefined;
607
+ const verified = await fromPublicKey(entry.pk, entryType).verify(bytesToHex(buffer), entry.signature, true, entry.extra);
608
+ if (!verified) {
609
+ throw new Error('Invalid existing multisig signature');
610
+ }
611
+ }
612
+ }
613
+
533
614
  item.signature = await wallet.sign(bytesToHex(buffer));
615
+ if (sigExtra) {
616
+ item.extra = typeof sigExtra === 'string' ? sigExtra : JSON.stringify(sigExtra);
617
+ }
534
618
  object.signatures = signatures;
535
619
  return _formatEncodedTx(object, encoding);
536
620
  };
@@ -1449,6 +1533,133 @@ const createExtensionMethods = (client, deps = defaultDeps) => {
1449
1533
  wallet
1450
1534
  }, extra);
1451
1535
  };
1536
+
1537
+ /**
1538
+ * Query the latest (or height-specific) Ledger Checkpoint.
1539
+ *
1540
+ * @memberof GraphQLClient
1541
+ * @function
1542
+ * @name GraphQLClient#getLatestCheckpoint
1543
+ * @param {object} [params]
1544
+ * @param {number} [params.height]
1545
+ * @returns {Promise<object>}
1546
+ */
1547
+ client.getLatestCheckpoint = async ({ height } = {}) => {
1548
+ const args = height !== undefined && height !== null ? `(height: ${Number(height)})` : '';
1549
+ const res = await client.doRawQuery(`{
1550
+ getLatestCheckpoint${args} {
1551
+ code
1552
+ checkpoint {
1553
+ height
1554
+ sequence
1555
+ prevSequence
1556
+ txRoot
1557
+ txCount
1558
+ stateRoot
1559
+ timestamp
1560
+ prevCheckpoint
1561
+ proposer
1562
+ hash
1563
+ signature
1564
+ }
1565
+ }
1566
+ }`);
1567
+ return get(res, 'getLatestCheckpoint') || { code: 'ERROR', checkpoint: null };
1568
+ };
1569
+
1570
+ /**
1571
+ * Query a Ledger entry by transaction hash or sequence number.
1572
+ *
1573
+ * @memberof GraphQLClient
1574
+ * @function
1575
+ * @name GraphQLClient#getLedgerEntry
1576
+ * @param {object} [params]
1577
+ * @param {string} [params.hash]
1578
+ * @param {number} [params.sequence]
1579
+ * @returns {Promise<object>}
1580
+ */
1581
+ client.getLedgerEntry = async ({ hash, sequence } = {}) => {
1582
+ const argParts = [];
1583
+ if (hash !== undefined && hash !== null) {
1584
+ argParts.push(`hash: ${JSON.stringify(String(hash))}`);
1585
+ }
1586
+ if (sequence !== undefined && sequence !== null) {
1587
+ argParts.push(`sequence: ${Number(sequence)}`);
1588
+ }
1589
+ const args = argParts.length > 0 ? `(${argParts.join(', ')})` : '';
1590
+ const res = await client.doRawQuery(`{
1591
+ getLedgerEntry${args} {
1592
+ code
1593
+ entry {
1594
+ sequence
1595
+ hash
1596
+ from
1597
+ nonce
1598
+ pk
1599
+ signature
1600
+ txRaw
1601
+ tx
1602
+ txType
1603
+ timestamp
1604
+ chainId
1605
+ entryHash
1606
+ txExtra
1607
+ stateCommitHash
1608
+ finalized
1609
+ }
1610
+ }
1611
+ }`);
1612
+ return get(res, 'getLedgerEntry') || { code: 'ERROR', entry: null };
1613
+ };
1614
+
1615
+ /**
1616
+ * Query a Ledger Merkle inclusion proof and its covering Checkpoint by sequence number.
1617
+ *
1618
+ * @memberof GraphQLClient
1619
+ * @function
1620
+ * @name GraphQLClient#getMerkleProof
1621
+ * @param {object} params
1622
+ * @param {number} params.sequence
1623
+ * @returns {Promise<object>}
1624
+ */
1625
+ client.getMerkleProof = async ({ sequence } = {}) => {
1626
+ const res = await client.doRawQuery(`{
1627
+ getMerkleProof(sequence: ${Number(sequence)}) {
1628
+ code
1629
+ proof {
1630
+ index
1631
+ leaf
1632
+ proof
1633
+ root
1634
+ }
1635
+ checkpoint {
1636
+ height
1637
+ sequence
1638
+ prevSequence
1639
+ txRoot
1640
+ txCount
1641
+ stateRoot
1642
+ timestamp
1643
+ prevCheckpoint
1644
+ proposer
1645
+ hash
1646
+ signature
1647
+ }
1648
+ }
1649
+ }`);
1650
+ return get(res, 'getMerkleProof') || { code: 'ERROR', proof: null, checkpoint: null };
1651
+ };
1652
+
1653
+ /**
1654
+ * Cryptographically verify transaction inclusion in a signed Checkpoint (< 1ms, zero network I/O).
1655
+ *
1656
+ * @memberof GraphQLClient
1657
+ * @function
1658
+ * @name GraphQLClient#verifyTxInclusion
1659
+ * @param {object} params
1660
+ * @returns {Promise<{ verified: boolean, reason?: string }>}
1661
+ */
1662
+ client.verifyTxInclusion = params => verifyTxInclusion(params);
1452
1663
  };
1453
1664
 
1454
1665
  module.exports = { createExtensionMethods, defaultDeps };