Skip to content
This repository has been archived by the owner on Aug 3, 2022. It is now read-only.

feat: example of sponsored transactions #1

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# don't use in production!
SECRET_COOKIE_PASSWORD=44b1bfe8aa9eb47043bb93a4fe0b203e1d5f2d7b0a4ad3a38a4a2f579833d3ce

# private key used to sponsor transactions
SPONSOR_PRIVATE_KEY=
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,5 @@ yarn-error.log*
.idea
.yalc
.swc
.yalc
yalc.lock
10 changes: 10 additions & 0 deletions common/fetchers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,13 @@ export const destroySession = async () => {
console.error(e);
}
};

export const sponsorTransaction = async (txHex: string) => {
const res = await fetch(APP_URL + '/api/sponsor', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ txHex }),
})
const data = await res.json();
return data.txid as string;
}
32 changes: 32 additions & 0 deletions components/transaction-signing.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { useCallback, useState } from 'react';
import { useOpenContractCall } from '@micro-stacks/react';
import styles from '../styles/Home.module.css';
import { sponsorTransaction } from '../common/fetchers';

export const TransactionSigning = () => {
const [txid, setTxid] = useState('');
const { openContractCall } = useOpenContractCall();

const signAndSponsor = useCallback(async () => {
const receipt = await openContractCall({
contractName: 'micro-stacks-demo-dc56721f',
functionName: 'say-hi',
sponsored: true,
functionArgs: [],
contractAddress: 'ST2CY5V39NHDPWSXMW9QDT3HC3GD6Q6XX4CFRK9AG',
});
if (typeof receipt === 'undefined') return;

const txid = await sponsorTransaction(receipt.txRaw);
setTxid(txid);
}, [openContractCall]);

return (
<>
<button className={styles.button} onClick={signAndSponsor}>
Sign Sponsored Contract Call
</button>
{ txid ? <p>TXID: {txid}</p> : null}
</>
)
}
38 changes: 19 additions & 19 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,29 @@
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@micro-stacks/client": "1.0.0-beta.7",
"@micro-stacks/react": "1.0.0-beta.11",
"iron-session": "6.1.3",
"micro-stacks": "0.6.1",
"next": "12.2.2",
"react": "18.2.0",
"react-dom": "18.2.0"
"@micro-stacks/client": "1.0.0-beta.7",
"@micro-stacks/react": "1.0.0-beta.11",
"iron-session": "6.1.3",
"micro-stacks": "0.6.1",
"next": "12.2.2",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"@stacks/prettier-config": "0.0.10",
"@types/node": "18.0.3",
"@types/react": "18.0.15",
"@types/react-dom": "18.0.6",
"eslint": "8.19.0",
"eslint-config-next": "12.2.0",
"prettier": "2.7.1",
"typescript": "4.7.4"
"@stacks/prettier-config": "0.0.10",
"@types/node": "18.0.3",
"@types/react": "18.0.15",
"@types/react-dom": "18.0.6",
"eslint": "8.19.0",
"eslint-config-next": "12.2.0",
"prettier": "2.7.1",
"typescript": "4.7.4"
},
"prettier": "@stacks/prettier-config"
}
1 change: 1 addition & 0 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ function MyApp({ Component, pageProps }: AppProps) {
dehydratedState={pageProps?.dehydratedState}
onPersistState={onPersistState}
onSignOut={onSignOut}
network="testnet"
>
<Component {...pageProps} />
</ClientProvider>
Expand Down
43 changes: 43 additions & 0 deletions pages/api/sponsor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { withIronSessionApiRoute } from 'iron-session/next';
import { sessionOptions } from '../../common/session';
import { deserializeTransaction, sponsorTransaction, broadcastTransaction } from 'micro-stacks/transactions';
import { StacksTestnet } from 'micro-stacks/network';

import type { NextApiRequest, NextApiResponse } from 'next';

async function sponsorTx(txHex: string) {
const transaction = deserializeTransaction(txHex);
const sponsorPrivateKey = process.env.SPONSOR_PRIVATE_KEY;
if (!sponsorPrivateKey) throw new Error('SPONSOR_PRIVATE_KEY is required');

const network = new StacksTestnet();
const sponsoredTx = await sponsorTransaction({
transaction,
sponsorPrivateKey: sponsorPrivateKey,
network,
fee: '1000',
})
// return sponsoredTx.txid();
const result = await broadcastTransaction(sponsoredTx, network);
if ('error' in result) {
console.error('Transaction broadcast failed:', result);
throw new Error(`Broadcast failed: ${result.error}`);
}
return result.txid;
}

async function sponsorTransactionRoute(req: NextApiRequest, res: NextApiResponse) {
const { txHex } = await req.body;

if (!txHex)
return res.status(500).json({ message: 'No `txHex` was found in body' });

try {
const txid = await sponsorTx(txHex);
res.json({ txid });
} catch (error) {
res.status(500).json({ message: (error as Error).message });
}
}

export default withIronSessionApiRoute(sponsorTransactionRoute, sessionOptions);
2 changes: 2 additions & 0 deletions pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import styles from '../styles/Home.module.css';
import { WalletConnectButton } from '../components/wallet-connect-button';
import { UserCard } from '../components/user-card';
import { getDehydratedStateFromSession } from '../common/session-helpers';
import { TransactionSigning } from '../components/transaction-signing';

import type { NextPage, GetServerSidePropsContext } from 'next';

Expand All @@ -22,6 +23,7 @@ const Home: NextPage = () => {
</h1>
<UserCard />
<WalletConnectButton />
<TransactionSigning />
</main>
</div>
);
Expand Down
4 changes: 4 additions & 0 deletions styles/Home.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,7 @@
flex-direction: column;
}
}

.button {
margin-top: 10px;
}