Skip to content

Feat/enable cross chain queries in smart contracts - #560

Open
ltardivo wants to merge 15 commits into
stagingfrom
feat/cross-chain-innercomputer
Open

ltardivo wants to merge 15 commits into
stagingfrom
feat/cross-chain-innercomputer

Conversation

@ltardivo

@ltardivo ltardivo commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator

This PR adds cross-chain reads. A contract can read one confirmed object from another built-in chain. The host configures the node URL on its own Computer. The contract calls computer.sync(location, chain) and receives plain JSON. The host computer.sync(rev) is unchanged and still returns a smart object.

Lib

New configuration, and a new in-contract call:

const computer = new Computer({
  chain: 'LTC',
  network: 'regtest',
  url: 'http://127.0.0.1:1031',
  remoteChains: {
    BTC: { url: 'http://127.0.0.1:1032' },
  },
})

// Host sync is still one argument. This is a smart object on LTC.
const local = await ltc.sync(rev)

class Reader extends Contract {
  async foreignN(btcRev: string) {
    // Plain JSON from BTC. Methods are not present.
    const remote = await computer.sync(btcRev, 'BTC')
    return remote.n
  }

  async homeN(ltcRev: string) {
    // One argument still reads this contract's own chain. Also plain JSON.
    const home = await computer.sync(ltcRev)
    return home.n
  }
}
  • RemoteChainConfig is an optional field on ComputerOptions. Each entry is { url } for one built-in chain other than the computer's own. The URL is an absolute http or https origin.
  • RemoteChainConfig is published. The two-argument sync overload is on the contract computer, not on Computer.
  • computer.sync(rev, 'LTC') inside an LTC contract is the one-argument read. The home chain is not looked up in remoteChains.
  • The returned _rev stays txid:vout.
  • An unknown chain, a chain with no remoteChains entry, a location that is not a txid or revision, or a missing or unconfirmed transaction invalidates the contract evaluation. A try/catch around that call does not let the transition commit.
  • A bad remoteChains value throws when the Computer is constructed. It does not wait for a contract to run.
  • In the browser, the foreign read joins the evaluation already in progress. Without that, it waits on the same line the home evaluation is holding, and the call deadlocks.

Node

Multi-chain regtest can be tested locally.

  • npm run up:regtest (and down:regtest) starts one stack per chain. The chain named in .env keeps the example host ports; later chains take the next free ports.
  • docker-compose.yml publishes host ports separately from container ports (BCN_HOST_PORT, POSTGRES_HOST_PORT, BITCOIN_RPC_HOST_PORT, BCN_ZMQ_HOST_PORT) and accepts a per-stack env file and log directory.
  • New packages/node/scripts/up-regtest.sh implements the ordering and port allocation.

Breaking changes

Inside a contract, a second argument to computer.sync used to be ignored. It is now the chain name. One-argument computer.sync(location) is unchanged, including computer.sync('BTC'): that string is still a location, not a chain.

No readOnly option is added. Foreign data is plain JSON because the contract computer has no spend methods.

Migration

Existing computers and one-argument sync calls stay as they are. To let a contract read another chain, set remoteChains on the computer that runs the contract:

new Computer({
  chain: 'LTC',
  url: 'http://127.0.0.1:1031',
  remoteChains: {
    BTC: { url: 'http://127.0.0.1:1032' },
  },
})

Do not put the computer's own chain in remoteChains. Set that chain with chain and url.

@ltardivo
ltardivo added this pull request to stack #562 November 5, 2026 22:27
@ltardivo
ltardivo removed this pull request from stack #562 November 5, 2026 23:29
@ltardivo ltardivo changed the title Enable cross chain queries in smart contracts Feat/enable cross chain queries in smart contracts Nov 5, 2026
Describe remoteChains, readOnly, and computer.sync(chain, location)
on the constructor, sync, and Contract querying pages. Publish the
matching types: RemoteChainConfig, the two-argument InnerComputer.sync
overload, and synthesizedRemoteUrl.
… chain keeps the example host ports, and only the later chains move. With the current .env, LTC is first even if you pass BTC LTC.
Add Lib/Contract/cross-chain.md and link it from the contract, constructor, sync, and sandbox pages. Every in-contract read takes the chain as the optional second argument. The published sync overload is sync(location, chain).
@ltardivo
ltardivo force-pushed the feat/cross-chain-innercomputer branch from 8d90270 to 41d661c Compare November 12, 2026 22:31
computer.sync(location, { chain }) and the other in-contract reads take { chain } instead of a chain string. Omit the object, or omit chain, to read this computer. Host Computer.sync still takes one argument.

