Skip to content

Commit

Permalink
refactor(examples): switch to the entry pkg to simplify package.json
Browse files Browse the repository at this point in the history
  • Loading branch information
homura committed Dec 16, 2023
1 parent 48cba6f commit efc4550
Show file tree
Hide file tree
Showing 17 changed files with 183 additions and 1,031 deletions.
10 changes: 4 additions & 6 deletions examples/cardano-lock-namiwallet/CardanoWitnessLock.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { blockchain } from "@ckb-lumos/base";
import { molecule } from "@ckb-lumos/codec";
import { blockchain, table } from "@ckb-lumos/lumos/codec";

const { Byte32, Bytes } = blockchain;
const Byte64 = blockchain.createFixedHexBytesCodec(64);

export const CardanoWitnessLock = molecule.table(
export const CardanoWitnessLock = table(
{
pubkey: Byte32,
pubkey: blockchain.Byte32,
signature: Byte64,
sig_structure: Bytes,
sig_structure: blockchain.Bytes,
},
["pubkey", "signature", "sig_structure"]
);
9 changes: 4 additions & 5 deletions examples/cardano-lock-namiwallet/lib.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { bytes } from "@ckb-lumos/codec";
import { blockchain } from "@ckb-lumos/base";
import { hexify, blockchain } from "@ckb-lumos/lumos/codec";
import { BI, Cell, config, helpers, RPC, commons, Indexer } from "@ckb-lumos/lumos";
import {
COSESign1Builder,
Expand Down Expand Up @@ -144,7 +143,7 @@ export async function transfer(options: Options): Promise<string> {
);

const tmpWitnessArgs = blockchain.WitnessArgs.pack({ lock: placeHolder });
const witness = bytes.hexify(tmpWitnessArgs);
const witness = hexify(tmpWitnessArgs);

for (let i = 0; i < tx.inputs.toArray().length; i++) {
tx = tx.update("witnesses", (witnesses) => witnesses.push(witness));
Expand All @@ -166,15 +165,15 @@ export async function transfer(options: Options): Promise<string> {
const label = Label.new_int(Int.new_negative(BigNum.from_str("2")));
const CBORPubkey = signedKey.header(label)!;

const signedWitnessArgs = bytes.hexify(
const signedWitnessArgs = hexify(
CardanoWitnessLock.pack({
pubkey: CBORPubkey.as_bytes()!.buffer,
signature: COSESignature.signature().buffer,
sig_structure: toSign.buffer,
})
);

const signedWitness = bytes.hexify(blockchain.WitnessArgs.pack({ lock: signedWitnessArgs }));
const signedWitness = hexify(blockchain.WitnessArgs.pack({ lock: signedWitnessArgs }));
tx = tx.update("witnesses", (witnesses) => witnesses.set(0, signedWitness));

const signedTx = helpers.createTransactionFromSkeleton(tx);
Expand Down
5 changes: 4 additions & 1 deletion examples/cardano-lock-namiwallet/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,15 @@
"author": "",
"license": "MIT",
"dependencies": {
"@ckb-lumos/lumos": "next",
"@ckb-lumos/lumos": "canary",
"@emurgo/cardano-message-signing-asmjs": "^1.0.1",
"@emurgo/cardano-serialization-lib-asmjs": "^10.0.4",
"@types/react": "^18.0.25",
"@types/react-dom": "^18.0.9",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"parcel": "^2.9.3"
}
}
4 changes: 0 additions & 4 deletions examples/exchange-sudt-for-ckb/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@
"typescript": "5.0.4"
},
"dependencies": {
"@ckb-lumos/base": "canary",
"@ckb-lumos/bi": "canary",
"@ckb-lumos/codec": "canary",
"@ckb-lumos/common-scripts": "canary",
"@ckb-lumos/lumos": "canary",
"@types/react": "^18.0.25",
"@types/react-dom": "^18.0.9",
Expand Down
31 changes: 15 additions & 16 deletions examples/exchange-sudt-for-ckb/src/lib.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import { Indexer, helpers, Address, Script, RPC, hd, config, Cell, commons, BI } from "@ckb-lumos/lumos";
import { sudt } from "@ckb-lumos/common-scripts";
import { BIish } from "@ckb-lumos/bi";
import { payFeeByFeeRate } from "@ckb-lumos/common-scripts/lib/common";
import { addCellDep } from "@ckb-lumos/common-scripts/lib/helper";
import { Indexer, helpers, Address, Script, RPC, hd, config, Cell, commons, BI, BIish } from "@ckb-lumos/lumos";
import { sudt, common } from "@ckb-lumos/lumos/common-scripts";
import { addCellDep } from "@ckb-lumos/lumos/helpers";
import { hexify, Uint128, blockchain } from "@ckb-lumos/lumos/codec";
import { computeScriptHash } from "@ckb-lumos/lumos/utils";
import { List } from "immutable";
import { computeScriptHash } from "@ckb-lumos/base/lib/utils";
import { bytes } from "@ckb-lumos/codec";
import { blockchain } from "@ckb-lumos/base";

export const { AGGRON4 } = config.predefined;
const CKB_RPC_URL = "https://testnet.ckb.dev/rpc";
Expand Down Expand Up @@ -53,7 +50,7 @@ export const issueSUDT = async (privateKey: string) => {
config: AGGRON4,
});

txSkeleton = await payFeeByFeeRate(txSkeleton, [account.address], 1000, undefined, { config: AGGRON4 });
txSkeleton = await common.payFeeByFeeRate(txSkeleton, [account.address], 1000, undefined, { config: AGGRON4 });
const tx = signTx(txSkeleton, [privateKey]);

const txHash = await rpc.sendTransaction(tx, "passthrough");
Expand Down Expand Up @@ -122,7 +119,7 @@ export async function transferCKB2SUDT(issuerPrivateKey: string, holderPrivateKe
break;
}
inputs = inputs.push(cell);
total = total.add(sudt.unpackAmount(cell.data));
total = total.add(Uint128.unpack(cell.data));
}
return inputs;
});
Expand All @@ -146,7 +143,7 @@ export async function transferCKB2SUDT(issuerPrivateKey: string, holderPrivateKe
lock: holderAccountInfo.lockScript,
type: issuerTypeScript,
},
data: sudt.packAmount(SUDTAmount),
data: hexify(Uint128.pack(SUDTAmount)),
};

