Skip to content

Commit

Permalink
封装一个 sui 的一个浏览器扩展调用
Browse files Browse the repository at this point in the history
  • Loading branch information
v1xingyue committed Dec 15, 2023
1 parent 5a7d2a8 commit 21ef735
Show file tree
Hide file tree
Showing 15 changed files with 383 additions and 0 deletions.
39 changes: 39 additions & 0 deletions examples/sui-tool/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

#cache
.turbo

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# local env files
.env*

out/
build/
dist/

# plasmo - https://www.plasmo.com
.plasmo

# bpp - http://bpp.browser.market/
keys.json

# typescript
.tsbuildinfo
26 changes: 26 additions & 0 deletions examples/sui-tool/.prettierrc.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @type {import('prettier').Options}
*/
export default {
printWidth: 80,
tabWidth: 2,
useTabs: false,
semi: false,
singleQuote: false,
trailingComma: "none",
bracketSpacing: true,
bracketSameLine: true,
plugins: ["@ianvs/prettier-plugin-sort-imports"],
importOrder: [
"<BUILTIN_MODULES>", // Node.js built-in modules
"<THIRD_PARTY_MODULES>", // Imports not matched by other special words or groups.
"", // Empty line
"^@plasmo/(.*)$",
"",
"^@plasmohq/(.*)$",
"",
"^~(.*)$",
"",
"^[./]"
]
}
33 changes: 33 additions & 0 deletions examples/sui-tool/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
This is a [Plasmo extension](https://docs.plasmo.com/) project bootstrapped with [`plasmo init`](https://www.npmjs.com/package/plasmo).

## Getting Started

First, run the development server:

```bash
pnpm dev
# or
npm run dev
```

Open your browser and load the appropriate development build. For example, if you are developing for the chrome browser, using manifest v3, use: `build/chrome-mv3-dev`.

You can start editing the popup by modifying `popup.tsx`. It should auto-update as you make changes. To add an options page, simply add a `options.tsx` file to the root of the project, with a react component default exported. Likewise to add a content page, add a `content.ts` file to the root of the project, importing some module and do some logic, then reload the extension on your browser.

For further guidance, [visit our Documentation](https://docs.plasmo.com/)

## Making production build

Run the following:

```bash
pnpm build
# or
npm run build
```

This should create a production bundle for your extension, ready to be zipped and published to the stores.

## Submit to the webstores

The easiest way to deploy your Plasmo extension is to use the built-in [bpp](https://bpp.browser.market) GitHub action. Prior to using this action however, make sure to build your extension and upload the first version to the store to establish the basic credentials. Then, simply follow [this setup instruction](https://docs.plasmo.com/framework/workflows/submit) and you should be on your way for automated submission!
Binary file added examples/sui-tool/assets/icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 9 additions & 0 deletions examples/sui-tool/move/Move.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "example"
version = "0.0.1"

[dependencies]
Sui = { git = "https://github.com/MystenLabs/sui.git", subdir = "crates/sui-framework/packages/sui-framework", rev = "framework/testnet" }

[addresses]
example = "0x0"
23 changes: 23 additions & 0 deletions examples/sui-tool/move/sources/counter.move
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module example::counter {

use sui::object::{Self, UID};
use sui::transfer;
use sui::tx_context::TxContext;

struct CounterValue has key,store {
id:UID,
value: u64,
}

fun init(ctx:&mut TxContext) {
transfer::share_object(CounterValue{
id:object::new(ctx),
value:0
});
}

entry fun add_value(counter:&mut CounterValue,v:u64){
counter.value = counter.value + v;
}

}
35 changes: 35 additions & 0 deletions examples/sui-tool/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "sui-tool",
"displayName": "Sui tool",
"version": "0.0.1",
"description": "A chrome extension communicate with sui.",
"author": "v1xingyue<qixingyue.gmail.com>",
"scripts": {
"dev": "plasmo dev",
"build": "plasmo build",
"package": "plasmo package"
},
"dependencies": {
"@mysten/sui.js": "^0.48.1",
"@plasmohq/storage": "^1.9.0",
"plasmo": "0.84.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"tailwindcss": "3.3.5"
},
"devDependencies": {
"@ianvs/prettier-plugin-sort-imports": "4.1.1",
"@types/chrome": "0.0.251",
"@types/node": "20.9.0",
"@types/react": "18.2.37",
"@types/react-dom": "18.2.15",
"postcss": "8.4.31",
"prettier": "3.0.3",
"typescript": "5.2.2"
},
"manifest": {
"host_permissions": [
"https://*/*"
]
}
}
8 changes: 8 additions & 0 deletions examples/sui-tool/postcss.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* @type {import('postcss').ProcessOptions}
*/
module.exports = {
plugins: {
tailwindcss: {}
}
}
37 changes: 37 additions & 0 deletions examples/sui-tool/src/background/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { getFullnodeUrl, SuiClient } from "@mysten/sui.js/client"
import { Ed25519Keypair } from "@mysten/sui.js/keypairs/ed25519"
import { TransactionBlock } from "@mysten/sui.js/transactions"
import { fromB64 } from "@mysten/sui.js/utils"

import { Storage } from "@plasmohq/storage"

export {}

const storage = new Storage()

chrome.runtime.onInstalled.addListener(async () => {
const keypair = Ed25519Keypair.generate()
await storage.set("secret", keypair.export().privateKey)
await storage.set("address", keypair.getPublicKey().toSuiAddress().toString())
console.log("Extension installed.")
})

chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
if (message.action === "executeTransaction") {
const client = new SuiClient({ url: getFullnodeUrl("testnet") })
const transactionBytes = message.transactionBytes
const txb = TransactionBlock.from(transactionBytes)
const privateKey = await storage.get("secret")
const privateKeyBytes = fromB64(privateKey)
// console.log(privateKeyBytes)
sendResponse({ privateKeyBytes })
const signer = Ed25519Keypair.fromSecretKey(privateKeyBytes)
console.log(signer.toSuiAddress().toString())
const tx = await client.signAndExecuteTransactionBlock({
signer: signer,
transactionBlock: txb
})

sendResponse(tx)
}
})
24 changes: 24 additions & 0 deletions examples/sui-tool/src/content.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import cssText from "data-text:~style.css"
import type { PlasmoCSConfig } from "plasmo"

