Skip to content

Commit

Permalink
chore: port over stx sign transaction examples from old app
Browse files Browse the repository at this point in the history
  • Loading branch information
teebszet committed Aug 7, 2024
1 parent 097a3e4 commit 3d050f8
Show file tree
Hide file tree
Showing 2 changed files with 132 additions and 0 deletions.
3 changes: 3 additions & 0 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { NetworkSelector } from './components/NetworkSelector';
import { SendInscription } from './components/sendInscriptions';
import { SendSip10 } from './components/stacks/SendSip10';
import { SendStx } from './components/stacks/SendStx';
import { SignTransaction } from './components/stacks/SignTransaction';
import { WalletType } from './components/wallet/WalletType';
import { useLocalStorage } from './hooks';
import { CollapseDesktop } from './layouts/CollapseDesktop';
Expand Down Expand Up @@ -146,6 +147,7 @@ function AppWithProviders({ children }: React.PropsWithChildren<{}>) {
);
}

// TODO move to pages or routes.tsx
const WalletMethods = () => {
const { network, btcAddressInfo, legacyAddressInfo, stxAddressInfo, onDisconnect } =
useConnectionContext();
Expand Down Expand Up @@ -194,6 +196,7 @@ const StacksMethods = () => {
/>
<SendStx network={network} />
<SendSip10 network={network} stxAddressInfo={stxAddressInfo} />
<SignTransaction stxAddressInfo={stxAddressInfo} />
</>
);
};
Expand Down
129 changes: 129 additions & 0 deletions example/src/components/stacks/SignTransaction.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { Button, Card, Stack, Switch } from '@mantine/core';
import {
PostConditionMode,
makeUnsignedContractCall,
makeUnsignedContractDeploy,
makeUnsignedSTXTokenTransfer,
uintCV,
} from '@stacks/transactions';
import { useState } from 'react';
import { Address, request } from 'sats-connect';

const codeBody = `
(define-data-var greeting (string-ascii 100) "Hello, World!")
(define-read-only (get-greeting)
(ok (var-get greeting))
)
(define-public (set-greeting (new-greeting (string-ascii 100)))
(begin
(var-set greeting new-greeting)
(ok new-greeting))
)
`;

function uint8ArrayToHex(uint8Array: Uint8Array) {
return Array.from(uint8Array, (byte) => byte.toString(16).padStart(2, '0')).join('');
}

const errorMessage = 'Error signing transaction. Check console for error logs.';

export function SignTransaction({ stxAddressInfo }: { stxAddressInfo: Address[] }) {
const [broadcast, setBroadcast] = useState(false);
const [postConditionMode, setPostConditionMode] = useState<PostConditionMode>(
PostConditionMode.Deny,
);

const publicKey = stxAddressInfo[0].publicKey;

const requestSignTransaction = async (transaction: any) => {
try {
const response = await request('stx_signTransaction', {
transaction: uint8ArrayToHex(transaction.serialize()),
broadcast,
});
if (response.status === 'success') {
alert('Success! Check console for result.');
console.log(response.result.transaction);
} else {
alert('Error signing transaction. Check console for error logs');
console.error(response.error);
}
} catch (error) {
alert(errorMessage);
console.error(error);
}
};

// TODO handle networks
const handleSignTransactionContractCallClick = async () => {
const transaction = await makeUnsignedContractCall({
fee: 3000,
anchorMode: 'onChainOnly',
contractAddress: 'SP21YTSM60CAY6D011EZVEVNKXVW8FVZE198XEFFP',
contractName: 'pox-fast-pool-v2',
functionName: 'set-stx-buffer',
functionArgs: [uintCV(1)],
postConditionMode,
publicKey,
});
requestSignTransaction(transaction);
};

const handleSignTransactionSTXTokenTransferClick = async () => {
const transaction = await makeUnsignedSTXTokenTransfer({
anchorMode: 'any',
fee: 3000,
recipient: 'SP2FFKDKR122BZWS7GDPFWC0J0FK4WMW5NPQ0Z21M', // account 4
amount: 1000,
publicKey,
});
requestSignTransaction(transaction);
};

const handleSignTransactionContractDeployClick = async () => {
const transaction = await makeUnsignedContractDeploy({
anchorMode: 'any',
contractName: 'my-contract',
codeBody,
fee: 3000,
postConditionMode,
publicKey,
});
requestSignTransaction(transaction);
};

return (
<Card>
<h3>Sign transaction</h3>
<Stack>
<Switch
checked={broadcast}
onChange={() => setBroadcast((prev) => !prev)}
label={`Broadcast: ${broadcast ? 'True' : 'False'}`}
/>
<Switch
checked={postConditionMode === PostConditionMode.Allow}
onChange={() =>
setPostConditionMode((prev) =>
prev === PostConditionMode.Allow ? PostConditionMode.Deny : PostConditionMode.Allow,
)
}
label={`Post condition mode: ${
postConditionMode === PostConditionMode.Allow ? 'Allow' : 'Deny'
} `}
/>
<Button onClick={handleSignTransactionSTXTokenTransferClick}>
Sign Transaction (token transfer)
</Button>
<Button onClick={handleSignTransactionContractCallClick}>
Sign Transaction (contract call)
</Button>
<Button onClick={handleSignTransactionContractDeployClick}>
Sign Transaction (contract deploy)
</Button>
</Stack>
</Card>
);
}

0 comments on commit 3d050f8

Please sign in to comment.