console.log(calculateSUDTAmountSum(issuerSUDTCells).toBigInt());
Expand All @@ -157,7 +154,7 @@ export async function transferCKB2SUDT(issuerPrivateKey: string, holderPrivateKe
lock: issuerAccountInfo.lockScript,
type: issuerTypeScript,
},
data: sudt.packAmount(calculateSUDTAmountSum(issuerSUDTCells).sub(SUDTAmount)),
data: hexify(Uint128.pack(calculateSUDTAmountSum(issuerSUDTCells).sub(SUDTAmount))),
};

SUDTTargetOutput.cellOutput.capacity = BI.from(helpers.minimalCellCapacity(SUDTTargetOutput)).toHexString();
Expand Down Expand Up @@ -238,7 +235,7 @@ export async function transferCKB2SUDT(issuerPrivateKey: string, holderPrivateKe
lock: "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
};

const witnessArgs = bytes.hexify(blockchain.WitnessArgs.pack(placeholderWitness));
const witnessArgs = hexify(blockchain.WitnessArgs.pack(placeholderWitness));

for (let index = 0; index < txSkeleton.inputs.size; index++) {
witnesses = witnesses.push(witnessArgs);
Expand All @@ -248,7 +245,9 @@ export async function transferCKB2SUDT(issuerPrivateKey: string, holderPrivateKe
});

console.log(txSkeleton.toJS());
txSkeleton = await payFeeByFeeRate(txSkeleton, [holderAccountInfo.address], 1000, undefined, { config: AGGRON4 });
txSkeleton = await common.payFeeByFeeRate(txSkeleton, [holderAccountInfo.address], 1000, undefined, {
config: AGGRON4,
});

