Skip to content
This repository has been archived by the owner on Nov 28, 2020. It is now read-only.

Feature for confirm custom transaction #306

Open
wants to merge 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
/dist/main.css
*.sw[po]
/store
.idea
54 changes: 51 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ window.addEventListener('message', (e) => {
}
});
```
4. Send an `'addFunds'` request
4. Send an `'addFunds'` or `'sendCustomTransaction'` request
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to re-organize this README section rather than adding more things to the "Funding dApps" section. I recommend

## Wallet Setup
... steps 1 - 3

## Requesting Funds
... steps 4 - 5

## Sending Custom Transactions
... your new steps

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

```js
walletWindow.postMessage({
method: 'addFunds',
Expand All @@ -65,9 +65,52 @@ walletWindow.postMessage({
network: 'https://api.beta.testnet.solana.com',
},
}, WALLET_URL);

or

walletWindow.postMessage({
method: 'sendCustomTransaction',
params: {
description: "Description of transaction",
format: 'JSON',
transaction: `[
{
"keys": [
{
"pubkey": "9dpzQrAWRJet26mFt2pt4PXGv9J3uUj7onSTBuJYXXdZ",
"isSigner": true,
"isDebitable": true
},
],
"programId": "11111111111111111111111111111111",
"data": "000000003c00000000000000a90000000000000038ca84e115c5fec729ff33b77202760da632a30633f95c529a4c223c3ed6142a"
},
{
"keys": [
{
"pubkey": "9dpzQrAWRJet26mFt2pt4PXGv9J3uUj7onSTBuJYXXdZ",
"isSigner": true,
"isDebitable": false
},
{
"pubkey": "Sysca11Current11111111111111111111111111111",
"isSigner": false,
"isDebitable": false
}
],
"programId": "4pgwX1zWz8NaegwTcH1YmntCdVn7qdXwZkxqgDN7P6cR",
"data": "010000000a00000000000000320000000000000000000000000000000000000000000000"
}
]`,
network: 'https://api.beta.testnet.solana.com',
},
}, WALLET_URL);
```
5. Listen for an `'addFundsResponse'` event which will include the amount transferred and the transaction signature
```js

The `sendCustomTransaction` request accepts a transaction in JSON format containing only the `TransactionInstruction` set. Field `data` must be in HEX, `programId` and `pubkey` must be in Base58

5. Listen for an `'addFundsResponse'` event which will include the amount transferred and the transaction signature. And listen for an `'sendCustomTransactionResponse'` event which will include the transaction signature
```js
window.addEventListener('message', (e) => {
// ...
switch (e.data.method) {
Expand All @@ -80,6 +123,11 @@ window.addEventListener('message', (e) => {
// ...
break;
}
case 'sendCustomTransactionResponse': {
const {signature} = e.data.params;
// ...
break;
}
}
});
```
139 changes: 132 additions & 7 deletions src/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -321,14 +321,16 @@ export class Wallet extends React.Component {
account: null,
requestMode: false,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's change this state flag from a boolean to an enum and rename to displayMode since we have 3 display modes now

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

requesterOrigin: '*',
requestPending: false,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did you remove this?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The user may not close the wallet window after the last request and may simply not respond to it, but may also request a new action in the DAPP therefore. For useful, I allowed DAPP to update the request, and in the future we will need a request queue.

requestedPublicKey: '',
requestedAmount: '',
recipientPublicKey: '',
recipientAmount: '',
recipientIdentity: null,
confirmationSignature: null,
transactionConfirmed: null,
unsignedTransaction: null,
formattedUnsignedTransaction: '',
description: '',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please namespace this: unsignedTransactionDescription is more wordy but easier to understand what it's used for

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

};

setConfirmationSignature(confirmationSignature) {
Expand Down Expand Up @@ -414,7 +416,6 @@ export class Wallet extends React.Component {
};

onAddFunds(params, origin) {
if (!params || this.state.requestPending) return;
if (!params.pubkey || !params.network) {
if (!params.pubkey) this.addError(`Request did not specify a public key`);
if (!params.network) this.addError(`Request did not specify a network`);
Expand All @@ -439,12 +440,62 @@ export class Wallet extends React.Component {

this.setState({
requesterOrigin: origin,
requestPending: true,
requestedAmount: `${params.amount || ''}`,
requestedPublicKey: params.pubkey,
});
}

onSendCustomTransactionRequest(params, origin) {
if (!params.format || !params.network || !params.transaction) {
if (!params.network) this.addError(`Request did not specify a network`);
if (!params.format) this.addError(`Request did not specify a transaction format`);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like you aren't checking the value of format anywhere. Let's remove it for now, and add if we introduce other formats.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

if (!params.transaction) this.addError(`Request did not specify a transaction`);
return;
}

let requestedNetwork;
try {
requestedNetwork = new URL(params.network).origin;
} catch (err) {
this.addError(`Request network is invalid: "${params.network}"`);
return;
}

const walletNetwork = new URL(this.props.store.networkEntryPoint).origin;
if (requestedNetwork !== walletNetwork) {
this.props.store.setNetworkEntryPoint(requestedNetwork);
this.addWarning(
`Changed wallet network from "${walletNetwork}" to "${requestedNetwork}"`,
);
}

const transaction = new web3.Transaction();
const inputs = JSON.parse(params.transaction);

inputs.map(input => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not a big fan of this approach because if we change Transaction structure, it would break. I would prefer to rely on the web3 sdk serialization methods instead for passing messages: transaction.serialize(): Buffer and Transaction.from(buffer: Buffer).

I like that you are displaying the json formatted transaction in the confirmation before sending. I think that a toJSON method would be nice to have inside Web3, thoughts?

Copy link
Author

@Tarzeron Tarzeron Sep 11, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I also wanted to do this, but SDK does not serialize an unsigned transaction, can you give an example how to do it?

public serialize(): Buffersource
Serialize the Transaction in the wire format.
The Transaction must have a valid signature before invoking this method

I have error
Uncaught Error: Transaction recentBlockhash required

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

@Tarzeron Tarzeron Sep 11, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need to fill out recentBlockhash, what if the user did not immediately confirm the transaction, it needs to be filled again on the wallet side?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting a placeholder is fine because the wallet will always set the recentBlockhash when signing. Something like:

transaction.recentBlockhash = new PublicKey(0).toBase58();

const converted = {};
converted.keys = [];
converted.programId = new web3.PublicKey(input.programId);
converted.data = Buffer.from(input.data, 'hex');
input.keys.map(key => {
converted.keys.push({
pubkey: new web3.PublicKey(key.pubkey),
isSigner: key.isSigner,
isDebitable: key.isDebitable,
});
});
transaction.add(converted);
});

this.setState({
requesterOrigin: origin,
description: params.description ? params.description : '',
unsignedTransaction: transaction,
formattedUnsignedTransaction: JSON.stringify(JSON.parse(params.transaction), null, 4),
requestedPublicKey: null,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please remove, we can use a different approach to distinguish between "addFunds" and "sendCustomTransaction"

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

});
}

postWindowMessage(method, params) {
if (window.opener) {
window.opener.postMessage({method, params}, this.state.requesterOrigin);
Expand All @@ -457,7 +508,10 @@ export class Wallet extends React.Component {
if (e.data) {
switch (e.data.method) {
case 'addFunds':
this.onAddFunds(e.data.params, e.origin);
this.onAddFunds(e.data.params, e.currentTarget.origin);
return true;
case 'sendCustomTransaction':
this.onSendCustomTransactionRequest(e.data.params, e.currentTarget.origin);
return true;
}
}
Expand Down Expand Up @@ -508,7 +562,7 @@ export class Wallet extends React.Component {
sendTransaction(closeOnSuccess) {
this.runModal('Sending Transaction', 'Please wait...', async () => {
const amount = this.state.recipientAmount;
this.setState({requestedAmount: '', requestPending: false});
this.setState({requestedAmount: ''});
const transaction = web3.SystemProgram.transfer(
this.state.account.publicKey,
new web3.PublicKey(this.state.recipientPublicKey),
Expand Down Expand Up @@ -542,10 +596,43 @@ export class Wallet extends React.Component {
});
}

signAndSendTransaction(closeOnSuccess) {
this.runModal('Sending Transaction', 'Please wait...', async () => {
let signature = '';
try {
signature = await web3.sendAndConfirmTransaction(
this.web3sol,
this.state.unsignedTransaction,
this.state.account,
);
} catch (err) {
// Transaction failed but fees were still taken
this.setState({
balance: await this.web3sol.getBalance(this.state.account.publicKey),
});
this.postWindowMessage('sendCustomTransactionResponse', {err: true});
throw err;
}

this.postWindowMessage('sendCustomTransactionResponse', {signature});
if (closeOnSuccess) {
window.close();
} else {
this.setState({
balance: await this.web3sol.getBalance(this.state.account.publicKey),
});
}
});
}

confirmTransaction() {
jstarry marked this conversation as resolved.
Show resolved Hide resolved
this.runModal('Confirming Transaction', 'Please wait...', async () => {
const signature = await this.web3sol.sendTransaction(
this.state.unsignedTransaction,
this.state.account,
);
const result = await this.web3sol.confirmTransaction(
this.state.confirmationSignature,
signature,
);
this.setState({
transactionConfirmed: result,
Expand All @@ -557,6 +644,8 @@ export class Wallet extends React.Component {
return (
this.state.recipientPublicKey === null ||
this.state.recipientAmount === null
) && (
this.state.formattedUnsignedTransaction === null
);
}

Expand Down Expand Up @@ -586,7 +675,7 @@ export class Wallet extends React.Component {
{busyModal}
{settingsModal}
{this.state.requestMode
? this.renderTokenRequestPanel()
? (this.state.requestedPublicKey ? this.renderTokenRequestPanel() : this.renderSendCustomTransactionRequestPanel())
: this.renderMainPanel()}
</div>
);
Expand Down Expand Up @@ -817,10 +906,46 @@ export class Wallet extends React.Component {
</Col>
</Row>
</Grid>
<div className="container">{this.renderPanels()}</div>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please revert this change

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

</div>
);
}

renderSendCustomTransactionRequestPanel() {
return (
<Panel>
<Panel.Heading>Send custom transaction Request</Panel.Heading>
<Panel.Body>
<div>
{this.state.description.split('\n').map((i, key) => {
return <p key={key}>{i}</p>;
})}
</div>
<div className="btns">
<Button
disabled={this.sendDisabled()}
onClick={() => this.signAndSendTransaction(false)}
>
Send
</Button>
<Button
disabled={this.sendDisabled()}
onClick={() => this.signAndSendTransaction(true)}
>
Send & Close
</Button>
</div>
<p/>
<div>
<pre>
{this.state.formattedUnsignedTransaction}
</pre>
</div>
</Panel.Body>
</Panel>
);
}

renderSendTokensPanel() {
return (
<Panel>
Expand Down