@ClemensLey ClemensLey left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

This PR documents in-contract reads of another built-in chain (computer.sync(location, { chain: 'BTC' }), and the same optional second argument on every other inner read), adds the matching remoteChains and ChainRead types, and starts one regtest stack per chain from npm run up:regtest with separate host ports. The docs match that behavior: omit the object or chain to read this computer, sync('BTC') stays a location, only chain is accepted, and try/catch does not commit a failed read. The one gap is that a non-revision is described as a non-invalidating Invalid Rev only for load and getAncestors, not for first, prev, next, and last. Mergeable. Thanks marie for spelling out the argument rules.

Issue counts by severity

  • bugs: 0
  • suggestions: 1
  • nits: 0

`try/catch` does not commit. A failed read marks the evaluation, and the public error does not include the node URL. It ends with one copy of “Accessing non-existent on-chain state inside a smart contract is forbidden.”
These locations do not use `sync`’s location check. `load` and `getAncestors` parse a revision inside their own body. A value that is not a revision throws `Invalid Rev` and does not mark the evaluation. `sync(notARev, { chain })` does mark it when `chain` is set. `sync(notARev)` and `sync(notARev, {})` do not: an omitted `chain` is the one-argument read.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] This sentence says load and getAncestors throw Invalid Rev for a value that is not a revision and do not mark the evaluation. first, prev, next, and last do the same, including with { chain } set, so a try/catch around those calls can still commit. That matches the one-argument methods.

Suggestion: Name first, prev, next, and last in that sentence beside load and getAncestors.

load, getAncestors, first, prev, next, and last parse a revision in their own body. A value that is not a revision throws Invalid Rev and does not mark the evaluation, even when { chain } is set. sync(notARev, { chain }) still marks the evaluation. sync(notARev) and sync(notARev, {}) do not, because an omitted chain is the one-argument read.

@ClemensLey ClemensLey left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

This PR documents in-contract reads of another built-in chain (computer.sync(location, { chain: 'BTC' }), and the same optional object on every other inner read), publishes remoteChains and ChainRead, and starts one regtest stack per chain from npm run up:regtest with separate host ports. The docs match that call shape: omit the object or chain to read this computer, sync('BTC') stays a location, the home chain is not looked up in remoteChains, and outer Computer.sync stays one argument. npm run up still publishes the example ports; a second stack does not take those host ports, and container listen ports stay the example values. The GitHub PR body is stale: it still shows computer.sync(btcRev, 'BTC') and says the second argument is the chain name, while a string invalidates and the docs correctly use { chain }. Do not merge until up:regtest provides the daemon conf compose bind-mounts, without overwriting the litecoin.conf the regtest quickstart already created. Thanks ltardivo.

Issue counts by severity

  • bugs: 1
  • suggestions: 0
  • nits: 0

lower=$(printf '%s' "$chain" | tr '[:upper:]' '[:lower:]')
project="bcn-$lower"
out="/tmp/bcn-regtest-$lower.env"
cp "$example" "$out"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[bug] up:regtest copies only chain-setup/$CHAIN/regtest/.env.example and never the daemon conf, but compose still bind-mounts ./${BITCOIN_CONF_FILE} from the package root. The regtest quickstart copies litecoin.conf only, and *.conf is gitignored, so a normal checkout has no bitcoin.conf and the default LTC-then-BTC run cannot start the BTC node. That env file keeps the example BITCOIN_RPC_PASSWORD while the mounted file is whatever conf is already there, so a litecoin.conf whose rpcauth was replaced does not match the LTC stack either.

Suggestion: Copy chain-setup/$CHAIN/regtest/${BITCOIN_CONF_FILE}.example to a path this script owns, and point the compose mount at that file. Leave the package-root conf npm run up uses in place, and do not pair the example password with a conf whose rpcauth was replaced.

ClemensLey and others added 3 commits November 19, 2026 13:54
On the browser stack, _tie pushed a frame for the foreign computer and left it current until the await resumed. A same-turn home read then ran on the foreign chain, and a caught invalidation was dropped with that frame, so the evaluation could commit.

Record the foreign computer on running only. That is what the line check reads, so the foreign sync still joins the evaluation in progress. The contract frame stays current.

