JavaScript SDK
@chaindaddy/js puts Chain Daddy on any website. It does Sign in with Chain Daddy (a button, a popup, and a callback page), a coin's apps on its own site, checkout in a popup and, on your server, a check that a store order was paid. Every approval happens on chaindaddy.io, in a popup; your page receives the result.
From a script tag
<script src="https://js.chaindaddy.io/v1/cd.js"></script>It defines window.ChainDaddy and the <cd-signin-button>, <cd-app>, <cd-coin> and <cd-buy> elements.
| URL | Caching | Use |
|---|---|---|
https://js.chaindaddy.io/v1/cd.js | 5 minutes | the current build: fixes reach your site without a change |
https://js.chaindaddy.io/v<version>/cd.js | forever | one exact version, for Subresource Integrity |
https://js.chaindaddy.io/v<version>/cd.js.sri | forever | its sha384-… integrity value |
https://js.chaindaddy.io/v1/cd.json | 5 minutes | {"version","integrity"} of the current build, to print a pinned tag |
To pin a version with Subresource Integrity, read the .sri file next to it and add both attributes:
<script src="https://js.chaindaddy.io/v0.1.0/cd.js"
integrity="sha384-…" crossorigin="anonymous"></script>From npm
npm install @chaindaddy/jsimport { signIn, handleCallback, exchangeCode } from '@chaindaddy/js/signin';
import { defineSignInButton } from '@chaindaddy/js';The package is ESM with type declarations, and safe to import where there is no DOM (a server render). Each release is published with npm provenance from gitlab.com/opencrown/chaindaddy-js.
The API
signIn(options) opens the Chain Daddy popup and resolves with { code, codeVerifier, state, nonce, issuer, clientId, redirectUri } once the person approves. Call it from a click handler, so the browser lets the popup open. If the popup is blocked, the page goes to Chain Daddy instead and signIn resolves null; your callback page then finishes.
If the person closes the window without answering, signIn rejects with an Error whose message is closed: stop your spinner and show the button again, with no error message. A second call while the window is still open brings that window back to the front and returns the same promise.
| Option | |
|---|---|
clientId | your client id: the URL of your client.json, or a registered cdc_ id. On http://localhost, chaindaddy-dev needs neither (Developing locally) |
redirectUri | your callback page, exactly as your client lists it, on the same origin as the page with the button |
scope | default openid; add wallets, profile |
claims | an OpenID Connect claims request (holdings of your coin, crowns), as an object |
signal | an AbortSignal to stop waiting: signIn then rejects with aborted |
If the page with the button or your callback page sends a Cross-Origin-Opener-Policy header, the browser can cut your page off from the popup: signIn then rejects closed straight away, while the person finishes signing in inside the popup and your callback page gets the result as it does after a redirect. Leave the header off those two pages.
handleCallback() runs on your callback page. In the popup it passes the answer back to your page and closes the popup. After a redirect it returns the same result signIn would have.
exchangeCode(result) redeems the code at the token endpoint from the browser (a public client: no secret) and returns { id_token, … }.
Content Security Policy. If your site sends one, allow script-src https://js.chaindaddy.io, and connect-src https://api.chaindaddy.io for exchangeCode. The popup is a window of its own, so it needs no frame-src. The button carries its look in a <style> of its own: under a style-src without 'unsafe-inline' it works but is unstyled. The quickstart's pages run inline scripts, so under a script-src without 'unsafe-inline' move them into files.
Your server must verify the ID token before it trusts anything in it: ES256, keys at https://api.chaindaddy.io/api/v2/oauth/jwks, and check iss, aud (your client id), typ (signin+v1) and exp. It must also refuse a token whose jti it has already accepted. See step 4 of the quickstart. A token checked only in the browser proves nothing.
API types
The package also carries TypeScript types for the public API contract: every stable operation, with its parameters and responses. They are types only. Call the API with fetch.
import type { paths, components } from '@chaindaddy/js/api';
type Order = components['schemas']['IapOrder'];
type Sites = paths['/api/v2/public/crowns/{chain}/{crownId}/sites']['get']['responses'][200]['content']['application/json'];The button
<cd-signin-button
client-id="https://you.example/client.json"
redirect-uri="https://you.example/callback"
scope="openid wallets"
theme="light"
text="signin"></cd-signin-button>
<p id="signed-in"></p>
<p id="signin-error" role="alert"></p>
<script>
// Show who your server says is signed in.
fetch('/me').then((r) => (r.ok ? r.json() : null)).then((me) => {
if (me) document.querySelector('#signed-in').textContent = 'Signed in as ' + me.wallet;
});
document.querySelector('cd-signin-button').addEventListener('cd-signin', async (e) => {
const { id_token } = await ChainDaddy.exchangeCode(e.detail);
const res = await fetch('/session', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id_token }) });
if (!res.ok) {
const { message } = await res.json().catch(() => ({}));
document.querySelector('#signin-error').textContent = message || 'Sign-in did not work. Try again.';
return;
}
location.reload();
});
</script>/session and /me are your own server's: step 4 of the quickstart is that server, whole. It can refuse a sign-in (a token it has already seen, say), so the page shows the server's message instead of moving on.
It fires cd-signin with the result as detail, or cd-signin-error with { message }: access_denied when the person cancels, closed when they close the window without answering (show the button again, not an error). A second click while the window is open brings the window back and fires nothing more. theme is light or dark; text is signin ("Sign in with Chain Daddy") or continue ("Continue with Chain Daddy"). The text and the crown are fixed, and the button is at least 40 pixels tall. Do not restyle it.
Sign returning visitors in on load
Add auto to the button, and render it only for a visitor your site hasn't signed in:
<cd-signin-button client-id="https://you.example/client.json" redirect-uri="https://you.example/callback" auto></cd-signin-button>On load, the page visits Chain Daddy once and comes straight back to your callback page, with nothing shown. A visitor who is signed in to Chain Daddy and has approved your site before comes back with a code, as from a click. Anyone else is taken back to the page they were on, still signed out, with the button where it was. It is tried once per tab. From your own code, ChainDaddy.signInSilently({ clientId, redirectUri, scope }) does the same, and answers false when it was already tried.
The callback page
<script src="https://js.chaindaddy.io/v1/cd.js"></script>
<p id="signin-error" role="alert"></p>
<script>
ChainDaddy.handleCallback().then(async (result) => {
if (!result) return; // the popup handed it back and closed
const { id_token } = await ChainDaddy.exchangeCode(result); // after a redirect: finish here
const res = await fetch('/session', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id_token }) });
if (!res.ok) {
const { message } = await res.json().catch(() => ({}));
document.querySelector('#signin-error').textContent = message || 'Sign-in did not work. Try again.';
return;
}
location.replace(result.returnTo ?? '/');
});
</script>After a sign-in on load (auto), result.returnTo is the page the visitor was on.
A coin's apps on its own site
The same script defines four elements. Put a link inside each one: it shows until the app is ready, and stays if the app can't load.
<script async src="https://js.chaindaddy.io/v1/cd.js"></script>
<!-- One of the coin's apps -->
<cd-app crown="123" chain="base" app="slug"><a href="https://chaindaddy.io/SYM/base">$SYM on Chain Daddy</a></cd-app>
<!-- The coin's card: ticker, chain, price, market cap -->
<cd-coin crown="123" chain="base"><a href="https://chaindaddy.io/SYM/base">$SYM on Chain Daddy</a></cd-coin>
<!-- The coin's identity, for the top of the page: logo, $SYM and name, chain, contract, status, Terms and Creator -->
<cd-identity crown="123" chain="base"><a href="https://chaindaddy.io/SYM/base">$SYM on Chain Daddy</a></cd-identity>
<!-- A button that opens the coin's page in a small window -->
<cd-buy><a href="https://chaindaddy.io/SYM/base">Buy $SYM</a></cd-buy>| Attribute | On | Meaning |
|---|---|---|
crown | cd-app, cd-coin, cd-identity | The coin's id on Chain Daddy: crownId in the keyless coin read |
chain | cd-app, cd-coin, cd-identity | Its chain: a key (base) or a CAIP-2 id (eip155:8453) |
app | cd-app | The app's slug. It must be installed on the coin and allowed on other sites |
mode | cd-app, cd-coin, cd-identity | light or dark. Left out, it follows the visitor's system setting |
density | cd-identity | line (two lines, the default) or stacked (one fact a line, for a narrow column) |
The coin's owner copies each snippet, filled in, from the coin manager. Without it, all three values come from reads that need no key: Without the coin manager.
- Where it works.
cd-coin,cd-identityand read-only apps work on any https site, and on a page your own computer serves athttp://localhostorhttp://127.0.0.1(any port), so you can try them before a site is live. They do not show on a page opened as a file or on any otherhttp://address.cd-buyis a button with no frame, and works wherever the script loads. An app that uses a wallet works only on the coin's verified sites; anywhere else, your own computer included, the link stays. - Events.
cd-app,cd-coinandcd-identityfirecd:readywhen the app or card is showing andcd:unavailablewhen they fall back to the link. The events do not bubble, so listen on the element itself.cd-buyfires neither. - How long it waits.
cd:unavailablefires at once when the frame says it cannot show, and otherwise 8 seconds after the frame started to load. On a page that may not show the app, the browser's console shows a redframe-ancestorserror, and the script's own line follows with the event: You should see. - Colors. Set
--cd-accent,--cd-surface,--cd-text,--cd-text-mutedand--cd-borderon the element or any parent. An app takes the ones its developer chose to take;cd-buyuses them all.cd-identitytakes none: it followsmodeonly, so the page around it cannot fade or restyle what it states. - Size. The element is a block as wide as its container, so your page sets the width. It cannot set the height: the frame tells the element how tall it is, up to 4,000 pixels. An app is at least as tall as its tile on a coin page, or the minimum height it declares if that is more, and grows and shrinks with its content; the coin's card is as tall as its content (Apps on other sites).
- Not the
<cd-app>of a code page. A code page has a tag with the same name, other attributes and the opposite rule: that tag is empty. On your own site, keep the link inside. - Content Security Policy. If your site sends one, allow
script-src https://js.chaindaddy.ioandframe-src https://embed.chaindaddy.io, and forcd-identityalsoconnect-src https://api.chaindaddy.io. - From npm.
import { defineEmbedElements } from '@chaindaddy/js/embed', then calldefineEmbedElements()once in the browser.
The identity above the fold
Put cd-identity where a visitor sees it without scrolling, at the top of the page. Once it is showing, it checks that it sits wholly inside the first screen (as if the page were scrolled to the top) and that nothing hides it, and if so tells Chain Daddy, once a day per browser, with a request from your page that carries no cookies. On a verified site that report keeps checkout, paid apps and the sign-in Verified mark working there. An identity placed below the fold, or inside a hidden or clipped box, sends nothing.
Checkout in a popup
The same script opens a checkout session in a popup, so the buyer pays on chaindaddy.io without leaving your page. Your server opens the session and gives your page its url; the script does the rest.
<script async src="https://js.chaindaddy.io/v1/cd.js"></script>
<a href="https://chaindaddy.io/_pay/cs_0f3a9c1e…" data-cd-checkout data-cd-success="/thanks">Pay with Chain Daddy</a>Start from a plain link to the session. It works with no script at all: the buyer follows it, pays, and comes back to your successUrl. data-cd-checkout turns the same link into a popup when the script has loaded.
| Attribute | Meaning |
|---|---|
data-cd-checkout | Open this element's session in the popup. On a link the session is its href; on anything else, put the session's url in the attribute: <button data-cd-checkout="https://chaindaddy.io/_pay/cs_…"> |
data-cd-success | Optional. The page to go to once the buyer has paid. session_id is added to it, the same way the checkout adds it to your successUrl |
When the visit ends the element fires a cd:checkout event, which bubbles. Its detail says how it ended:
detail.status | What happened | Also in detail |
|---|---|---|
completed | The buyer paid | session: its id, its orderId, and status: complete when the payment is confirmed, paid when it was sent and is still confirming |
cancelled | The buyer left the checkout without paying | session.id |
closed | The popup closed and said nothing. Read the session on your server to know how it ended | |
redirected | The browser blocked the popup, so the page is going to the session by link |
document.addEventListener('cd:checkout', (e) => {
if (e.detail.status === 'completed') showThanks(e.detail.session);
});With data-cd-success the page goes there after completed. Without it, nothing moves: handle the event.
From your own code
button.addEventListener('click', async () => {
const result = await ChainDaddy.checkout({ url: sessionUrl, successUrl: '/thanks' });
// { status: 'completed' | 'cancelled' | 'closed' | 'redirected', session? }
});session.livemode is false for a test store's session.
Call it inside a click, or the browser blocks the popup. If your page does not have the session yet, pass a function that fetches it. The popup opens blank at once and goes to the session when the link arrives:
ChainDaddy.checkout({
url: () => fetch('/api/checkout', { method: 'POST' }).then((r) => r.json()).then((s) => s.url),
});/api/checkout is a route on your own server that opens the session with your store key: the route, and a whole example to run on http://localhost. If the function throws, its promise rejects, or what it returns is not a session link, the blank popup closes and the call rejects.
| Option | |
|---|---|
url | The session's url, or a function that returns it or a promise of it |
successUrl | Optional. Where the page goes after completed, with session_id added. A path on your site or a full address |
From npm: import { checkout, bindCheckoutButtons } from '@chaindaddy/js/checkout', and call bindCheckoutButtons() once in the browser if you use the attribute.
What to know
urlmust be a session link onhttps://chaindaddy.io/_pay/…, theurlyour server got when it opened the session. Anything else is refused: the call rejects, and adata-cd-checkoutlink is left to work as an ordinary link. A query or fragment added to the link is dropped.- A result is for your page's display, not proof of payment. Deliver from your server, on the webhook or by reading the session. Anyone can open your success page by hand.
- Your page must be on one of your coin's verified sites, over https. On any other page the buyer still pays and is returned by link, and your page hears
closed. A test store's session also answers a page onhttp://localhostorhttp://127.0.0.1, on any port. - A blocked popup is not an error. The page goes to the session by link, and the buyer comes back to your
successUrl. - One checkout at a time. While a checkout your page opened is still open, another click shows it again and does not open a second one.
- If your site sends
Cross-Origin-Opener-Policy: same-origin, the browser cuts your page off from every popup it opens: the buyer still pays and is returned by link, and your page hearsclosedstraight away. Sendsame-origin-allow-popupson the page with the button. - Content Security Policy. Allow
script-src https://js.chaindaddy.io. The popup is a window of its own, so it needs noframe-src.
Check a store payment on your server
@chaindaddy/js/verify is for a server. It checks on chain that a store order was paid, without asking Chain Daddy: it reads the checkout contract through a JSON-RPC endpoint you choose. It is not in the script-tag build.
import { verifyPayment, VerifyError, NATIVE_TOKEN } from '@chaindaddy/js/verify';
const result = await verifyPayment(order.verification, {
rpcUrl: process.env.RPC_URL,
expect: { orderId, chainId: 'eip155:8453', token: COIN_ADDRESS, payee: PAYOUT_ADDRESS, amount: 975000n },
});
// { paid, payer, depth, checkout, blockNumber, orderHash, chainId }When the buyer paid with another coin through Chain Daddy's swap-pay contract, payer is null and via is 'swap-pay': the contract paid the order for the buyer, so take the buyer from the order, and do not send funds to the contract.
| Option | |
|---|---|
expect | Required. What you sold, from your own records: orderId, chainId, token (NATIVE_TOKEN for the chain's own coin), payee (your payout address) and amount (the least it must receive; a bigint or a decimal string) |
rpcUrl | Your JSON-RPC endpoint for the order's chain |
request | In place of rpcUrl: a function shaped like ({ method, params }) => result, such as a viem client's request |
fetch | Used with rpcUrl in place of the global fetch |
confirmations | Wait for more confirmations than the order asks for; this can only raise the depth |
signal | An AbortSignal for the requests made through rpcUrl |
It resolves paid: true when the contract says that order was paid, depth blocks deep, and paid: false when it was not (yet). Anything it cannot vouch for is a VerifyError with a code: a block that is not what expect says, a checkout that is not one of ours on that chain, an RPC endpoint on another chain or one that fails. It also checks a Solana order: it finds the finalized transfer through your own RPC endpoint and answers paid, or late for a transfer that landed after the order's deadline (pass signature, the order's txHash, when you have it). Verify a payment has a full example, every code, and the same check by hand.
Check a signed answer
The same entry checks a signed answer: what Chain Daddy says about a coin's registration, signed so you can take it from anyone.
import { verifyAnswer, signingKeysFromRecord } from '@chaindaddy/js/verify';
const answer = await verifyAnswer(jws, { expect: { chain: 'base', symbol: 'FLUXGP' } });
// { status: 'registered', holder, tokenAddress, crownId, symbol, chain, chainId, iat, exp, … }| Option | |
|---|---|
keys | The keys to trust: what signingKeysFromRecord(value) returns for the io.chaindaddy.signing-keys text record on chaindaddy.eth, or JWKs |
jwksUrl | In place of keys: a key set to fetch. With neither, https://api.chaindaddy.io/api/v2/iap/jwks |
expect | What you asked about: chain or chainId, symbol, kind. An answer about anything else is refused |
issuer | The iss to accept. Default https://chaindaddy.io |
clockToleranceSeconds | Seconds past exp an answer is still accepted. Default 0 |
now | The time to check exp against, in Unix seconds. Default: the clock |
fetch, signal | For the key set request |
It resolves the claims, and rejects with a VerifyError for anything it cannot vouch for. A coin that is not registered resolves too, with status: 'not_registered'. It needs Ed25519 in the runtime's Web Crypto (Node 20 or later). Signed answers has the keys on chaindaddy.eth and the check by hand.