Unable to sign transaction to PDA in Solana using anchor - web3js

I'm working on learning Solana full stack using Anchor. I've run into a problem with signing a transaction sending Sol to a PDA owned by a program I'm making. I'm unable to call the rpc for the function with the proper signatures. Below is my code:
await program.rpc.payPool(pool.data.name, new BN(payment), {
accounts: {
pool: pool.publicKey,
poolOwner: owner.key.PublicKey,
user: adder.key.publicKey,
systemProgram: SystemProgram.programId,
},
signers: [
adder.key,
// I need to put another signature here I think
],
});
The error I'm getting is, which I think is related to a problem varying the transaction.
Error: Invalid arguments: poolOwner not provided.
at ~/learnsolana/node_modules/#project-serum/anchor/dist/cjs/program/common.js:39:23
at Array.forEach (<anonymous>)
at validateAccounts (node_modules/#project-serum/anchor/dist/cjs/program/common.js:33:16)
at ix (node_modules/#project-serum/anchor/dist/cjs/program/namespace/instruction.js:34:46)
at txFn (node_modules/#project-serum/anchor/dist/cjs/program/namespace/transaction.js:16:20)
at Object.rpc [as payPool] (node_modules/#project-serum/anchor/dist/cjs/program/namespace/rpc.js:28:24)
at payPool (tests/learnsolana.js:70:23)
at Context.<anonymous> (tests/learnsolana.js:117:28)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
The relevant information from the Solana program is:
pub fn pay_pool(ctx: Context<PayPool>, _pool_name: String, payment: u64,) ->
ProgramResult {
let user = &ctx.accounts.user;
let pool = &mut ctx.accounts.pool;
if pool.payers.len() >= pool.capacity as usize {
return Err(PoolError::PayersFull.into());
}
pool.payers.push(*user.to_account_info().key);
invoke(
&transfer(
user.to_account_info().key,
pool.to_account_info().key,
payment,
),
&[
user.to_account_info(),
pool.to_account_info(),
ctx.accounts.system_program.to_account_info(),
],
)?;
Ok(())
}
#[derive(Accounts)]
#[instruction(pool_name: String, payment: u64)]
pub struct PayPool<'info>{
#[account(mut, has_one=pool_owner # PoolError::WrongPoolOwner, seeds=[b"pool", pool_owner.to_account_info().key.as_ref(), name_seed(&pool_name)], bump=pool.bump)]
pub pool: Account<'info, Pool>,
pub pool_owner: AccountInfo<'info>,
pub user: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct Pool {
pub pool_owner: Pubkey,
pub bump: u8,
pub capacity: u16,
pub name: String,
pub payers: Vec<Pubkey>,
}
Any help is appreciated. Thank you.

poolOwner: owner.key.PublicKey -> poolOwner: owner.key.publicKey
You just need to lower case the "P" in publicKey. You also shouldn't need to provide the signers param as anchor will generate that automatically.

Related

FileError { kind: IOError(Os { code: 2, kind: NotFound, message: "No such file or directory" }), path: "Some(\"assets/images/tiles/air.png\")" }'

Tell me if I need to provide more info, I am rather new here. Here is the code:
let mut image_paths = vec![];
let mut images = vec![];
let mut image_path = "assets/images/tiles/";
for img in glob(format!("{}*.png",image_path).as_str()).unwrap() {
match img {
Ok(path) =>{
image_paths.push(format!("{:?}",path.to_str()));
},
Err(e) => continue,
}
}
for i in &image_paths {
images.push(load_texture(i).await.unwrap());
}
But I get this error:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: FileError {
kind: IOError(Os { code: 2, kind: NotFound, message: "No such file or directory" }),
path: "Some(\"assets/images/tiles/air.png\")" }', src/main.rs:71:43
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Which is really bizarre, because I can confirm that 'air.png' is in the 'tiles' folder, I have been able to load the image simply by doing load_texture(), but I don't understand why I cannot load it now.
Path::to_str returns an Option<&str>. You're applying debug formatting ({:?}) on that, then adding the result to image_paths. I'm pretty sure your file path isn't supposed to start with Some(.
When you work with paths in Rust, you generally want to use Path or PathBuf unless you need to display the path. Check to see if load_texture could receive a &Path or a PathBuf. If not, then you need to unwrap the Option or deal with the None in whatever way is appropriate for your situation.
image_paths.push(path.to_str().unwrap());
// or if you need a `String` instead of a `&str`:
image_paths.push(path.to_str().unwrap().to_string());

Error with URL in NextJS and I can't find the problem

I have an error that appear in both development and production mode, however, this error only crash the website in production.
I have this error returned:
unhandledRejection: TypeError: Only absolute URLs are supported
at getNodeRequestOptions (D:\FIV\nextjs-fiv-4\node_modules\node-fetch\lib\index.js:1305:9)
at D:\FIV\nextjs-fiv-4\node_modules\node-fetch\lib\index.js:1410:19
at new Promise (<anonymous>)
at Function.fetch [as default] (D:\FIV\nextjs-fiv-4\node_modules\node-fetch\lib\index.js:1407:9)
at fetchWithAgent (D:\FIV\nextjs-fiv-4\node_modules\next\dist\server\node-polyfill-fetch.js:38:39)
at _callee$ (D:\FIV\nextjs-fiv-4\node_modules\swell-js\dist\api.js:191:20)
at tryCatch (D:\FIV\nextjs-fiv-4\node_modules\regenerator-runtime\runtime.js:63:40)
at Generator.invoke [as _invoke] (D:\FIV\nextjs-fiv-4\node_modules\regenerator-runtime\runtime.js:294:22)
at Generator.next (D:\FIV\nextjs-fiv-4\node_modules\regenerator-runtime\runtime.js:119:21)
at asyncGeneratorStep (D:\FIV\nextjs-fiv-4\node_modules\swell-js\node_modules\#babel\runtime\helpers\asyncToGenerator.js:3:24)
And I know that this is the element below causing this error, when I remove it, the error disappears. But I do not understand how to correct it, or what's wrong when checking the network tab. In the network tab I see that this is calling http://localhost:3000/null/api/cart instead of https://my-store.swell.store/api/cart which is weird because on other page this URL is called correctly and I use an .env file to set my environment variables.
//Render Stripe Card Element
var customCardElement = swell.payment.createElements({
card: {
elementId: '#card-element', // default: #card-element
options: {
style: {
base: {
fontWeight: 500,
fontSize: "16px"
},
},
},
onChange: event => {
//setDisabled(event.empty);
if(event.error){
//setError(event.error.message);
}
}
}
});
Client side NextJS variables are only available if prefixed with NEXT_PUBLIC_ because well... they're public

Simple Peer on data stream throws process not defined error

I am trying to open a data channel using simple peer. I send the signal using Firebase and am able to get the on connect function to fire.
const [thisPeer, setThisPeer] = useState();
const [connectionStatus, setConnectionStatus] = useState(false);
// in a function
var thisPeerT = new Peer({
initiator: false,
config: {
iceServers: iceServers,
},
});
// signaling code
thisPeerT.on("connect", function (data) {
console.log("onconnect");
console.log(data);
setConnectionStatus(true);
});
setThisPeer(thisPeerT);
In the on connect, I set a state hook that triggers a use effect where I create my on data.
useEffect(
function () {
console.log("here");
console.log(roomID);
console.log(thisPeer);
console.log(connectionStatus);
if (roomID && thisPeer && connectionStatus) {
console.log("here2");
thisPeer.on("data", function (data) {
console.log(data);
});
}
},
[roomID, thisPeer, connectionStatus]
);
However, I get the following error when I try to use thisPeer.on("data"...
here
XXYDCgqle4XvZDZ6gm6
Peer {_readableState: ReadableState, readable: true, _events: {…}, _eventsCount: 4, _maxListeners: undefined, …}
true
here2
Uncaught ReferenceError: process is not defined
at resume (_stream_readable.js:905:1)
at Peer.Readable.resume (_stream_readable.js:895:1)
at Peer.Readable.on (_stream_readable.js:813:1)
at ConnectionContext.js:142:1
at invokePassiveEffectCreate (react-dom.development.js:23487:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at flushPassiveEffectsImpl (react-dom.development.js:23574:1)
at unstable_runWithPriority (scheduler.development.js:468:1)
I have tried placing the on data at various places throughout my code, and regardless of the position, it seems this error occurs. If I call peer.send() on the other peer, it also gives a process is not defined error on the peer that received the data. Does anyone know how I can resolve the error or where I should open the data channel?
I got the same issue but I can do a workaround by using CDN script
<script src="https://cdnjs.cloudflare.com/ajax/libs/simple-peer/9.11.1/simplepeer.min.js"></script>
And here is a code example of how to call it in React
var peer1 = new window.SimplePeer({ initiator: true })

Redux-saga with Internet Explorer

I have a React app using redux-saga in IE 11
It seems to be breaking with the following error
Note that this app works perfectly fine in Chrome for versions of last 3 years and in Safari as well (aside for some display issues)
sagas.js
// functions are called bottom to top, this one is called at the end (also can be seen in stack trace below)
function* getGlobalData() {
console.log('Get global data called'); // this is executed
// something is failing from here on
const [
wardrobeResponse,
lastListingsResponse,
] = yield [
call(api_request, {url: 'store/wardrobes/'}),
call(api_request, {url: 'store/last_listings/'}),
]
yield put(actions.wardrobe.success(wardrobeResponse.json));
yield put(actions.lastListings.success(lastListingsResponse.json));
}
/**
* Watches for LOAD_SEARCH_RESULTS action and calls handler
*/
function* getGlobalDataWatcher() {
console.log('Get data - check if working');
console.log("global data watcher saga run")
yield take(Constants.LOAD_GLOBAL_DATA)
console.log('LOAD_GLOBAL_DATA received in saga')
const state = yield select()
if (state.getIn(['global', 'wardrobes']).isEmpty()) {
console.log('Empty global data, call api')
yield call(getGlobalData);
} else {
console.log('Global data already present, dont call API')
}
}
function* data() {
console.log('Get global results saga data called');
yield fork(getGlobalDataWatcher);
}
export default [
data
]
console error
uncaught at data
at loadMeDataWatcher
at loadMeData
TypeError: Object doesn't support this action
at api_request (http://localhost:3002/main.js:5905:3)
at runCallEffect (eval code:446:7)
at runEffect (eval code:370:5)
at next (eval code:259:9)
at currCb (eval code:329:7)
at runSelectEffect (eval code:651:7)
at runEffect (eval code:370:5)
at next (eval code:259:9)
at proc (eval code:214:3)
at resolveIterator (eval code:390:5)
You may install 'babel-polyfill' to your dependencies and add this line to your app.js.
import 'babel-polyfill';
See more

In-Context Checkout: Uncaught SecurityError: Blocked a frame with origin: checkout.js:4734 throws error

I'm implementing PayPal's In-Context Checkout and am using Advanced In-Context JavaScript settings (https://developer.paypal.com/docs/classic/express-checkout/in-context/javascript_advanced_settings)
My app is a React app. So I can't use PP API as they suggest it, that is just throw a code between <script> ... </script> tags somewhere in the page under their buttons. My React components have state and data that I need to send to server within PP function calls. So I placed PP code in componentDidMount method. And for some reason PP throws this error:
checkout.js:4734 Uncaught SecurityError: Blocked a frame with origin "http://example.com:3000" from accessing a frame with origin "https://www.sandbox.paypal.com". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "https". Protocols must match.
(anonymous function) # checkout.js:4734
checkout.js:4515 GET http://www.paypalobjects.com/api/oneTouch.html net::ERR_EMPTY_RESPONSE
Here is the code:
componentDidMount() {
window.paypalCheckoutReady = function() {
paypal.checkout.setup(config[NODE_ENV].ppMerchantID, {
locale: 'en_US',
environment: 'sandbox',
buttons: [
{
container: 'checkoutBtnContainer',
type: 'checkout',
color: 'gold',
size: 'medium',
shape: 'pill',
click: (ev)=>{
paypal.checkout.initXO();
$.post('/checkout', {
checkoutData: this.props.checkoutData,
})
.done(res => {
paypal.checkout.startFlow(res.link);
})
.fail(err => {
paypal.checkout.closeFlow();
});
}
}
],
});
};
},
I know about cross-origin policy. I don't understand why it is the case here. Why the code works fine if I throw it on the page between <script> ... </script> tags, but PP throws an error if I use it in my React component. What is the cause of that? Is it React fault or PayPal's?
UPD: No, below is not a solution for the problem. Occasionally Paypal's checkout.js script throws the error.
However, it solves this issue
Apparently,
1) there was no this:
window.paypalCheckoutReady = function() {
// wrong this is here
}
I changed to:
window.paypalCheckoutReady = () => {
// correct this is here now
}
I don't like .bind(this).
2) I removed <form /> tag and set plain <div> instead:
// before
<form id="checkoutBtnContainer" method="post" action="/checkout"></form>
// after
<div id="checkoutBtnContainer"></div>
I don't know why and how, but all works fine now.

Resources