The new checks cover Promise.all of a foreign sync and a home getBlockHash, and a caught getTXOs started in that same turn. Node runs them with AsyncLocalStorage hidden. The browser suite runs them in process.
…Compose still bind-mounted ./${BITCOIN_CONF_FILE} from the package root. *.conf is gitignored, so a fresh checkout has no bitcoin.conf, and a litecoin.conf whose rpcauth was replaced would not match the example password in that env file.

Each regtest stack now gets its own copy of chain-setup/$CHAIN/regtest/${BITCOIN_CONF_FILE}.example at packages/node/.regtest/<chain>.conf, and Compose mounts that file. The copy lives under the package because Docker Desktop does not share /tmp: a bind mount there shows up in the container as an empty directory. npm run up is unchanged and still mounts the package-root conf. The example password stays paired with the example rpcauth.

@ClemensLey ClemensLey left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

The published ComputerOptions.remoteChains type, the in-contract { chain } argument, and the detailed cross-chain page match the private implementation: the map is optional and checked in the Computer constructor, a home-chain name is an alias rather than a remoteChains lookup, host Computer.sync stays one argument and returns a smart object, and a foreign sync returns plain JSON with _rev still txid:vout. packages/lib has no src; shipping types/ plus the rebuilt dist/ bundles is the existing publish pattern, and those bundles do contain the new read path. npm run up keeps its current ports when the new host-port variables are unset. down:regtest does not stop every stack up:regtest started, and sync.md overstates which failed reads mark the evaluation.

Issue counts by severity

  • bugs: 3
  • suggestions: 1
  • nits: 0

if [ "$action" = up ]; then
docker compose -p "$project" -f docker-compose.yml --env-file "$out" up -d
else
docker compose -p "$project" -f docker-compose.yml --env-file "$out" down

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[bug] down uses the same chain list as up (arguments, else BCN_REGTEST_CHAINS, else LTC BTC at line 24) and never records the projects it started. docker compose -p bcn-<chain> down therefore only stops that list. After npm run up:regtest -- DOGE PEPE, a later npm run down:regtest stops bcn-ltc and bcn-btc if those exist and leaves bcn-doge and bcn-pepe running, still holding their host ports. packages/docs/Node/index.md:74 shows that exact sequence and says “Stop those stacks”, and line 81 says down:regtest stops the stacks from up:regtest. The script header only shows npm run down:regtest -- LTC BTC, so the user-facing docs and the script disagree. A second up:regtest with a different list also does not remove the previous projects.

Suggestion: On a successful up, write the project names (for example under .regtest/). When down is given no chain arguments, stop that saved set instead of the LTC/BTC default. Make the Node docs example pass the same chain list, or stop saying a bare down:regtest stops a custom up.

Comment thread packages/docs/Lib/Computer/sync.md Outdated