// STEP2: sign the transaction skeleton
const tx = signTx(txSkeleton, [issuerPrivateKey, holderPrivateKey, issuerPrivateKey]);
Expand All @@ -274,7 +273,7 @@ export function calculateSUDTAmountSum(cells: Cell[]) {
let amount = BI.from(0);
for (const cell of cells) {
if (cell.cellOutput.type?.codeHash === AGGRON4.SCRIPTS.SUDT.CODE_HASH) {
amount = amount.add(sudt.unpackAmount(cell.data));
amount = amount.add(Uint128.unpack(cell.data));
}
}

Expand Down Expand Up @@ -310,7 +309,7 @@ export async function fetchSUDTBalance(address: string, issuerLockScript: Script
let amount = BI.from(0);

for await (const cell of collector.collect()) {
amount = amount.add(sudt.unpackAmount(cell.data));
amount = amount.add(Uint128.unpack(cell.data));
}
return amount;
}
Expand Down
12 changes: 6 additions & 6 deletions examples/omni-lock-metamask/lib.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { bytes } from "@ckb-lumos/codec";
import { blockchain } from "@ckb-lumos/base";
import { BI, Cell, helpers, Indexer, RPC, config, commons } from "@ckb-lumos/lumos";
import { blockchain, bytify, hexify } from "@ckb-lumos/lumos/codec";

const CKB_RPC_URL = "https://testnet.ckb.dev/rpc";
const rpc = new RPC(CKB_RPC_URL);
const indexer = new Indexer(CKB_RPC_URL);
Expand Down Expand Up @@ -30,7 +30,7 @@ interface Options {
to: string;
amount: string;
}
const SECP_SIGNATURE_PLACEHOLDER = bytes.hexify(
const SECP_SIGNATURE_PLACEHOLDER = hexify(
new Uint8Array(
commons.omnilock.OmnilockWitnessLock.pack({
signature: new Uint8Array(65).buffer,
Expand Down Expand Up @@ -100,7 +100,7 @@ export async function transfer(options: Options): Promise<string> {
)
);

const witness = bytes.hexify(blockchain.WitnessArgs.pack({ lock: SECP_SIGNATURE_PLACEHOLDER }));
const witness = hexify(blockchain.WitnessArgs.pack({ lock: SECP_SIGNATURE_PLACEHOLDER }));

// fill txSkeleton's witness with placeholder
for (let i = 0; i < tx.inputs.toArray().length; i++) {
Expand All @@ -118,10 +118,10 @@ export async function transfer(options: Options): Promise<string> {
if (v >= 27) v -= 27;
signedMessage = "0x" + signedMessage.slice(2, -2) + v.toString(16).padStart(2, "0");

const signedWitness = bytes.hexify(
const signedWitness = hexify(
blockchain.WitnessArgs.pack({
lock: commons.omnilock.OmnilockWitnessLock.pack({
signature: bytes.bytify(signedMessage).buffer,
signature: bytify(signedMessage).buffer,
}),
})
);
Expand Down
4 changes: 1 addition & 3 deletions examples/omni-lock-metamask/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@
"author": "",
"license": "MIT",
"dependencies": {
"@ckb-lumos/base": "next",
"@ckb-lumos/codec": "next",
"@ckb-lumos/lumos": "next",
"@ckb-lumos/lumos": "canary",
"@types/react": "^18.0.25",
"@types/react-dom": "^18.0.9",
"react": "18.2.0",
Expand Down
40 changes: 21 additions & 19 deletions examples/omni-lock-secp256k1-blake160/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React, { useState } from "react";
import { helpers, Script } from "@ckb-lumos/lumos";
import { key } from '@ckb-lumos/hd';
import { Script, hd } from "@ckb-lumos/lumos";
import { ec as EC } from "elliptic";
import ReactDOM from "react-dom";
import { capacityOf, CONFIG, buildTransfer, signByPrivateKey, sendTransaction } from "./lib";
import { encodeToAddress } from "@ckb-lumos/lumos/helpers";

const app = document.getElementById("root");
ReactDOM.render(<App />, app);
Expand All @@ -26,17 +26,10 @@ export function Connect({ onConnect }: ConnectProps) {
<div>
<input value={privateKey} onChange={(e) => setPrivateKey(e.target.value)} placeholder="0x..." />

<button
onClick={genRandomKeyPair}
style={{ marginLeft: 8 }}
>
<button onClick={genRandomKeyPair} style={{ marginLeft: 8 }}>
generatePrivateKey
</button>
<button
onClick={() => onConnect(privateKey)}
disabled={privateKey === ""}
style={{ marginLeft: 8 }}
>
<button onClick={() => onConnect(privateKey)} disabled={privateKey === ""} style={{ marginLeft: 8 }}>
Connect
</button>
</div>
Expand All @@ -49,14 +42,16 @@ export function App() {
const [omniLock, setOmniLock] = useState<Script>();
const [balance, setBalance] = useState("-");

const [transferAddr, setTransferAddress] = useState("ckt1q3uljza4azfdsrwjzdpea6442yfqadqhv7yzfu5zknlmtusm45hpuq9tv9dma3hzzt8k7a7ekqpkja4saaf2fecq3l3xmk");
const [transferAddr, setTransferAddress] = useState(
"ckt1q3uljza4azfdsrwjzdpea6442yfqadqhv7yzfu5zknlmtusm45hpuq9tv9dma3hzzt8k7a7ekqpkja4saaf2fecq3l3xmk"
);
const [transferAmount, setTransferAmount] = useState("10000000000");

const [isSendingTx, setIsSendingTx] = useState(false);
const [txHash, setTxHash] = useState("");

function connectByPrivateKey(pk: string) {
const pubkeyHash = key.privateKeyToBlake160(pk);
const pubkeyHash = hd.key.privateKeyToBlake160(pk);

const omniLock: Script = {
codeHash: CONFIG.SCRIPTS.OMNILOCK.CODE_HASH,
Expand All @@ -69,27 +64,27 @@ export function App() {
args: `0x00${pubkeyHash.substring(2)}00`,
};

const omniAddr = helpers.generateAddress(omniLock);
const omniAddr = encodeToAddress(omniLock);
setPrivateKey(pk);
setOmniAddr(omniAddr);
setOmniLock(omniLock);
capacityOf(omniAddr).then(balance => setBalance(balance.div(10 ** 8).toString() + " CKB"))
capacityOf(omniAddr).then((balance) => setBalance(balance.div(10 ** 8).toString() + " CKB"));
}

async function transfer(): Promise<string> {
const unsigned = await buildTransfer({ amount: transferAmount, from: omniAddr, to: transferAddr });

const signed = await signByPrivateKey(unsigned, privateKey);

const txHash = await sendTransaction(signed)
const txHash = await sendTransaction(signed);

return txHash;
}

async function onTransfer() {
if (isSendingTx) return;
setIsSendingTx(true);

transfer()
.then(setTxHash)
.catch((e) => alert(e.message || JSON.stringify(e)))
Expand All @@ -110,7 +105,7 @@ export function App() {

<li>Balance: {balance}</li>

<button onClick={() => setOmniAddr('')}>disconnect</button>
<button onClick={() => setOmniAddr("")}>disconnect</button>
</ul>

<div>
Expand All @@ -125,7 +120,14 @@ export function App() {
<button onClick={onTransfer} disabled={isSendingTx}>
Transfer
</button>
<p>Tx Hash: {txHash !== '' && <a target='_blank' href={`https://explorer.nervos.org/aggron/transaction/${txHash}`}>{txHash}</a>} </p>
<p>
Tx Hash:{" "}
{txHash !== "" && (
<a target="_blank" href={`https://explorer.nervos.org/aggron/transaction/${txHash}`}>
{txHash}
</a>
)}{" "}
</p>
</div>
</div>
);
Expand Down
7 changes: 3 additions & 4 deletions examples/omni-lock-secp256k1-blake160/lib.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Transaction } from "@ckb-lumos/base";
import { bytes } from "@ckb-lumos/codec";
import { BI, config, helpers, Indexer, RPC, commons, hd, Hash } from "@ckb-lumos/lumos";
import { BI, config, helpers, Indexer, RPC, commons, hd, Hash, Transaction } from "@ckb-lumos/lumos";
import { hexify } from "@ckb-lumos/lumos/codec";

export const CONFIG = config.predefined.AGGRON4;
config.initializeConfig(CONFIG);
Expand Down Expand Up @@ -40,7 +39,7 @@ export async function signByPrivateKey(txSkeleton: helpers.TransactionSkeletonTy
txSkeleton = commons.common.prepareSigningEntries(txSkeleton);
const message = txSkeleton.get("signingEntries").get(0)!.message;
const signature = hd.key.signRecoverable(message, privateKey);
const packedSignature = bytes.hexify(
const packedSignature = hexify(
commons.omnilock.OmnilockWitnessLock.pack({
signature: signature,
})
Expand Down
5 changes: 1 addition & 4 deletions examples/omni-lock-secp256k1-blake160/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@
"author": "",
"license": "MIT",
"dependencies": {
"@ckb-lumos/base": "next",
"@ckb-lumos/codec": "next",
"@ckb-lumos/hd": "next",
"@ckb-lumos/lumos": "next",
"@ckb-lumos/lumos": "canary",
"@types/react": "^18.0.25",
"@types/react-dom": "^18.0.9",
"elliptic": "^6.5.4",
Expand Down
Loading

0 comments on commit efc4550

Please sign in to comment.