import { CountButton } from "~features/count-button"

export const config: PlasmoCSConfig = {
matches: ["https://www.plasmo.com/*"]
}

export const getStyle = () => {
const style = document.createElement("style")
style.textContent = cssText
return style
}

const PlasmoOverlay = () => {
return (
<div className="plasmo-z-50 plasmo-flex plasmo-fixed plasmo-top-32 plasmo-right-8">
<CountButton />
</div>
)
}

export default PlasmoOverlay
19 changes: 19 additions & 0 deletions examples/sui-tool/src/features/count-button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useReducer } from "react"

export const CountButton = () => {
const [count, increase] = useReducer((c) => c + 1, 0)

return (
<button
onClick={() => increase()}
type="button"
className="plasmo-flex plasmo-flex-row plasmo-items-center plasmo-px-4 plasmo-py-2 plasmo-text-sm plasmo-rounded-lg plasmo-transition-all plasmo-border-none
plasmo-shadow-lg hover:plasmo-shadow-md
active:plasmo-scale-105 plasmo-bg-slate-50 hover:plasmo-bg-slate-100 plasmo-text-slate-800 hover:plasmo-text-slate-900">
Count:
<span className="plasmo-inline-flex plasmo-items-center plasmo-justify-center plasmo-w-8 plasmo-h-4 plasmo-ml-2 plasmo-text-xs plasmo-font-semibold plasmo-rounded-full">
{count}
</span>
</button>
)
}
100 changes: 100 additions & 0 deletions examples/sui-tool/src/popup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { getFullnodeUrl, SuiClient } from "@mysten/sui.js/client"
import { getFaucetHost, requestSuiFromFaucetV0 } from "@mysten/sui.js/faucet"
import { TransactionBlock } from "@mysten/sui.js/transactions"
import { MIST_PER_SUI } from "@mysten/sui.js/utils"
import { useEffect, useState } from "react"

import { useStorage } from "@plasmohq/storage/hook"

import "~style.css"

function IndexPopup() {
const counterID =
"0xca9b2043af3accad328bbae361a4941a778ebc6d2f02ffe09b001c06ed643934"
const packageId =
"0x9e38050fd03f181c17f6f1d682ab55c7c16666eed4e17470489e24c64b11b4cd"

const suiClient = new SuiClient({ url: getFullnodeUrl("testnet") })
const [address] = useStorage("address")
const [balance, setBalance] = useState("0")
const [counter, setCounter] = useState("")
const [counterVersion, updateCounterVersion] = useState(0)

const doFaucet = async () => {
const result = await requestSuiFromFaucetV0({
host: getFaucetHost("testnet"),
recipient: address
})
console.log(result)
}

const addCounter = async () => {
const txb = new TransactionBlock()
txb.moveCall({
target: `${packageId}::counter::add_value`,
arguments: [txb.object(counterID), txb.pure(1)]
})
console.log(txb.serialize())
const tx = await chrome.runtime.sendMessage({
action: "executeTransaction",
transactionBytes: txb.serialize()
})
console.log(tx)
updateCounterVersion(counterVersion + 1)
}

useEffect(() => {
if (address) {
const initWallet = async () => {
console.log("init wallet ", address)
const balance = await suiClient.getBalance({
owner: address
})
setBalance(balance.totalBalance)
}
initWallet()
}
}, [address])

useEffect(() => {
const updateCounter = async () => {
const counter = await suiClient.getObject({
id: counterID,
options: {
showContent: true
}
})
if (counter.data && counter.data.content) {
const content = counter.data.content as any
if (counter && content.fields && content.fields.value) {
setCounter(content.fields.value)
}
}
}
updateCounter()
}, [counterVersion])

return (
<div
style={{
width: "500px",
height: "500px"
}}
className="plasmo-p-5 plasmo-flex-auto">
<div>Address : {address}</div>
<div>Balance : {balance}</div>
<div>Counter: {counter}</div>
<div>
<button
className="plasmo-flex plasmo-flex-row plasmo-items-center plasmo-px-4 plasmo-py-2 plasmo-text-sm plasmo-rounded-lg plasmo-transition-all plasmo-border-none
plasmo-shadow-lg hover:plasmo-shadow-md
active:plasmo-scale-105 plasmo-bg-slate-50 hover:plasmo-bg-slate-100 plasmo-text-slate-800 hover:plasmo-text-slate-900"
onClick={addCounter}>
Add Counter
</button>
</div>
</div>
)
}

export default IndexPopup
5 changes: 5 additions & 0 deletions examples/sui-tool/src/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap");

@tailwind base;
@tailwind components;
@tailwind utilities;
6 changes: 6 additions & 0 deletions examples/sui-tool/tailwind.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{tsx,html}"],
darkMode: "media",
prefix: "plasmo-"
}
19 changes: 19 additions & 0 deletions examples/sui-tool/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"extends": "plasmo/templates/tsconfig.base",
"exclude": [
"node_modules"
],
"include": [
".plasmo/index.d.ts",
"./**/*.ts",
"./**/*.tsx"
],
"compilerOptions": {
"paths": {
"~*": [
"./src/*"
]
},
"baseUrl": "."
}
}

0 comments on commit 21ef735

Please sign in to comment.