The location’s transaction must be **confirmed**. Missing or mempool-only locations invalidate the contract evaluation. Objects returned inside contracts are deep-cloned plain data (not live proxies for mutation). See [Contract – Querying](../Contract/index.md#querying-inside-of-a-contract).

`computer.sync(location, { chain })` reads one confirmed object on another built-in chain. `location` is a transaction id or `txid:vout` on that chain. The second argument is a plain object, and `chain` is that chain’s name (`'BTC'`, any case). Omit the object, or omit `chain`, to read this computer. The node URL comes from the computer’s [`remoteChains`](./constructor.md) configuration, not from the contract. The result is the same plain JSON as a one-argument `sync`: methods are removed, `bigint` is kept, and `_rev` stays `txid:vout` with no chain prefix. One-argument `sync`, including `sync('BTC')`, is still a read on this computer’s own chain: that string is a location, not a chain name. `{ chain: 'LTC' }` on a Litecoin computer is that same read. The only accepted key is `chain`. A string, a number, `null`, an array, an unknown key, or a third argument invalidates. So does an unknown chain, a chain with no `remoteChains` entry, a `chain` that is not a string, or a location that is not a transaction id or revision. The outer `Computer.sync` shown above does not take `chain`. Inside a contract, every inner-computer method takes the same object, with the same rules as `sync(location, { chain })`. Those methods are listed in [Cross-chain reads](../Contract/cross-chain.md). A host that wants a live object on another chain constructs a `Computer` for that chain and calls one-argument `sync`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[bug] This paragraph says a location that is not a transaction id or revision invalidates, then says every inner-computer method uses the same rules as sync(location, { chain }). That is true for the options object (plain object, only key chain, no third argument). It is not true for the location. In the private InnerComputer, sync rejects a non-txid/non-rev with _invalidate before the read, including when { chain } names the home chain. load, getAncestors, first, prev, next, and last parse the location in their own body, outside _safeCall. A value such as 'nope' throws Invalid Rev and leaves frame.invalid false even when { chain } is set, so a try/catch around that call can still commit. packages/docs/Lib/Contract/cross-chain.md:65 states that exception, but the same page’s line 63 says “try/catch does not commit” with no limit. A contract written from sync.md will treat a caught Invalid Rev from load or prev as a failed evaluation, or the reverse.

Suggestion: Keep the location-invalidation rule on sync only. Point the other methods at the cross-chain page, and limit “try/catch does not commit” to reads that mark the frame.

getBlockHeader(blockHash: string): Promise<string>
sync<T extends Class = any>(location: string, options: ChainRead): Promise<JsonData<T>>
private _syncLocation
decode(txId: string, options?: ChainRead): Promise<TransitionJSON>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[bug] decode and every later method are typed options?: ChainRead. Under strictNullChecks that allows decode(txId, undefined) and forwarding options?: ChainRead. The implementation chooses the home read only when arguments.length < 2. An explicit undefined has length 2, fails the plain-object check, and marks the evaluation (The second argument must be a plain object.). A wrapper that always passes its optional second argument therefore invalidates a home read that would have succeeded as a one-argument call. sync does not have this hole: its second overload requires options: ChainRead (line 57), so passing undefined is a type error. The runtime rule is the same for every method.

Suggestion: Give each method the same two overloads as sync (one argument, or a required ChainRead), so an omitted chain is expressed by omitting the argument rather than passing undefined.

}
export declare const INNER_TXO_QUERY_KEYS: (keyof InnerTXOQuery)[]
export type ChainRead = {
chain?: Chain

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] ChainRead.chain is Chain, the uppercase SUPPORTED_CHAINS union. The docs (sync.md:41, cross-chain.md:43) say the in-contract name is case-insensitive, and the implementation uppercases it before the supported-chain check and the remoteChains lookup ({ chain: 'btc' } reads remoteChains.BTC). The shipped type rejects that call. remoteChains keys are the opposite: they must already be the uppercase id, and btc throws at new Computer. The constructor snippet at packages/docs/Lib/Computer/constructor.md:18 types the map as { [chain: string]: { url: string } }, which accepts lowercase keys, the home chain, and unknown chains. All three throw in the constructor (not a supported chain, or duplicates the home chain), not on the first in-contract read. The published ComputerOptions.remoteChains (types.d.ts:388) correctly limits keys to Chain, but still allows the computer’s own chain, which construction rejects.

Suggestion: Document that map keys are the uppercase chain id and that a bad map throws from new Computer. Either type ChainRead.chain as string, or say the typed form is Chain and that any case is only a runtime convenience. The home-chain exclusion cannot be expressed from a sibling field; the prose should keep saying it throws.

Bare down:regtest stopped LTC and BTC even after up:regtest -- DOGE PEPE.
A successful up now records the chains under .regtest/stacks, and a down
with no chain names stops that set.

sync.md no longer says every inner read invalidates a bad location. That
rule is sync only, and only when chain is set. load, getAncestors, first,
prev, next, and last still throw Invalid Rev and can be caught.

The published ChainRead overloads match sync: one argument, or a required
options object. Passing undefined is not a home read. The docs say the
typed chain id is uppercase, and that a bad remoteChains map throws from
new Computer.

@ClemensLey ClemensLey left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Thanks to ltardivo. The earlier blockers are fixed: down:regtest stops the stacks recorded in .regtest/stacks, the docs separate sync's location invalidation from Invalid Rev, the overloads reject an explicit undefined, and regtest conf copies do not replace the quickstart litecoin.conf. It is not mergeable yet. A later up:regtest assigns the same host ports the previous stacks still hold, so the two commands in the node docs cannot both stay up. Seed the used-port sets from stacks already recorded, or stop documenting that sequence as safe. The PR body still shows computer.sync(btcRev, 'BTC'); the docs use { chain }, which is not a merge blocker.

Issue counts by severity

  • bugs: 1
  • suggestions: 2
  • nits: 0

chain_list="$home_first$others"

seen_chains=''
used_bcn=''

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[bug] used_bcn, used_pg, used_zmq, and used_rpc start empty on every run, and next_free only sees ports assigned in this invocation. Every chain's example BCN_PORT is 1031, POSTGRES_PORT 5432, and BCN_ZMQ_PORT 28332. A dry run of up then up DOGE PEPE prints 1031/5432/28332 for LTC and again for DOGE, and 1032/5433/28333 for BTC and again for PEPE. The node docs show those two commands one after the other and say a later up:regtest leaves the earlier stacks on their host ports, so the second docker compose up cannot bind.

Suggestion: Treat host ports already published by stacks in .regtest/stacks as used before next_free. The chain named in .env should still keep 1031 when it is the one being started and that port is free.

satPerByte?: number,
moduleStorageType?: 'taproot' | 'multisig'
moduleStorageType?: 'taproot' | 'multisig',
remoteChains?: Partial<Record<'LTC' | 'BTC' | 'DOGE', { url: string }>>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] The constructor signature types remoteChains keys as only 'LTC' | 'BTC' | 'DOGE'. The shipped ComputerOptions type is Partial<Record<Chain, { url: string }>>, and Chain is the same five uppercase ids as ChainRead in the contract docs (PEPE and WOJAK included). new Computer accepts those keys, and npm run up:regtest -- DOGE PEPE is how the node docs tell you to publish a Pepecoin URL for that map. A caller who copies this signature cannot type a valid Pepecoin or Wojak entry.

Suggestion: Use the same five-id union as the shipped Chain type and as ChainRead. Keep the note that the type cannot drop the computer's own chain.

Comment thread packages/node/scripts/up-regtest.sh Outdated
mv "$tmp" "$file"
}

# node-secret tests dial the chain named in .env on its example host ports

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] The comment that explains why the chain named in .env keeps the example host ports names an internal test package. That name is not part of the public node docs. The reason itself is right: those ports are the ones npm run up already publishes, so only the later chains should move.

Suggestion: Keep the port reason and drop the internal package name.

A second up:regtest assigned the example host ports again, so it could not bind while the stacks from the first up were still running. Record those ports and treat them as taken. The chain named in .env still keeps the example ports when they are free.

@ClemensLey ClemensLey left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

The previous port-collision bug is fixed for the sequence the node docs show. With the quickstart .env (BCN_CHAIN=LTC), npm run up:regtest records LTC on the example host ports and BTC on the next ones, and a later npm run up:regtest -- DOGE PEPE keeps those ports. Docs and the published .d.ts match the lib-secret { chain } behavior. The fix is not complete. A later up:regtest that also restarts the chain holding the example ports drops those ports from the used set. A dry run of npm run up:regtest -- BTC followed by npm run up:regtest assigns 1031, 5432, and 28332 to LTC while BTC still holds them.

Issue counts by severity

  • bugs: 1
  • suggestions: 0
  • nits: 0

''|*[!A-Z0-9]*) continue ;;
esac
if in_list "$chain_list" "$recorded"; then
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[bug] Recorded host ports are dropped for every chain this command restarts (in_list then continue), on the assumption that docker compose up will replace that project before anyone else binds. Replacement happens only when the loop reaches that chain. A chain ordered earlier can take the ports while the holder is still up.

Dry run with quickstart BCN_CHAIN=LTC and .regtest/hosts containing BTC 1031 5432 28332 8332 (what npm run up:regtest -- BTC publishes): the next npm run up:regtest prints LTC on 1031, 5432, and 28332, and only then BTC on 1032. RPC does not overlap (LTC 19332, BTC 8332). A real docker compose up for bcn-ltc therefore fails the bind, and set -e stops the script before bcn-btc is replaced. The same skip gives LTC DOGE's live 1031/5432/28332 for npm run up:regtest -- DOGE followed by npm run up:regtest -- LTC DOGE.

Suggestion: Seed used_bcn, used_pg, used_zmq, and used_rpc from every .regtest/hosts line, including chains this command restarts. In the loop, if this chain has a recorded line, publish those four host ports again. Otherwise keep next_free. Leave the recorded ports in the used sets until that assignment, so an earlier chain cannot take them. npm run up:regtest -- BTC followed by npm run up:regtest then leaves BTC on 1031 and gives LTC the next free ports. That matches the comment above: the chain named in .env keeps the example ports only when they are free. The sentence in packages/docs/Node/index.md (a later up does not reuse recorded host ports) stays true.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants